context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
namespace Microsoft.Protocols.TestSuites.MS_WOPI
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
/// <summary>
/// A class is used to perform serializer operations for MS-WOPI protocol.
/// </summary>
public class WOPIResponseHelper : HelperBase
{
/// <summary>
/// Prevents a default instance of the WOPIResponseHelper class from being created
/// </summary>
private WOPIResponseHelper()
{
}
/// <summary>
/// A method is used to read the HTTP response body to the bytes array.
/// </summary>
/// <param name="wopiHttpResponse">A parameter represents the HTTP response.</param>
/// <returns>A return value represents the raw body content. If the body length is larger than (int.MaxValue) bytes, the body contents will be chunked by 1024 bytes. The max length of this method is (1024 * int.MaxValue) bytes.</returns>
public static List<byte[]> ReadRawHTTPResponseToBytes(WOPIHttpResponse wopiHttpResponse)
{
if (null == wopiHttpResponse)
{
throw new ArgumentNullException("wopiHttpResponse");
}
using (Stream bodyStream = wopiHttpResponse.GetResponseStream())
{
long contentLengthValue = wopiHttpResponse.ContentLength;
return ReadBytesFromHttpBodyStream(bodyStream, contentLengthValue);
}
}
/// <summary>
/// A method is used to read the HTTP response body and decode to string.
/// </summary>
/// <param name="wopiHttpResponse">A parameter represents the HTTP response.</param>
/// <returns>A return value represents the string which is decode from the HTTP response body. The decode format is UTF-8 by default.</returns>
public static string ReadHTTPResponseBodyToString(WOPIHttpResponse wopiHttpResponse)
{
if (null == wopiHttpResponse)
{
throw new ArgumentNullException("wopiHttpResponse");
}
string bodyString = string.Empty;
long bodyLength = wopiHttpResponse.ContentLength;
if (bodyLength != 0)
{
Stream bodStream = null;
try
{
bodStream = wopiHttpResponse.GetResponseStream();
using (StreamReader strReader = new StreamReader(bodStream))
{
bodyString = strReader.ReadToEnd();
}
}
finally
{
if (bodStream != null)
{
bodStream.Dispose();
}
}
}
return bodyString;
}
/// <summary>
/// A method is used to get raw body contents whose length is in 1 to int.MaxValue bytes scope.
/// </summary>
/// <param name="wopiHttpResponse">A parameter represents the HTTP response.</param>
/// <returns>A return value represents the raw body content.</returns>
public static byte[] GetContentFromResponse(WOPIHttpResponse wopiHttpResponse)
{
List<byte[]> rawBytesOfBody = ReadRawHTTPResponseToBytes(wopiHttpResponse);
byte[] returnContent = rawBytesOfBody.SelectMany(bytes => bytes).ToArray();
DiscoveryProcessHelper.AppendLogs(
typeof(WOPIResponseHelper),
string.Format(
"Read normal size(1 to int.MaxValue bytes) data from response. actual size[{0}] bytes",
returnContent.Length));
return returnContent;
}
/// <summary>
/// A method used to get byte string values from the response. 50 bytes per line.
/// </summary>
/// <param name="rawData">A parameter represents a WOPI response instance which contains the response body.</param>
/// <returns>A return value represents byte string values.</returns>
public static string GetBytesStringValue(byte[] rawData)
{
if (null == rawData || 0 == rawData.Length)
{
throw new ArgumentNullException("rawData");
}
string bitsString = BitConverter.ToString(rawData);
char[] splitSymbol = new char[] { '-' };
string[] bitStringValue = bitsString.Split(splitSymbol, StringSplitOptions.RemoveEmptyEntries);
// Output 50 bits string value per line.
int wrapNumberOfBitString = 50;
if (bitStringValue.Length <= wrapNumberOfBitString)
{
return bitsString;
}
else
{
StringBuilder strBuilder = new StringBuilder();
int beginIndexOfOneLine = 0;
bool stopSplitLine = false;
int oneLineLength = wrapNumberOfBitString * 3;
// Wrap the bits string value.
do
{
// If it meets the last line, get the actual bits value.
if (beginIndexOfOneLine + oneLineLength > bitsString.Length)
{
oneLineLength = bitsString.Length - beginIndexOfOneLine;
stopSplitLine = true;
}
string oneLineContent = bitsString.Substring(beginIndexOfOneLine, oneLineLength);
beginIndexOfOneLine = beginIndexOfOneLine + oneLineLength;
strBuilder.AppendLine(oneLineContent);
}
while (!stopSplitLine);
return strBuilder.ToString();
}
}
/// <summary>
/// A method used to read bytes data from the stream of the HTTP response.
/// </summary>
/// <param name="bodyBinaries">A parameter represents the stream which contain the body binaries data.</param>
/// <param name="contentLengthValue">A parameter represents the length of the body binaries.</param>
/// <returns>A return value represents the raw body content. If the body length is larger than (int.MaxValue) bytes, the body contents will be chunked by 1024 bytes. The max length of this method is (1024 * int.MaxValue) bytes.</returns>
private static List<byte[]> ReadBytesFromHttpBodyStream(Stream bodyBinaries, long contentLengthValue)
{
if (null == bodyBinaries)
{
throw new ArgumentNullException("bodyBinaries");
}
long maxKBSize = (long)int.MaxValue;
long totalSize = contentLengthValue;
if (contentLengthValue > maxKBSize * 1024)
{
throw new InvalidOperationException(string.Format("The test suite only support [{0}]KB size content in a HTTP response.", maxKBSize));
}
List<byte[]> bytesOfResponseBody = new List<byte[]>();
bool isuseChunk = false;
using (BinaryReader binReader = new BinaryReader(bodyBinaries))
{
if (contentLengthValue < int.MaxValue && contentLengthValue > 0)
{
byte[] bytesBlob = binReader.ReadBytes((int)contentLengthValue);
bytesOfResponseBody.Add(bytesBlob);
}
else
{
isuseChunk = true;
totalSize = 0;
// set chunk size to 1KB per reading.
int chunkSize = 1024;
byte[] bytesBlockTemp = null;
do
{
bytesBlockTemp = binReader.ReadBytes(chunkSize);
if (bytesBlockTemp.Length > 0)
{
bytesOfResponseBody.Add(bytesBlockTemp);
totalSize += bytesBlockTemp.Length;
}
}
while (bytesBlockTemp.Length > 0);
}
}
string chunkProcessLogs = string.Format(
"Read [{0}] KB size data from response body.{1}",
(totalSize / 1024.0).ToString("f2"),
isuseChunk ? "Use the chunk reading mode." : string.Empty);
DiscoveryProcessHelper.AppendLogs(typeof(WOPIResponseHelper), chunkProcessLogs);
return bytesOfResponseBody;
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#pragma warning disable 436
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
#if !((UNITY_WINRT && !UNITY_EDITOR))
using System.Security.Permissions;
#endif
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Serialization
{
internal interface IMetadataTypeAttribute
{
Type MetadataClassType { get; }
}
internal static class JsonTypeReflector
{
public const string IdPropertyName = "$id";
public const string RefPropertyName = "$ref";
public const string TypePropertyName = "$type";
public const string ValuePropertyName = "$value";
public const string ArrayValuesPropertyName = "$values";
public const string ShouldSerializePrefix = "ShouldSerialize";
public const string SpecifiedPostfix = "Specified";
private static readonly ThreadSafeStore<ICustomAttributeProvider, Type> JsonConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetJsonConverterTypeFromAttribute);
#if !(UNITY_WP8 || UNITY_WP_8_1) && (!UNITY_WINRT || UNITY_EDITOR)
private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute);
private const string MetadataTypeAttributeTypeName =
"System.ComponentModel.DataAnnotations.MetadataTypeAttribute, System.ComponentModel.DataAnnotations, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
private static Type _cachedMetadataTypeAttributeType;
#endif
public static JsonContainerAttribute GetJsonContainerAttribute(Type type)
{
return CachedAttributeGetter<JsonContainerAttribute>.GetAttribute(type);
}
public static JsonObjectAttribute GetJsonObjectAttribute(Type type)
{
return GetJsonContainerAttribute(type) as JsonObjectAttribute;
}
public static JsonArrayAttribute GetJsonArrayAttribute(Type type)
{
return GetJsonContainerAttribute(type) as JsonArrayAttribute;
}
public static MemberSerialization GetObjectMemberSerialization(Type objectType)
{
JsonObjectAttribute objectAttribute = GetJsonObjectAttribute(objectType);
if (objectAttribute == null)
{
return MemberSerialization.OptOut;
}
return objectAttribute.MemberSerialization;
}
private static Type GetJsonConverterType(ICustomAttributeProvider attributeProvider)
{
return JsonConverterTypeCache.Get(attributeProvider);
}
private static Type GetJsonConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider)
{
JsonConverterAttribute converterAttribute = GetAttribute<JsonConverterAttribute>(attributeProvider);
return (converterAttribute != null)
? converterAttribute.ConverterType
: null;
}
public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType)
{
Type converterType = GetJsonConverterType(attributeProvider);
if (converterType != null)
{
JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType);
if (!memberConverter.CanConvert(targetConvertedType))
throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, attributeProvider, targetConvertedType.Name));
return memberConverter;
}
return null;
}
#if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
public static TypeConverter GetTypeConverter(Type type)
{
#if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
return TypeDescriptor.GetConverter(type);
#else
Type converterType = GetTypeConverterType(type);
if (converterType != null)
return (TypeConverter)ReflectionUtils.CreateInstance(converterType);
return null;
#endif
}
#endif
#if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
private static Type GetAssociatedMetadataType(Type type)
{
return AssociatedMetadataTypesCache.Get(type);
}
private static Type GetAssociateMetadataTypeFromAttribute(Type type)
{
Type metadataTypeAttributeType = GetMetadataTypeAttributeType();
if (metadataTypeAttributeType == null)
return null;
object attribute = type.GetCustomAttributes(metadataTypeAttributeType, true).SingleOrDefault();
if (attribute == null)
return null;
#if (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID)
IMetadataTypeAttribute metadataTypeAttribute = new LateBoundMetadataTypeAttribute(attribute);
#else
IMetadataTypeAttribute metadataTypeAttribute = (DynamicCodeGeneration)
? DynamicWrapper.CreateWrapper<IMetadataTypeAttribute>(attribute)
: new LateBoundMetadataTypeAttribute(attribute);
#endif
return metadataTypeAttribute.MetadataClassType;
}
private static Type GetMetadataTypeAttributeType()
{
// always attempt to get the metadata type attribute type
// the assembly may have been loaded since last time
if (_cachedMetadataTypeAttributeType == null)
{
Type metadataTypeAttributeType = Type.GetType(MetadataTypeAttributeTypeName);
if (metadataTypeAttributeType != null)
_cachedMetadataTypeAttributeType = metadataTypeAttributeType;
else
return null;
}
return _cachedMetadataTypeAttributeType;
}
#endif
private static T GetAttribute<T>(Type type) where T : System.Attribute
{
T attribute;
#if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
Type metadataType = GetAssociatedMetadataType(type);
if (metadataType != null)
{
attribute = ReflectionUtils.GetAttribute<T>(metadataType, true);
if (attribute != null)
return attribute;
}
#endif
attribute = ReflectionUtils.GetAttribute<T>(type, true);
if (attribute != null)
return attribute;
foreach (Type typeInterface in type.GetInterfaces())
{
attribute = ReflectionUtils.GetAttribute<T>(typeInterface, true);
if (attribute != null)
return attribute;
}
return null;
}
private static T GetAttribute<T>(MemberInfo memberInfo) where T : System.Attribute
{
T attribute;
#if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType);
if (metadataType != null)
{
MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo);
if (metadataTypeMemberInfo != null)
{
attribute = ReflectionUtils.GetAttribute<T>(metadataTypeMemberInfo, true);
if (attribute != null)
return attribute;
}
}
#endif
attribute = ReflectionUtils.GetAttribute<T>(memberInfo, true);
if (attribute != null)
return attribute;
foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces())
{
MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo);
if (interfaceTypeMemberInfo != null)
{
attribute = ReflectionUtils.GetAttribute<T>(interfaceTypeMemberInfo, true);
if (attribute != null)
return attribute;
}
}
return null;
}
public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : System.Attribute
{
Type type = attributeProvider as Type;
if (type != null)
return GetAttribute<T>(type);
MemberInfo memberInfo = attributeProvider as MemberInfo;
if (memberInfo != null)
return GetAttribute<T>(memberInfo);
return ReflectionUtils.GetAttribute<T>(attributeProvider, true);
}
private static bool? _dynamicCodeGeneration;
public static bool DynamicCodeGeneration
{
get
{
if (_dynamicCodeGeneration == null)
{
#if !(UNITY_ANDROID || UNITY_WEBPLAYER || (UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) || (UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR))
try
{
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess).Demand();
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand();
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 108
new SecurityPermission(PermissionState.Unrestricted).Demand();
_dynamicCodeGeneration = true;
}
catch (Exception)
{
_dynamicCodeGeneration = false;
}
#else
_dynamicCodeGeneration = false;
#endif
}
return _dynamicCodeGeneration.Value;
}
}
public static ReflectionDelegateFactory ReflectionDelegateFactory
{
get
{
#if !((UNITY_WP8 || UNITY_WP_8_1) || (UNITY_WINRT && !UNITY_EDITOR) || UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID)
if (DynamicCodeGeneration)
return DynamicReflectionDelegateFactory.Instance;
#endif
return LateBoundReflectionDelegateFactory.Instance;
}
}
}
}
#pragma warning restore 436
#endif
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using osu.Framework;
using osu.Framework.Bindables;
using osu.Framework.Logging;
using osu.Game.Online.API;
namespace osu.Game.Online
{
public class HubClientConnector : IHubClientConnector
{
/// <summary>
/// Invoked whenever a new hub connection is built, to configure it before it's started.
/// </summary>
public Action<HubConnection>? ConfigureConnection { get; set; }
private readonly string clientName;
private readonly string endpoint;
private readonly string versionHash;
private readonly IAPIProvider api;
/// <summary>
/// The current connection opened by this connector.
/// </summary>
public HubConnection? CurrentConnection { get; private set; }
/// <summary>
/// Whether this is connected to the hub, use <see cref="CurrentConnection"/> to access the connection, if this is <c>true</c>.
/// </summary>
public IBindable<bool> IsConnected => isConnected;
private readonly Bindable<bool> isConnected = new Bindable<bool>();
private readonly SemaphoreSlim connectionLock = new SemaphoreSlim(1);
private CancellationTokenSource connectCancelSource = new CancellationTokenSource();
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
/// <summary>
/// Constructs a new <see cref="HubClientConnector"/>.
/// </summary>
/// <param name="clientName">The name of the client this connector connects for, used for logging.</param>
/// <param name="endpoint">The endpoint to the hub.</param>
/// <param name="api"> An API provider used to react to connection state changes.</param>
/// <param name="versionHash">The hash representing the current game version, used for verification purposes.</param>
public HubClientConnector(string clientName, string endpoint, IAPIProvider api, string versionHash)
{
this.clientName = clientName;
this.endpoint = endpoint;
this.api = api;
this.versionHash = versionHash;
apiState.BindTo(api.State);
apiState.BindValueChanged(state =>
{
switch (state.NewValue)
{
case APIState.Failing:
case APIState.Offline:
Task.Run(() => disconnect(true));
break;
case APIState.Online:
Task.Run(connect);
break;
}
}, true);
}
private async Task connect()
{
cancelExistingConnect();
if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false))
throw new TimeoutException("Could not obtain a lock to connect. A previous attempt is likely stuck.");
try
{
while (apiState.Value == APIState.Online)
{
// ensure any previous connection was disposed.
// this will also create a new cancellation token source.
await disconnect(false).ConfigureAwait(false);
// this token will be valid for the scope of this connection.
// if cancelled, we can be sure that a disconnect or reconnect is handled elsewhere.
var cancellationToken = connectCancelSource.Token;
cancellationToken.ThrowIfCancellationRequested();
Logger.Log($"{clientName} connecting...", LoggingTarget.Network);
try
{
// importantly, rebuild the connection each attempt to get an updated access token.
CurrentConnection = buildConnection(cancellationToken);
await CurrentConnection.StartAsync(cancellationToken).ConfigureAwait(false);
Logger.Log($"{clientName} connected!", LoggingTarget.Network);
isConnected.Value = true;
return;
}
catch (OperationCanceledException)
{
//connection process was cancelled.
throw;
}
catch (Exception e)
{
Logger.Log($"{clientName} connection error: {e}", LoggingTarget.Network);
// retry on any failure.
await Task.Delay(5000, cancellationToken).ConfigureAwait(false);
}
}
}
finally
{
connectionLock.Release();
}
}
private HubConnection buildConnection(CancellationToken cancellationToken)
{
var builder = new HubConnectionBuilder()
.WithUrl(endpoint, options =>
{
options.Headers.Add("Authorization", $"Bearer {api.AccessToken}");
options.Headers.Add("OsuVersionHash", versionHash);
});
if (RuntimeInfo.SupportsJIT)
builder.AddMessagePackProtocol();
else
{
// eventually we will precompile resolvers for messagepack, but this isn't working currently
// see https://github.com/neuecc/MessagePack-CSharp/issues/780#issuecomment-768794308.
builder.AddNewtonsoftJsonProtocol(options => { options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; });
}
var newConnection = builder.Build();
ConfigureConnection?.Invoke(newConnection);
newConnection.Closed += ex => onConnectionClosed(ex, cancellationToken);
return newConnection;
}
private Task onConnectionClosed(Exception? ex, CancellationToken cancellationToken)
{
isConnected.Value = false;
Logger.Log(ex != null ? $"{clientName} lost connection: {ex}" : $"{clientName} disconnected", LoggingTarget.Network);
// make sure a disconnect wasn't triggered (and this is still the active connection).
if (!cancellationToken.IsCancellationRequested)
Task.Run(connect, default);
return Task.CompletedTask;
}
private async Task disconnect(bool takeLock)
{
cancelExistingConnect();
if (takeLock)
{
if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false))
throw new TimeoutException("Could not obtain a lock to disconnect. A previous attempt is likely stuck.");
}
try
{
if (CurrentConnection != null)
await CurrentConnection.DisposeAsync().ConfigureAwait(false);
}
finally
{
CurrentConnection = null;
if (takeLock)
connectionLock.Release();
}
}
private void cancelExistingConnect()
{
connectCancelSource.Cancel();
connectCancelSource = new CancellationTokenSource();
}
public override string ToString() => $"Connector for {clientName} ({(IsConnected.Value ? "connected" : "not connected")}";
public void Dispose()
{
apiState.UnbindAll();
cancelExistingConnect();
}
}
}
| |
//
// X509Extensions.cs: Handles X.509 extensions.
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// (C) 2004 Novell (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using Mono.Security;
namespace Mono.Security.X509 {
/*
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Note: 1..MAX -> There shouldn't be 0 Extensions in the ASN1 structure
*/
#if INSIDE_CORLIB
internal
#else
public
#endif
sealed class X509ExtensionCollection : CollectionBase, IEnumerable {
private bool readOnly;
public X509ExtensionCollection () : base ()
{
}
public X509ExtensionCollection (ASN1 asn1) : this ()
{
readOnly = true;
if (asn1 == null)
return;
if (asn1.Tag != 0x30)
throw new Exception ("Invalid extensions format");
for (int i=0; i < asn1.Count; i++) {
X509Extension extension = new X509Extension (asn1 [i]);
InnerList.Add (extension);
}
}
public int Add (X509Extension extension)
{
if (extension == null)
throw new ArgumentNullException ("extension");
if (readOnly)
throw new NotSupportedException ("Extensions are read only");
return InnerList.Add (extension);
}
public void AddRange (X509Extension[] extension)
{
if (extension == null)
throw new ArgumentNullException ("extension");
if (readOnly)
throw new NotSupportedException ("Extensions are read only");
for (int i = 0; i < extension.Length; i++)
InnerList.Add (extension [i]);
}
public void AddRange (X509ExtensionCollection collection)
{
if (collection == null)
throw new ArgumentNullException ("collection");
if (readOnly)
throw new NotSupportedException ("Extensions are read only");
for (int i = 0; i < collection.InnerList.Count; i++)
InnerList.Add (collection [i]);
}
public bool Contains (X509Extension extension)
{
return (IndexOf (extension) != -1);
}
public bool Contains (string oid)
{
return (IndexOf (oid) != -1);
}
public void CopyTo (X509Extension[] extensions, int index)
{
if (extensions == null)
throw new ArgumentNullException ("extensions");
InnerList.CopyTo (extensions, index);
}
public int IndexOf (X509Extension extension)
{
if (extension == null)
throw new ArgumentNullException ("extension");
for (int i=0; i < InnerList.Count; i++) {
X509Extension ex = (X509Extension) InnerList [i];
if (ex.Equals (extension))
return i;
}
return -1;
}
public int IndexOf (string oid)
{
if (oid == null)
throw new ArgumentNullException ("oid");
for (int i=0; i < InnerList.Count; i++) {
X509Extension ex = (X509Extension) InnerList [i];
if (ex.Oid == oid)
return i;
}
return -1;
}
public void Insert (int index, X509Extension extension)
{
if (extension == null)
throw new ArgumentNullException ("extension");
InnerList.Insert (index, extension);
}
public void Remove (X509Extension extension)
{
if (extension == null)
throw new ArgumentNullException ("extension");
InnerList.Remove (extension);
}
public void Remove (string oid)
{
if (oid == null)
throw new ArgumentNullException ("oid");
int index = IndexOf (oid);
if (index != -1)
InnerList.RemoveAt (index);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return InnerList.GetEnumerator ();
}
public X509Extension this [int index] {
get { return (X509Extension) InnerList [index]; }
}
public X509Extension this [string oid] {
get {
int index = IndexOf (oid);
if (index == -1)
return null;
return (X509Extension) InnerList [index];
}
}
public byte[] GetBytes ()
{
if (InnerList.Count < 1)
return null;
ASN1 sequence = new ASN1 (0x30);
for (int i=0; i < InnerList.Count; i++) {
X509Extension x = (X509Extension) InnerList [i];
sequence.Add (x.ASN1);
}
return sequence.GetBytes ();
}
}
}
| |
using System;
/// <summary>
/// String.Replace(String, String)
/// Replaces all occurrences of a specified Unicode character in this instance
/// with another specified Unicode character.
/// </summary>
public class StringReplace2
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringReplace2 sr = new StringReplace2();
TestLibrary.TestFramework.BeginTestCase("for method: System.String.Replace(String, String)");
if(sr.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive test scenarios
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Source string contains old string.";
const string c_TEST_ID = "P001";
string strSrc;
string oldStr, newStr;
bool condition;
bool expectedValue = true;
bool actualValue = false;
//Initialize the parameters
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex;
startIndex = GetInt32(0, strSrc.Length - 1);
oldStr = strSrc.Substring(startIndex, GetInt32(1, strSrc.Length - startIndex));
newStr = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReplaced = strSrc.Replace(oldStr, newStr);
string subStrOld, subStrNew;
int oldIndex = 0;
int newIndex;
int maxValidIndex = strReplaced.Length - newStr.Length;
condition = true;
// compare string replaed and source string
for (newIndex = 0; newIndex < maxValidIndex; )
{
subStrNew = strReplaced.Substring(newIndex, newStr.Length);
if(0 == string.CompareOrdinal(subStrNew, newStr))
{
subStrOld = strSrc.Substring(oldIndex, oldStr.Length);
condition = (0 == string.CompareOrdinal(subStrOld, oldStr)) && condition;
oldIndex += oldStr.Length;
newIndex += newStr.Length;
}
else
{
condition = (strReplaced[newIndex] == strSrc[oldIndex]) && condition;
oldIndex++;
newIndex++;
}
}
actualValue = condition;
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, oldStr, newStr);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Source string does not contain old string.";
const string c_TEST_ID = "P002";
string strSrc;
string oldStr, newStr;
bool expectedValue = true;
bool actualValue = false;
//Initialize the parameters
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
oldStr = strSrc + TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
newStr = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReplaced = strSrc.Replace(oldStr, newStr);
actualValue = (0 == string.CompareOrdinal(strSrc, strReplaced));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, oldStr, newStr);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
return retVal;
}
//new update added by Noter(v-yaduoj) 8-10-2006
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Source string contains old string, replace with \"\\0\"";
const string c_TEST_ID = "P003";
string strSrc;
string oldStr, newStr;
bool condition;
bool expectedValue = true;
bool actualValue = false;
//Initialize the parameters
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int startIndex;
startIndex = GetInt32(0, strSrc.Length - 1);
oldStr = strSrc.Substring(startIndex, GetInt32(1, strSrc.Length - startIndex));
newStr = "\0";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReplaced = strSrc.Replace(oldStr, newStr);
string subStrOld, subStrNew;
int oldIndex = 0;
int newIndex;
int maxValidIndex = strReplaced.Length - newStr.Length;
condition = true;
// compare string replaed and source string
for (newIndex = 0; newIndex < maxValidIndex; )
{
subStrNew = strReplaced.Substring(newIndex, newStr.Length);
if (0 == string.CompareOrdinal(subStrNew, newStr))
{
subStrOld = strSrc.Substring(oldIndex, oldStr.Length);
condition = (0 == string.CompareOrdinal(subStrOld, oldStr)) && condition;
oldIndex += oldStr.Length;
newIndex += newStr.Length;
}
else
{
condition = (strReplaced[newIndex] == strSrc[oldIndex]) && condition;
oldIndex++;
newIndex++;
}
}
actualValue = condition;
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, oldStr, newStr);
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
return retVal;
}
#endregion
#region Negative test scenarios
//ArgumentNullException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: old string value is null reference.";
const string c_TEST_ID = "N001";
string strSrc;
string oldStr, newStr;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
oldStr = null;
newStr = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSrc.Replace(oldStr, newStr);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, "ArgumentNullException is not thrown as expected." + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
catch (ArgumentNullException)
{}
catch(Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
return retVal;
}
//ArgumentException
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: old string value is String.Empty";
const string c_TEST_ID = "N002";
string strSrc;
string oldStr, newStr;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
oldStr = String.Empty;
newStr = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
strSrc.Replace(oldStr, newStr);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected." + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
catch (ArgumentException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldStr, newStr));
retVal = false;
}
return retVal;
}
#endregion
#region helper methods for generating test data
private bool GetBoolean()
{
Int32 i = this.GetInt32(1, 2);
return (i == 1) ? true : false;
}
//Get a non-negative integer between minValue and maxValue
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Int32 Min(Int32 i1, Int32 i2)
{
return (i1 <= i2) ? i1 : i2;
}
private Int32 Max(Int32 i1, Int32 i2)
{
return (i1 >= i2) ? i1 : i2;
}
#endregion
private string GetDataString(string strSrc, string oldStr, string newStr)
{
string str1, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str = string.Format("\n[Source string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source string]\n {0}", len1);
str += string.Format("\n[Old string]\n{0}", oldStr);
str += string.Format("\n[New string]\n{0}", newStr);
return str;
}
}
| |
// 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.
//
////////////////////////////////////////////////////////////////////////////////
#pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
namespace System.Threading
{
/// <summary>
/// Propagates notification that operations should be canceled.
/// </summary>
/// <remarks>
/// <para>
/// A <see cref="CancellationToken"/> may be created directly in an unchangeable canceled or non-canceled state
/// using the CancellationToken's constructors. However, to have a CancellationToken that can change
/// from a non-canceled to a canceled state,
/// <see cref="System.Threading.CancellationTokenSource">CancellationTokenSource</see> must be used.
/// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its
/// <see cref="System.Threading.CancellationTokenSource.Token">Token</see> property.
/// </para>
/// <para>
/// Once canceled, a token may not transition to a non-canceled state, and a token whose
/// <see cref="CanBeCanceled"/> is false will never change to one that can be canceled.
/// </para>
/// <para>
/// All members of this struct are thread-safe and may be used concurrently from multiple threads.
/// </para>
/// </remarks>
[ComVisible(false)]
[HostProtection(Synchronization = true, ExternalThreading = true)]
[DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")]
public struct CancellationToken
{
// The backing TokenSource.
// if null, it implicitly represents the same thing as new CancellationToken(false).
// When required, it will be instantiated to reflect this.
private CancellationTokenSource m_source;
//!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid
/* Properties */
/// <summary>
/// Returns an empty CancellationToken value.
/// </summary>
/// <remarks>
/// The <see cref="CancellationToken"/> value returned by this property will be non-cancelable by default.
/// </remarks>
public static CancellationToken None
{
get { return default(CancellationToken); }
}
/// <summary>
/// Gets whether cancellation has been requested for this token.
/// </summary>
/// <value>Whether cancellation has been requested for this token.</value>
/// <remarks>
/// <para>
/// This property indicates whether cancellation has been requested for this token,
/// either through the token initially being construted in a canceled state, or through
/// calling <see cref="System.Threading.CancellationTokenSource.Cancel()">Cancel</see>
/// on the token's associated <see cref="CancellationTokenSource"/>.
/// </para>
/// <para>
/// If this property is true, it only guarantees that cancellation has been requested.
/// It does not guarantee that every registered handler
/// has finished executing, nor that cancellation requests have finished propagating
/// to all registered handlers. Additional synchronization may be required,
/// particularly in situations where related objects are being canceled concurrently.
/// </para>
/// </remarks>
public bool IsCancellationRequested
{
get
{
return m_source != null && m_source.IsCancellationRequested;
}
}
/// <summary>
/// Gets whether this token is capable of being in the canceled state.
/// </summary>
/// <remarks>
/// If CanBeCanceled returns false, it is guaranteed that the token will never transition
/// into a canceled state, meaning that <see cref="IsCancellationRequested"/> will never
/// return true.
/// </remarks>
public bool CanBeCanceled
{
get
{
return m_source != null && m_source.CanBeCanceled;
}
}
/// <summary>
/// Gets a <see cref="T:System.Threading.WaitHandle"/> that is signaled when the token is canceled.</summary>
/// <remarks>
/// Accessing this property causes a <see cref="T:System.Threading.WaitHandle">WaitHandle</see>
/// to be instantiated. It is preferable to only use this property when necessary, and to then
/// dispose the associated <see cref="CancellationTokenSource"/> instance at the earliest opportunity (disposing
/// the source will dispose of this allocated handle). The handle should not be closed or disposed directly.
/// </remarks>
/// <exception cref="T:System.ObjectDisposedException">The associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public WaitHandle WaitHandle
{
get
{
if (m_source == null)
{
InitializeDefaultSource();
}
return m_source.WaitHandle;
}
}
// public CancellationToken()
// this constructor is implicit for structs
// -> this should behaves exactly as for new CancellationToken(false)
/// <summary>
/// Internal constructor only a CancellationTokenSource should create a CancellationToken
/// </summary>
internal CancellationToken(CancellationTokenSource source)
{
m_source = source;
}
/// <summary>
/// Initializes the <see cref="T:System.Threading.CancellationToken">CancellationToken</see>.
/// </summary>
/// <param name="canceled">
/// The canceled state for the token.
/// </param>
/// <remarks>
/// Tokens created with this constructor will remain in the canceled state specified
/// by the <paramref name="canceled"/> parameter. If <paramref name="canceled"/> is false,
/// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be false.
/// If <paramref name="canceled"/> is true,
/// both <see cref="CanBeCanceled"/> and <see cref="IsCancellationRequested"/> will be true.
/// </remarks>
public CancellationToken(bool canceled) :
this()
{
if(canceled)
m_source = CancellationTokenSource.InternalGetStaticSource(canceled);
}
/* Methods */
private readonly static Action<Object> s_ActionToActionObjShunt = new Action<Object>(ActionToActionObjShunt);
private static void ActionToActionObjShunt(object obj)
{
Action action = obj as Action;
Contract.Assert(action != null, "Expected an Action here");
action();
}
/// <summary>
/// Registers a delegate that will be called when this <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.
/// </summary>
/// <remarks>
/// <para>
/// If this token is already in the canceled state, the
/// delegate will be run immediately and synchronously. Any exception the delegate generates will be
/// propagated out of this method call.
/// </para>
/// <para>
/// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured
/// along with the delegate and will be used when executing it.
/// </para>
/// </remarks>
/// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param>
/// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can
/// be used to deregister the callback.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
public CancellationTokenRegistration Register(Action callback)
{
if (callback == null)
throw new ArgumentNullException("callback");
return Register(
s_ActionToActionObjShunt,
callback,
false, // useSync=false
true // useExecutionContext=true
);
}
/// <summary>
/// Registers a delegate that will be called when this
/// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.
/// </summary>
/// <remarks>
/// <para>
/// If this token is already in the canceled state, the
/// delegate will be run immediately and synchronously. Any exception the delegate generates will be
/// propagated out of this method call.
/// </para>
/// <para>
/// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured
/// along with the delegate and will be used when executing it.
/// </para>
/// </remarks>
/// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param>
/// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture
/// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it
/// when invoking the <paramref name="callback"/>.</param>
/// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can
/// be used to deregister the callback.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext)
{
if (callback == null)
throw new ArgumentNullException("callback");
return Register(
s_ActionToActionObjShunt,
callback,
useSynchronizationContext,
true // useExecutionContext=true
);
}
/// <summary>
/// Registers a delegate that will be called when this
/// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.
/// </summary>
/// <remarks>
/// <para>
/// If this token is already in the canceled state, the
/// delegate will be run immediately and synchronously. Any exception the delegate generates will be
/// propagated out of this method call.
/// </para>
/// <para>
/// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists, will be captured
/// along with the delegate and will be used when executing it.
/// </para>
/// </remarks>
/// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param>
/// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param>
/// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can
/// be used to deregister the callback.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
public CancellationTokenRegistration Register(Action<Object> callback, Object state)
{
if (callback == null)
throw new ArgumentNullException("callback");
return Register(
callback,
state,
false, // useSync=false
true // useExecutionContext=true
);
}
/// <summary>
/// Registers a delegate that will be called when this
/// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.
/// </summary>
/// <remarks>
/// <para>
/// If this token is already in the canceled state, the
/// delegate will be run immediately and synchronously. Any exception the delegate generates will be
/// propagated out of this method call.
/// </para>
/// <para>
/// The current <see cref="System.Threading.ExecutionContext">ExecutionContext</see>, if one exists,
/// will be captured along with the delegate and will be used when executing it.
/// </para>
/// </remarks>
/// <param name="callback">The delegate to be executed when the <see cref="T:System.Threading.CancellationToken">CancellationToken</see> is canceled.</param>
/// <param name="state">The state to pass to the <paramref name="callback"/> when the delegate is invoked. This may be null.</param>
/// <param name="useSynchronizationContext">A Boolean value that indicates whether to capture
/// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see> and use it
/// when invoking the <paramref name="callback"/>.</param>
/// <returns>The <see cref="T:System.Threading.CancellationTokenRegistration"/> instance that can
/// be used to deregister the callback.</returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="T:System.ObjectDisposedException">The associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public CancellationTokenRegistration Register(Action<Object> callback, Object state, bool useSynchronizationContext)
{
return Register(
callback,
state,
useSynchronizationContext,
true // useExecutionContext=true
);
}
// helper for internal registration needs that don't require an EC capture (e.g. creating linked token sources, or registering unstarted TPL tasks)
// has a handy signature, and skips capturing execution context.
internal CancellationTokenRegistration InternalRegisterWithoutEC(Action<object> callback, Object state)
{
return Register(
callback,
state,
false, // useSyncContext=false
false // useExecutionContext=false
);
}
// the real work..
[SecuritySafeCritical]
[MethodImpl(MethodImplOptions.NoInlining)]
private CancellationTokenRegistration Register(Action<Object> callback, Object state, bool useSynchronizationContext, bool useExecutionContext)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
if (callback == null)
throw new ArgumentNullException("callback");
if (CanBeCanceled == false)
{
return new CancellationTokenRegistration(); // nothing to do for tokens than can never reach the canceled state. Give them a dummy registration.
}
// Capture sync/execution contexts if required.
// Note: Only capture sync/execution contexts if IsCancellationRequested = false
// as we know that if it is true that the callback will just be called synchronously.
SynchronizationContext capturedSyncContext = null;
ExecutionContext capturedExecutionContext = null;
if (!IsCancellationRequested)
{
if (useSynchronizationContext)
capturedSyncContext = SynchronizationContext.Current;
if (useExecutionContext)
capturedExecutionContext = ExecutionContext.Capture(
ref stackMark, ExecutionContext.CaptureOptions.OptimizeDefaultCase); // ideally we'd also use IgnoreSyncCtx, but that could break compat
}
// Register the callback with the source.
return m_source.InternalRegister(callback, state, capturedSyncContext, capturedExecutionContext);
}
/// <summary>
/// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the
/// specified token.
/// </summary>
/// <param name="other">The other <see cref="T:System.Threading.CancellationToken">CancellationToken</see> to which to compare this
/// instance.</param>
/// <returns>True if the instances are equal; otherwise, false. Two tokens are equal if they are associated
/// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed
/// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns>
public bool Equals(CancellationToken other)
{
//if both sources are null, then both tokens represent the Empty token.
if (m_source == null && other.m_source == null)
{
return true;
}
// one is null but other has inflated the default source
// these are only equal if the inflated one is the staticSource(false)
if (m_source == null)
{
return other.m_source == CancellationTokenSource.InternalGetStaticSource(false);
}
if (other.m_source == null)
{
return m_source == CancellationTokenSource.InternalGetStaticSource(false);
}
// general case, we check if the sources are identical
return m_source == other.m_source;
}
/// <summary>
/// Determines whether the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance is equal to the
/// specified <see cref="T:System.Object"/>.
/// </summary>
/// <param name="other">The other object to which to compare this instance.</param>
/// <returns>True if <paramref name="other"/> is a <see cref="T:System.Threading.CancellationToken">CancellationToken</see>
/// and if the two instances are equal; otherwise, false. Two tokens are equal if they are associated
/// with the same <see cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> or if they were both constructed
/// from public CancellationToken constructors and their <see cref="IsCancellationRequested"/> values are equal.</returns>
/// <exception cref="T:System.ObjectDisposedException">An associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public override bool Equals(Object other)
{
if (other is CancellationToken)
{
return Equals((CancellationToken) other);
}
return false;
}
/// <summary>
/// Serves as a hash function for a <see cref="T:System.Threading.CancellationToken">CancellationToken</see>.
/// </summary>
/// <returns>A hash code for the current <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instance.</returns>
public override Int32 GetHashCode()
{
if (m_source == null)
{
// link to the common source so that we have a source to interrogate.
return CancellationTokenSource.InternalGetStaticSource(false).GetHashCode();
}
return m_source.GetHashCode();
}
/// <summary>
/// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are equal.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True if the instances are equal; otherwise, false.</returns>
/// <exception cref="T:System.ObjectDisposedException">An associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public static bool operator ==(CancellationToken left, CancellationToken right)
{
return left.Equals(right);
}
/// <summary>
/// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are not equal.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True if the instances are not equal; otherwise, false.</returns>
/// <exception cref="T:System.ObjectDisposedException">An associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public static bool operator !=(CancellationToken left, CancellationToken right)
{
return !left.Equals(right);
}
/// <summary>
/// Throws a <see cref="T:System.OperationCanceledException">OperationCanceledException</see> if
/// this token has had cancellation requested.
/// </summary>
/// <remarks>
/// This method provides functionality equivalent to:
/// <code>
/// if (token.IsCancellationRequested)
/// throw new OperationCanceledException(token);
/// </code>
/// </remarks>
/// <exception cref="System.OperationCanceledException">The token has had cancellation requested.</exception>
/// <exception cref="T:System.ObjectDisposedException">The associated <see
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public void ThrowIfCancellationRequested()
{
if (IsCancellationRequested)
ThrowOperationCanceledException();
}
// Throw an ODE if this CancellationToken's source is disposed.
internal void ThrowIfSourceDisposed()
{
if ((m_source != null) && m_source.IsDisposed)
ThrowObjectDisposedException();
}
// Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested
private void ThrowOperationCanceledException()
{
throw new OperationCanceledException(Environment.GetResourceString("OperationCanceled"), this);
}
private static void ThrowObjectDisposedException()
{
throw new ObjectDisposedException(null, Environment.GetResourceString("CancellationToken_SourceDisposed"));
}
// -----------------------------------
// Private helpers
private void InitializeDefaultSource()
{
// Lazy is slower, and although multiple threads may try and set m_source repeatedly, the race condition is benign.
// Alternative: LazyInititalizer.EnsureInitialized(ref m_source, ()=>CancellationTokenSource.InternalGetStaticSource(false));
m_source = CancellationTokenSource.InternalGetStaticSource(false);
}
}
}
| |
namespace Evelyn.Core.Tests.WriteModel.Project.DeleteProject
{
using System;
using System.Collections.Generic;
using System.Linq;
using AutoFixture;
using FluentAssertions;
using global::Evelyn.Core.WriteModel.Project.Commands.DeleteProject;
using global::Evelyn.Core.WriteModel.Project.Events;
using TestStack.BDDfy;
using Xunit;
public class CommandSpecs : ProjectCommandHandlerSpecs<Handler, Command>
{
private Guid _accountId;
private int _accountEventCount;
private Guid _projectId;
private int _projectEventCount;
private int _projectLastModifiedVersion;
private string _environment1Key;
private string _environment2Key;
private string _toggle1Key;
private string _toggle2Key;
public CommandSpecs()
{
IgnoreCollectionOrderDuringComparison = true;
_accountEventCount = 0;
_projectEventCount = 0;
_projectLastModifiedVersion = -1;
}
[Fact]
public void AlreadyDeleted()
{
this.Given(_ => GivenWeHaveRegisteredAnAccount())
.And(_ => GivenWeHaveCreatedAProject())
.And(_ => GivenWeHaveDeletedTheProject())
.When(_ => WhenWeDeleteTheProject())
.Then(_ => ThenNoEventIsPublished())
.And(_ => ThenAProjectDeletedExceptionIsThrownFor(_projectId))
.And(_ => ThenThereAreNoChangesOnTheAggregate())
.BDDfy();
}
[Fact]
public void StaleExpectedProjectVersion()
{
this.Given(_ => GivenWeHaveRegisteredAnAccount())
.And(_ => GivenWeHaveCreatedAProject())
.And(_ => GivenWeHaveAddedAToggle())
.And(_ => GivenWeHaveAddedAnotherToggle())
.And(_ => GivenWeHaveAddedTwoEnvironments())
.And(_ => GivenTheExpectedProjectVersionForOurNextCommandIsOffsetBy(-1))
.When(_ => WhenWeDeleteTheProject())
.Then(_ => ThenNoEventIsPublished())
.And(_ => ThenAConcurrencyExceptionIsThrown())
.And(_ => ThenThereAreNoChangesOnTheAggregate())
.BDDfy();
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void ProjectExistsWithTogglesAndEnvironments(int projectVersionOffset)
{
this.Given(_ => GivenWeHaveRegisteredAnAccount())
.And(_ => GivenWeHaveCreatedAProject())
.And(_ => GivenWeHaveAddedAToggle())
.And(_ => GivenWeHaveAddedAnotherToggle())
.And(_ => GivenWeHaveAddedTwoEnvironments())
.And(_ => GivenTheExpectedProjectVersionForOurNextCommandIsOffsetBy(projectVersionOffset))
.When(_ => WhenWeDeleteTheProject())
.Then(_ => ThenEightEventsArePublished())
.And(_ => ThenAProjectDeletedEventIsPublished())
.And(_ => ThenAnEnvironmentDeletedEventIsPublishedForEnvironment1())
.And(_ => ThenAnEnvironmentStateDeletedEventIsPublishedForEnvironment1())
.And(_ => ThenAnEnvironmentDeletedEventIsPublishedForEnvironment2())
.And(_ => ThenAnEnvironmentStateDeletedEventIsPublishedForEnvironment2())
.And(_ => ThenAToggleDeletedEventIsPublishedForToggle1())
.And(_ => ThenAToggleDeletedEventIsPublishedForToggle2())
.And(_ => ThenTheNumberOfChangesOnTheAggregateIs(14))
.And(_ => ThenTheAggregateRootIsMarkedAsDeleted())
.And(_ => ThenTheAggregateRootHasHadToggle1Removed())
.And(_ => ThenTheAggregateRootHasHadToggle2Removed())
.And(_ => ThenTheAggregateRootHasNoToggles())
.And(_ => ThenTheAggregateRootHasHadEnvironment1Removed())
.And(_ => ThenTheAggregateRootHasHadEnvironment2Removed())
.And(_ => ThenTheAggregateRootHasNoEnvironments())
.And(_ => ThenTheAggregateRootHasHadTheStatesForEnvironment1Removed())
.And(_ => ThenTheAggregateRootHasHadTheStatesForEnvironment2Removed())
.And(_ => ThenTheAggregateRootHasNoEnvironmentStates())
.And(_ => ThenTheAggregateRootLastModifiedVersionIs(NewAggregate.Version - 2))
.And(_ => ThenTheAggregateRootLastModifiedTimeHasBeenUpdated())
.And(_ => ThenTheAggregateRootLastModifiedByHasBeenUpdated())
.And(_ => ThenTheAggregateRootVersionHasBeenIncreasedBy(7))
.BDDfy();
}
protected override Handler BuildHandler()
{
return new Handler(Logger, Session);
}
private void GivenWeHaveRegisteredAnAccount()
{
_accountId = DataFixture.Create<Guid>();
HistoricalEvents.Add(new Core.WriteModel.Account.Events.AccountRegistered(UserId, _accountId, DateTimeOffset.UtcNow) { Version = _accountEventCount });
_accountEventCount++;
}
private void GivenWeHaveCreatedAProject()
{
_projectId = DataFixture.Create<Guid>();
HistoricalEvents.Add(new Core.WriteModel.Account.Events.ProjectCreated(UserId, _accountId, _projectId, DateTimeOffset.UtcNow) { Version = _accountEventCount });
_accountEventCount++;
GivenWeHaveCreatedAProjectWith(_projectId, _projectEventCount);
_projectEventCount++;
_projectLastModifiedVersion = _projectEventCount - 1;
}
private void GivenWeHaveDeletedTheProject()
{
HistoricalEvents.Add(new ProjectDeleted(UserId, _projectId, DateTimeOffset.UtcNow) { Version = _projectEventCount });
_projectEventCount++;
_projectLastModifiedVersion = _projectEventCount - 1;
}
private void GivenWeHaveAddedTwoEnvironments()
{
_environment1Key = DataFixture.Create<string>();
_environment2Key = DataFixture.Create<string>();
GivenWeHaveAddedAnEnvironmentWith(_projectId, _environment1Key, _projectEventCount);
_projectEventCount++;
_projectLastModifiedVersion = _projectEventCount - 1;
GivenWeHaveAddedAnEnvironmentStateWith(
_projectId,
_environment1Key,
_projectEventCount,
new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(_toggle1Key, default), new KeyValuePair<string, string>(_toggle2Key, default) });
_projectEventCount++;
GivenWeHaveAddedAnEnvironmentWith(_projectId, _environment2Key, _projectEventCount);
_projectEventCount++;
_projectLastModifiedVersion = _projectEventCount - 1;
GivenWeHaveAddedAnEnvironmentStateWith(
_projectId,
_environment2Key,
_projectEventCount,
new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(_toggle1Key, default), new KeyValuePair<string, string>(_toggle2Key, default) });
_projectEventCount++;
}
private void GivenWeHaveAddedAToggle()
{
_toggle1Key = DataFixture.Create<string>();
HistoricalEvents.Add(new ToggleAdded(UserId, _projectId, _toggle1Key, DataFixture.Create<string>(), DateTimeOffset.UtcNow) { Version = _projectEventCount });
_projectEventCount++;
_projectLastModifiedVersion = _projectEventCount - 1;
}
private void GivenWeHaveAddedAnotherToggle()
{
_toggle2Key = DataFixture.Create<string>();
HistoricalEvents.Add(new ToggleAdded(UserId, _projectId, _toggle2Key, DataFixture.Create<string>(), DateTimeOffset.UtcNow) { Version = _projectEventCount });
_projectEventCount++;
_projectLastModifiedVersion = _projectEventCount - 1;
}
private void GivenTheExpectedProjectVersionForOurNextCommandIsOffsetBy(int projectVersionOffset)
{
_projectLastModifiedVersion += projectVersionOffset;
}
private void WhenWeDeleteTheProject()
{
UserId = DataFixture.Create<string>();
var command = new Command(UserId, _accountId, _projectId, _projectLastModifiedVersion);
WhenWeHandle(command);
}
private void ThenAProjectDeletedEventIsPublished()
{
var ev = (ProjectDeleted)PublishedEvents.First(e => e.GetType() == typeof(ProjectDeleted));
ev.UserId.Should().Be(UserId);
ev.Id.Should().Be(_projectId);
ev.OccurredAt.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling);
}
private void ThenAnEnvironmentDeletedEventIsPublishedForEnvironment1()
{
ThenAnEnvironmentDeletedEventIsPublishedForEnvironment(_environment1Key);
}
private void ThenAnEnvironmentDeletedEventIsPublishedForEnvironment2()
{
ThenAnEnvironmentDeletedEventIsPublishedForEnvironment(_environment2Key);
}
private void ThenAnEnvironmentDeletedEventIsPublishedForEnvironment(string environmentKey)
{
var ev = (EnvironmentDeleted)PublishedEvents.First(e =>
e.GetType() == typeof(EnvironmentDeleted) &&
((EnvironmentDeleted)e).Key == environmentKey);
ev.UserId.Should().Be(UserId);
ev.Key.Should().Be(environmentKey);
ev.OccurredAt.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling);
}
private void ThenAnEnvironmentStateDeletedEventIsPublishedForEnvironment1()
{
ThenAnEnvironmentStateDeletedEventsIsPublishedForEnvironment(_environment1Key);
}
private void ThenAnEnvironmentStateDeletedEventIsPublishedForEnvironment2()
{
ThenAnEnvironmentStateDeletedEventsIsPublishedForEnvironment(_environment2Key);
}
private void ThenAnEnvironmentStateDeletedEventsIsPublishedForEnvironment(string environmentKey)
{
var ev = (EnvironmentStateDeleted)PublishedEvents.First(e =>
e.GetType() == typeof(EnvironmentStateDeleted) &&
((EnvironmentStateDeleted)e).EnvironmentKey == environmentKey);
ev.OccurredAt.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling);
ev.UserId.Should().Be(UserId);
}
private void ThenAToggleDeletedEventIsPublishedForToggle1()
{
ThenAToggleDeletedEventIsPublishedFor(_toggle1Key);
}
private void ThenAToggleDeletedEventIsPublishedForToggle2()
{
ThenAToggleDeletedEventIsPublishedFor(_toggle2Key);
}
private void ThenAToggleDeletedEventIsPublishedFor(string toggleKey)
{
var ev = (ToggleDeleted)PublishedEvents.First(e =>
e.GetType() == typeof(ToggleDeleted) &&
((ToggleDeleted)e).Key == toggleKey);
ev.UserId.Should().Be(UserId);
ev.OccurredAt.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling);
}
private void ThenTheAggregateRootIsMarkedAsDeleted()
{
NewAggregate.IsDeleted.Should().BeTrue();
}
private void ThenTheAggregateRootHasHadToggle1Removed()
{
NewAggregate.Toggles.Any(t => t.Key == _toggle1Key).Should().BeFalse();
}
private void ThenTheAggregateRootHasHadToggle2Removed()
{
NewAggregate.Toggles.Any(t => t.Key == _toggle2Key).Should().BeFalse();
}
private void ThenTheAggregateRootHasNoToggles()
{
NewAggregate.Toggles.Count().Should().Be(0);
}
private void ThenTheAggregateRootHasHadEnvironment1Removed()
{
NewAggregate.Environments.Any(t => t.Key == _environment1Key).Should().BeFalse();
}
private void ThenTheAggregateRootHasHadEnvironment2Removed()
{
NewAggregate.Environments.Any(t => t.Key == _environment2Key).Should().BeFalse();
}
private void ThenTheAggregateRootHasNoEnvironments()
{
NewAggregate.Environments.Count().Should().Be(0);
}
private void ThenTheAggregateRootHasHadTheStatesForEnvironment1Removed()
{
NewAggregate.EnvironmentStates.Any(t => t.EnvironmentKey == _environment1Key).Should().BeFalse();
}
private void ThenTheAggregateRootHasHadTheStatesForEnvironment2Removed()
{
NewAggregate.EnvironmentStates.Any(t => t.EnvironmentKey == _environment2Key).Should().BeFalse();
}
private void ThenTheAggregateRootHasNoEnvironmentStates()
{
NewAggregate.EnvironmentStates.Count().Should().Be(0);
}
}
}
| |
/*
*
* 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.Query;
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Test.Analysis;
using NUnit.Framework;
using Version=Lucene.Net.Util.Version;
namespace Lucene.Net.Analyzers.Query
{
[TestFixture]
public class QueryAutoStopWordAnalyzerTest : BaseTokenStreamTestCase
{
String[] variedFieldValues = { "the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "boring", "dog" };
String[] repetitiveFieldValues = { "boring", "boring", "vaguelyboring" };
RAMDirectory dir;
Analyzer appAnalyzer;
IndexReader reader;
QueryAutoStopWordAnalyzer protectedAnalyzer;
public override void SetUp()
{
dir = new RAMDirectory();
appAnalyzer = new WhitespaceAnalyzer();
IndexWriter writer = new IndexWriter(dir, appAnalyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
int numDocs = 200;
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
String variedFieldValue = variedFieldValues[i % variedFieldValues.Length];
String repetitiveFieldValue = repetitiveFieldValues[i % repetitiveFieldValues.Length];
doc.Add(new Field("variedField", variedFieldValue, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field("repetitiveField", repetitiveFieldValue, Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(doc);
}
writer.Close();
reader = IndexReader.Open(dir, true);
protectedAnalyzer = new QueryAutoStopWordAnalyzer(Version.LUCENE_CURRENT, appAnalyzer);
base.SetUp();
}
public override void TearDown()
{
reader.Close();
base.TearDown();
}
//Helper method to query
private int Search(Analyzer a, String queryString)
{
QueryParser qp = new QueryParser(Version.LUCENE_CURRENT, "repetitiveField", a);
var q = qp.Parse(queryString);
return new IndexSearcher(reader).Search(q, null, 1000).TotalHits;
}
[Test]
public void TestUninitializedAnalyzer()
{
//Note: no calls to "addStopWord"
String query = "variedField:quick repetitiveField:boring";
int numHits1 = Search(protectedAnalyzer, query);
int numHits2 = Search(appAnalyzer, query);
Assert.AreEqual(numHits1, numHits2, "No filtering test");
}
/*
* Test method for 'org.apache.lucene.analysis.QueryAutoStopWordAnalyzer.AddStopWords(IndexReader)'
*/
[Test]
public void TestDefaultAddStopWordsIndexReader()
{
protectedAnalyzer.AddStopWords(reader);
int numHits = Search(protectedAnalyzer, "repetitiveField:boring");
Assert.AreEqual(0, numHits, "Default filter should remove all docs");
}
/*
* Test method for 'org.apache.lucene.analysis.QueryAutoStopWordAnalyzer.AddStopWords(IndexReader, int)'
*/
[Test]
public void TestAddStopWordsIndexReaderInt()
{
protectedAnalyzer.AddStopWords(reader, 1f / 2f);
int numHits = Search(protectedAnalyzer, "repetitiveField:boring");
Assert.AreEqual(0, numHits, "A filter on terms in > one half of docs remove boring docs");
numHits = Search(protectedAnalyzer, "repetitiveField:vaguelyboring");
Assert.True(numHits > 1, "A filter on terms in > half of docs should not remove vaguelyBoring docs");
protectedAnalyzer.AddStopWords(reader, 1f / 4f);
numHits = Search(protectedAnalyzer, "repetitiveField:vaguelyboring");
Assert.AreEqual(0, numHits, "A filter on terms in > quarter of docs should remove vaguelyBoring docs");
}
[Test]
public void TestAddStopWordsIndexReaderStringFloat()
{
protectedAnalyzer.AddStopWords(reader, "variedField", 1f / 2f);
int numHits = Search(protectedAnalyzer, "repetitiveField:boring");
Assert.True(numHits > 0, "A filter on one Field should not affect queris on another");
protectedAnalyzer.AddStopWords(reader, "repetitiveField", 1f / 2f);
numHits = Search(protectedAnalyzer, "repetitiveField:boring");
Assert.AreEqual(numHits, 0, "A filter on the right Field should affect queries on it");
}
[Test]
public void TestAddStopWordsIndexReaderStringInt()
{
int numStopWords = protectedAnalyzer.AddStopWords(reader, "repetitiveField", 10);
Assert.True(numStopWords > 0, "Should have identified stop words");
Term[] t = protectedAnalyzer.GetStopWords();
Assert.AreEqual(t.Length, numStopWords, "num terms should = num stopwords returned");
int numNewStopWords = protectedAnalyzer.AddStopWords(reader, "variedField", 10);
Assert.True(numNewStopWords > 0, "Should have identified more stop words");
t = protectedAnalyzer.GetStopWords();
Assert.AreEqual(t.Length, numStopWords + numNewStopWords, "num terms should = num stopwords returned");
}
[Test]
public void TestNoFieldNamePollution()
{
protectedAnalyzer.AddStopWords(reader, "repetitiveField", 10);
int numHits = Search(protectedAnalyzer, "repetitiveField:boring");
Assert.AreEqual(0, numHits, "Check filter set up OK");
numHits = Search(protectedAnalyzer, "variedField:boring");
Assert.True(numHits > 0, "Filter should not prevent stopwords in one field being used in another ");
}
/*
* subclass that acts just like whitespace analyzer for testing
*/
private class QueryAutoStopWordSubclassAnalyzer : QueryAutoStopWordAnalyzer
{
public QueryAutoStopWordSubclassAnalyzer(Version matchVersion)
: base(matchVersion, new WhitespaceAnalyzer())
{
}
public override TokenStream TokenStream(String fieldName, TextReader reader)
{
return new WhitespaceTokenizer(reader);
}
}
[Test]
public void TestLucene1678BwComp()
{
QueryAutoStopWordAnalyzer a = new QueryAutoStopWordSubclassAnalyzer(Version.LUCENE_CURRENT);
a.AddStopWords(reader, "repetitiveField", 10);
int numHits = Search(a, "repetitiveField:boring");
Assert.False(numHits == 0);
}
/*
* analyzer that does not support reuse
* it is LetterTokenizer on odd invocations, WhitespaceTokenizer on even.
*/
private class NonreusableAnalyzer : Analyzer
{
int invocationCount = 0;
public override TokenStream TokenStream(String fieldName, TextReader reader)
{
if (++invocationCount % 2 == 0)
return new WhitespaceTokenizer(reader);
else
return new LetterTokenizer(reader);
}
}
[Test]
public void TestWrappingNonReusableAnalyzer()
{
QueryAutoStopWordAnalyzer a = new QueryAutoStopWordAnalyzer(Version.LUCENE_CURRENT, new NonreusableAnalyzer());
a.AddStopWords(reader, 10);
int numHits = Search(a, "repetitiveField:boring");
Assert.True(numHits == 0);
numHits = Search(a, "repetitiveField:vaguelyboring");
Assert.True(numHits == 0);
}
[Test]
public void TestTokenStream()
{
QueryAutoStopWordAnalyzer a = new QueryAutoStopWordAnalyzer(Version.LUCENE_CURRENT, new WhitespaceAnalyzer());
a.AddStopWords(reader, 10);
TokenStream ts = a.TokenStream("repetitiveField", new StringReader("this boring"));
ITermAttribute termAtt = ts.GetAttribute<ITermAttribute>();
Assert.True(ts.IncrementToken());
Assert.AreEqual("this", termAtt.Term);
Assert.False(ts.IncrementToken());
}
}
}
| |
using ColossalFramework;
using ColossalFramework.UI;
using ICities;
using UnityEngine;
using System;
namespace FavoriteCims
{
public class MyAtlas
{
public static UITextureAtlas FavCimsAtlas;
public void LoadAtlasIcons() {
string[] sPritesNames = {
"FavoriteCimsButton",
"FavoriteCimsButtonHovered",
"FavoriteCimsButtonPressed",
"FavoriteCimsButtonFocused",
"FavoriteCimsButtonDisabled",
"icon_fav_subscribed",
"icon_fav_unsubscribed",
"vehicleButton",
"vehicleButtonDisabled",
"vehicleButtonHovered",
"scrollbarthumb",
"scrollbartrack",
"bg_row1",
"bg_row2",
"touristIcon",
"driverIcon",
"passengerIcon",
"citizenbuttonenabled",
"citizenbuttondisabled",
"CommercialHigh",
"CommercialLow",
"homeIconHigh",
"homeIconLow",
"homelessIcon",
"houseofthedead",
"FavCimsCrimeArrested",
"FavCimsIconScooter",
"FavCimsPoliceVehicle",
"icon_citisenisgone",
"IndustrialIcon",
"nojob",
"OfficeIcon",
"workretired",
"workstudy",
"Car",
"CarDisabled",
"Dog",
"DogDisabled",
"Female",
"Male",
"BapartmentIcon",
"BcommercialIcon",
"BworkingIcon",
"greenArrowIcon",
"redArrowIcon",
"BuildingButtonIcon",
"BuildingButtonIconDisabled",
"BuildingButtonIconHovered",
"CommercialBuildingButtonIcon",
"CommercialBuildingButtonIconDisabled",
"CommercialBuildingButtonIconHovered",
"IndustrialBuildingButtonIcon",
"IndustrialBuildingButtonIconDisabled",
"IndustrialBuildingButtonIconHovered",
"focusIcon",
"focusIconFocused",
"focusIconDisabled"
};
string[] sPritesPath = {
"",
"",
"",
"",
"",
"",
"",
"VehiclePanel.",
"VehiclePanel.",
"VehiclePanel.",
"VehiclePanel.",
"VehiclePanel.",
"VehiclePanel.",
"VehiclePanel.",
"VehiclePanel.",
"VehiclePanel.",
"VehiclePanel.",
"UIMainPanel.",
"UIMainPanel.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.Rows.",
"UIMainPanel.BubblePanel.",
"UIMainPanel.BubblePanel.",
"UIMainPanel.BubblePanel.",
"UIMainPanel.BubblePanel.",
"UIMainPanel.BubblePanel.",
"UIMainPanel.BubblePanel.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels.",
"BuildingPanels."
};
FavCimsAtlas = CreateMyAtlas ("FavCimsAtlas", UIView.GetAView ().defaultAtlas.material, sPritesPath, sPritesNames);
}
UITextureAtlas CreateMyAtlas(string AtlasName, Material BaseMat, string[] sPritesPath, string[] sPritesNames){
var size = 1024;
Texture2D atlasTex = new Texture2D(size, size, TextureFormat.ARGB32, false);
Texture2D[] textures = new Texture2D[sPritesNames.Length];
Rect[] rects = new Rect[sPritesNames.Length];
for(int i = 0; i < sPritesNames.Length; i++)
{
textures[i] = ResourceLoader.loadTexture(0, 0, sPritesPath[i] + sPritesNames[i] + ".png");
}
rects = atlasTex.PackTextures(textures, 2, size);
UITextureAtlas atlas = ScriptableObject.CreateInstance<UITextureAtlas>();
Material material = Material.Instantiate(BaseMat);
material.mainTexture = atlasTex;
atlas.material = material;
atlas.name = AtlasName;
//atlas.padding = 0;
//atlas.hasMipmaps = false;
for (int i = 0; i < sPritesNames.Length; i++)
{
var spriteInfo = new UITextureAtlas.SpriteInfo()
{
name = sPritesNames[i],
texture = atlasTex,
region = rects[i]
};
atlas.AddSprite(spriteInfo);
}
return atlas;
}
}
public class TextureDB : Texture
{
//BubblePanel
public static Texture FavCimsOtherInfoTexture;
public static Texture BubbleHeaderIconSpriteTextureFemale;
public static Texture BubbleHeaderIconSpriteTextureMale;
public static Texture BubbleFamPortBgSpriteTexture;
public static Texture BubbleFamPortBgSpriteBackTexture;
public static Texture BubbleDetailsBgSprite;
public static Texture BubbleDetailsBgSpriteProblems;
public static Texture BubbleBgBar1;
public static Texture BubbleBgBar2;
public static Texture BubbleBgBar1Big;
public static Texture BubbleBgBar2Big;
public static Texture BubbleBgBar1Small;
public static Texture BubbleBgBar2Small;
public static Texture BubbleBg1Special;
public static Texture BubbleBg1Special2;
public static Texture BubbleBgBarHover;
public static Texture BubbleDog;
public static Texture BubbleDogDisabled;
public static Texture BubbleCar;
public static Texture BubbleCarDisabled;
public static Texture LittleStarGrey;
public static Texture LittleStarGold;
public static Texture VehiclePanelTitleBackground;
public static Texture VehiclePanelBackground;
public static Texture VehiclePanelFooterBackground;
//CitizenRow Textures//
//Row Separator Texture
public static Texture FavCimsSeparator;
//Happiness override texture
public static Texture FavCimsHappyOverride_texture;
//Citizen Name override texture
public static Texture FavCimsNameBgOverride_texture;
//Row Icons
public static Texture FavCimsCitizenHomeTexture;
public static Texture FavCimsCitizenHomeTextureHigh;
public static Texture FavCimsWorkingPlaceTexture;
public static Texture FavCimsCitizenHomeTextureDead;
public static Texture FavCimsCitizenHomeTextureHomeless;
public static Texture FavCimsWorkingPlaceTextureStudent;
public static Texture FavCimsWorkingPlaceTextureRetired;
public static Texture FavCimsCitizenCommercialLowTexture;
public static Texture FavCimsCitizenCommercialHighTexture;
public static Texture FavCimsCitizenIndustrialGenericTexture;
//public static Texture FavCimsWorkingPlaceTextureWorkerGeneric;
public static Texture FavCimsCitizenOfficeTexture;
//Building Level Icons
public static Texture[] FavCimsResidentialLevel = new Texture[6];
public static Texture[] FavCimsIndustrialLevel = new Texture[6];
public static Texture[] FavCimsCommercialLevel = new Texture[6];
public static Texture[] FavCimsOfficeLevel = new Texture[6];
public static void LoadFavCimsTextures () {
try { //Building Level Icons
FavCimsResidentialLevel[0] = null;
for(int i = 1; i <= 5; i++) {
FavCimsResidentialLevel[i] = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.levels.ResidentialLevel" + i.ToString() + ".png");
FavCimsResidentialLevel[i].wrapMode = TextureWrapMode.Clamp;
FavCimsResidentialLevel[i].filterMode = FilterMode.Bilinear;
FavCimsResidentialLevel[i].mipMapBias = -0.5f;
FavCimsResidentialLevel[i].name = "FavCimsResidentialLevel" + i;
FavCimsIndustrialLevel[i] = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.levels.IndustrialLevel" + i.ToString() + ".png");
FavCimsIndustrialLevel[i].wrapMode = TextureWrapMode.Clamp;
FavCimsIndustrialLevel[i].filterMode = FilterMode.Bilinear;
FavCimsIndustrialLevel[i].mipMapBias = -0.5f;
FavCimsIndustrialLevel[i].name = "FavCimsIndustrialLevel" + i;
FavCimsCommercialLevel[i] = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.levels.CommercialLevel" + i.ToString() + ".png");
FavCimsCommercialLevel[i].wrapMode = TextureWrapMode.Clamp;
FavCimsCommercialLevel[i].filterMode = FilterMode.Bilinear;
FavCimsCommercialLevel[i].mipMapBias = -0.5f;
FavCimsCommercialLevel[i].name = "FavCimsCommercialLevel" + i;
FavCimsOfficeLevel[i] = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.levels.OfficeLevel" + i.ToString() + ".png");
FavCimsOfficeLevel[i].wrapMode = TextureWrapMode.Clamp;
FavCimsOfficeLevel[i].filterMode = FilterMode.Bilinear;
FavCimsOfficeLevel[i].mipMapBias = -0.5f;
FavCimsOfficeLevel[i].name = "FavCimsOfficeLevel" + i;
}
}catch(Exception e) {
Debug.Error("Can't load level icons : " + e.ToString());
}
try { //Citizen row list textures
//Icon Separator_texture
FavCimsSeparator = ResourceLoader.loadTexture (1, 40, "UIMainPanel.Rows.col_separator.png");
FavCimsSeparator.wrapMode = TextureWrapMode.Clamp;
FavCimsSeparator.filterMode = FilterMode.Bilinear;
FavCimsSeparator.name = "FavCimsSeparator";
//Happiness Override Texture
FavCimsHappyOverride_texture = ResourceLoader.loadTexture (30, 30, "UIMainPanel.Rows.icon_citisenisgone.png");
FavCimsHappyOverride_texture.wrapMode = TextureWrapMode.Clamp;
FavCimsHappyOverride_texture.filterMode = FilterMode.Bilinear;
FavCimsHappyOverride_texture.name = "FavCimsHappyOverride_texture";
FavCimsHappyOverride_texture.mipMapBias = -0.5f;
//Citizen Name Override Texture
FavCimsNameBgOverride_texture = ResourceLoader.loadTexture (180, 40, "UIMainPanel.submenubar.png");
FavCimsNameBgOverride_texture.wrapMode = TextureWrapMode.Clamp;
FavCimsNameBgOverride_texture.filterMode = FilterMode.Bilinear;
FavCimsNameBgOverride_texture.name = "FavCimsNameOverride_texture";
FavCimsNameBgOverride_texture.mipMapBias = -0.5f;
//Row Icons texture
//Home
FavCimsCitizenHomeTexture = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.homeIconLow.png");
FavCimsCitizenHomeTexture.wrapMode = TextureWrapMode.Clamp;
FavCimsCitizenHomeTexture.filterMode = FilterMode.Bilinear;
FavCimsCitizenHomeTexture.mipMapBias = -0.5f;
FavCimsCitizenHomeTexture.name = "FavCimsCitizenHomeTexture";
FavCimsCitizenHomeTextureHigh = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.homeIconHigh.png");
FavCimsCitizenHomeTextureHigh.wrapMode = TextureWrapMode.Clamp;
FavCimsCitizenHomeTextureHigh.filterMode = FilterMode.Bilinear;
FavCimsCitizenHomeTextureHigh.mipMapBias = -0.5f;
FavCimsCitizenHomeTextureHigh.name = "FavCimsCitizenHomeTexture";
FavCimsCitizenHomeTextureDead = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.houseofthedead.png");
FavCimsCitizenHomeTextureDead.wrapMode = TextureWrapMode.Clamp;
FavCimsCitizenHomeTextureDead.filterMode = FilterMode.Bilinear;
FavCimsCitizenHomeTextureDead.mipMapBias = -0.5f;
FavCimsCitizenHomeTextureDead.name = "FavCimsCitizenHomeTextureDead";
FavCimsCitizenHomeTextureHomeless = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.homelessIcon.png");
FavCimsCitizenHomeTextureHomeless.wrapMode = TextureWrapMode.Clamp;
FavCimsCitizenHomeTextureHomeless.filterMode = FilterMode.Bilinear;
FavCimsCitizenHomeTextureHomeless.mipMapBias = -0.5f;
FavCimsCitizenHomeTextureHomeless.name = "FavCimsCitizenHomeTextureHomeless";
//Work
FavCimsWorkingPlaceTexture = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.nojob.png");
//FavCimsWorkingPlaceTextureWorkerGeneric = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.workIndustry.png");
FavCimsWorkingPlaceTextureStudent = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.workstudy.png");
FavCimsWorkingPlaceTextureRetired = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.workretired.png");
FavCimsCitizenCommercialLowTexture = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.CommercialLow.png");
FavCimsCitizenCommercialHighTexture = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.CommercialHigh.png");
FavCimsCitizenIndustrialGenericTexture = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.IndustrialIcon.png");
FavCimsCitizenOfficeTexture = ResourceLoader.loadTexture (20, 40, "UIMainPanel.Rows.OfficeIcon.png");
FavCimsWorkingPlaceTexture.wrapMode = TextureWrapMode.Clamp;
FavCimsWorkingPlaceTextureStudent.wrapMode = TextureWrapMode.Clamp;
FavCimsWorkingPlaceTextureRetired.wrapMode = TextureWrapMode.Clamp;
FavCimsWorkingPlaceTexture.filterMode = FilterMode.Bilinear;
FavCimsCitizenCommercialLowTexture.wrapMode = TextureWrapMode.Clamp;
FavCimsCitizenCommercialHighTexture.wrapMode = TextureWrapMode.Clamp;
FavCimsCitizenIndustrialGenericTexture.wrapMode = TextureWrapMode.Clamp;
FavCimsCitizenOfficeTexture.wrapMode = TextureWrapMode.Clamp;
FavCimsWorkingPlaceTextureStudent.filterMode = FilterMode.Bilinear;
FavCimsWorkingPlaceTextureRetired.filterMode = FilterMode.Bilinear;
FavCimsCitizenCommercialLowTexture.filterMode = FilterMode.Bilinear;
FavCimsCitizenCommercialHighTexture.filterMode = FilterMode.Bilinear;
FavCimsCitizenIndustrialGenericTexture.filterMode = FilterMode.Bilinear;
FavCimsCitizenOfficeTexture.filterMode = FilterMode.Bilinear;
FavCimsWorkingPlaceTextureStudent.mipMapBias = -0.5f;
FavCimsWorkingPlaceTextureRetired.mipMapBias = -0.5f;
FavCimsCitizenCommercialLowTexture.mipMapBias = -0.5f;
FavCimsCitizenCommercialHighTexture.mipMapBias = -0.5f;
FavCimsCitizenIndustrialGenericTexture.mipMapBias = -0.5f;
FavCimsCitizenOfficeTexture.mipMapBias = -0.5f;
FavCimsWorkingPlaceTexture.name = "FavCimsWorkingPlaceTexture";
//FavCimsWorkingPlaceTextureWorkerGeneric.name = "FavCimsWorkingPlaceTextureWorker";
FavCimsWorkingPlaceTextureStudent.name = "FavCimsWorkingPlaceTextureStudent";
FavCimsWorkingPlaceTextureRetired.name = "FavCimsWorkingPlaceTextureRetired";
FavCimsCitizenCommercialLowTexture.name = "FavCimsCitizenCommercialLowTexture";
FavCimsCitizenCommercialHighTexture.name = "FavCimsCitizenCommercialHighTexture";
FavCimsCitizenIndustrialGenericTexture.name = "FavCimsCitizenIndustrialHighTexture";
FavCimsCitizenOfficeTexture.name = "FavCimsCitizenOfficeTexture";
//BubblePanel
BubbleHeaderIconSpriteTextureFemale = ResourceLoader.loadTexture (28, 26, "UIMainPanel.BubblePanel.Female.png");
BubbleHeaderIconSpriteTextureFemale.wrapMode = TextureWrapMode.Clamp;
BubbleHeaderIconSpriteTextureFemale.filterMode = FilterMode.Bilinear;
BubbleHeaderIconSpriteTextureFemale.mipMapBias = -0.5f;
BubbleHeaderIconSpriteTextureFemale.name = "BubbleHeaderIconSpriteTextureFemale";
BubbleHeaderIconSpriteTextureMale = ResourceLoader.loadTexture (28, 26, "UIMainPanel.BubblePanel.Male.png");
BubbleHeaderIconSpriteTextureMale.wrapMode = TextureWrapMode.Clamp;
BubbleHeaderIconSpriteTextureMale.filterMode = FilterMode.Bilinear;
BubbleHeaderIconSpriteTextureMale.mipMapBias = -0.5f;
BubbleHeaderIconSpriteTextureMale.name = "BubbleHeaderIconSpriteTextureFemale";
BubbleFamPortBgSpriteTexture = ResourceLoader.loadTexture (238, 151, "UIMainPanel.BubblePanel.camBg.png");
BubbleFamPortBgSpriteTexture.wrapMode = TextureWrapMode.Clamp;
BubbleFamPortBgSpriteTexture.filterMode = FilterMode.Bilinear;
BubbleFamPortBgSpriteTexture.name = "BubbleCamBgSpriteTexture";
BubbleFamPortBgSpriteBackTexture = ResourceLoader.loadTexture (234, 147, "UIMainPanel.BubblePanel.backgroundBack.jpg");
BubbleFamPortBgSpriteBackTexture.wrapMode = TextureWrapMode.Clamp;
BubbleFamPortBgSpriteBackTexture.filterMode = FilterMode.Bilinear;
BubbleFamPortBgSpriteBackTexture.name = "BubbleCamBgSpriteBackTexture";
BubbleDetailsBgSprite = ResourceLoader.loadTexture (238, 151, "UIMainPanel.BubblePanel.BubbleDetailsBgSprite.png");
BubbleDetailsBgSprite.wrapMode = TextureWrapMode.Clamp;
BubbleDetailsBgSprite.filterMode = FilterMode.Bilinear;
BubbleDetailsBgSprite.name = "BubbleDetailsBgSprite";
BubbleDetailsBgSpriteProblems = ResourceLoader.loadTexture (238, 151, "UIMainPanel.BubblePanel.BubbleDetailsBgSpriteProblems.png");
BubbleDetailsBgSpriteProblems.wrapMode = TextureWrapMode.Clamp;
BubbleDetailsBgSpriteProblems.filterMode = FilterMode.Bilinear;
BubbleDetailsBgSpriteProblems.name = "BubbleDetailsBgSpriteProblems";
BubbleBgBar1 = ResourceLoader.loadTexture (236, 26, "UIMainPanel.BubblePanel.BubbleBg1.png");
BubbleBgBar1.name = "BubbleBgBar1";
BubbleBgBar1.wrapMode = TextureWrapMode.Clamp;
BubbleBgBar1.filterMode = FilterMode.Bilinear;
BubbleBgBar1.mipMapBias = -0.5f;
BubbleBgBar2 = ResourceLoader.loadTexture (236, 26, "UIMainPanel.BubblePanel.BubbleBg2.png");
BubbleBgBar2.name = "BubbleBgBar1";
BubbleBgBar2.wrapMode = TextureWrapMode.Clamp;
BubbleBgBar2.filterMode = FilterMode.Bilinear;
BubbleBgBar2.mipMapBias = -0.5f;
BubbleBgBar1Big = ResourceLoader.loadTexture (198, 40, "UIMainPanel.BubblePanel.BubbleBg1Big.png");
BubbleBgBar1Big.wrapMode = TextureWrapMode.Clamp;
BubbleBgBar1Big.filterMode = FilterMode.Bilinear;
BubbleBgBar1Big.name = "BubbleBgBar1Big";
BubbleBgBar1Small = ResourceLoader.loadTexture (198, 15, "UIMainPanel.BubblePanel.BubbleBg1Small.png");
BubbleBgBar1Small.name = "BubbleBgBar1Small";
BubbleBgBar1Small.wrapMode = TextureWrapMode.Clamp;
BubbleBgBar1Small.filterMode = FilterMode.Bilinear;
BubbleBgBar2Small = ResourceLoader.loadTexture (198, 15, "UIMainPanel.BubblePanel.BubbleBg2Small.png");
BubbleBgBar2Small.name = "BubbleBgBar1Small";
BubbleBgBar2Small.wrapMode = TextureWrapMode.Clamp;
BubbleBgBar2Small.filterMode = FilterMode.Bilinear;
BubbleBg1Special = ResourceLoader.loadTexture (236, 26, "UIMainPanel.BubblePanel.BubbleBg1Special.png");
BubbleBg1Special.wrapMode = TextureWrapMode.Clamp;
BubbleBg1Special.filterMode = FilterMode.Bilinear;
BubbleBg1Special.name = "BubbleBg1Special";
BubbleBg1Special2 = ResourceLoader.loadTexture (236, 26, "UIMainPanel.BubblePanel.BubbleBg1Special2.png");
BubbleBg1Special2.wrapMode = TextureWrapMode.Clamp;
BubbleBg1Special2.filterMode = FilterMode.Bilinear;
BubbleBg1Special2.name = "BubbleBg1Special2";
BubbleBgBarHover = ResourceLoader.loadTexture (236, 20, "UIMainPanel.BubblePanel.BubbleBgHeader.png");
BubbleBgBarHover.name = "BubbleBgBar1";
BubbleBgBarHover.wrapMode = TextureWrapMode.Clamp;
BubbleBgBarHover.filterMode = FilterMode.Bilinear;
BubbleDog = ResourceLoader.loadTexture (14, 20, "UIMainPanel.BubblePanel.Dog.png");
BubbleDog.name = "BubbleDog";
BubbleDog.wrapMode = TextureWrapMode.Clamp;
BubbleDog.filterMode = FilterMode.Bilinear;
BubbleDog.mipMapBias = -0.5f;
BubbleDogDisabled = ResourceLoader.loadTexture (14, 20, "UIMainPanel.BubblePanel.DogDisabled.png");
BubbleDogDisabled.name = "BubbleDogDisabled";
BubbleDogDisabled.wrapMode = TextureWrapMode.Clamp;
BubbleDogDisabled.filterMode = FilterMode.Bilinear;
BubbleDogDisabled.mipMapBias = -0.5f;
BubbleCar = ResourceLoader.loadTexture (31, 20, "UIMainPanel.BubblePanel.Car.png");
BubbleCar.name = "BubbleCar";
BubbleCar.wrapMode = TextureWrapMode.Clamp;
BubbleCar.filterMode = FilterMode.Bilinear;
BubbleCar.mipMapBias = -0.5f;
BubbleCarDisabled = ResourceLoader.loadTexture (31, 20, "UIMainPanel.BubblePanel.CarDisabled.png");
BubbleCarDisabled.name = "BubbleCarDisabled";
BubbleCarDisabled.wrapMode = TextureWrapMode.Clamp;
BubbleCarDisabled.filterMode = FilterMode.Bilinear;
BubbleCarDisabled.mipMapBias = -0.5f;
LittleStarGrey = ResourceLoader.loadTexture (20, 20, "UIMainPanel.BubblePanel.LittleStarGrey.png");
LittleStarGrey.name = "LittleStarGrey";
LittleStarGrey.wrapMode = TextureWrapMode.Clamp;
LittleStarGrey.filterMode = FilterMode.Bilinear;
LittleStarGrey.mipMapBias = -0.5f;
LittleStarGold = ResourceLoader.loadTexture (20, 20, "UIMainPanel.BubblePanel.LittleStarGold.png");
LittleStarGold.name = "LittleStarGold";
LittleStarGold.wrapMode = TextureWrapMode.Clamp;
LittleStarGold.filterMode = FilterMode.Bilinear;
LittleStarGold.mipMapBias = -0.5f;
FavCimsOtherInfoTexture = ResourceLoader.loadTexture (250, 500, "UIMainPanel.panel_middle.png");
FavCimsOtherInfoTexture.wrapMode = TextureWrapMode.Clamp;
FavCimsOtherInfoTexture.filterMode = FilterMode.Bilinear;
FavCimsOtherInfoTexture.name = "FavCimsOtherInfoTexture";
VehiclePanelTitleBackground = ResourceLoader.loadTexture (250, 41, "VehiclePanel.VehiclePanelTitleBg.png");
VehiclePanelTitleBackground.wrapMode = TextureWrapMode.Clamp;
VehiclePanelTitleBackground.filterMode = FilterMode.Bilinear;
VehiclePanelTitleBackground.name = "VehiclePanelTitleBackground";
VehiclePanelBackground = ResourceLoader.loadTexture (250, 1, "VehiclePanel.VehiclePanelBg.png");
VehiclePanelBackground.wrapMode = TextureWrapMode.Repeat;
VehiclePanelBackground.filterMode = FilterMode.Point;
VehiclePanelBackground.name = "VehiclePanelBackground";
VehiclePanelFooterBackground = ResourceLoader.loadTexture (250, 12, "VehiclePanel.VehiclePanelBottomBg.png");
VehiclePanelFooterBackground.wrapMode = TextureWrapMode.Clamp;
VehiclePanelFooterBackground.filterMode = FilterMode.Bilinear;
VehiclePanelFooterBackground.name = "VehiclePanelFooterBackground";
}catch(Exception e) {
Debug.Error("Can't load row icons : " + e.ToString());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using CK.CodeGen;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Linq;
namespace CK.CodeGen
{
sealed class NamespaceScopeImpl : TypeDefinerScopeImpl, INamespaceScope
{
readonly static Regex _nsName = new Regex( @"^\s*(?<1>\w+)(\s*\.\s*(?<1>\w+))*\s*$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture );
readonly Dictionary<string, KeyValuePair<string?, string?>> _usings;
readonly List<NamespaceScopeImpl> _subNamespaces;
readonly CodePartRaw _beforeNamespace;
internal NamespaceScopeImpl( CodeWorkspaceImpl ws, INamespaceScope? parent, string name )
: base( ws, parent )
{
Debug.Assert( (parent == null) == (name.Length == 0) );
Debug.Assert( parent == null || parent is NamespaceScopeImpl );
_usings = new Dictionary<string, KeyValuePair<string?, string?>>();
_subNamespaces = new List<NamespaceScopeImpl>();
_beforeNamespace = new CodePartRaw();
if( parent != null ) SetName( name );
}
internal void MergeWith( NamespaceScopeImpl other )
{
Debug.Assert( other != null );
_beforeNamespace.MergeWith( other._beforeNamespace );
foreach( var u in other._usings )
{
DoEnsureUsing( u.Key, u.Value.Key, u.Value.Value );
}
CodePart.MergeWith( other.CodePart );
MergeTypes( other );
foreach( var oNS in other._subNamespaces )
{
var my = _subNamespaces.FirstOrDefault( x => x.Name == oNS.Name );
if( my == null )
{
my = new NamespaceScopeImpl( Workspace, this, oNS.Name );
_subNamespaces.Add( my );
}
my.MergeWith( oNS );
}
}
INamespaceScope? INamespaceScope.Parent => Parent;
internal new NamespaceScopeImpl? Parent => (NamespaceScopeImpl?)base.Parent;
public ICodePart BeforeNamespace => _beforeNamespace;
public INamespaceScope EnsureUsing( string ns )
{
if( !String.IsNullOrWhiteSpace( ns ) )
{
int assignIdx = ns.IndexOf( '=', StringComparison.Ordinal );
if( assignIdx != 0 )
{
if( assignIdx > 0 )
{
var def = ns.Substring( assignIdx + 1 );
ns = CheckAndNormalizeOneName( ns.Substring( 0, assignIdx ) );
return DoEnsureUsing( ns, def );
}
return DoEnsureUsing( CheckAndNormalizeNamespace( ns ), null );
}
}
throw new ArgumentException( $"'using {ns}' is invalid.", nameof( ns ) );
}
public INamespaceScope EnsureUsingAlias( string alias, string definition )
{
if( String.IsNullOrWhiteSpace( definition ) ) throw new ArgumentException( $"'{definition}' is not a valid alias definition.", nameof( definition ) );
return DoEnsureUsing( CheckAndNormalizeOneName( alias ), definition );
}
INamespaceScope DoEnsureUsing( string alias, string? definition )
{
Debug.Assert( (definition == null && CheckAndNormalizeNamespace( alias ) == alias)
|| (definition != null && CheckAndNormalizeOneName( alias ) == alias) );
var keyDef = definition;
if( keyDef != null )
{
Debug.Assert( definition != null, "Obviously..." );
// We must normalize the trailing ;.
definition = definition.Trim();
if( definition.Length == 0 || definition == ";" ) throw new ArgumentException( $"'{definition}' is not a valid alias definition.", nameof( definition ) );
if( definition[definition.Length - 1] != ',' ) definition += ';';
keyDef = RemoveWhiteSpaces( definition );
}
return DoEnsureUsing( alias, keyDef, definition );
}
INamespaceScope DoEnsureUsing( string alias, string? keyDef, string? definition )
{
Debug.Assert( alias != null );
Debug.Assert( (keyDef == null) == (definition == null) );
if( _usings.TryGetValue( alias, out var defs ) )
{
if( defs.Key == keyDef ) return this;
string existing = defs.Value != null ? " = " + defs.Value : ";";
string newOne = definition != null ? " = " + definition : ";";
throw new ArgumentException( $"using {alias}{newOne} is already defined in this scope as: {alias}{existing}." );
}
NamespaceScopeImpl? scope = this;
while( (scope = scope.Parent) != null )
{
if( scope._usings.TryGetValue( alias, out defs ) && defs.Key == keyDef ) return this;
}
_usings.Add( alias, new KeyValuePair<string?, string?>( keyDef, definition ) );
return this;
}
static public string[] CheckAndGetNamespaceParts( string ns )
{
if( ns == null ) throw new ArgumentNullException( ns );
var m = _nsName.Match( ns );
if( !m.Success ) throw new ArgumentException( $"Invalid namespace: {ns}" );
var captures = m.Groups[1].Captures;
var result = new string[captures.Count];
for( int i = 0; i < result.Length; ++i ) result[i] = captures[i].Value;
return result;
}
static string CheckAndNormalizeNamespace( string ns )
{
return String.Join( ".", CheckAndGetNamespaceParts( ns ) );
}
static public string CheckAndNormalizeOneName( string ns )
{
var n = CheckAndGetNamespaceParts( ns );
if( n.Length != 1 ) throw new ArgumentException( $"Only one identifier is expected: {ns}." );
return n[0];
}
public INamespaceScope FindOrCreateNamespace( string ns )
{
string[] names = CheckAndGetNamespaceParts( ns );
return DoFindOrCreateNamespace( names, 0 );
}
INamespaceScope DoFindOrCreateNamespace( string[] names, int idx )
{
var exist = _subNamespaces.FirstOrDefault( x => x.Name == names[idx] );
if( exist == null )
{
exist = new NamespaceScopeImpl( Workspace, this, names[idx] );
_subNamespaces.Add( exist );
Workspace.OnNamespaceCreated( exist );
}
return names.Length == ++idx ? exist : exist.DoFindOrCreateNamespace( names, idx );
}
public IReadOnlyCollection<INamespaceScope> Namespaces => _subNamespaces;
internal protected override SmarterStringBuilder Build( SmarterStringBuilder b, bool closeScope )
{
_beforeNamespace.Build( b );
// A global using prevent any attribute definition (and [assembly::...] attributes cannot be defined
// in a namespace.
// We write the global usings in the TOP namespaces: they are duplicated among the top-level namespaces
// but this enables to define attributes at the top of one file.
if( Workspace.Global != this )
{
b.Append( "namespace " )
.Append( Name )
.AppendLine()
.Append( "{" )
.AppendLine();
if( Parent == Workspace.Global )
{
Parent.WriteThisUsings( b );
}
WriteThisUsings( b );
}
else if( _subNamespaces.Count == 0 )
{
// However, if there is no namespace defined, the global
// usings must be written. We have no choice.
WriteThisUsings( b );
}
CodePart.Build( b );
foreach( var ns in _subNamespaces )
{
ns.Build( b, true );
}
BuildTypes( b );
if( Workspace.Global != this && closeScope ) b.AppendLine().Append( "}" );
return b;
}
private void WriteThisUsings( SmarterStringBuilder b )
{
foreach( var e in _usings )
{
b.AppendLine().Append( "using " ).Append( e.Key );
if( e.Value.Value == null ) b.Append( ";" );
else b.Append( " = " ).Append( e.Value.Value );
b.AppendLine();
}
}
public INamespaceScopePart CreatePart( bool top )
{
var p = new Part( this );
if( top ) CodePart.Parts.Insert( 0, p );
else CodePart.Parts.Add( p );
return p;
}
class Part : TypeDefinerPart, INamespaceScopePart
{
public Part( INamespaceScope owner )
: base( owner )
{
}
public new INamespaceScope PartOwner => (INamespaceScope)base.PartOwner;
public INamespaceScope? Parent => PartOwner.Parent;
public IReadOnlyCollection<INamespaceScope> Namespaces => PartOwner.Namespaces;
public ICodePart BeforeNamespace => PartOwner.BeforeNamespace;
public INamespaceScopePart CreatePart( bool top )
{
var p = new Part( this );
if( top ) Parts.Insert( 0, p );
else Parts.Add( p );
return p;
}
public INamespaceScope EnsureUsing( string ns ) => PartOwner.EnsureUsing( ns );
public INamespaceScope EnsureUsingAlias( string alias, string definition ) => PartOwner.EnsureUsingAlias( alias, definition );
public INamespaceScope FindOrCreateNamespace( string ns ) => PartOwner.FindOrCreateNamespace( ns );
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class AverageTests
{
//
// Average
//
// Get a set of ranges from 0 to each count, with an extra parameter containing the expected average.
public static IEnumerable<object[]> AverageData(int[] counts)
{
foreach (int count in counts)
{
yield return new object[] { count, (count - 1) / 2.0 };
}
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Int(int count, double average)
{
Assert.Equal(average, UnorderedSources.Default(count).Average());
Assert.Equal((double?)average, UnorderedSources.Default(count).Select(x => (int?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -x));
Assert.Equal(-(double?)average, UnorderedSources.Default(count).Average(x => -(int?)x));
}
[Fact]
[OuterLoop]
public static void Average_Int_Longrunning()
{
Average_Int(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Int_SomeNull(int count, double average)
{
Assert.Equal(Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (int?)x : null).Average());
Assert.Equal(Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(int?)x : null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Average_Int_AllNull(int count)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (int?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (int?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Long(int count, double average)
{
Assert.Equal(average, UnorderedSources.Default(count).Select(x => (long)x).Average());
Assert.Equal((double?)average, UnorderedSources.Default(count).Select(x => (long?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -(long)x));
Assert.Equal(-(double?)average, UnorderedSources.Default(count).Average(x => -(long?)x));
}
[Fact]
[OuterLoop]
public static void Average_Long_Longrunning()
{
Average_Long(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0);
}
[Fact]
public static void Average_Long_Overflow()
{
AssertThrows.Wrapped<OverflowException>(() => UnorderedSources.Default(2).Select(x => x == 0 ? 1 : long.MaxValue).Average());
AssertThrows.Wrapped<OverflowException>(() => UnorderedSources.Default(2).Select(x => x == 0 ? (long?)1 : long.MaxValue).Average());
AssertThrows.Wrapped<OverflowException>(() => UnorderedSources.Default(2).Average(x => x == 0 ? -1 : long.MinValue));
AssertThrows.Wrapped<OverflowException>(() => UnorderedSources.Default(2).Average(x => x == 0 ? (long?)-1 : long.MinValue));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Long_SomeNull(int count, double average)
{
Assert.Equal(Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (long?)x : null).Average());
Assert.Equal(Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(long?)x : null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Average_Long_AllNull(int count)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (long?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (long?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Float(int count, float average)
{
Assert.Equal(average, UnorderedSources.Default(count).Select(x => (float)x).Average());
Assert.Equal((float?)average, UnorderedSources.Default(count).Select(x => (float?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -(float)x));
Assert.Equal(-(float?)average, UnorderedSources.Default(count).Average(x => -(float?)x));
}
[Fact]
[OuterLoop]
public static void Average_Float_Longrunning()
{
Average_Float(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0F);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Float_SomeNull(int count, float average)
{
Assert.Equal((float?)Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (float?)x : null).Average());
Assert.Equal((float?)Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(float?)x : null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Average_Float_AllNull(int count)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (float?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (float?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Double(int count, double average)
{
Assert.Equal(average, UnorderedSources.Default(count).Select(x => (double)x).Average());
Assert.Equal((double?)average, UnorderedSources.Default(count).Select(x => (double?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -(double)x));
Assert.Equal(-(double?)average, UnorderedSources.Default(count).Average(x => -(double?)x));
}
[Fact]
[OuterLoop]
public static void Average_Double_Longrunning()
{
Average_Double(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Double_SomeNull(int count, double average)
{
Assert.Equal(Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (double?)x : null).Average());
Assert.Equal(Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(double?)x : null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Average_Double_AllNull(int count)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (double?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (double?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Decimal(int count, decimal average)
{
Assert.Equal(average, UnorderedSources.Default(count).Select(x => (decimal)x).Average());
Assert.Equal((decimal?)average, UnorderedSources.Default(count).Select(x => (decimal?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -(decimal)x));
Assert.Equal(-(decimal?)average, UnorderedSources.Default(count).Average(x => -(decimal?)x));
}
[Fact]
[OuterLoop]
public static void Average_Decimal_Longrunning()
{
Average_Decimal(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0M);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Decimal_SomeNull(int count, decimal average)
{
Assert.Equal(Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (decimal?)x : null).Average());
Assert.Equal(Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(decimal?)x : null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Average_Decimal_AllNull(int count)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (decimal?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (decimal?)null));
}
[Fact]
public static void Average_InvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average(x => x));
// Nullables return null when empty
Assert.Null(ParallelEnumerable.Empty<int?>().Average());
Assert.Null(ParallelEnumerable.Empty<int?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<long?>().Average());
Assert.Null(ParallelEnumerable.Empty<long?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<float?>().Average());
Assert.Null(ParallelEnumerable.Empty<float?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<double?>().Average());
Assert.Null(ParallelEnumerable.Empty<double?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<decimal?>().Average());
Assert.Null(ParallelEnumerable.Empty<decimal?>().Average(x => x));
}
[Fact]
public static void Average_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (int?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (long)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (long?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (float)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (float?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (double)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (double?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal?)x; }));
}
[Fact]
public static void Average_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (int?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (long)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (long?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (float)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (float?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (double)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (double?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (int?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (long)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (long?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (float)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (float?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (double)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (double?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal?)x; }));
}
[Fact]
public static void Average_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.Average(x => x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (int?)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (long)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (long?)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (float)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (float?)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (double)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (double?)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (decimal)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (decimal?)x));
}
[Fact]
public static void Average_AggregateException()
{
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, int>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, int?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, long>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, long?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, float>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, float?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, double>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, double?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, decimal>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, decimal?>)(x => { throw new DeliberateTestException(); })));
}
[Fact]
public static void Average_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat(0, 1).Average((Func<int, int>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((int?)0, 1).Average((Func<int?, int?>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<long>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((long)0, 1).Average((Func<long, long>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<long?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((long?)0, 1).Average((Func<long?, long?>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<float>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((float)0, 1).Average((Func<float, float>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<float?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((float?)0, 1).Average((Func<float?, float?>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<double>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((double)0, 1).Average((Func<double, double>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<double?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((double?)0, 1).Average((Func<double?, double?>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<decimal>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((decimal)0, 1).Average((Func<decimal, decimal>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<decimal?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((decimal?)0, 1).Average((Func<decimal?, decimal?>)null));
}
}
}
| |
// Copyright 2008-2011. This work is licensed under the BSD license, available at
// http://www.movesinstitute.org/licenses
//
// Orignal authors: DMcG, Jason Nelson
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace OpenDis.Enumerations.Environment.ObjectState
{
/// <summary>
/// Enumeration values for ExhaustSmoke (env.obj.appear.linear.exhaust, Exhaust smoke,
/// section 12.1.2.3.2)
/// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was
/// obtained from http://discussions.sisostds.org/default.asp?action=10&fd=31
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Serializable]
public struct ExhaustSmoke
{
/// <summary>
/// Describes whether the smoke is attached to the vehicle
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Describes whether the smoke is attached to the vehicle")]
public enum AttachedValue : uint
{
/// <summary>
/// Not attached
/// </summary>
NotAttached = 0,
/// <summary>
/// Attached
/// </summary>
Attached = 1
}
/// <summary>
/// Describes the chemical content of the smoke
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")]
[Description("Describes the chemical content of the smoke")]
public enum ChemicalValue : uint
{
/// <summary>
/// Other
/// </summary>
Other = 0,
/// <summary>
/// Hydrochloric
/// </summary>
Hydrochloric = 1,
/// <summary>
/// White phosphorous
/// </summary>
WhitePhosphorous = 2,
/// <summary>
/// Red phosphorous
/// </summary>
RedPhosphorous = 3
}
private byte opacity;
private ExhaustSmoke.AttachedValue attached;
private ExhaustSmoke.ChemicalValue chemical;
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(ExhaustSmoke left, ExhaustSmoke right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(ExhaustSmoke left, ExhaustSmoke right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
// If parameters are null return false (cast to object to prevent recursive loop!)
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
/// <summary>
/// Performs an explicit conversion from <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> to <see cref="System.UInt32"/>.
/// </summary>
/// <param name="obj">The <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> scheme instance.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator uint(ExhaustSmoke obj)
{
return obj.ToUInt32();
}
/// <summary>
/// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/>.
/// </summary>
/// <param name="value">The uint value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator ExhaustSmoke(uint value)
{
return ExhaustSmoke.FromUInt32(value);
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> instance from the byte array.
/// </summary>
/// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/>.</param>
/// <param name="index">The starting position within value.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> instance, represented by a byte array.</returns>
/// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception>
/// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception>
public static ExhaustSmoke FromByteArray(byte[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (index < 0 ||
index > array.Length - 1 ||
index + 4 > array.Length - 1)
{
throw new IndexOutOfRangeException();
}
return FromUInt32(BitConverter.ToUInt32(array, index));
}
/// <summary>
/// Creates the <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> instance from the uint value.
/// </summary>
/// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> instance.</param>
/// <returns>The <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> instance, represented by the uint value.</returns>
public static ExhaustSmoke FromUInt32(uint value)
{
ExhaustSmoke ps = new ExhaustSmoke();
uint mask0 = 0xff0000;
byte shift0 = 16;
uint newValue0 = value & mask0 >> shift0;
ps.Opacity = (byte)newValue0;
uint mask1 = 0x1000000;
byte shift1 = 24;
uint newValue1 = value & mask1 >> shift1;
ps.Attached = (ExhaustSmoke.AttachedValue)newValue1;
uint mask2 = 0x6000000;
byte shift2 = 25;
uint newValue2 = value & mask2 >> shift2;
ps.Chemical = (ExhaustSmoke.ChemicalValue)newValue2;
return ps;
}
/// <summary>
/// Gets or sets the opacity.
/// </summary>
/// <value>The opacity.</value>
public byte Opacity
{
get { return this.opacity; }
set { this.opacity = value; }
}
/// <summary>
/// Gets or sets the attached.
/// </summary>
/// <value>The attached.</value>
public ExhaustSmoke.AttachedValue Attached
{
get { return this.attached; }
set { this.attached = value; }
}
/// <summary>
/// Gets or sets the chemical.
/// </summary>
/// <value>The chemical.</value>
public ExhaustSmoke.ChemicalValue Chemical
{
get { return this.chemical; }
set { this.chemical = value; }
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (!(obj is ExhaustSmoke))
{
return false;
}
return this.Equals((ExhaustSmoke)obj);
}
/// <summary>
/// Determines whether the specified <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> instance is equal to this instance.
/// </summary>
/// <param name="other">The <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> instance to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public bool Equals(ExhaustSmoke other)
{
// If parameter is null return false (cast to object to prevent recursive loop!)
if ((object)other == null)
{
return false;
}
return
this.Opacity == other.Opacity &&
this.Attached == other.Attached &&
this.Chemical == other.Chemical;
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> to the byte array.
/// </summary>
/// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> instance.</returns>
public byte[] ToByteArray()
{
return BitConverter.GetBytes(this.ToUInt32());
}
/// <summary>
/// Converts the instance of <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> to the uint value.
/// </summary>
/// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.Environment.ObjectState.ExhaustSmoke"/> instance.</returns>
public uint ToUInt32()
{
uint val = 0;
val |= (uint)((uint)this.Opacity << 16);
val |= (uint)((uint)this.Attached << 24);
val |= (uint)((uint)this.Chemical << 25);
return val;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
int hash = 17;
// Overflow is fine, just wrap
unchecked
{
hash = (hash * 29) + this.Opacity.GetHashCode();
hash = (hash * 29) + this.Attached.GetHashCode();
hash = (hash * 29) + this.Chemical.GetHashCode();
}
return hash;
}
}
}
| |
/* 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:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using XenAdmin.Controls;
using XenAdmin.Core;
using XenAPI;
using XenAdmin.Actions;
using XenAdmin.Dialogs;
namespace XenAdmin.Wizards.BugToolWizardFiles
{
public partial class BugToolPageSelectCapabilities : XenTabPage
{
#region Private fields
private List<Host> _hostList = new List<Host>();
private List<Capability> _capabilities = new List<Capability>();
private Dictionary<Host, List<Capability>> hostCapabilities;
private List<GetSystemStatusCapabilities> actions;
private ActionProgressDialog dialog;
private bool cancelled;
#endregion
public BugToolPageSelectCapabilities()
{
InitializeComponent();
//set this here due to a framework bug
splitContainer1.Panel1MinSize = 250;
splitContainer1.Panel2MinSize = 200;
this.linkLabel1.Visible = !XenAdmin.Core.HiddenFeatures.LinkLabelHidden;
}
public override string Text{get { return Messages.BUGTOOL_PAGE_CAPABILITIES_TEXT; }}
public override string PageTitle { get { return Messages.BUGTOOL_PAGE_CAPABILITIES_PAGETITLE; } }
public override string HelpID { get { return "SelectReportContents"; } }
public override bool EnableNext()
{
return wizardCheckAnyChecked();
}
public override void PageLoaded(PageLoadedDirection direction)
{
base.PageLoaded(direction);
if (direction == PageLoadedDirection.Forward)
{
ClearButton.Enabled = wizardCheckAnyChecked();
SelectButton.Enabled = wizardCheckAnyUnchecked();
}
}
private bool wizardCheckAnyChecked()
{
foreach (DataGridViewRow row in dataGridViewItems.Rows)
{
var capRow = row as CapabilityRow;
if (capRow != null && capRow.Capability.Checked)
return true;
}
return false;
}
private bool wizardCheckAnyUnchecked()
{
foreach (DataGridViewRow row in dataGridViewItems.Rows)
{
var capRow = row as CapabilityRow;
if (capRow != null && !capRow.Capability.Checked)
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="HostList"></param>
/// <returns>If success of not - false with stop moving to next page</returns>
public bool GetCommonCapabilities(List<Host> HostList)
{
if (!cancelled && Helpers.ListsContentsEqual<Host>(_hostList, HostList))
return true;
_hostList = HostList;
dataGridViewItems.Rows.Clear();
if (dialog != null && dialog.Visible)
dialog.Close();
hostCapabilities = new Dictionary<Host, List<Capability>>();
actions = new List<GetSystemStatusCapabilities>();
cancelled = false;
dialog = new ActionProgressDialog(Messages.SERVER_STATUS_REPORT_GET_CAPABILITIES);
dialog.ShowCancel = true;
dialog.CancelClicked += new EventHandler(dialog_CancelClicked);
foreach (Host host in _hostList)
{
GetSystemStatusCapabilities action = new GetSystemStatusCapabilities(host);
actions.Add(action);
action.Completed += Common_action_Completed;
action.RunAsync();
}
if (_hostList.Count > 0)
dialog.ShowDialog(this);
return !cancelled;
}
private void dialog_CancelClicked(object sender, EventArgs e)
{
dialog.Close();
cancelled = true;
// Need to unhook events on current actions, to stop them
// interfeering when they return in 20mins
foreach (GetSystemStatusCapabilities action in actions)
action.Completed -= Common_action_Completed;
}
private void Common_action_Completed(ActionBase sender)
{
Program.Invoke(this, delegate()
{
if (cancelled)
return;
GetSystemStatusCapabilities caps = sender as GetSystemStatusCapabilities;
if (caps == null)
return;
hostCapabilities[caps.Host] =
caps.Succeeded ? parseXMLToList(caps) : null;
if (hostCapabilities.Count >= _hostList.Count)
{
dialog.Close();
CombineCapabilitiesLists();
}
});
}
private List<Capability> parseXMLToList(Actions.GetSystemStatusCapabilities action)
{
List<Capability> capabilities = new List<Capability>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(action.Result);
foreach (XmlNode node in doc.GetElementsByTagName("capability"))
{
Capability c = new Capability();
foreach (XmlAttribute a in node.Attributes)
{
string name = a.Name;
string value = a.Value;
if (name == "content-type")
c.ContentType = value == "text/plain" ? ContentType.text_plain : ContentType.application_data;
else if (name == "default-checked")
c.DefaultChecked = value == "yes" ? true : false;
else if (name == "key")
c.Key = value;
else if (name == "max-size")
c.MaxSize = Int64.Parse(value);
else if (name == "min-size")
c.MinSize = Int64.Parse(value);
else if (name == "max-time")
c.MaxTime = Int64.Parse(value);
else if (name == "min-time")
c.MinTime = Int64.Parse(value);
else if (name == "pii")
c.PII = value == "yes" ? PrivateInformationIncluded.yes :
value == "no" ? PrivateInformationIncluded.no :
value == "maybe" ? PrivateInformationIncluded.maybe : PrivateInformationIncluded.customized;
}
capabilities.Add(c);
}
return capabilities;
}
private void CombineCapabilitiesLists()
{
List<Capability> combination = null;
foreach (List<Capability> capabilities in hostCapabilities.Values)
{
if (capabilities == null)
continue;
if (combination == null)
{
combination = capabilities;
continue;
}
combination = Helpers.ListsCommonItems<Capability>(combination, capabilities);
}
if (combination == null || combination.Count <= 0)
{
using (var dlg = new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
Messages.SERVER_STATUS_REPORT_CAPABILITIES_FAILED,
Messages.SERVER_STATUS_REPORT)))
{
dlg.ShowDialog(this);
}
cancelled = true;
return;
}
_capabilities = combination;
_capabilities.Add(GetClientCapability());
Sort_capabilities();
buildList();
}
private Capability GetClientCapability()
{
Capability clientCap = new Capability();
clientCap.ContentType = ContentType.text_plain;
clientCap.DefaultChecked = true;
clientCap.Key = "client-logs";
clientCap.MaxSize = getLogSize();
clientCap.MinSize = clientCap.MaxSize;
clientCap.MaxTime = -1;
clientCap.MinTime = -1;
clientCap.PII = PrivateInformationIncluded.yes;
return clientCap;
}
private void Sort_capabilities()
{
_capabilities.Sort(new Comparison<Capability>(delegate(Capability obj1, Capability obj2)
{
int piicompare = obj1.PII.CompareTo(obj2.PII);
if (piicompare == 0)
return StringUtility.NaturalCompare(obj1.ToString(), obj2.ToString());
else
return piicompare;
}));
}
private void OnCheckedCapabilitiesChanged()
{
string totalSize, totalTime;
CalculateTotalSizeAndTime(out totalSize, out totalTime);
TotalSizeValue.Text = totalSize;
TotalTimeValue.Text = totalTime;
ClearButton.Enabled = wizardCheckAnyChecked();
SelectButton.Enabled = wizardCheckAnyUnchecked();
OnPageUpdated();
}
private void buildList()
{
try
{
dataGridViewItems.SuspendLayout();
dataGridViewItems.Rows.Clear();
var list = new List<DataGridViewRow>();
foreach (Capability c in _capabilities)
list.Add(new CapabilityRow(c));
dataGridViewItems.Rows.AddRange(list.ToArray());
}
finally
{
dataGridViewItems.ResumeLayout();
}
OnCheckedCapabilitiesChanged();
}
private long getLogSize()
{
String path = Program.GetLogFile_();
if (path != null)
{
// Size of XenCenter.log
FileInfo logFileInfo = new FileInfo(path);
long total = logFileInfo.Length;
// Add size of any XenCenter.log.x
DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(path));
Regex regex = new Regex(Regex.Escape(Path.GetFileName(path)) + @"\.\d+");
foreach (FileInfo file in di.GetFiles())
{
if (regex.IsMatch(file.Name))
total += file.Length;
}
return total;
}
else
{
return 50 * Util.BINARY_MEGA;
}
}
private void CalculateTotalSizeAndTime(out string totalSize, out string totalTime)
{
var sizeMinList = new List<long>();
var sizeMaxList = new List<long>();
var timeMinList = new List<long>();
var timeMaxList = new List<long>();
foreach (var row in dataGridViewItems.Rows)
{
var capRow = row as CapabilityRow;
if (capRow != null && capRow.Capability.Checked)
{
var c = capRow.Capability;
int m = c.Key == "client-logs" ? 1 : _hostList.Count;
sizeMinList.Add(c.MinSize * m);
sizeMaxList.Add(c.MaxSize * m);
timeMinList.Add(c.MinTime * m);
timeMaxList.Add(c.MaxTime * m);
}
}
totalSize = Helpers.StringFromMaxMinSizeList(sizeMinList, sizeMaxList);
totalTime = Helpers.StringFromMaxMinTimeList(timeMinList, timeMaxList);
}
public IEnumerable<Capability> Capabilities
{
get
{
return from DataGridViewRow row in dataGridViewItems.Rows
let capRow = row as CapabilityRow
where capRow != null && capRow.Capability.Checked
select capRow.Capability;
}
}
#region Control event handlers
private void dataGridViewItems_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
var row1 = dataGridViewItems.Rows[e.RowIndex1] as CapabilityRow;
var row2 = dataGridViewItems.Rows[e.RowIndex2] as CapabilityRow;
if (row1 != null && row2 != null && e.Column.Index == columnImage.Index)
{
e.SortResult = row1.Capability.PII.CompareTo(row2.Capability.PII);
e.Handled = true;
}
}
private void dataGridViewItems_SelectionChanged(object sender, EventArgs e)
{
if (dataGridViewItems.SelectedRows.Count > 0)
{
var row = dataGridViewItems.SelectedRows[0] as CapabilityRow;
if (row == null)
return;
DescriptionValue.Text = row.Capability.Description;
SizeValue.Text = row.Capability.EstimatedSize;
TimeValue.Text = row.Capability.EstimatedTime;
}
}
private void dataGridViewItems_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex != columnCheck.Index)
return;
if (e.RowIndex < 0 || e.RowIndex >= dataGridViewItems.RowCount)
return;
var row = dataGridViewItems.Rows[e.RowIndex] as CapabilityRow;
if (row == null)
return;
row.Capability.Checked = !row.Capability.Checked;
row.Update();
OnCheckedCapabilitiesChanged();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
System.Diagnostics.Process.Start(InvisibleMessages.PRIVACY);
}
catch
{
using (var dlg = new ThreeButtonDialog(
new ThreeButtonDialog.Details(
SystemIcons.Error,
Messages.HOMEPAGE_ERROR_MESSAGE,
Messages.XENCENTER)))
{
dlg.ShowDialog(this);
}
}
}
private void SelectButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridViewItems.Rows)
{
var capRow = row as CapabilityRow;
if (capRow != null && !capRow.Capability.Checked)
{
capRow.Capability.Checked = true;
capRow.Update();
}
}
OnCheckedCapabilitiesChanged();
}
private void ClearButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridViewItems.Rows)
{
var capRow = row as CapabilityRow;
if (capRow != null && capRow.Capability.Checked)
{
capRow.Capability.Checked = false;
capRow.Update();
}
}
OnCheckedCapabilitiesChanged();
}
#endregion
private class CapabilityRow : DataGridViewRow
{
public readonly Capability Capability;
private readonly DataGridViewCheckBoxCell cellCheck = new DataGridViewCheckBoxCell();
private readonly DataGridViewTextBoxCell cellItem = new DataGridViewTextBoxCell();
private readonly DataGridViewImageCell cellImage = new DataGridViewImageCell();
public CapabilityRow(Capability capability)
{
Capability = capability;
Cells.AddRange(cellCheck, cellItem, cellImage);
Update();
}
public void Update()
{
cellCheck.Value = Capability.Checked;
cellItem.Value = Capability.Name;
switch(Capability.PII)
{
case PrivateInformationIncluded.maybe:
cellImage.Value = Properties.Resources.alert2_16;
break;
case PrivateInformationIncluded.customized:
cellImage.Value = Properties.Resources.alert3_16;
break;
case PrivateInformationIncluded.no:
cellImage.Value = Properties.Resources.alert4_16;
break;
case PrivateInformationIncluded.yes:
default:
cellImage.Value = Properties.Resources.alert1_16;
break;
}
cellImage.ToolTipText = Capability.PiiText;
}
}
}
public enum ContentType { text_plain, application_data };
public enum PrivateInformationIncluded { yes, maybe, customized, no};
public class Capability : IComparable<Capability>, IEquatable<Capability>
{
public ContentType ContentType;
bool _defaultChecked;
public long MaxSize;
public long MinSize;
public long MaxTime;
public long MinTime;
public PrivateInformationIncluded PII;
private string _key;
private string _name;
private string _description;
public bool Checked;
public bool DefaultChecked
{
get
{
return _defaultChecked;
}
set
{
_defaultChecked = value;
Checked = value;
}
}
public string PiiText
{
get
{
switch (PII)
{
case PrivateInformationIncluded.yes:
return Messages.PII_YES;
case PrivateInformationIncluded.maybe:
return Messages.PII_MAYBE;
case PrivateInformationIncluded.customized:
return Messages.PII_CUSTOMISED;
case PrivateInformationIncluded.no:
default:
return Messages.PII_NO;
}
}
}
public string Key
{
get
{
return _key;
}
set
{
_key = value;
_name = Core.PropertyManager.GetFriendlyName(string.Format("Label-host.system_status-{0}", _key));
if (string.IsNullOrEmpty(_name))
_name = _key;
_description = Core.PropertyManager.GetFriendlyName(string.Format("Description-host.system_status-{0}", _key));
}
}
public string Name
{
get { return _name; }
}
public string Description
{
get { return _description; }
}
public string EstimatedSize
{
get
{
return Helpers.StringFromMaxMinSize(MinSize, MaxSize);
}
}
public string EstimatedTime
{
get
{
return Helpers.StringFromMaxMinTime(MinTime, MaxTime);
}
}
public override string ToString()
{
return _name;
}
public int CompareTo(Capability other)
{
return StringUtility.NaturalCompare(this.Key, other.Key);
}
public bool Equals(Capability other)
{
return this.Key.Equals(other.Key);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Versioning;
namespace NuGet
{
public static class PackageExtensions
{
private const string TagsProperty = "Tags";
private static readonly string[] _packagePropertiesToSearch = new[] { "Id", "Description", TagsProperty };
public static bool IsReleaseVersion(this IPackageMetadata packageMetadata)
{
return String.IsNullOrEmpty(packageMetadata.Version.SpecialVersion);
}
public static bool IsListed(this IPackage package)
{
return package.Listed || package.Published > Constants.Unpublished;
}
public static IEnumerable<IPackage> FindByVersion(this IEnumerable<IPackage> source, IVersionSpec versionSpec)
{
if (versionSpec == null)
{
throw new ArgumentNullException("versionSpec");
}
return source.Where(versionSpec.ToDelegate());
}
public static IEnumerable<IPackageFile> GetFiles(this IPackage package, string directory)
{
return package.GetFiles().Where(file => file.Path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase));
}
public static IEnumerable<IPackageFile> GetContentFiles(this IPackage package)
{
return package.GetFiles(Constants.ContentDirectory);
}
public static IEnumerable<IPackageFile> GetLibFiles(this IPackage package)
{
return package.GetFiles(Constants.LibDirectory);
}
/// <summary>
/// Returns the list of files from a satellite package that are considered satellite files.
/// </summary>
/// <remarks>
/// This method must only be called for packages that specify a language
/// </remarks>
/// <param name="package">The package to get satellite files from.</param>
/// <returns>The list of satellite files, which may be an empty list.</returns>
public static IEnumerable<IPackageFile> GetSatelliteFiles(this IPackage package)
{
if (String.IsNullOrEmpty(package.Language))
{
return Enumerable.Empty<IPackageFile>();
}
// Satellite files are those within the Lib folder that have a culture-specific subfolder anywhere in the path
return package.GetLibFiles().Where(file => Path.GetDirectoryName(file.Path).Split(Path.DirectorySeparatorChar)
.Contains(package.Language, StringComparer.OrdinalIgnoreCase));
}
public static IEnumerable<PackageIssue> Validate(this IPackage package, IEnumerable<IPackageRule> rules)
{
if (package == null)
{
return null;
}
if (rules == null)
{
throw new ArgumentNullException("rules");
}
return rules.Where(r => r != null).SelectMany(r => r.Validate(package));
}
public static string GetHash(this IPackage package, string hashAlgorithm)
{
return GetHash(package, new CryptoHashProvider(hashAlgorithm));
}
public static string GetHash(this IPackage package, IHashProvider hashProvider)
{
using (Stream stream = package.GetStream())
{
byte[] packageBytes = stream.ReadAllBytes();
return Convert.ToBase64String(hashProvider.CalculateHash(packageBytes));
}
}
/// <summary>
/// Returns true if a package has no content that applies to a project.
/// </summary>
public static bool HasProjectContent(this IPackage package)
{
// Note that while checking for both AssemblyReferences and LibFiles seems redundant,
// there are tests that directly inject items into the AssemblyReferences collection
// without having those files represented in the Lib folder. We keep the redundant
// check to play it on the safe side.
return package.FrameworkAssemblies.Any() ||
package.AssemblyReferences.Any() ||
package.GetContentFiles().Any() ||
package.GetLibFiles().Any();
}
public static IEnumerable<FrameworkName> GetSupportedFrameworks(this IPackage package)
{
return package.FrameworkAssemblies
.SelectMany(a => a.SupportedFrameworks)
.Concat(package.AssemblyReferences.SelectMany(a => a.SupportedFrameworks))
.Distinct();
}
/// <summary>
/// Returns true if a package has dependencies but no files.
/// </summary>
public static bool IsDependencyOnly(this IPackage package)
{
return !package.GetFiles().Any() && package.Dependencies.Any();
}
public static string GetFullName(this IPackageMetadata package)
{
return package.Id + " " + package.Version;
}
/// <summary>
/// Calculates the canonical list of operations.
/// </summary>
internal static IList<PackageOperation> Reduce(this IEnumerable<PackageOperation> operations)
{
// Convert the list of operations to a dictionary from (Action, Id, Version) -> [Operations]
// We keep track of the index so that we preserve the ordering of the operations
var operationLookup = operations.Select((o, index) => new { Operation = o, Index = index })
.ToLookup(o => GetOperationKey(o.Operation))
.ToDictionary(g => g.Key,
g => g.ToList());
// Given a list of operations we're going to eliminate the ones that have opposites (i.e.
// if the list contains +A 1.0 and -A 1.0, then we eliminate them both entries).
foreach (var operation in operations)
{
// We get the opposing operation for the current operation:
// if o is +A 1.0 then the opposing key is - A 1.0
Tuple<PackageAction, string, SemanticVersion> opposingKey = GetOpposingOperationKey(operation);
// We can't use TryGetValue since the value of the dictionary entry
// is a List of an anonymous type.
if (operationLookup.ContainsKey(opposingKey))
{
// If we find an opposing entry, we remove it from the list of candidates
var opposingOperations = operationLookup[opposingKey];
opposingOperations.RemoveAt(0);
// Remove the list from the dictionary if nothing is in it
if (!opposingOperations.Any())
{
operationLookup.Remove(opposingKey);
}
}
}
// Create the final list of operations and order them by their original index
return operationLookup.SelectMany(o => o.Value)
.OrderBy(o => o.Index)
.Select(o => o.Operation)
.ToList();
}
private static Tuple<PackageAction, string, SemanticVersion> GetOperationKey(PackageOperation operation)
{
return Tuple.Create(operation.Action, operation.Package.Id, operation.Package.Version);
}
private static Tuple<PackageAction, string, SemanticVersion> GetOpposingOperationKey(PackageOperation operation)
{
return Tuple.Create(operation.Action == PackageAction.Install ?
PackageAction.Uninstall :
PackageAction.Install, operation.Package.Id, operation.Package.Version);
}
/// <summary>
/// Returns a distinct set of elements using the comparer specified. This implementation will pick the last occurrence
/// of each element instead of picking the first. This method assumes that similar items occur in order.
/// </summary>
public static IEnumerable<IPackage> AsCollapsed(this IEnumerable<IPackage> source)
{
return source.DistinctLast(PackageEqualityComparer.Id, PackageComparer.Version);
}
/// <summary>
/// Collapses the packages by Id picking up the highest version for each Id that it encounters
/// </summary>
internal static IEnumerable<IPackage> CollapseById(this IEnumerable<IPackage> source)
{
return source.GroupBy(p => p.Id, StringComparer.OrdinalIgnoreCase)
.Select(g => g.OrderByDescending(p => p.Version).First());
}
public static IEnumerable<IPackage> FilterByPrerelease(this IEnumerable<IPackage> packages, bool allowPrerelease)
{
if (packages == null)
{
return null;
}
if (!allowPrerelease)
{
packages = packages.Where(p => p.IsReleaseVersion());
}
return packages;
}
/// <summary>
/// Returns packages where the search text appears in the default set of properties to search. The default set includes Id, Description and Tags.
/// </summary>
public static IQueryable<T> Find<T>(this IQueryable<T> packages, string searchText) where T : IPackage
{
return Find(packages, _packagePropertiesToSearch, searchText);
}
/// <summary>
/// Returns packages where the search text appears in any of the properties to search.
/// Note that not all properties can be successfully queried via this method particularly over a OData feed. Verify indepedently if it works for the properties that need to be searched.
/// </summary>
public static IQueryable<T> Find<T>(this IQueryable<T> packages, IEnumerable<string> propertiesToSearch, string searchText) where T : IPackage
{
if (propertiesToSearch.IsEmpty())
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "propertiesToSearch");
}
if (String.IsNullOrEmpty(searchText))
{
return packages;
}
return Find(packages, propertiesToSearch, searchText.Split());
}
private static IQueryable<T> Find<T>(this IQueryable<T> packages, IEnumerable<string> propertiesToSearch, IEnumerable<string> searchTerms) where T : IPackage
{
if (!searchTerms.Any())
{
return packages;
}
IEnumerable<string> nonNullTerms = searchTerms.Where(s => s != null);
if (!nonNullTerms.Any())
{
return packages;
}
return packages.Where(BuildSearchExpression<T>(propertiesToSearch, nonNullTerms));
}
/// <summary>
/// Constructs an expression to search for individual tokens in a search term in the Id and Description of packages
/// </summary>
private static Expression<Func<T, bool>> BuildSearchExpression<T>(IEnumerable<string> propertiesToSearch, IEnumerable<string> searchTerms) where T : IPackage
{
Debug.Assert(searchTerms != null);
var parameterExpression = Expression.Parameter(typeof(IPackageMetadata));
// package.Id.ToLower().Contains(term1) || package.Id.ToLower().Contains(term2) ...
Expression condition = (from term in searchTerms
from property in propertiesToSearch
select BuildExpressionForTerm(parameterExpression, term, property)).Aggregate(Expression.OrElse);
return Expression.Lambda<Func<T, bool>>(condition, parameterExpression);
}
[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower",
Justification = "The expression is remoted using Odata which does not support the culture parameter")]
private static Expression BuildExpressionForTerm(ParameterExpression packageParameterExpression, string term, string propertyName)
{
// For tags we want to prepend and append spaces to do an exact match
if (propertyName.Equals(TagsProperty, StringComparison.OrdinalIgnoreCase))
{
term = " " + term + " ";
}
MethodInfo stringContains = typeof(String).GetMethod("Contains", new Type[] { typeof(string) });
MethodInfo stringToLower = typeof(String).GetMethod("ToLower", Type.EmptyTypes);
// package.Id / package.Description
var propertyExpression = Expression.Property(packageParameterExpression, propertyName);
// .ToLower()
var toLowerExpression = Expression.Call(propertyExpression, stringToLower);
// Handle potentially null properties
// package.{propertyName} != null && package.{propertyName}.ToLower().Contains(term.ToLower())
return Expression.AndAlso(Expression.NotEqual(propertyExpression,
Expression.Constant(null)),
Expression.Call(toLowerExpression, stringContains, Expression.Constant(term.ToLower())));
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace Microsoft.CodeQuality.Analyzers.Maintainability.UnitTests
{
public class DoNotIgnoreMethodResultsTests : DiagnosticAnalyzerTestBase
{
#region Unit tests for no analyzer diagnostic
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UsedInvocationResult()
{
VerifyCSharp(@"
using System.Runtime.InteropServices;
public class C
{
private static void M(string x, out int y)
{
// Object creation
var c = new C();
// String creation
var xUpper = x.ToUpper();
// Try parse
if (!int.TryParse(x, out y))
{
return;
}
var result = NativeMethod();
}
[DllImport(""user32.dll"")]
private static extern int NativeMethod();
}
");
VerifyBasic(@"
Imports System.Runtime.InteropServices
Public Class C
Private Shared Sub M(x As String, ByRef y As Integer)
' Object creation
Dim c = New C()
' String creation
Dim xUpper = x.ToUpper()
' Try parse
If Not Integer.TryParse(x, y) Then
Return
End If
Dim result = NativeMethod()
End Sub
<DllImport(""user32.dll"")> _
Private Shared Function NativeMethod() As Integer
End Function
End Class
");
}
#endregion
#region Unit tests for analyzer diagnostic(s)
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UnusedStringCreation()
{
VerifyCSharp(@"
using System;
using System.Globalization;
class C
{
public void DoesNotAssignStringToVariable()
{
Console.WriteLine(this);
string sample = ""Sample"";
sample.ToLower(CultureInfo.InvariantCulture);
return;
}
}
",
GetCSharpStringCreationResultAt(11, 9, "DoesNotAssignStringToVariable", "ToLower"));
VerifyBasic(@"
Imports System
Imports System.Globalization
Class C
Public Sub DoesNotAssignStringToVariable()
Console.WriteLine(Me)
Dim sample As String = ""Sample""
sample.ToLower(CultureInfo.InvariantCulture)
Return
End Sub
End Class
",
GetBasicStringCreationResultAt(9, 9, "DoesNotAssignStringToVariable", "ToLower"));
}
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UnusedObjectCreation()
{
VerifyCSharp(@"
using System;
using System.Globalization;
class C
{
public void DoesNotAssignObjectToVariable()
{
new C();
}
}
",
GetCSharpObjectCreationResultAt(9, 9, "DoesNotAssignObjectToVariable", "C"));
// Following code produces syntax error for VB, so no object creation diagnostic.
VerifyBasic(@"
Imports System
Imports System.Globalization
Class C
Public Sub DoesNotAssignObjectToVariable()
New C() ' error BC30035: Syntax error
End Sub
End Class
", TestValidationMode.AllowCompileErrors);
}
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UnusedTryParseResult()
{
VerifyCSharp(@"
using System.Runtime.InteropServices;
public class C
{
private static void M(string x, out int y)
{
// Try parse
int.TryParse(x, out y);
}
}
",
GetCSharpTryParseResultAt(9, 9, "M", "TryParse"));
VerifyBasic(@"
Imports System.Runtime.InteropServices
Public Class C
Private Shared Sub M(x As String, ByRef y As Integer)
' Try parse
Integer.TryParse(x, y)
End Sub
End Class
",
GetBasicTryParseResultAt(7, 9, "M", "TryParse"));
}
[Fact]
[WorkItem(462, "https://github.com/dotnet/roslyn-analyzers/issues/462")]
public void UnusedPInvokeResult()
{
VerifyCSharp(@"
using System.Runtime.InteropServices;
public class C
{
private static void M(string x, out int y)
{
y = 1;
NativeMethod();
}
[DllImport(""user32.dll"")]
private static extern int NativeMethod();
}
",
GetCSharpHResultOrErrorCodeResultAt(9, 9, "M", "NativeMethod"));
VerifyBasic(@"
Imports System.Runtime.InteropServices
Public Class C
Private Shared Sub M(x As String, ByRef y As Integer)
NativeMethod()
End Sub
<DllImport(""user32.dll"")> _
Private Shared Function NativeMethod() As Integer
End Function
End Class
",
GetBasicHResultOrErrorCodeResultAt(6, 9, "M", "NativeMethod"));
}
[Fact(Skip = "746")]
[WorkItem(746, "https://github.com/dotnet/roslyn-analyzers/issues/746")]
public void UnusedComImportPreserveSig()
{
VerifyCSharp(@"
using System.Runtime.InteropServices;
public class C
{
private static void M(IComClass cc)
{
cc.NativeMethod();
}
}
[ComImport]
[Guid(""060DDE7F-A9CD-4669-A443-B6E25AF44E7C"")]
public interface IComClass
{
[PreserveSig]
int NativeMethod();
}
",
GetCSharpHResultOrErrorCodeResultAt(8, 9, "M", "NativeMethod"));
VerifyBasic(@"
Imports System.Runtime.InteropServices
Public Class C
Private Shared Sub M(cc As IComClass)
cc.NativeMethod()
End Sub
End Class
<ComImport> _
<Guid(""060DDE7F-A9CD-4669-A443-B6E25AF44E7C"")> _
Public Interface IComClass
<PreserveSig> _
Function NativeMethod() As Integer
End Interface
",
GetBasicHResultOrErrorCodeResultAt(6, 9, "M", "NativeMethod"));
}
[Fact]
[WorkItem(1164, "https://github.com/dotnet/roslyn-analyzers/issues/1164")]
public void UnusedPureMethodTriggersError()
{
VerifyCSharp(@"
using System.Diagnostics.Contracts;
class C
{
[Pure]
public int Returns1() => 1;
public void DoesNotUseResult()
{
Returns1();
}
}",
GetCSharpPureMethodResultAt(11, 9, "DoesNotUseResult", "Returns1"));
VerifyBasic(@"
Imports System.Diagnostics.Contracts
Module Module1
<Pure>
Function Returns1() As Integer
Return 1
End Function
Sub DoesNotUseResult()
Returns1()
End Sub
End Module
",
GetBasicPureMethodResultAt(11, 9, "DoesNotUseResult", "Returns1"));
}
#endregion
#region Helpers
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new DoNotIgnoreMethodResultsAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new DoNotIgnoreMethodResultsAnalyzer();
}
private static DiagnosticResult GetCSharpStringCreationResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageStringCreation, containingMethodName, invokedMethodName);
return GetCSharpResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetBasicStringCreationResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageStringCreation, containingMethodName, invokedMethodName);
return GetBasicResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCSharpObjectCreationResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageObjectCreation, containingMethodName, invokedMethodName);
return GetCSharpResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCSharpTryParseResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageTryParse, containingMethodName, invokedMethodName);
return GetCSharpResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetBasicTryParseResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageTryParse, containingMethodName, invokedMethodName);
return GetBasicResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCSharpHResultOrErrorCodeResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageHResultOrErrorCode, containingMethodName, invokedMethodName);
return GetCSharpResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetBasicHResultOrErrorCodeResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessageHResultOrErrorCode, containingMethodName, invokedMethodName);
return GetBasicResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetCSharpPureMethodResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessagePureMethod, containingMethodName, invokedMethodName);
return GetCSharpResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
private static DiagnosticResult GetBasicPureMethodResultAt(int line, int column, string containingMethodName, string invokedMethodName)
{
string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.DoNotIgnoreMethodResultsMessagePureMethod, containingMethodName, invokedMethodName);
return GetBasicResultAt(line, column, DoNotIgnoreMethodResultsAnalyzer.RuleId, message);
}
#endregion
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using Alachisoft.NCache.Caching.DataGrouping;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Runtime.Serialization;
using Alachisoft.NCache.Runtime.Serialization.IO;
namespace Alachisoft.NCache.Caching.Statistics
{
/// <summary>
/// The class that contains information specific to a single node in the cluster.
/// Contains the address as well as statistics of the local cache.
/// </summary>
[Serializable]
public class NodeInfo : ICloneable, IComparable, ICompactSerializable
{
/// <summary> The IP address, port tuple; uniquely identifying the node. </summary>
private Address _address;
/// <summary> The name of the sub-cluster this node belongs to. </summary>
private string _subgroupName;
/// <summary> The statistics of the node. </summary>
private CacheStatistics _stats;
/// <summary> Up status of node. </summary>
private BitSet _status = new BitSet();
/// <summary>Data groups associated with this node</summary>
private DataAffinity _dataAffinity;
private ArrayList _connectedClients = ArrayList.Synchronized(new ArrayList());
/// <summary>Client/Server address of the node.</summary>
private Address _rendererAddress;
private bool _isInproc;
private bool _isStartedAsMirror;
/// <summary>
/// Constructor.
/// </summary>
private NodeInfo() {}
/// <summary>
/// Overloaded Constructor
/// </summary>
/// <param name="address"></param>
public NodeInfo(Address address)
{
_address = address;
}
public NodeInfo(Address address,bool isStartedAsMirror)
{
_address = address;
_isStartedAsMirror = isStartedAsMirror;
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="info"></param>
protected NodeInfo(NodeInfo info)
{
this._address = info._address == null ? null : info._address.Clone() as Address;
this._rendererAddress = info._rendererAddress != null ? info._rendererAddress.Clone() as Address : null;
this._stats = info._stats == null ? null:info._stats.Clone() as CacheStatistics;
this._status = info._status;
this._subgroupName = info._subgroupName;
this._isInproc = info._isInproc;
this._dataAffinity = info._dataAffinity == null ? null : info._dataAffinity.Clone() as DataAffinity;
_isStartedAsMirror = info.IsStartedAsMirror;
if(info._connectedClients != null)
{
lock(info._connectedClients.SyncRoot)
this._connectedClients = info._connectedClients.Clone() as ArrayList;
}
}
/// <summary>
/// The IP address, port tuple; uniquely identifying the node.
/// </summary>
public Address Address
{
get { return _address; }
set { _address = value; }
}
public Address RendererAddress
{
get { return _rendererAddress; }
set { _rendererAddress = value; }
}
public bool IsStartedAsMirror
{
get { return _isStartedAsMirror; }
set { _isStartedAsMirror = value; }
}
/// <summary>
/// Gets/sets the status of the node whether a node is InProc or OutProc.
/// </summary>
public bool IsInproc
{
get { return _isInproc; }
set { _isInproc = value; }
}
/// <summary>
/// The name of the sub-cluster this node belongs to.
/// </summary>
public string SubgroupName
{
get { return _subgroupName; }
set { _subgroupName = value; }
}
/// <summary>
/// The data groups settings for the node.
/// </summary>
public DataAffinity DataAffinity
{
get { return _dataAffinity; }
set { _dataAffinity = value; }
}
/// <summary>
/// The number of nodes in the cluster that are providers or consumers, i.e., group members.
/// </summary>
public CacheStatistics Statistics
{
get { return _stats; }
set { _stats = value; }
}
/// <summary>
/// The runtime status of node.
/// </summary>
internal BitSet Status
{
get { return _status; }
set { _status = value; }
}
public ArrayList ConnectedClients
{
get { return _connectedClients; }
set { _connectedClients = value; }
}
/// <summary>
/// Get/Set the value indicating whether this node is active or not.
/// This property is valid only for Mirror Cache Topology.
/// </summary>
public bool IsActive
{
get { return Status.IsAnyBitSet(NodeStatus.Coordinator); }
}
#region / --- IComparable --- /
/// <summary>
/// Compares the current instance with another object of the same type.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>A 32-bit signed integer that indicates the relative order of the comparands.</returns>
public int CompareTo(object obj)
{
return _address.CompareTo(((NodeInfo)obj).Address);
}
#endregion
public override bool Equals(object obj)
{
return CompareTo(obj) == 0;
}
#region / --- ICloneable --- /
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>A new object that is a copy of this instance.</returns>
public object Clone()
{
return new NodeInfo(this);
}
#endregion
/// <summary>
/// returns the string representation of the statistics.
/// </summary>
/// <returns></returns>
public override string ToString()
{
System.Text.StringBuilder ret = new System.Text.StringBuilder();
try
{
ret.Append("Node[Adr:" + _address);
if(_stats != null)
ret.Append(", " + _stats);
ret.Append("]");
}
catch(Exception e)
{
}
return ret.ToString();
}
#region / --- ICompactSerializable --- /
public void Deserialize(CompactReader reader)
{
_address = Address.ReadAddress(reader);
_subgroupName = reader.ReadObject() as string;
_stats = CacheStatistics.ReadCacheStatistics(reader);
_status = new BitSet(reader.ReadByte());
_dataAffinity = DataAffinity.ReadDataAffinity(reader);
_connectedClients = (ArrayList)reader.ReadObject();
_isInproc = reader.ReadBoolean();
_rendererAddress = Address.ReadAddress(reader);
_isStartedAsMirror = reader.ReadBoolean();
}
public void Serialize(CompactWriter writer)
{
Address.WriteAddress(writer, _address);
writer.WriteObject(_subgroupName);
CacheStatistics.WriteCacheStatistics(writer, _stats);
writer.Write(_status.Data);
DataAffinity.WriteDataAffinity(writer, _dataAffinity);
writer.WriteObject(_connectedClients);
writer.Write(_isInproc);
Address.WriteAddress(writer, _rendererAddress);
writer.Write(_isStartedAsMirror);
}
#endregion
public static NodeInfo ReadNodeInfo(CompactReader reader)
{
byte isNull = reader.ReadByte();
if (isNull == 1)
return null;
NodeInfo newInfo = new NodeInfo();
newInfo.Deserialize(reader);
return newInfo;
}
public static void WriteNodeInfo(CompactWriter writer, NodeInfo nodeInfo)
{
byte isNull = 1;
if (nodeInfo == null)
writer.Write(isNull);
else
{
isNull = 0;
writer.Write(isNull);
nodeInfo.Serialize(writer);
}
return;
}
}
}
| |
using System;
using Xunit;
using Medo.Math;
namespace Tests.Medo.Math {
public class WelfordVarianceTests {
[Fact(DisplayName = "WelfordVariance: Example (1)")]
public void Example1() {
var stats = new WelfordVariance();
stats.Add(4);
stats.Add(7);
stats.Add(13);
stats.Add(16);
Assert.Equal(4, stats.Count);
Assert.Equal(10, stats.Mean, 15);
Assert.Equal(22.5, stats.Variance, 15);
Assert.Equal(30, stats.SampleVariance, 15);
Assert.Equal(4.743416490252569, stats.StandardDeviation, 15);
Assert.Equal(5.477225575051661, stats.SampleStandardDeviation, 15);
Assert.Equal(0.547722557505166, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: Example (2)")]
public void Example2() {
var stats = new WelfordVariance();
stats.Add(100000004);
stats.Add(100000007);
stats.Add(100000013);
stats.Add(100000016);
Assert.Equal(4, stats.Count);
Assert.Equal(100000010, stats.Mean, 15);
Assert.Equal(22.5, stats.Variance, 15);
Assert.Equal(30, stats.SampleVariance, 15);
Assert.Equal(4.743416490252569, stats.StandardDeviation, 15);
Assert.Equal(5.477225575051661, stats.SampleStandardDeviation, 15);
Assert.Equal(0.000000054772250, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: Example (3)")]
public void Example3() {
var stats = new WelfordVariance();
stats.Add(1000000004);
stats.Add(1000000007);
stats.Add(1000000013);
stats.Add(1000000016);
Assert.Equal(4, stats.Count);
Assert.Equal(1000000010, stats.Mean, 15);
Assert.Equal(22.5, stats.Variance, 15);
Assert.Equal(30, stats.SampleVariance, 15);
Assert.Equal(4.743416490252569, stats.StandardDeviation, 15);
Assert.Equal(5.477225575051661, stats.SampleStandardDeviation, 15);
Assert.Equal(0.000000005477226, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: Example (4)")]
public void Example4() {
var stats = new WelfordVariance();
stats.Add(6);
stats.Add(2);
stats.Add(3);
stats.Add(1);
Assert.Equal(4, stats.Count);
Assert.Equal(3, stats.Mean, 15);
Assert.Equal(3.5, stats.Variance, 15);
Assert.Equal(4.666666666666667, stats.SampleVariance, 15);
Assert.Equal(1.870828693386971, stats.StandardDeviation, 15);
Assert.Equal(2.160246899469287, stats.SampleStandardDeviation, 15);
Assert.Equal(0.720082299823096, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: Example (5)")]
public void Example5() {
var stats = new WelfordVariance(new double[] { 2, 2, 5, 7 });
Assert.Equal(4, stats.Count);
Assert.Equal(4, stats.Mean, 15);
Assert.Equal(4.5, stats.Variance, 15);
Assert.Equal(6, stats.SampleVariance, 15);
Assert.Equal(2.121320343559642, stats.StandardDeviation, 15);
Assert.Equal(2.449489742783178, stats.SampleStandardDeviation, 15);
Assert.Equal(0.612372435695794, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: Example (6)")]
public void Example6() {
var stats = new WelfordVariance();
stats.AddRange(new double[] { 2, 4, 4, 4, 5, 5, 7, 9 });
Assert.Equal(8, stats.Count);
Assert.Equal(5, stats.Mean, 15);
Assert.Equal(4, stats.Variance, 15);
Assert.Equal(4.571428571428571, stats.SampleVariance, 15);
Assert.Equal(2, stats.StandardDeviation, 15);
Assert.Equal(2.138089935299395, stats.SampleStandardDeviation, 15);
Assert.Equal(0.427617987059879, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: Example (7)")]
public void Example7() {
var stats = new WelfordVariance();
stats.AddRange(new double[] { 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4 });
Assert.Equal(20, stats.Count);
Assert.Equal(7, stats.Mean, 15);
Assert.Equal(8.9, stats.Variance, 15);
Assert.Equal(9.368421052631579, stats.SampleVariance, 15);
Assert.Equal(2.983286778035260, stats.StandardDeviation, 15);
Assert.Equal(3.060787652326044, stats.SampleStandardDeviation, 15);
Assert.Equal(0.437255378903721, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: Example (8)")]
public void Example8() {
var stats = new WelfordVariance();
stats.AddRange(new double[] { 51.3, 55.6, 49.9, 52.0 });
Assert.Equal(4, stats.Count);
Assert.Equal(52.2, stats.Mean, 15);
Assert.Equal(4.425000000000004, stats.Variance, 15);
Assert.Equal(5.900000000000006, stats.SampleVariance, 15);
Assert.Equal(2.103568396796264, stats.StandardDeviation, 15);
Assert.Equal(2.428991560298225, stats.SampleStandardDeviation, 15);
Assert.Equal(0.046532405369698, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: Example (9)")]
public void Example9() {
var stats = new WelfordVariance();
stats.AddRange(new double[] { -5, -3, -1, 1, 3 });
Assert.Equal(5, stats.Count);
Assert.Equal(-1, stats.Mean, 15);
Assert.Equal(8, stats.Variance, 15);
Assert.Equal(10, stats.SampleVariance, 15);
Assert.Equal(2.82842712474619, stats.StandardDeviation, 15);
Assert.Equal(3.16227766016838, stats.SampleStandardDeviation, 15);
Assert.Equal(3.16227766016838, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: Example (10)")]
public void Example10() {
var stats = new WelfordVariance();
stats.AddRange(new double[] { -1, 0, 1 });
Assert.Equal(3, stats.Count);
Assert.Equal(0, stats.Mean, 15);
Assert.Equal(0.666666666666667, stats.Variance, 15);
Assert.Equal(1, stats.SampleVariance, 15);
Assert.Equal(0.816496580927726, stats.StandardDeviation, 15);
Assert.Equal(1, stats.SampleStandardDeviation, 15);
Assert.Equal(double.PositiveInfinity, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: No values")]
public void NoValue() {
var stats = new WelfordVariance();
Assert.Equal(0, stats.Count);
Assert.Equal(double.NaN, stats.Mean);
Assert.Equal(double.NaN, stats.Variance);
Assert.Equal(double.NaN, stats.SampleVariance);
Assert.Equal(double.NaN, stats.StandardDeviation);
Assert.Equal(double.NaN, stats.SampleStandardDeviation);
Assert.Equal(double.NaN, stats.RelativeStandardDeviation);
}
[Fact(DisplayName = "WelfordVariance: One value")]
public void OneValue() {
var stats = new WelfordVariance();
stats.Add(1);
Assert.Equal(1, stats.Count);
Assert.Equal(double.NaN, stats.Mean);
Assert.Equal(double.NaN, stats.Variance);
Assert.Equal(double.NaN, stats.SampleVariance);
Assert.Equal(double.NaN, stats.StandardDeviation);
Assert.Equal(double.NaN, stats.SampleStandardDeviation);
Assert.Equal(double.NaN, stats.RelativeStandardDeviation);
}
[Fact(DisplayName = "WelfordVariance: Two values")]
public void TwoValues() {
var stats = new WelfordVariance();
stats.Add(1);
stats.Add(2);
Assert.Equal(2, stats.Count);
Assert.Equal(1.5, stats.Mean, 15);
Assert.Equal(0.25, stats.Variance, 15);
Assert.Equal(0.5, stats.SampleVariance, 15);
Assert.Equal(0.5, stats.StandardDeviation, 15);
Assert.Equal(0.707106781186548, stats.SampleStandardDeviation, 15);
Assert.Equal(0.471404520791032, stats.RelativeStandardDeviation, 15);
}
[Fact(DisplayName = "WelfordVariance: No infinities")]
public void NoInfinity() {
var stats = new WelfordVariance();
Assert.Throws<ArgumentOutOfRangeException>(delegate {
stats.Add(double.NegativeInfinity);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
stats.Add(double.PositiveInfinity);
});
Assert.Throws<ArgumentOutOfRangeException>(delegate {
stats.Add(double.NaN);
});
}
[Fact(DisplayName = "WelfordVariance: No null collection")]
public void NoNullCollection() {
Assert.Throws<ArgumentNullException>(delegate {
var stats = new WelfordVariance(null);
});
Assert.Throws<ArgumentNullException>(delegate {
var stats = new WelfordVariance();
stats.AddRange(null);
});
}
}
}
| |
namespace Projections
{
partial class EllipsoidPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.m_toolTip = new System.Windows.Forms.ToolTip(this.components);
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.m_setButton = new System.Windows.Forms.Button();
this.m_flatteningTextBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.m_equatorialRadiusTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.m_minorRadiusTextBox = new System.Windows.Forms.TextBox();
this.m_quarterMeridianTextBox = new System.Windows.Forms.TextBox();
this.m_areaTextBox = new System.Windows.Forms.TextBox();
this.m_volumeTextBox = new System.Windows.Forms.TextBox();
this.m_2ndFlatTextBox = new System.Windows.Forms.TextBox();
this.m_3rdFlatTextBox = new System.Windows.Forms.TextBox();
this.m_ecc2TextBox = new System.Windows.Forms.TextBox();
this.m_2ecc2TextBox = new System.Windows.Forms.TextBox();
this.label11 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.m_phiTextBox = new System.Windows.Forms.TextBox();
this.label14 = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.label17 = new System.Windows.Forms.Label();
this.m_parametericLatTextBox = new System.Windows.Forms.TextBox();
this.m_geocentricLatTextBox = new System.Windows.Forms.TextBox();
this.m_rectifyingLatTextBox = new System.Windows.Forms.TextBox();
this.m_authalicLatTextBox = new System.Windows.Forms.TextBox();
this.m_conformalTextBox = new System.Windows.Forms.TextBox();
this.m_isometricLatTextBox = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.m_setButton);
this.groupBox1.Controls.Add(this.m_flatteningTextBox);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.m_equatorialRadiusTextBox);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Location = new System.Drawing.Point(3, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(146, 140);
this.groupBox1.TabIndex = 7;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Ellipsoid Parameters";
//
// m_setButton
//
this.m_setButton.Location = new System.Drawing.Point(12, 107);
this.m_setButton.Name = "m_setButton";
this.m_setButton.Size = new System.Drawing.Size(75, 23);
this.m_setButton.TabIndex = 4;
this.m_setButton.Text = "Set";
this.m_toolTip.SetToolTip(this.m_setButton, "Sets ellipsoid parameters");
this.m_setButton.UseVisualStyleBackColor = true;
this.m_setButton.Click += new System.EventHandler(this.OnSet);
//
// m_flatteningTextBox
//
this.m_flatteningTextBox.Location = new System.Drawing.Point(12, 83);
this.m_flatteningTextBox.Name = "m_flatteningTextBox";
this.m_flatteningTextBox.Size = new System.Drawing.Size(125, 20);
this.m_flatteningTextBox.TabIndex = 3;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 25);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(109, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Equatorial Radius (meters)";
//
// m_equatorialRadiusTextBox
//
this.m_equatorialRadiusTextBox.Location = new System.Drawing.Point(12, 42);
this.m_equatorialRadiusTextBox.Name = "m_equatorialRadiusTextBox";
this.m_equatorialRadiusTextBox.Size = new System.Drawing.Size(125, 20);
this.m_equatorialRadiusTextBox.TabIndex = 2;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 66);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Flattening";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(159, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(69, 13);
this.label3.TabIndex = 8;
this.label3.Text = "Minor Radius";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(159, 34);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(85, 13);
this.label4.TabIndex = 9;
this.label4.Text = "Quarter Meridian";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(159, 60);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(29, 13);
this.label5.TabIndex = 10;
this.label5.Text = "Area";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(159, 86);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(42, 13);
this.label6.TabIndex = 11;
this.label6.Text = "Volume";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(159, 112);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(74, 13);
this.label7.TabIndex = 12;
this.label7.Text = "2nd Flattening";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(159, 138);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(71, 13);
this.label8.TabIndex = 13;
this.label8.Text = "3rd Flattening";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(159, 164);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(74, 13);
this.label9.TabIndex = 14;
this.label9.Text = "Eccentricity^2";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(159, 190);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(94, 13);
this.label10.TabIndex = 15;
this.label10.Text = "2nd eccentricity^2";
//
// m_minorRadiusTextBox
//
this.m_minorRadiusTextBox.Location = new System.Drawing.Point(259, 4);
this.m_minorRadiusTextBox.Name = "m_minorRadiusTextBox";
this.m_minorRadiusTextBox.ReadOnly = true;
this.m_minorRadiusTextBox.Size = new System.Drawing.Size(134, 20);
this.m_minorRadiusTextBox.TabIndex = 16;
//
// m_quarterMeridianTextBox
//
this.m_quarterMeridianTextBox.Location = new System.Drawing.Point(259, 30);
this.m_quarterMeridianTextBox.Name = "m_quarterMeridianTextBox";
this.m_quarterMeridianTextBox.ReadOnly = true;
this.m_quarterMeridianTextBox.Size = new System.Drawing.Size(134, 20);
this.m_quarterMeridianTextBox.TabIndex = 17;
//
// m_areaTextBox
//
this.m_areaTextBox.Location = new System.Drawing.Point(259, 56);
this.m_areaTextBox.Name = "m_areaTextBox";
this.m_areaTextBox.ReadOnly = true;
this.m_areaTextBox.Size = new System.Drawing.Size(134, 20);
this.m_areaTextBox.TabIndex = 18;
//
// m_volumeTextBox
//
this.m_volumeTextBox.Location = new System.Drawing.Point(259, 82);
this.m_volumeTextBox.Name = "m_volumeTextBox";
this.m_volumeTextBox.ReadOnly = true;
this.m_volumeTextBox.Size = new System.Drawing.Size(134, 20);
this.m_volumeTextBox.TabIndex = 19;
//
// m_2ndFlatTextBox
//
this.m_2ndFlatTextBox.Location = new System.Drawing.Point(259, 108);
this.m_2ndFlatTextBox.Name = "m_2ndFlatTextBox";
this.m_2ndFlatTextBox.ReadOnly = true;
this.m_2ndFlatTextBox.Size = new System.Drawing.Size(134, 20);
this.m_2ndFlatTextBox.TabIndex = 20;
//
// m_3rdFlatTextBox
//
this.m_3rdFlatTextBox.Location = new System.Drawing.Point(259, 134);
this.m_3rdFlatTextBox.Name = "m_3rdFlatTextBox";
this.m_3rdFlatTextBox.ReadOnly = true;
this.m_3rdFlatTextBox.Size = new System.Drawing.Size(134, 20);
this.m_3rdFlatTextBox.TabIndex = 21;
//
// m_ecc2TextBox
//
this.m_ecc2TextBox.Location = new System.Drawing.Point(259, 160);
this.m_ecc2TextBox.Name = "m_ecc2TextBox";
this.m_ecc2TextBox.ReadOnly = true;
this.m_ecc2TextBox.Size = new System.Drawing.Size(134, 20);
this.m_ecc2TextBox.TabIndex = 22;
//
// m_2ecc2TextBox
//
this.m_2ecc2TextBox.Location = new System.Drawing.Point(259, 186);
this.m_2ecc2TextBox.Name = "m_2ecc2TextBox";
this.m_2ecc2TextBox.ReadOnly = true;
this.m_2ecc2TextBox.Size = new System.Drawing.Size(134, 20);
this.m_2ecc2TextBox.TabIndex = 23;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(402, 8);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(22, 13);
this.label11.TabIndex = 24;
this.label11.Text = "Phi";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(402, 34);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(98, 13);
this.label12.TabIndex = 25;
this.label12.Text = "Parametric Latitude";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(402, 60);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(100, 13);
this.label13.TabIndex = 26;
this.label13.Text = "Geocentric Latitude";
//
// m_phiTextBox
//
this.m_phiTextBox.Location = new System.Drawing.Point(512, 4);
this.m_phiTextBox.Name = "m_phiTextBox";
this.m_phiTextBox.Size = new System.Drawing.Size(100, 20);
this.m_phiTextBox.TabIndex = 27;
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(402, 86);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(95, 13);
this.label14.TabIndex = 28;
this.label14.Text = "Rectifying Latitude";
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(402, 112);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(86, 13);
this.label15.TabIndex = 29;
this.label15.Text = "Authalic Latitude";
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(402, 138);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(95, 13);
this.label16.TabIndex = 30;
this.label16.Text = "Conformal Latitude";
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(402, 164);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(90, 13);
this.label17.TabIndex = 31;
this.label17.Text = "Isometric Latitude";
//
// m_parametericLatTextBox
//
this.m_parametericLatTextBox.Location = new System.Drawing.Point(512, 30);
this.m_parametericLatTextBox.Name = "m_parametericLatTextBox";
this.m_parametericLatTextBox.ReadOnly = true;
this.m_parametericLatTextBox.Size = new System.Drawing.Size(100, 20);
this.m_parametericLatTextBox.TabIndex = 32;
//
// m_geocentricLatTextBox
//
this.m_geocentricLatTextBox.Location = new System.Drawing.Point(512, 56);
this.m_geocentricLatTextBox.Name = "m_geocentricLatTextBox";
this.m_geocentricLatTextBox.ReadOnly = true;
this.m_geocentricLatTextBox.Size = new System.Drawing.Size(100, 20);
this.m_geocentricLatTextBox.TabIndex = 33;
//
// m_rectifyingLatTextBox
//
this.m_rectifyingLatTextBox.Location = new System.Drawing.Point(512, 82);
this.m_rectifyingLatTextBox.Name = "m_rectifyingLatTextBox";
this.m_rectifyingLatTextBox.ReadOnly = true;
this.m_rectifyingLatTextBox.Size = new System.Drawing.Size(100, 20);
this.m_rectifyingLatTextBox.TabIndex = 34;
//
// m_authalicLatTextBox
//
this.m_authalicLatTextBox.Location = new System.Drawing.Point(512, 108);
this.m_authalicLatTextBox.Name = "m_authalicLatTextBox";
this.m_authalicLatTextBox.ReadOnly = true;
this.m_authalicLatTextBox.Size = new System.Drawing.Size(100, 20);
this.m_authalicLatTextBox.TabIndex = 35;
//
// m_conformalTextBox
//
this.m_conformalTextBox.Location = new System.Drawing.Point(512, 134);
this.m_conformalTextBox.Name = "m_conformalTextBox";
this.m_conformalTextBox.ReadOnly = true;
this.m_conformalTextBox.Size = new System.Drawing.Size(100, 20);
this.m_conformalTextBox.TabIndex = 36;
//
// m_isometricLatTextBox
//
this.m_isometricLatTextBox.Location = new System.Drawing.Point(512, 160);
this.m_isometricLatTextBox.Name = "m_isometricLatTextBox";
this.m_isometricLatTextBox.ReadOnly = true;
this.m_isometricLatTextBox.Size = new System.Drawing.Size(100, 20);
this.m_isometricLatTextBox.TabIndex = 37;
//
// button1
//
this.button1.Location = new System.Drawing.Point(435, 185);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(126, 23);
this.button1.TabIndex = 38;
this.button1.Text = "Calculate Latitudes";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.OnCalculateLatitudes);
//
// button2
//
this.button2.Location = new System.Drawing.Point(18, 150);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 39;
this.button2.Text = "Validate";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.OnValidate);
//
// EllipsoidPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.m_isometricLatTextBox);
this.Controls.Add(this.m_conformalTextBox);
this.Controls.Add(this.m_authalicLatTextBox);
this.Controls.Add(this.m_rectifyingLatTextBox);
this.Controls.Add(this.m_geocentricLatTextBox);
this.Controls.Add(this.m_parametericLatTextBox);
this.Controls.Add(this.label17);
this.Controls.Add(this.label16);
this.Controls.Add(this.label15);
this.Controls.Add(this.label14);
this.Controls.Add(this.m_phiTextBox);
this.Controls.Add(this.label13);
this.Controls.Add(this.label12);
this.Controls.Add(this.label11);
this.Controls.Add(this.m_2ecc2TextBox);
this.Controls.Add(this.m_ecc2TextBox);
this.Controls.Add(this.m_3rdFlatTextBox);
this.Controls.Add(this.m_2ndFlatTextBox);
this.Controls.Add(this.m_volumeTextBox);
this.Controls.Add(this.m_areaTextBox);
this.Controls.Add(this.m_quarterMeridianTextBox);
this.Controls.Add(this.m_minorRadiusTextBox);
this.Controls.Add(this.label10);
this.Controls.Add(this.label9);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.groupBox1);
this.Name = "EllipsoidPanel";
this.Size = new System.Drawing.Size(798, 356);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolTip m_toolTip;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button m_setButton;
private System.Windows.Forms.TextBox m_flatteningTextBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox m_equatorialRadiusTextBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox m_minorRadiusTextBox;
private System.Windows.Forms.TextBox m_quarterMeridianTextBox;
private System.Windows.Forms.TextBox m_areaTextBox;
private System.Windows.Forms.TextBox m_volumeTextBox;
private System.Windows.Forms.TextBox m_2ndFlatTextBox;
private System.Windows.Forms.TextBox m_3rdFlatTextBox;
private System.Windows.Forms.TextBox m_ecc2TextBox;
private System.Windows.Forms.TextBox m_2ecc2TextBox;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.TextBox m_phiTextBox;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.TextBox m_parametericLatTextBox;
private System.Windows.Forms.TextBox m_geocentricLatTextBox;
private System.Windows.Forms.TextBox m_rectifyingLatTextBox;
private System.Windows.Forms.TextBox m_authalicLatTextBox;
private System.Windows.Forms.TextBox m_conformalTextBox;
private System.Windows.Forms.TextBox m_isometricLatTextBox;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
}
}
| |
// $Id$
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace Org.Apache.Etch.Bindings.Csharp.Util
{
/// <summary>
/// Models a url of the form scheme://user:password@host:port/uri;parms?terms#fragment
/// </summary>
public class URL
{
#region MEMBER VARIABLES
private string scheme;
private string user;
private string password;
private string host;
private int? port;
private string uri;
private List<string> parms;
private Dictionary<string, object> terms;
private string fragment;
#endregion
#region CONSTRUCTORS
/// <summary>
/// Constructs a url from a string.
/// </summary>
/// <param name="urlString"></param>
public URL( string urlString )
{
Parse( urlString );
}
/// <summary>
/// Constructs a URL from another URL
/// </summary>
/// <param name="other"></param>
public URL( URL other )
{
scheme = other.scheme;
user = other.user;
password = other.password;
host = other.host;
port = other.port;
uri = other.uri;
parms = CopyList( other.parms );
terms = CopyTerms( other.terms );
fragment = other.fragment;
}
/// <summary>
/// Constructs an empty URL
/// </summary>
public URL()
{
// nothing to do.
}
#endregion
private void Parse( string s )
{
// s is scheme:[//[user[:password]@]host[:port]/]uri[;params][?terms][#fragment]
string[] x = StringUtil.LeftSplit( s, ':' );
if ( x == null )
throw new ArgumentNullException( "missing scheme" );
Scheme = Unescape( x[ 0 ] );
s = x[ 1 ];
// s is [//[user[:password]@]host[:port]/]uri[;params][?terms][#fragment]
x = StringUtil.LeftSplit( s, '#' );
if ( x!=null )
{
Fragment = Unescape( x[ 1 ] );
s = x[ 0 ];
}
// s is [//[user[:password]@]host[:port]/]uri[;params][?terms]
x = StringUtil.LeftSplit( s, '?' );
if ( x != null )
{
ParseTerms( x[ 1 ] );
s = x[ 0 ];
}
// s is [//[user[:password]@]host[:port]/]uri[;params]
x = StringUtil.LeftSplit( s, ';' );
if ( x != null )
{
ParseParams( x[ 1 ] );
s = x[ 0 ];
}
// s is [//[user[:password]@]host[:port]/]uri
if ( s.StartsWith( "//" ) )
{
s = s.Substring( 2 );
// s is [user[:password]@]host[:port]/uri
x = StringUtil.LeftSplit( s, '/' );
if ( x != null )
{
// s is [user[:password]@]host[:port]/uri
ParseHost( x[ 0 ] );
s = x[ 1 ];
}
else
{
// s is [user[:password]@]host[:port]
ParseHost( s );
s = "";
}
}
Uri = Unescape( s );
}
private void ParseHost( string s )
{
// s is [user[:password]@]host[:port]
string[] x = StringUtil.LeftSplit( s, '@' );
if ( x != null )
{
ParseUserPassword( x[ 0 ] );
ParseHostPort( x[ 1 ] );
}
else
{
ParseHostPort( s );
}
}
private void ParseUserPassword( string s )
{
// s is user[:password]
string[] x = StringUtil.LeftSplit( s, ':' );
if ( x != null )
{
User = Unescape( x[ 0 ] );
Password = Unescape( x[ 1 ] );
}
else
{
User = Unescape( s );
}
}
private void ParseHostPort( string s )
{
// s is host[:port]
string[] x = StringUtil.LeftSplit( s, ':' );
if ( x != null )
{
Host = Unescape( x[ 0 ] );
string p = Unescape(x[1]);
CheckNotInteger("port", p);
Port = int.Parse(p);
}
else
{
Host = Unescape( s );
}
}
private void ParseParams( string s )
{
// s is param[;param]*
if ( s.Length == 0 )
return;
EnsureParams();
string[] x;
while ( ( x = StringUtil.LeftSplit( s, ';' ) ) != null )
{
AddParam( Unescape( x[ 0 ] ) );
s = x[ 1 ];
}
AddParam( Unescape( s ) );
}
private void ParseTerms( string s )
{
// s is term[&term]*
if ( s.Length == 0 )
return;
string[] x;
while ( ( x = StringUtil.LeftSplit( s, '&' ) ) != null )
{
ParseTerm( x[ 0 ] );
s = x[ 1 ];
}
ParseTerm( s );
}
private void ParseTerm( string s )
{
// s is name[=value]
if ( s.Length == 0 )
return;
EnsureTerms();
string[] x = StringUtil.LeftSplit( s, '=' );
if ( x != null )
AddTerm( Unescape( x[ 0 ] ), Unescape( x[ 1 ] ) );
else
AddTerm( Unescape( s ), "" );
}
#region SCHEME
/// <summary>
/// Gets and Sets the scheme.
/// Return the scheme which may be null but not blank.
/// </summary>
public string Scheme
{
get
{
return scheme;
}
set
{
CheckNotBlank( "scheme", value );
scheme = value;
}
}
/// <summary>
/// Tests the scheme for a match. The schemes are case-insensitive.
/// </summary>
/// <param name="testScheme">a scheme to test against.</param>
/// <returns>true if the schemes match, false otherwise.</returns>
public bool IsScheme( string testScheme )
{
return testScheme.Equals( scheme, StringComparison.CurrentCultureIgnoreCase );
}
#endregion
#region USER
public string User
{
get
{
return user;
}
set
{
CheckNotBlank( "user", value );
user = value;
}
}
#endregion
#region PASSWORD
public string Password
{
get
{
return password;
}
set
{
//CheckNotBlank( "password", value );
password = value;
}
}
#endregion
#region HOST
public string Host
{
get
{
return host;
}
set
{
CheckNotBlank( "host", value );
host = value;
}
}
#endregion
#region PORT
public int? Port
{
get
{
return port;
}
set
{
if ( value != null && value < 0 || value > 65535 )
throw new ArgumentOutOfRangeException( "port < 0 || port > 65535 " );
port = value;
}
}
public bool HasPort()
{
return port != null;
}
#endregion
#region URI
public string Uri
{
get
{
return uri;
}
set
{
uri = value;
}
}
#endregion
#region PARAMS
/// <summary>
///
/// </summary>
/// <returns>true if there is atleast one param</returns>
public bool HasParams()
{
return ( ( parms!=null ) && ( parms.Count > 0 ) );
}
/// <summary>
/// Fetches the first param found which starts with the given prefix. The
/// search order is not specified, and the params are not maintained in any
/// specific order.
/// </summary>
/// <param name="prefix">the prefix of the param to fetch (e.g., "transport=").</param>
/// <returns>the param which starts with the specified prefix.</returns>
///
public string GetParam( string prefix )
{
CheckNotNull( prefix, "prefix == null");
if (parms == null)
return null;
foreach (string p in parms)
if (p.StartsWith(prefix))
return p;
return null;
}
/// <summary>
///
/// </summary>
/// <returns>an iterator over all the params. The params are strings, generally
/// of the form "transport=tcp". But they can be anything you like, really.
/// The iterator might be empty.</returns>
///
public string[] GetParams()
{
if ( parms == null )
return new string[] {};
return parms.ToArray();
}
/// <summary>
/// Adds a param to the set of params for this url. Only the set of unique
/// params is maintained. Duplicate param values are suppressed.
/// </summary>
/// <param name="param">a param (e.g., "transport=tcp" or "01831864574898475").</param>
///
public void AddParam( string param )
{
CheckNotNull(param, "param == null");
EnsureParams();
parms.Add( param );
}
/// <summary>
/// Removes the first param found which starts with the given prefix. The
/// search order is not specified, and the params are not maintained in any
/// specific order.
///
/// </summary>
/// <param name="prefix">the prefix of the param to remove (e.g., "transport=").</param>
/// <returns>the param removed.</returns>
///
public string RemoveParam( string prefix )
{
CheckNotNull(prefix, "prefix == null");
if ( parms == null )
return null;
foreach ( string p in GetParams() )
{
if ( p.StartsWith( prefix ) )
{
parms.Remove( p );
return p;
}
}
return null;
}
/// <summary>
/// Clear all params
/// </summary>
public void ClearParams()
{
if ( parms != null )
parms.Clear();
}
public void EnsureParams()
{
if ( parms == null )
parms = new List<string>();
}
#endregion
#region QUERY TERMS
/// <summary>
///
/// </summary>
/// <returns>true if there is at least one query term. Query terms
/// are of the form name=value</returns>
public bool HasTerms()
{
return terms != null && terms.Count > 0;
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns>true if there is at least one query term with the specified
/// name</returns>
public bool HasTerm( string name )
{
CheckName(name);
if ( terms == null )
return false;
return terms.ContainsKey( name );
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns>if there is a query term with the specified value.</returns>
public bool HasTerm( string name, string value )
{
CheckName(name);
if ( terms == null )
return false;
if (value == null)
return HasTerm(name);
object obj;
if (!terms.TryGetValue(name, out obj))
return false;
if ( obj is List<string> )
return ( ( List<string> ) obj ).Contains( value );
return obj.Equals( value );
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns>if there is a query term with the specified value.</returns>
public bool HasTerm( string name, int? value )
{
return HasTerm( name, ToString(value) );
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns>if there is a query term with the specified value.</returns>
public bool HasTerm(string name, double? value)
{
return HasTerm(name, ToString(value));
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns>if there is a query term with the specified value.</returns>
public bool HasTerm(string name, bool? value)
{
return HasTerm(name, ToString(value));
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns>true if the query term specified by name has multiple values.</returns>
public bool HasMultipleValues(string name)
{
CheckName(name);
if ( terms == null )
return false;
object obj;
if (!terms.TryGetValue(name, out obj))
return false;
if ( obj is List<string> )
return ( ( List<string> ) obj ).Count > 1;
return false;
}
/// <summary>
/// Gets the value of the specified query term.
/// </summary>
/// <param name="name"></param>
/// <returns>the value of the specified term, or null if not found.</returns>
public string GetTerm(string name)
{
CheckName(name);
if (terms == null)
return null;
object obj;
if (!terms.TryGetValue(name, out obj))
return null;
if (obj is List<string>)
{
IEnumerator<string> i = ((List<string>)obj).GetEnumerator();
if (!i.MoveNext())
return null;
string v = i.Current;
if (i.MoveNext())
throw new Exception(string.Format("term {0} has multiple values", name));
return v;
}
return (string)obj;
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="defaultValue"></param>
/// <returns>the value of the specified term, or defaultValue if not found.</returns>
public string GetTerm( string name, string defaultValue )
{
string value = GetTerm( name );
if ( value == null )
return defaultValue;
return value;
}
/// <summary>
/// Gets the integer value of the specified query term.
/// </summary>
/// <param name="name"></param>
/// <returns>the integer value, or null if not found.</returns>
///
public int? GetIntegerTerm(string name)
{
string s = GetTerm(name);
if (s == null)
return null;
return int.Parse(s);
}
/// <summary>
/// Gets the integer value of the specified query term.
/// </summary>
/// <param name="name"></param>
/// <param name="defaultValue">the value to return if the term is not found.</param>
/// <returns>the integer value, or defaultValue if not found.</returns>
/// <see cref="GetTerm( string )"/>
///
public int GetIntegerTerm(string name, int defaultValue)
{
int? v = GetIntegerTerm(name);
if (v == null)
return defaultValue;
return v.Value;
}
/// <summary>
/// Gets the double value of the specified query term.
/// </summary>
/// <param name="name"></param>
/// <returns>the double value, or null if not found.</returns>
///
public double? GetDoubleTerm(string name)
{
string s = GetTerm(name);
if (s == null)
return null;
return double.Parse(s);
}
/// <summary>
/// Gets the double value of the specified query term.
/// </summary>
/// <param name="name"></param>
/// <param name="defaultValue">the value to return if the term is not found.</param>
/// <returns>the double value, or defaultValue if not found.</returns>
/// <see cref="GetTerm( string )"/>
///
public double GetDoubleTerm(string name, double defaultValue)
{
double? v = GetDoubleTerm(name);
if (v == null)
return defaultValue;
return v.Value;
}
/// <summary>
/// Gets the boolean value of the specified query term.
/// </summary>
/// <param name="name"></param>
/// <returns>the boolean value, or null if not found.</returns>
/// <see cref="GetTerm(string)"/>
public bool? GetBooleanTerm(string name)
{
string s = GetTerm(name);
if (s == null)
return null;
return s.Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// Gets the bool value of the specified query term.
/// </summary>
/// <param name="name"></param>
/// <param name="defaultValue">the value to return if the term is not found.</param>
/// <returns>the bool value, or defaultValue if not found.</returns>
/// <see cref="GetTerm( string )"/>
///
public bool GetBooleanTerm(string name, bool defaultValue)
{
bool? v = GetBooleanTerm(name);
if (v == null)
return defaultValue;
return v.Value;
}
/// <summary>
/// Gets the values of the specified query term.
/// </summary>
/// <param name="name"></param>
/// <returns>an iterator over the string values of the query term. May be empty.</returns>
public string[] GetTerms( string name )
{
CheckName(name);
if ( terms == null )
return new string[] {};
object obj;
if (!terms.TryGetValue(name, out obj))
return new string[] { };
if ( obj is List<string> )
return ( ( List<string> ) obj ).ToArray();
return new string[] { (string)obj };
}
/// <summary>
/// Gets the names of the query terms.
/// </summary>
/// <returns>an iterator over the string names.</returns>
public string[] GetTermNames()
{
if ( terms == null )
return new string[] { };
return ToArray(terms.Keys);
}
/// <summary>
/// Adds the specified query term to the set of query terms. Duplicate
/// name/value pairs are suppressed.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void AddTerm(string name, string value)
{
CheckName(name);
if (value == null)
return;
EnsureTerms();
object obj;
if (!terms.TryGetValue(name, out obj))
{
terms.Add( name, value );
return;
}
if ( obj is List<string> )
{
List<string> values = (List<string>)obj;
if (!values.Contains(value))
values.Add(value);
return;
}
// obj is not a list but we need one, so replace obj in terms with a
// list, then add value to the list.
List<string> nvalues = new List<string>();
terms[name] = nvalues;
nvalues.Add( ( string ) obj );
nvalues.Add( value );
}
/// <summary>
/// Adds the specified query term to the set of query terms. Duplicate
/// name/value pairs are suppressed.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void AddTerm( string name, int? value )
{
AddTerm(name, ToString(value));
}
/// <summary>
/// Adds the specified query term to the set of query terms. Duplicate
/// name/value pairs are suppressed.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void AddTerm(string name, double? value)
{
AddTerm(name, ToString(value));
}
/// <summary>
/// Adds the specified query term to the set of query terms. Duplicate
/// name/value pairs are suppressed.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void AddTerm(string name, bool? value)
{
AddTerm(name, ToString(value));
}
/// <summary>
/// Removes all the values associated with the specified query term.
/// </summary>
/// <param name="name"></param>
/// <returns>true if something was removed, false otherwise.</returns>
public bool RemoveTerm( string name )
{
CheckName(name);
if (terms == null)
return false;
return terms.Remove(name);
}
/// <summary>
/// Removes the specified name/value pair from the set of query terms.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns>true if the name/value pair was found and removed.</returns>
///
public bool RemoveTerm( string name, string value )
{
CheckName(name);
if ( terms == null )
return false;
if (value == null)
return RemoveTerm(name);
object obj;
if (!terms.TryGetValue(name, out obj))
return false;
if ( obj is List<string> )
{
List<string> x = ( List<string> ) obj;
bool ok = x.Remove( value );
if (x.Count == 0)
terms.Remove(name);
return ok;
}
if (obj.Equals(value))
{
terms.Remove(name);
return true;
}
return false;
}
public Boolean RemoveTerm(string name, int? value)
{
return RemoveTerm(name, ToString(value));
}
public Boolean RemoveTerm(string name, double? value)
{
return RemoveTerm(name, ToString(value));
}
public Boolean RemoveTerm(string name, bool? value)
{
return RemoveTerm(name, ToString(value));
}
/// <summary>
/// Removes all query terms
/// </summary>
public void ClearTerms()
{
if ( terms != null )
terms.Clear();
}
private void EnsureTerms()
{
if ( terms == null )
terms = new Dictionary<string, object>();
}
#endregion
#region FRAGMENT
public string Fragment
{
get
{
return fragment;
}
set
{
CheckNotBlank( "fragment", value );
fragment = value;
}
}
#endregion
#region UTIL
public override string ToString()
{
StringBuilder sb = new StringBuilder();
Escape( sb, scheme );
sb.Append( ':' );
if ( host != null )
{
sb.Append( "//" );
if ( user != null )
{
Escape( sb, user );
if ( password != null )
{
sb.Append( ':' );
Escape( sb, password );
}
sb.Append( '@' );
}
Escape( sb, host );
if ( port != null )
{
sb.Append( ':' );
sb.Append( port );
}
sb.Append( '/' );
}
if ( uri != null )
Escape( sb, uri );
if ( HasParams() )
ParamsToString( sb );
if ( HasTerms() )
TermsToString( sb );
if ( fragment != null )
{
sb.Append( '#' );
Escape( sb, fragment );
}
return sb.ToString();
}
public override int GetHashCode()
{
int code = 23547853;
code ^= hc( scheme );
code ^= hc( user );
code ^= hc( password );
code ^= hc( host );
code ^= hc( port );
code ^= hc( uri );
code ^= hc( parms );
code ^= hc( terms );
code ^= hc( fragment );
return code;
}
private int hc( Dictionary<string,object> m )
{
return m != null ? m.GetHashCode() : 793;
}
private int hc( List<string> s )
{
return s != null ? s.GetHashCode() : 161;
}
private int hc( int? i )
{
return i != null ? i.GetHashCode() : 59;
}
private int hc( string s )
{
return s != null ? s.GetHashCode() : 91;
}
public override bool Equals( object obj )
{
if ( obj == this )
return true;
if (obj == null)
return false;
if (obj.GetType() != typeof(URL))
return false;
URL other = ( URL ) obj;
if ( !StringUtil.EqIgnoreCase(scheme, other.scheme) )
return false;
if (!StringUtil.Eq(user, other.user))
return false;
if (!StringUtil.Eq(password, other.password))
return false;
if (!StringUtil.Eq(host, other.host))
return false;
if (!Eq(port, other.port))
return false;
if (!StringUtil.Eq(uri, other.uri))
return false;
if ( !Eq( parms, other.parms ) )
return false;
if ( !Eq( terms, other.terms ) )
return false;
if (!StringUtil.Eq(fragment, other.fragment))
return false;
return true;
}
private static bool Eq(object a, object b)
{
if (ReferenceEquals(a, b))
return true;
if (a == null || b == null)
return false;
return a.Equals(b);
}
private void ParamsToString( StringBuilder sb )
{
foreach (string param in GetParams())
{
sb.Append( ';' );
Escape( sb, param );
}
}
private void TermsToString( StringBuilder sb )
{
char sep = '?';
foreach (string name in GetTermNames())
{
foreach (string value in GetTerms(name))
{
sb.Append(sep);
Escape(sb, name);
sb.Append('=');
Escape(sb, value);
sep = '&';
}
}
}
/// <summary>
/// Dumps URL contents for easy viewing
/// </summary>
public void Dump()
{
Console.WriteLine( "---------------" );
Console.WriteLine( "scheme = "+scheme );
Console.WriteLine( "user = "+user );
Console.WriteLine( "password = "+password );
Console.WriteLine( "host = "+host );
Console.WriteLine( "port = "+port );
Console.WriteLine( "uri = "+uri );
Console.WriteLine( "params = "+parms );
Console.WriteLine( "terms = "+terms );
Console.WriteLine( "fragment = "+fragment );
}
private static void Escape( StringBuilder sb, string s )
{
if (s == null)
{
sb.Append("null");
return;
}
CharIterator i = new CharIterator( s );
while ( i.MoveNext() )
{
char c = i.Current;
if ( IsEscaped( c ) )
{
sb.Append( '%' );
sb.Append( StringUtil.ToHex( ( c >> 4 )& 15 ) );
sb.Append( StringUtil.ToHex( c & 15 ) );
}
else if ( c == ' ' )
{
sb.Append( '+' );
}
else
{
sb.Append( c );
}
}
}
private static bool IsEscaped( char c )
{
if ( c >= '0' && c <= '9' )
return false;
if ( c >= 'A' && c <= 'Z' )
return false;
if ( c >= 'a' && c <= 'z' )
return false;
if ( c == ' ' )
return false;
if ( c == ',' )
return false;
if ( c == '.' )
return false;
if ( c == '/' )
return false;
if ( c == '!' )
return false;
if ( c == '$' )
return false;
if ( c == '^' )
return false;
if ( c == '*' )
return false;
if ( c == '(' )
return false;
if ( c == ')' )
return false;
if ( c == '_' )
return false;
if ( c == '-' )
return false;
if ( c == '{' )
return false;
if ( c == '}' )
return false;
if ( c == '[' )
return false;
if ( c == ']' )
return false;
if ( c == '|' )
return false;
if ( c == '\\' )
return false;
return true;
}
private static string Unescape( string s )
{
StringBuilder sb = new StringBuilder();
CharIterator i = new CharIterator( s );
while ( i.MoveNext() )
{
char c = i.Current;
if ( c == '%')
{
i.MoveNext();
char c1 = i.Current;
i.MoveNext();
char c2 = i.Current;
sb.Append( ( char ) ( ( StringUtil.FromHex( c1 ) << 4 ) | StringUtil.FromHex( c2 ) ) );
}
else if ( c == '+' )
{
sb.Append( ' ' );
}
else
{
sb.Append( c );
}
}
return sb.ToString();
}
private static void CheckName(string name)
{
if (name == null || name.Length == 0)
throw new ArgumentException("name null or empty");
}
private static string ToString(object value)
{
return value != null ? value.ToString() : null;
}
private static string[] ToArray(Dictionary<string, object>.KeyCollection keyCollection)
{
string[] a = new string[keyCollection.Count];
keyCollection.CopyTo(a, 0);
return a;
}
private void CheckNotNull(string value, string msg)
{
if (value == null)
throw new NullReferenceException(msg);
}
private static void CheckNotBlank( string name, string value )
{
if ( value != null && value.Length == 0 )
throw new ArgumentException( name + " is blank" );
}
private static void CheckNotInteger(string name, string value)
{
CheckNotBlank(name, value);
try
{
int.Parse(value);
}
catch (FormatException)
{
throw new ArgumentException(name + " is not integer");
}
}
private static List<string> CopyList( List<string> parms )
{
// just goes one level deep.
if (parms == null)
return null;
return new List<string>(parms);
}
private static Dictionary<string, object> CopyTerms( Dictionary<string, object> terms )
{
if ( terms == null )
return null;
Dictionary<string, object> nterms = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> me in terms)
{
string name = me.Key;
object value = me.Value;
if (value is List<string>)
value = CopyList((List<string>) value);
nterms.Add(name, value);
}
return nterms;
}
#endregion
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL 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.
For additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Data;
using System.Collections;
namespace fyiReporting.Data
{
/// <summary>
/// iTunesCommand represents the command. The user is allowed to specify the table needed.
/// </summary>
public class iTunesCommand : IDbCommand
{
iTunesConnection _xc; // connection we're running under
string _cmd; // command to execute
// parsed constituents of the command
string _Table; // table requested
DataParameterCollection _Parameters = new DataParameterCollection();
public iTunesCommand(iTunesConnection conn)
{
_xc = conn;
}
internal string Table
{
get
{
IDbDataParameter dp= _Parameters["Table"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Table"] as IDbDataParameter;
// Then check to see if the Table value is a parameter?
if (dp == null)
dp = _Parameters[_Table] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _Table; // don't pass null; pass existing value
return _Table; // the value must be a constant
}
set {_Table = value;}
}
#region IDbCommand Members
public void Cancel()
{
throw new NotImplementedException("Cancel not implemented");
}
public void Prepare()
{
return; // Prepare is a noop
}
public System.Data.CommandType CommandType
{
get
{
throw new NotImplementedException("CommandType not implemented");
}
set
{
throw new NotImplementedException("CommandType not implemented");
}
}
public IDataReader ExecuteReader(System.Data.CommandBehavior behavior)
{
if (!(behavior == CommandBehavior.SingleResult ||
behavior == CommandBehavior.SchemaOnly))
throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only.");
return new iTunesDataReader(behavior, _xc, this);
}
IDataReader System.Data.IDbCommand.ExecuteReader()
{
return ExecuteReader(System.Data.CommandBehavior.SingleResult);
}
public object ExecuteScalar()
{
throw new NotImplementedException("ExecuteScalar not implemented");
}
public int ExecuteNonQuery()
{
throw new NotImplementedException("ExecuteNonQuery not implemented");
}
public int CommandTimeout
{
get
{
return 0;
}
set
{
throw new NotImplementedException("CommandTimeout not implemented");
}
}
public IDbDataParameter CreateParameter()
{
return new XmlDataParameter();
}
public IDbConnection Connection
{
get
{
return this._xc;
}
set
{
throw new NotImplementedException("Setting Connection not implemented");
}
}
public System.Data.UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
set
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
}
public string CommandText
{
get
{
return this._cmd;
}
set
{
// Parse the command string for keyword value pairs separated by ';'
string[] args = value.Split(';');
string table=null;
foreach(string arg in args)
{
string[] param = arg.Trim().Split('=');
if (param == null || param.Length != 2)
continue;
string key = param[0].Trim().ToLower();
string val = param[1];
switch (key)
{
case "table":
table = val;
break;
default:
throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0]));
}
}
// User must specify both the url and the RowsXPath
if (table == null)
table = "Tracks";
_cmd = value;
_Table = table;
}
}
public IDataParameterCollection Parameters
{
get
{
return _Parameters;
}
}
public IDbTransaction Transaction
{
get
{
throw new NotImplementedException("Transaction not implemented");
}
set
{
throw new NotImplementedException("Transaction not implemented");
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose of
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
/*
Detonator - A parametric explosion system for Unity
Created by Ben Throop in August 2009 for the Unity Summer of Code
Simplest use case:
1) Use a prefab
OR
1) Attach a Detonator to a GameObject, either through code or the Unity UI
2) Either set the Detonator's ExplodeOnStart = true or call Explode() yourself when the time is right
3) View explosion :)
Medium Complexity Use Case:
1) Attach a Detonator as above
2) Change parameters, add your own materials, etc
3) Explode()
4) View Explosion
Super Fun Use Case:
1) Attach a Detonator as above
2) Drag one or more DetonatorComponents to that same GameObject
3) Tweak those parameters
4) Explode()
5) View Explosion
Better documentation is included as a PDF with this package, or is available online. Check the Unity site for a link
or visit my site, listed below.
Ben Throop
http://variancetheory.com
@benimaru
*/
/*
All pieces of Detonator inherit from this.
*/
public abstract class DetonatorComponent : MonoBehaviour
{
public bool on = true;
public bool detonatorControlled = true;
[HideInInspector]
public float startSize = 1f;
public float size = 1f;
public float explodeDelayMin = 0f;
public float explodeDelayMax = 0f;
[HideInInspector]
public float startDuration = 2f;
public float duration = 2f;
[HideInInspector]
public float timeScale = 1f;
[HideInInspector]
public float startDetail = 1f;
public float detail = 1f;
[HideInInspector]
public Color startColor = Color.white;
public Color color = Color.white;
[HideInInspector]
public Vector3 startLocalPosition = Vector3.zero;
public Vector3 localPosition = Vector3.zero;
public Vector3 force = Vector3.zero;
public abstract void Explode();
//The main Detonator calls this instead of using Awake() or Start() on subcomponents
//which ensures it happens when we want.
public abstract void Init();
public float detailThreshold;
/*
This exists because Detonator makes relative changes
to set values once the game is running, so we need to store their beginning
values somewhere to calculate against. An improved design could probably
avoid this.
*/
public void SetStartValues()
{
startSize = size;
startDuration = duration;
startDetail = detail;
startColor = color;
startLocalPosition = localPosition;
}
//implement functions to find the Detonator on this GO and get materials if they are defined
public Detonator MyDetonator()
{
Detonator _myDetonator = GetComponent("Detonator") as Detonator;
return _myDetonator;
}
}
[AddComponentMenu("Detonator/Detonator")]
public class Detonator : MonoBehaviour {
private static float _baseSize = 30f;
private static Color _baseColor = new Color(1f, .423f, 0f, .5f);
private static float _baseDuration = 3f;
/*
_baseSize reflects the size that DetonatorComponents at size 1 match. Yes, this is really big (30m)
size below is the default Detonator size, which is more reasonable for typical useage.
It wasn't my intention for them to be different, and I may change that, but for now, that's how it is.
*/
public float size = 10f;
public Color color = Detonator._baseColor;
public bool explodeOnStart = true;
public float duration = Detonator._baseDuration;
public float detail = 1f;
public float destroyTime = 7f; //sorry this is not auto calculated... yet.
public Material fireballAMaterial;
public Material fireballBMaterial;
public Material smokeAMaterial;
public Material smokeBMaterial;
public Material shockwaveMaterial;
public Material sparksMaterial;
public Material glowMaterial;
public Material heatwaveMaterial;
private Component[] components;
private DetonatorFireball _fireball;
private DetonatorSparks _sparks;
private DetonatorShockwave _shockwave;
private DetonatorSmoke _smoke;
private DetonatorGlow _glow;
private DetonatorLight _light;
private DetonatorForce _force;
private DetonatorHeatwave _heatwave;
public bool autoCreateFireball = true;
public bool autoCreateSparks = true;
public bool autoCreateShockwave = true;
public bool autoCreateSmoke = true;
public bool autoCreateGlow = true;
public bool autoCreateLight = true;
public bool autoCreateForce = true;
public bool autoCreateHeatwave = false;
void Awake()
{
FillDefaultMaterials();
components = this.GetComponents(typeof(DetonatorComponent));
foreach (DetonatorComponent dc in components)
{
if (dc is DetonatorFireball)
{
_fireball = dc as DetonatorFireball;
}
if (dc is DetonatorSparks)
{
_sparks = dc as DetonatorSparks;
}
if (dc is DetonatorShockwave)
{
_shockwave = dc as DetonatorShockwave;
}
if (dc is DetonatorSmoke)
{
_smoke = dc as DetonatorSmoke;
}
if (dc is DetonatorGlow)
{
_glow = dc as DetonatorGlow;
}
if (dc is DetonatorLight)
{
_light = dc as DetonatorLight;
}
if (dc is DetonatorForce)
{
_force = dc as DetonatorForce;
}
if (dc is DetonatorHeatwave)
{
_heatwave = dc as DetonatorHeatwave;
}
}
if (!_fireball && autoCreateFireball)
{
_fireball = gameObject.AddComponent("DetonatorFireball") as DetonatorFireball;
_fireball.Reset();
}
if (!_smoke && autoCreateSmoke)
{
_smoke = gameObject.AddComponent("DetonatorSmoke") as DetonatorSmoke;
_smoke.Reset();
}
if (!_sparks && autoCreateSparks)
{
_sparks = gameObject.AddComponent("DetonatorSparks") as DetonatorSparks;
_sparks.Reset();
}
if (!_shockwave && autoCreateShockwave)
{
_shockwave = gameObject.AddComponent("DetonatorShockwave") as DetonatorShockwave;
_shockwave.Reset();
}
if (!_glow && autoCreateGlow)
{
_glow = gameObject.AddComponent("DetonatorGlow") as DetonatorGlow;
_glow.Reset();
}
if (!_light && autoCreateLight)
{
_light = gameObject.AddComponent("DetonatorLight") as DetonatorLight;
_light.Reset();
}
if (!_force && autoCreateForce)
{
_force = gameObject.AddComponent("DetonatorForce") as DetonatorForce;
_force.Reset();
}
if (!_heatwave && autoCreateHeatwave && SystemInfo.supportsImageEffects)
{
_heatwave = gameObject.AddComponent("DetonatorHeatwave") as DetonatorHeatwave;
_heatwave.Reset();
}
components = this.GetComponents(typeof(DetonatorComponent));
}
void FillDefaultMaterials()
{
if (!fireballAMaterial) fireballAMaterial = DefaultFireballAMaterial();
if (!fireballBMaterial) fireballBMaterial = DefaultFireballBMaterial();
if (!smokeAMaterial) smokeAMaterial = DefaultSmokeAMaterial();
if (!smokeBMaterial) smokeBMaterial = DefaultSmokeBMaterial();
if (!shockwaveMaterial) shockwaveMaterial = DefaultShockwaveMaterial();
if (!sparksMaterial) sparksMaterial = DefaultSparksMaterial();
if (!glowMaterial) glowMaterial = DefaultGlowMaterial();
if (!heatwaveMaterial) heatwaveMaterial = DefaultHeatwaveMaterial();
}
void Start()
{
if (explodeOnStart)
{
UpdateComponents();
this.Explode();
}
}
private float _lastExplosionTime = 1000f;
void Update ()
{
if (destroyTime > 0f)
{
if (_lastExplosionTime + destroyTime <= Time.time)
{
Destroy(gameObject);
}
}
}
private bool _firstComponentUpdate = true;
void UpdateComponents()
{
if (_firstComponentUpdate)
{
foreach (DetonatorComponent component in components)
{
component.Init();
component.SetStartValues();
}
_firstComponentUpdate = false;
}
if (!_firstComponentUpdate)
{
foreach (DetonatorComponent component in components)
{
if (component.detonatorControlled)
{
component.size = component.startSize * (size / _baseSize);
component.timeScale = (duration / _baseDuration);
component.detail = component.startDetail * detail;
//take the alpha of detonator color and consider it a weight - 1=use all detonator, 0=use all components
component.color = Color.Lerp(component.startColor, color, color.a);
}
}
}
}
private Component[] _subDetonators;
public void Explode()
{
_lastExplosionTime = Time.time;
foreach (DetonatorComponent component in components)
{
UpdateComponents();
component.Explode();
}
}
public void Reset()
{
size = _baseSize;
color = _baseColor;
duration = _baseDuration;
FillDefaultMaterials();
}
//Default Materials
//The statics are so that even if there are multiple Detonators in the world, they
//don't each create their own default materials. Theoretically this will reduce draw calls, but I haven't really
//tested that.
public static Material defaultFireballAMaterial;
public static Material defaultFireballBMaterial;
public static Material defaultSmokeAMaterial;
public static Material defaultSmokeBMaterial;
public static Material defaultShockwaveMaterial;
public static Material defaultSparksMaterial;
public static Material defaultGlowMaterial;
public static Material defaultHeatwaveMaterial;
public static Material DefaultFireballAMaterial()
{
if (defaultFireballAMaterial != null) return defaultFireballAMaterial;
defaultFireballAMaterial = new Material(Shader.Find("Particles/Additive"));
defaultFireballAMaterial.name = "FireballA-Default";
Texture2D tex = Resources.Load("Detonator/Textures/Fireball") as Texture2D;
defaultFireballAMaterial.SetColor("_TintColor", Color.white);
defaultFireballAMaterial.mainTexture = tex;
defaultFireballAMaterial.mainTextureScale = new Vector2(0.5f, 1f);
return defaultFireballAMaterial;
}
public static Material DefaultFireballBMaterial()
{
if (defaultFireballBMaterial != null) return defaultFireballBMaterial;
defaultFireballBMaterial = new Material(Shader.Find("Particles/Additive"));
defaultFireballBMaterial.name = "FireballB-Default";
Texture2D tex = Resources.Load("Detonator/Textures/Fireball") as Texture2D;
defaultFireballBMaterial.SetColor("_TintColor", Color.white);
defaultFireballBMaterial.mainTexture = tex;
defaultFireballBMaterial.mainTextureScale = new Vector2(0.5f, 1f);
defaultFireballBMaterial.mainTextureOffset = new Vector2(0.5f, 0f);
return defaultFireballBMaterial;
}
public static Material DefaultSmokeAMaterial()
{
if (defaultSmokeAMaterial != null) return defaultSmokeAMaterial;
defaultSmokeAMaterial = new Material(Shader.Find("Particles/Alpha Blended"));
defaultSmokeAMaterial.name = "SmokeA-Default";
Texture2D tex = Resources.Load("Detonator/Textures/Smoke") as Texture2D;
defaultSmokeAMaterial.SetColor("_TintColor", Color.white);
defaultSmokeAMaterial.mainTexture = tex;
defaultSmokeAMaterial.mainTextureScale = new Vector2(0.5f, 1f);
return defaultSmokeAMaterial;
}
public static Material DefaultSmokeBMaterial()
{
if (defaultSmokeBMaterial != null) return defaultSmokeBMaterial;
defaultSmokeBMaterial = new Material(Shader.Find("Particles/Alpha Blended"));
defaultSmokeBMaterial.name = "SmokeB-Default";
Texture2D tex = Resources.Load("Detonator/Textures/Smoke") as Texture2D;
defaultSmokeBMaterial.SetColor("_TintColor", Color.white);
defaultSmokeBMaterial.mainTexture = tex;
defaultSmokeBMaterial.mainTextureScale = new Vector2(0.5f, 1f);
defaultSmokeBMaterial.mainTextureOffset = new Vector2(0.5f, 0f);
return defaultSmokeBMaterial;
}
public static Material DefaultSparksMaterial()
{
if (defaultSparksMaterial != null) return defaultSparksMaterial;
defaultSparksMaterial = new Material(Shader.Find("Particles/Additive"));
defaultSparksMaterial.name = "Sparks-Default";
Texture2D tex = Resources.Load("Detonator/Textures/GlowDot") as Texture2D;
defaultSparksMaterial.SetColor("_TintColor", Color.white);
defaultSparksMaterial.mainTexture = tex;
return defaultSparksMaterial;
}
public static Material DefaultShockwaveMaterial()
{
if (defaultShockwaveMaterial != null) return defaultShockwaveMaterial;
defaultShockwaveMaterial = new Material(Shader.Find("Particles/Additive"));
defaultShockwaveMaterial.name = "Shockwave-Default";
Texture2D tex = Resources.Load("Detonator/Textures/Shockwave") as Texture2D;
defaultShockwaveMaterial.SetColor("_TintColor", Color.white);
defaultShockwaveMaterial.mainTexture = tex;
return defaultShockwaveMaterial;
}
public static Material DefaultGlowMaterial()
{
if (defaultGlowMaterial != null) return defaultGlowMaterial;
defaultGlowMaterial = new Material(Shader.Find("Particles/Additive"));
defaultGlowMaterial.name = "Glow-Default";
Texture2D tex = Resources.Load("Detonator/Textures/Glow") as Texture2D;
defaultGlowMaterial.SetColor("_TintColor", Color.white);
defaultGlowMaterial.mainTexture = tex;
return defaultGlowMaterial;
}
public static Material DefaultHeatwaveMaterial()
{
//Unity Pro Only
if (SystemInfo.supportsImageEffects)
{
if (defaultHeatwaveMaterial != null) return defaultHeatwaveMaterial;
defaultHeatwaveMaterial = new Material(Shader.Find("HeatDistort"));
defaultHeatwaveMaterial.name = "Heatwave-Default";
Texture2D tex = Resources.Load("Detonator/Textures/Heatwave") as Texture2D;
defaultHeatwaveMaterial.SetTexture("_BumpMap", tex);
return defaultHeatwaveMaterial;
}
else
{
return null;
}
}
}
| |
/*
* SubSonic - http://subsonicproject.com
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Xml;
namespace SubSonic.Parser
{
/// <summary>
/// Some of this code was initially published on http://www.phdcc.com/xml2json.htm - thanks for your hard work!
/// </summary>
public class XmlToJSONParser
{
/// <summary>
/// XMLs to JSON.
/// </summary>
/// <param name="xmlDoc">The XML doc.</param>
/// <returns></returns>
public static string XmlToJSON(XmlDocument xmlDoc)
{
StringBuilder sbJSON = new StringBuilder();
sbJSON.Append("{ ");
XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true);
sbJSON.Append("}");
return sbJSON.ToString();
}
/// <summary>
/// XmlToJSONnode: Output an XmlElement, possibly as part of a higher array
/// </summary>
/// <param name="sbJSON">The sb JSON.</param>
/// <param name="node">The node.</param>
/// <param name="showNodeName">if set to <c>true</c> [show node name].</param>
private static void XmlToJSONnode(StringBuilder sbJSON, XmlNode node, bool showNodeName)
{
if(showNodeName)
sbJSON.Append(node.Name + ": ");
sbJSON.Append("{");
// Build a sorted list of key-value pairs
// where key is case-sensitive nodeName
// value is an ArrayList of string or XmlElement
// so that we know whether the nodeName is an array or not.
SortedList childNodeNames = new SortedList();
// Add in all node attributes
if(node.Attributes != null)
{
foreach(XmlAttribute attr in node.Attributes)
StoreChildNode(childNodeNames, attr.Name, attr.InnerText);
}
// Add in all nodes
foreach(XmlNode cnode in node.ChildNodes)
{
if(cnode is XmlText)
StoreChildNode(childNodeNames, "value", cnode.InnerText);
else if(cnode is XmlElement)
StoreChildNode(childNodeNames, cnode.Name, cnode);
}
// Now output all stored info
foreach(string childname in childNodeNames.Keys)
{
ArrayList alChild = (ArrayList)childNodeNames[childname];
if(alChild.Count == 1)
OutputNode(childname, alChild[0], sbJSON, true);
else
{
sbJSON.Append(childname + ": [ ");
foreach(object Child in alChild)
OutputNode(childname, Child, sbJSON, false);
sbJSON.Remove(sbJSON.Length - 2, 2);
sbJSON.Append(" ], ");
}
}
sbJSON.Remove(sbJSON.Length - 2, 2);
sbJSON.Append(" }");
}
/// <summary>
/// StoreChildNode: Store data associated with each nodeName
/// so that we know whether the nodeName is an array or not.
/// </summary>
/// <param name="childNodeNames">The child node names.</param>
/// <param name="nodeName">Name of the node.</param>
/// <param name="nodeValue">The node value.</param>
private static void StoreChildNode(IDictionary childNodeNames, string nodeName, object nodeValue)
{
// Pre-process contraction of XmlElement-s
if(nodeValue is XmlElement)
{
// Convert <aa></aa> into "aa":null
// <aa>xx</aa> into "aa":"xx"
XmlNode cnode = (XmlNode)nodeValue;
if(cnode.Attributes.Count == 0)
{
XmlNodeList children = cnode.ChildNodes;
if(children.Count == 0)
nodeValue = null;
else if(children.Count == 1 && (children[0] is XmlText))
nodeValue = ((children[0])).InnerText;
}
}
// Add nodeValue to ArrayList associated with each nodeName
// If nodeName doesn't exist then add it
object oValuesAL = childNodeNames[nodeName];
ArrayList ValuesAL;
if(oValuesAL == null)
{
ValuesAL = new ArrayList();
childNodeNames[nodeName] = ValuesAL;
}
else
ValuesAL = (ArrayList)oValuesAL;
ValuesAL.Add(nodeValue);
}
/// <summary>
/// Outputs the node.
/// </summary>
/// <param name="childname">The childname.</param>
/// <param name="alChild">The al child.</param>
/// <param name="sbJSON">The sb JSON.</param>
/// <param name="showNodeName">if set to <c>true</c> [show node name].</param>
private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName)
{
if(alChild == null)
{
if(showNodeName)
sbJSON.Append(SafeJSON(childname) + ": ");
sbJSON.Append("null");
}
else if(alChild is string)
{
if(showNodeName)
sbJSON.Append(SafeJSON(childname) + ": ");
string sChild = (string)alChild;
sChild = sChild.Trim();
sbJSON.Append(SafeJSON(sChild));
}
else
XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName);
sbJSON.Append(", ");
}
/// <summary>
/// make the json string safe for delivery across the wire
/// </summary>
/// <param name="s">The s.</param>
/// <returns></returns>
public static string SafeJSON(string s)
{
if(String.IsNullOrEmpty(s))
return "\"\"";
int i;
int len = s.Length;
StringBuilder sb = new StringBuilder(len + 4);
string t;
sb.Append('"');
for(i = 0; i < len; i += 1)
{
char c = s[i];
if((c == '\\') || (c == '"') || (c == '>'))
{
sb.Append('\\');
sb.Append(c);
}
else if(c == '\b')
sb.Append("\\b");
else if(c == '\t')
sb.Append("\\t");
else if(c == '\n')
sb.Append("\\n");
else if(c == '\f')
sb.Append("\\f");
else if(c == '\r')
sb.Append("\\r");
else
{
if(c < ' ')
{
//t = "000" + Integer.toHexString(c);
string tmp = new string(c, 1);
t = "000" + int.Parse(tmp, NumberStyles.HexNumber);
sb.Append("\\u" + t.Substring(t.Length - 4));
}
else
sb.Append(c);
}
}
sb.Append('"');
return sb.ToString();
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculus.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using System;
using System.Runtime.InteropServices;
// Internal C# wrapper for OVRPlugin.
internal static class OVRPlugin
{
public static readonly System.Version wrapperVersion = OVRP_1_10_0.version;
private static System.Version _version;
public static System.Version version
{
get {
if (_version == null)
{
try
{
string pluginVersion = OVRP_1_1_0.ovrp_GetVersion();
if (pluginVersion != null)
{
// Truncate unsupported trailing version info for System.Version. Original string is returned if not present.
pluginVersion = pluginVersion.Split('-')[0];
_version = new System.Version(pluginVersion);
}
else
{
_version = _versionZero;
}
}
catch
{
_version = _versionZero;
}
// Unity 5.1.1f3-p3 have OVRPlugin version "0.5.0", which isn't accurate.
if (_version == OVRP_0_5_0.version)
_version = OVRP_0_1_0.version;
if (_version > _versionZero && _version < OVRP_1_3_0.version)
throw new PlatformNotSupportedException("Oculus Utilities version " + wrapperVersion + " is too new for OVRPlugin version " + _version.ToString () + ". Update to the latest version of Unity.");
}
return _version;
}
}
private static System.Version _nativeSDKVersion;
public static System.Version nativeSDKVersion
{
get {
if (_nativeSDKVersion == null)
{
try
{
string sdkVersion = string.Empty;
if (version >= OVRP_1_1_0.version)
sdkVersion = OVRP_1_1_0.ovrp_GetNativeSDKVersion();
else
sdkVersion = _versionZero.ToString();
if (sdkVersion != null)
{
// Truncate unsupported trailing version info for System.Version. Original string is returned if not present.
sdkVersion = sdkVersion.Split('-')[0];
_nativeSDKVersion = new System.Version(sdkVersion);
}
else
{
_nativeSDKVersion = _versionZero;
}
}
catch
{
_nativeSDKVersion = _versionZero;
}
}
return _nativeSDKVersion;
}
}
[StructLayout(LayoutKind.Sequential)]
private struct GUID
{
public int a;
public short b;
public short c;
public byte d0;
public byte d1;
public byte d2;
public byte d3;
public byte d4;
public byte d5;
public byte d6;
public byte d7;
}
public enum Bool
{
False = 0,
True
}
public enum Eye
{
None = -1,
Left = 0,
Right = 1,
Count = 2
}
public enum Tracker
{
None = -1,
Zero = 0,
One = 1,
Two = 2,
Three = 3,
Count,
}
public enum Node
{
None = -1,
EyeLeft = 0,
EyeRight = 1,
EyeCenter = 2,
HandLeft = 3,
HandRight = 4,
TrackerZero = 5,
TrackerOne = 6,
TrackerTwo = 7,
TrackerThree = 8,
Head = 9,
Count,
}
public enum Controller
{
None = 0,
LTouch = 0x00000001,
RTouch = 0x00000002,
Touch = LTouch | RTouch,
Remote = 0x00000004,
Gamepad = 0x00000010,
Touchpad = 0x08000000,
Active = unchecked((int)0x80000000),
All = ~None,
}
public enum TrackingOrigin
{
EyeLevel = 0,
FloorLevel = 1,
Count,
}
public enum RecenterFlags
{
Default = 0,
IgnoreAll = unchecked((int)0x80000000),
Count,
}
public enum BatteryStatus
{
Charging = 0,
Discharging,
Full,
NotCharging,
Unknown,
}
public enum PlatformUI
{
None = -1,
GlobalMenu = 0,
ConfirmQuit,
GlobalMenuTutorial,
}
public enum SystemRegion
{
Unspecified = 0,
Japan,
China,
}
public enum SystemHeadset
{
None = 0,
GearVR_R320, // Note4 Innovator
GearVR_R321, // S6 Innovator
GearVR_R322, // Commercial 1
GearVR_R323, // Commercial 2 (USB Type C)
Rift_DK1 = 0x1000,
Rift_DK2,
Rift_CV1,
}
public enum OverlayShape
{
Quad = 0,
Cylinder = 1,
Cubemap = 2,
}
private const int OverlayShapeFlagShift = 4;
private enum OverlayFlag
{
None = unchecked((int)0x00000000),
OnTop = unchecked((int)0x00000001),
HeadLocked = unchecked((int)0x00000002),
// Using the 5-8 bits for shapes, total 16 potential shapes can be supported 0x000000[0]0 -> 0x000000[F]0
ShapeFlag_Quad = unchecked((int)OverlayShape.Quad << OverlayShapeFlagShift),
ShapeFlag_Cylinder = unchecked((int)OverlayShape.Cylinder << OverlayShapeFlagShift),
ShapeFlag_Cubemap = unchecked((int)OverlayShape.Cubemap << OverlayShapeFlagShift),
ShapeFlagRangeMask = unchecked((int)0xF << OverlayShapeFlagShift),
}
[StructLayout(LayoutKind.Sequential)]
public struct Vector2i
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
public struct Vector2f
{
public float x;
public float y;
}
[StructLayout(LayoutKind.Sequential)]
public struct Vector3f
{
public float x;
public float y;
public float z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Quatf
{
public float x;
public float y;
public float z;
public float w;
}
[StructLayout(LayoutKind.Sequential)]
public struct Posef
{
public Quatf Orientation;
public Vector3f Position;
}
[StructLayout(LayoutKind.Sequential)]
public struct ControllerState
{
public uint ConnectedControllers;
public uint Buttons;
public uint Touches;
public uint NearTouches;
public float LIndexTrigger;
public float RIndexTrigger;
public float LHandTrigger;
public float RHandTrigger;
public Vector2f LThumbstick;
public Vector2f RThumbstick;
}
[StructLayout(LayoutKind.Sequential)]
public struct HapticsBuffer
{
public IntPtr Samples;
public int SamplesCount;
}
[StructLayout(LayoutKind.Sequential)]
public struct HapticsState
{
public int SamplesAvailable;
public int SamplesQueued;
}
[StructLayout(LayoutKind.Sequential)]
public struct HapticsDesc
{
public int SampleRateHz;
public int SampleSizeInBytes;
public int MinimumSafeSamplesQueued;
public int MinimumBufferSamplesCount;
public int OptimalBufferSamplesCount;
public int MaximumBufferSamplesCount;
}
[StructLayout(LayoutKind.Sequential)]
public struct AppPerfFrameStats
{
public int HmdVsyncIndex;
public int AppFrameIndex;
public int AppDroppedFrameCount;
public float AppMotionToPhotonLatency;
public float AppQueueAheadTime;
public float AppCpuElapsedTime;
public float AppGpuElapsedTime;
public int CompositorFrameIndex;
public int CompositorDroppedFrameCount;
public float CompositorLatency;
public float CompositorCpuElapsedTime;
public float CompositorGpuElapsedTime;
public float CompositorCpuStartToGpuEndElapsedTime;
public float CompositorGpuEndToVsyncElapsedTime;
}
public const int AppPerfFrameStatsMaxCount = 5;
[StructLayout(LayoutKind.Sequential)]
public struct AppPerfStats
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=AppPerfFrameStatsMaxCount)]
public AppPerfFrameStats[] FrameStats;
public int FrameStatsCount;
public Bool AnyFrameStatsDropped;
public float AdaptiveGpuPerformanceScale;
}
[StructLayout(LayoutKind.Sequential)]
public struct Sizei
{
public int w;
public int h;
}
[StructLayout(LayoutKind.Sequential)]
public struct Frustumf
{
public float zNear;
public float zFar;
public float fovX;
public float fovY;
}
public enum BoundaryType
{
OuterBoundary = 0x0001,
PlayArea = 0x0100,
}
[StructLayout(LayoutKind.Sequential)]
public struct BoundaryTestResult
{
public Bool IsTriggering;
public float ClosestDistance;
public Vector3f ClosestPoint;
public Vector3f ClosestPointNormal;
}
[StructLayout(LayoutKind.Sequential)]
public struct BoundaryLookAndFeel
{
public Colorf Color;
}
[StructLayout(LayoutKind.Sequential)]
public struct BoundaryGeometry
{
public BoundaryType BoundaryType;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)]
public Vector3f[] Points;
public int PointsCount;
}
[StructLayout(LayoutKind.Sequential)]
public struct Colorf
{
public float r;
public float g;
public float b;
public float a;
}
public static bool initialized
{
get {
return OVRP_1_1_0.ovrp_GetInitialized() == OVRPlugin.Bool.True;
}
}
public static bool chromatic
{
get {
if (version >= OVRP_1_7_0.version)
return OVRP_1_7_0.ovrp_GetAppChromaticCorrection() == OVRPlugin.Bool.True;
#if UNITY_ANDROID && !UNITY_EDITOR
return false;
#else
return true;
#endif
}
set {
if (version >= OVRP_1_7_0.version)
OVRP_1_7_0.ovrp_SetAppChromaticCorrection(ToBool(value));
}
}
public static bool monoscopic
{
get { return OVRP_1_1_0.ovrp_GetAppMonoscopic() == OVRPlugin.Bool.True; }
set { OVRP_1_1_0.ovrp_SetAppMonoscopic(ToBool(value)); }
}
public static bool rotation
{
get { return OVRP_1_1_0.ovrp_GetTrackingOrientationEnabled() == Bool.True; }
set { OVRP_1_1_0.ovrp_SetTrackingOrientationEnabled(ToBool(value)); }
}
public static bool position
{
get { return OVRP_1_1_0.ovrp_GetTrackingPositionEnabled() == Bool.True; }
set { OVRP_1_1_0.ovrp_SetTrackingPositionEnabled(ToBool(value)); }
}
public static bool useIPDInPositionTracking
{
get {
if (version >= OVRP_1_6_0.version)
return OVRP_1_6_0.ovrp_GetTrackingIPDEnabled() == OVRPlugin.Bool.True;
return true;
}
set {
if (version >= OVRP_1_6_0.version)
OVRP_1_6_0.ovrp_SetTrackingIPDEnabled(ToBool(value));
}
}
public static bool positionSupported { get { return OVRP_1_1_0.ovrp_GetTrackingPositionSupported() == Bool.True; } }
public static bool positionTracked { get { return OVRP_1_1_0.ovrp_GetNodePositionTracked(Node.EyeCenter) == Bool.True; } }
public static bool powerSaving { get { return OVRP_1_1_0.ovrp_GetSystemPowerSavingMode() == Bool.True; } }
public static bool hmdPresent { get { return OVRP_1_1_0.ovrp_GetNodePresent(Node.EyeCenter) == Bool.True; } }
public static bool userPresent { get { return OVRP_1_1_0.ovrp_GetUserPresent() == Bool.True; } }
public static bool headphonesPresent { get { return OVRP_1_3_0.ovrp_GetSystemHeadphonesPresent() == OVRPlugin.Bool.True; } }
public static int recommendedMSAALevel
{
get {
if (version >= OVRP_1_6_0.version)
return OVRP_1_6_0.ovrp_GetSystemRecommendedMSAALevel ();
else
return 2;
}
}
public static SystemRegion systemRegion
{
get {
if (version >= OVRP_1_5_0.version)
return OVRP_1_5_0.ovrp_GetSystemRegion();
else
return SystemRegion.Unspecified;
}
}
private static Guid _cachedAudioOutGuid;
private static string _cachedAudioOutString;
public static string audioOutId
{
get
{
try
{
IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioOutId();
if (ptr != IntPtr.Zero)
{
GUID nativeGuid = (GUID)Marshal.PtrToStructure(ptr, typeof(OVRPlugin.GUID));
Guid managedGuid = new Guid(
nativeGuid.a,
nativeGuid.b,
nativeGuid.c,
nativeGuid.d0,
nativeGuid.d1,
nativeGuid.d2,
nativeGuid.d3,
nativeGuid.d4,
nativeGuid.d5,
nativeGuid.d6,
nativeGuid.d7);
if (managedGuid != _cachedAudioOutGuid)
{
_cachedAudioOutGuid = managedGuid;
_cachedAudioOutString = _cachedAudioOutGuid.ToString();
}
return _cachedAudioOutString;
}
}
catch {}
return string.Empty;
}
}
private static Guid _cachedAudioInGuid;
private static string _cachedAudioInString;
public static string audioInId
{
get
{
try
{
IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioInId();
if (ptr != IntPtr.Zero)
{
GUID nativeGuid = (GUID)Marshal.PtrToStructure(ptr, typeof(OVRPlugin.GUID));
Guid managedGuid = new Guid(
nativeGuid.a,
nativeGuid.b,
nativeGuid.c,
nativeGuid.d0,
nativeGuid.d1,
nativeGuid.d2,
nativeGuid.d3,
nativeGuid.d4,
nativeGuid.d5,
nativeGuid.d6,
nativeGuid.d7);
if (managedGuid != _cachedAudioInGuid)
{
_cachedAudioInGuid = managedGuid;
_cachedAudioInString = _cachedAudioInGuid.ToString();
}
return _cachedAudioInString;
}
}
catch {}
return string.Empty;
}
}
public static bool hasVrFocus { get { return OVRP_1_1_0.ovrp_GetAppHasVrFocus() == Bool.True; } }
public static bool shouldQuit { get { return OVRP_1_1_0.ovrp_GetAppShouldQuit() == Bool.True; } }
public static bool shouldRecenter { get { return OVRP_1_1_0.ovrp_GetAppShouldRecenter() == Bool.True; } }
public static string productName { get { return OVRP_1_1_0.ovrp_GetSystemProductName(); } }
public static string latency { get { return OVRP_1_1_0.ovrp_GetAppLatencyTimings(); } }
public static float eyeDepth
{
get { return OVRP_1_1_0.ovrp_GetUserEyeDepth(); }
set { OVRP_1_1_0.ovrp_SetUserEyeDepth(value); }
}
public static float eyeHeight
{
get { return OVRP_1_1_0.ovrp_GetUserEyeHeight(); }
set { OVRP_1_1_0.ovrp_SetUserEyeHeight(value); }
}
public static float batteryLevel
{
get { return OVRP_1_1_0.ovrp_GetSystemBatteryLevel(); }
}
public static float batteryTemperature
{
get { return OVRP_1_1_0.ovrp_GetSystemBatteryTemperature(); }
}
public static int cpuLevel
{
get { return OVRP_1_1_0.ovrp_GetSystemCpuLevel(); }
set { OVRP_1_1_0.ovrp_SetSystemCpuLevel(value); }
}
public static int gpuLevel
{
get { return OVRP_1_1_0.ovrp_GetSystemGpuLevel(); }
set { OVRP_1_1_0.ovrp_SetSystemGpuLevel(value); }
}
public static int vsyncCount
{
get { return OVRP_1_1_0.ovrp_GetSystemVSyncCount(); }
set { OVRP_1_2_0.ovrp_SetSystemVSyncCount(value); }
}
public static float systemVolume
{
get { return OVRP_1_1_0.ovrp_GetSystemVolume(); }
}
public static float ipd
{
get { return OVRP_1_1_0.ovrp_GetUserIPD(); }
set { OVRP_1_1_0.ovrp_SetUserIPD(value); }
}
public static bool occlusionMesh
{
get { return OVRP_1_3_0.ovrp_GetEyeOcclusionMeshEnabled() == Bool.True; }
set { OVRP_1_3_0.ovrp_SetEyeOcclusionMeshEnabled(ToBool(value)); }
}
public static BatteryStatus batteryStatus
{
get { return OVRP_1_1_0.ovrp_GetSystemBatteryStatus(); }
}
public static Posef GetEyeVelocity(Eye eyeId) { return GetNodeVelocity((Node)eyeId, false); }
public static Posef GetEyeAcceleration(Eye eyeId) { return GetNodeAcceleration((Node)eyeId, false); }
public static Frustumf GetEyeFrustum(Eye eyeId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)eyeId); }
public static Sizei GetEyeTextureSize(Eye eyeId) { return OVRP_0_1_0.ovrp_GetEyeTextureSize(eyeId); }
public static Posef GetTrackerPose(Tracker trackerId) { return GetNodePose((Node)((int)trackerId + (int)Node.TrackerZero), false); }
public static Frustumf GetTrackerFrustum(Tracker trackerId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)((int)trackerId + (int)Node.TrackerZero)); }
public static bool ShowUI(PlatformUI ui) { return OVRP_1_1_0.ovrp_ShowSystemUI(ui) == Bool.True; }
public static bool SetOverlayQuad(bool onTop, bool headLocked, IntPtr leftTexture, IntPtr rightTexture, IntPtr device, Posef pose, Vector3f scale, int layerIndex=0, OverlayShape shape=OverlayShape.Quad)
{
if (version >= OVRP_1_6_0.version)
{
uint flags = (uint)OverlayFlag.None;
if (onTop)
flags |= (uint)OverlayFlag.OnTop;
if (headLocked)
flags |= (uint)OverlayFlag.HeadLocked;
if (shape == OverlayShape.Cylinder || shape == OverlayShape.Cubemap)
{
#if UNITY_ANDROID
if (version >= OVRP_1_7_0.version)
flags |= (uint)(shape) << OverlayShapeFlagShift;
else
#else
if (shape == OverlayShape.Cubemap && version >= OVRP_1_10_0.version)
flags |= (uint)(shape) << OverlayShapeFlagShift;
else
#endif
return false;
}
return OVRP_1_6_0.ovrp_SetOverlayQuad3(flags, leftTexture, rightTexture, device, pose, scale, layerIndex) == Bool.True;
}
if (layerIndex != 0)
return false;
return OVRP_0_1_1.ovrp_SetOverlayQuad2(ToBool(onTop), ToBool(headLocked), leftTexture, device, pose, scale) == Bool.True;
}
public static bool UpdateNodePhysicsPoses(int frameIndex, double predictionSeconds)
{
if (version >= OVRP_1_8_0.version)
return OVRP_1_8_0.ovrp_Update2(0, frameIndex, predictionSeconds) == Bool.True;
return false;
}
public static Posef GetNodePose(Node nodeId, bool usePhysicsPose)
{
if (version >= OVRP_1_8_0.version && usePhysicsPose)
return OVRP_1_8_0.ovrp_GetNodePose2(0, nodeId);
return OVRP_0_1_2.ovrp_GetNodePose(nodeId);
}
public static Posef GetNodeVelocity(Node nodeId, bool usePhysicsPose)
{
if (version >= OVRP_1_8_0.version && usePhysicsPose)
return OVRP_1_8_0.ovrp_GetNodeVelocity2(0, nodeId);
return OVRP_0_1_3.ovrp_GetNodeVelocity(nodeId);
}
public static Posef GetNodeAcceleration(Node nodeId, bool usePhysicsPose)
{
if (version >= OVRP_1_8_0.version && usePhysicsPose)
return OVRP_1_8_0.ovrp_GetNodeAcceleration2(0, nodeId);
return OVRP_0_1_3.ovrp_GetNodeAcceleration(nodeId);
}
public static bool GetNodePresent(Node nodeId)
{
return OVRP_1_1_0.ovrp_GetNodePresent(nodeId) == Bool.True;
}
public static bool GetNodeOrientationTracked(Node nodeId)
{
return OVRP_1_1_0.ovrp_GetNodeOrientationTracked(nodeId) == Bool.True;
}
public static bool GetNodePositionTracked(Node nodeId)
{
return OVRP_1_1_0.ovrp_GetNodePositionTracked(nodeId) == Bool.True;
}
public static ControllerState GetControllerState(uint controllerMask)
{
return OVRP_1_1_0.ovrp_GetControllerState(controllerMask);
}
public static bool SetControllerVibration(uint controllerMask, float frequency, float amplitude)
{
return OVRP_0_1_2.ovrp_SetControllerVibration(controllerMask, frequency, amplitude) == Bool.True;
}
public static HapticsDesc GetControllerHapticsDesc(uint controllerMask)
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_GetControllerHapticsDesc(controllerMask);
}
else
{
return new HapticsDesc();
}
}
public static HapticsState GetControllerHapticsState(uint controllerMask)
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_GetControllerHapticsState(controllerMask);
}
else
{
return new HapticsState();
}
}
public static bool SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer)
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_SetControllerHaptics(controllerMask, hapticsBuffer) == Bool.True;
}
else
{
return false;
}
}
public static float GetEyeRecommendedResolutionScale()
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_GetEyeRecommendedResolutionScale();
}
else
{
return 1.0f;
}
}
public static float GetAppCpuStartToGpuEndTime()
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_GetAppCpuStartToGpuEndTime();
}
else
{
return 0.0f;
}
}
public static bool GetBoundaryConfigured()
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_GetBoundaryConfigured() == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static BoundaryTestResult TestBoundaryNode(Node nodeId, BoundaryType boundaryType)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_TestBoundaryNode(nodeId, boundaryType);
}
else
{
return new BoundaryTestResult();
}
}
public static BoundaryTestResult TestBoundaryPoint(Vector3f point, BoundaryType boundaryType)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_TestBoundaryPoint(point, boundaryType);
}
else
{
return new BoundaryTestResult();
}
}
public static bool SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_SetBoundaryLookAndFeel(lookAndFeel) == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static bool ResetBoundaryLookAndFeel()
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_ResetBoundaryLookAndFeel() == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static BoundaryGeometry GetBoundaryGeometry(BoundaryType boundaryType)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_GetBoundaryGeometry(boundaryType);
}
else
{
return new BoundaryGeometry();
}
}
public static bool GetBoundaryGeometry2(BoundaryType boundaryType, IntPtr points, ref int pointsCount)
{
if (version >= OVRP_1_9_0.version)
{
return OVRP_1_9_0.ovrp_GetBoundaryGeometry2(boundaryType, points, ref pointsCount) == OVRPlugin.Bool.True;
}
else
{
pointsCount = 0;
return false;
}
}
public static AppPerfStats GetAppPerfStats()
{
if (version >= OVRP_1_9_0.version)
{
return OVRP_1_9_0.ovrp_GetAppPerfStats();
}
else
{
return new AppPerfStats();
}
}
public static bool ResetAppPerfStats()
{
if (version >= OVRP_1_9_0.version)
{
return OVRP_1_9_0.ovrp_ResetAppPerfStats() == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static Vector3f GetBoundaryDimensions(BoundaryType boundaryType)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_GetBoundaryDimensions(boundaryType);
}
else
{
return new Vector3f();
}
}
public static bool GetBoundaryVisible()
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_GetBoundaryVisible() == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static bool SetBoundaryVisible(bool value)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_SetBoundaryVisible(ToBool(value)) == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static SystemHeadset GetSystemHeadsetType()
{
if (version >= OVRP_1_9_0.version)
return OVRP_1_9_0.ovrp_GetSystemHeadsetType();
return SystemHeadset.None;
}
public static Controller GetActiveController()
{
if (version >= OVRP_1_9_0.version)
return OVRP_1_9_0.ovrp_GetActiveController();
return Controller.None;
}
public static Controller GetConnectedControllers()
{
if (version >= OVRP_1_9_0.version)
return OVRP_1_9_0.ovrp_GetConnectedControllers();
return Controller.None;
}
private static Bool ToBool(bool b)
{
return (b) ? OVRPlugin.Bool.True : OVRPlugin.Bool.False;
}
public static TrackingOrigin GetTrackingOriginType()
{
return OVRP_1_0_0.ovrp_GetTrackingOriginType();
}
public static bool SetTrackingOriginType(TrackingOrigin originType)
{
return OVRP_1_0_0.ovrp_SetTrackingOriginType(originType) == Bool.True;
}
public static Posef GetTrackingCalibratedOrigin()
{
return OVRP_1_0_0.ovrp_GetTrackingCalibratedOrigin();
}
public static bool SetTrackingCalibratedOrigin()
{
return OVRP_1_2_0.ovrpi_SetTrackingCalibratedOrigin() == Bool.True;
}
public static bool RecenterTrackingOrigin(RecenterFlags flags)
{
return OVRP_1_0_0.ovrp_RecenterTrackingOrigin((uint)flags) == Bool.True;
}
//HACK: This makes Unity think it always has VR focus while OVRPlugin.cs reports the correct value.
internal static bool ignoreVrFocus
{
set { OVRP_1_2_1.ovrp_SetAppIgnoreVrFocus(ToBool(value)); }
}
private const string pluginName = "OVRPlugin";
private static Version _versionZero = new System.Version(0, 0, 0);
private static class OVRP_0_1_0
{
public static readonly System.Version version = new System.Version(0, 1, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Sizei ovrp_GetEyeTextureSize(Eye eyeId);
}
private static class OVRP_0_1_1
{
public static readonly System.Version version = new System.Version(0, 1, 1);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetOverlayQuad2(Bool onTop, Bool headLocked, IntPtr texture, IntPtr device, Posef pose, Vector3f scale);
}
private static class OVRP_0_1_2
{
public static readonly System.Version version = new System.Version(0, 1, 2);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodePose(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetControllerVibration(uint controllerMask, float frequency, float amplitude);
}
private static class OVRP_0_1_3
{
public static readonly System.Version version = new System.Version(0, 1, 3);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodeVelocity(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodeAcceleration(Node nodeId);
}
private static class OVRP_0_5_0
{
public static readonly System.Version version = new System.Version(0, 5, 0);
}
private static class OVRP_1_0_0
{
public static readonly System.Version version = new System.Version(1, 0, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern TrackingOrigin ovrp_GetTrackingOriginType();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetTrackingOriginType(TrackingOrigin originType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetTrackingCalibratedOrigin();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_RecenterTrackingOrigin(uint flags);
}
private static class OVRP_1_1_0
{
public static readonly System.Version version = new System.Version(1, 1, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetInitialized();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetVersion")]
private static extern IntPtr _ovrp_GetVersion();
public static string ovrp_GetVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetVersion()); }
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetNativeSDKVersion")]
private static extern IntPtr _ovrp_GetNativeSDKVersion();
public static string ovrp_GetNativeSDKVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetNativeSDKVersion()); }
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr ovrp_GetAudioOutId();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr ovrp_GetAudioInId();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetEyeTextureScale();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetEyeTextureScale(float value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingOrientationSupported();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingOrientationEnabled();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetTrackingOrientationEnabled(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingPositionSupported();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingPositionEnabled();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetTrackingPositionEnabled(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetNodePresent(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetNodeOrientationTracked(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetNodePositionTracked(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Frustumf ovrp_GetNodeFrustum(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern ControllerState ovrp_GetControllerState(uint controllerMask);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern int ovrp_GetSystemCpuLevel();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetSystemCpuLevel(int value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern int ovrp_GetSystemGpuLevel();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetSystemGpuLevel(int value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetSystemPowerSavingMode();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetSystemDisplayFrequency();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern int ovrp_GetSystemVSyncCount();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetSystemVolume();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern BatteryStatus ovrp_GetSystemBatteryStatus();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetSystemBatteryLevel();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetSystemBatteryTemperature();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetSystemProductName")]
private static extern IntPtr _ovrp_GetSystemProductName();
public static string ovrp_GetSystemProductName() { return Marshal.PtrToStringAnsi(_ovrp_GetSystemProductName()); }
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_ShowSystemUI(PlatformUI ui);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppMonoscopic();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetAppMonoscopic(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppHasVrFocus();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppShouldQuit();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppShouldRecenter();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetAppLatencyTimings")]
private static extern IntPtr _ovrp_GetAppLatencyTimings();
public static string ovrp_GetAppLatencyTimings() { return Marshal.PtrToStringAnsi(_ovrp_GetAppLatencyTimings()); }
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetUserPresent();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetUserIPD();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetUserIPD(float value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetUserEyeDepth();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetUserEyeDepth(float value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetUserEyeHeight();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetUserEyeHeight(float value);
}
private static class OVRP_1_2_0
{
public static readonly System.Version version = new System.Version(1, 2, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetSystemVSyncCount(int vsyncCount);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrpi_SetTrackingCalibratedOrigin();
}
private static class OVRP_1_2_1
{
public static readonly System.Version version = new System.Version(1, 2, 1);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetAppIgnoreVrFocus(Bool value);
}
private static class OVRP_1_3_0
{
public static readonly System.Version version = new System.Version(1, 3, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetEyeOcclusionMeshEnabled();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetEyeOcclusionMeshEnabled(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetSystemHeadphonesPresent();
}
private static class OVRP_1_5_0
{
public static readonly System.Version version = new System.Version(1, 5, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern SystemRegion ovrp_GetSystemRegion();
}
private static class OVRP_1_6_0
{
public static readonly System.Version version = new System.Version(1, 6, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingIPDEnabled();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetTrackingIPDEnabled(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern HapticsDesc ovrp_GetControllerHapticsDesc(uint controllerMask);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern HapticsState ovrp_GetControllerHapticsState(uint controllerMask);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetOverlayQuad3(uint flags, IntPtr textureLeft, IntPtr textureRight, IntPtr device, Posef pose, Vector3f scale, int layerIndex);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetEyeRecommendedResolutionScale();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetAppCpuStartToGpuEndTime();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern int ovrp_GetSystemRecommendedMSAALevel();
}
private static class OVRP_1_7_0
{
public static readonly System.Version version = new System.Version(1, 7, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppChromaticCorrection();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetAppChromaticCorrection(Bool value);
}
private static class OVRP_1_8_0
{
public static readonly System.Version version = new System.Version(1, 8, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetBoundaryConfigured();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern BoundaryTestResult ovrp_TestBoundaryNode(Node nodeId, BoundaryType boundaryType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern BoundaryTestResult ovrp_TestBoundaryPoint(Vector3f point, BoundaryType boundaryType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_ResetBoundaryLookAndFeel();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern BoundaryGeometry ovrp_GetBoundaryGeometry(BoundaryType boundaryType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Vector3f ovrp_GetBoundaryDimensions(BoundaryType boundaryType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetBoundaryVisible();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetBoundaryVisible(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_Update2(int stateId, int frameIndex, double predictionSeconds);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodePose2(int stateId, Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodeVelocity2(int stateId, Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodeAcceleration2(int stateId, Node nodeId);
}
private static class OVRP_1_9_0
{
public static readonly System.Version version = new System.Version(1, 9, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern SystemHeadset ovrp_GetSystemHeadsetType();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Controller ovrp_GetActiveController();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Controller ovrp_GetConnectedControllers();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetBoundaryGeometry2(BoundaryType boundaryType, IntPtr points, ref int pointsCount);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern AppPerfStats ovrp_GetAppPerfStats();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_ResetAppPerfStats();
}
private static class OVRP_1_10_0
{
public static readonly System.Version version = new System.Version(1, 10, 0);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Ssl
{
internal const int SSL_TLSEXT_ERR_OK = 0;
internal const int OPENSSL_NPN_NEGOTIATED = 1;
internal const int SSL_TLSEXT_ERR_NOACK = 3;
internal delegate int SslCtxSetVerifyCallback(int preverify_ok, IntPtr x509_ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureLibSslInitialized")]
internal static extern void EnsureLibSslInitialized();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")]
internal static extern IntPtr SslV2_3Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")]
internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")]
internal static extern SslErrorCode SslGetError(SafeSslHandle ssl, int ret);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")]
internal static extern SslErrorCode SslGetError(IntPtr ssl, int ret);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetQuietShutdown")]
internal static extern void SslSetQuietShutdown(SafeSslHandle ssl, int mode);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDestroy")]
internal static extern void SslDestroy(IntPtr ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetConnectState")]
internal static extern void SslSetConnectState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAcceptState")]
internal static extern void SslSetAcceptState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")]
private static extern IntPtr SslGetVersion(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSelectNextProto")]
internal static extern int SslSelectNextProto(out IntPtr outp, out byte outlen, IntPtr server, uint serverlen, IntPtr client, uint clientlen);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGet0AlpnSelected")]
internal static extern void SslGetAlpnSelected(SafeSslHandle ssl, out IntPtr protocol, out int len);
internal static byte[] SslGetAlpnSelected(SafeSslHandle ssl)
{
IntPtr protocol;
int len;
SslGetAlpnSelected(ssl, out protocol, out len);
if (len == 0)
return null;
byte[] result = new byte[len];
Marshal.Copy(protocol, result, 0, len);
return result;
}
internal static string GetProtocolVersion(SafeSslHandle ssl)
{
return Marshal.PtrToStringAnsi(SslGetVersion(ssl));
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetSslConnectionInfo")]
internal static extern bool GetSslConnectionInfo(
SafeSslHandle ssl,
out int dataCipherAlg,
out int keyExchangeAlg,
out int dataHashAlg,
out int dataKeySize,
out int hashKeySize);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite")]
internal static extern unsafe int SslWrite(SafeSslHandle ssl, byte* buf, int num);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead")]
internal static extern unsafe int SslRead(SafeSslHandle ssl, byte* buf, int num);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")]
internal static extern int SslShutdown(IntPtr ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")]
internal static extern int SslShutdown(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")]
internal static extern void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake")]
internal static extern int SslDoHandshake(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslStateOK")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslStateOK(SafeSslHandle ssl);
// NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs.
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")]
internal static extern unsafe int BioWrite(SafeBioHandle b, byte* data, int len);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")]
internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertChain")]
internal static extern SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerFinished")]
internal static extern int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetFinished")]
internal static extern int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSessionReused")]
internal static extern bool SslSessionReused(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")]
internal static extern bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetClientCAList")]
private static extern SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl);
internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl)
{
Crypto.CheckValidOpenSslHandle(ssl);
SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl);
if (!handle.IsInvalid)
{
handle.SetParent(ssl);
}
return handle;
}
internal static bool AddExtraChainCertificates(SafeSslHandle sslContext, X509Chain chain)
{
Debug.Assert(chain != null, "X509Chain should not be null");
Debug.Assert(chain.ChainElements.Count > 0, "chain.Build should have already been called");
for (int i = chain.ChainElements.Count - 2; i > 0; i--)
{
SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain.ChainElements[i].Certificate.Handle);
Crypto.CheckValidOpenSslHandle(dupCertHandle);
if (!SslAddExtraChainCert(sslContext, dupCertHandle))
{
dupCertHandle.Dispose(); // we still own the safe handle; clean it up
return false;
}
dupCertHandle.SetHandleAsInvalid(); // ownership has been transferred to sslHandle; do not free via this safe handle
}
return true;
}
internal static class SslMethods
{
internal static readonly IntPtr SSLv23_method = SslV2_3Method();
}
internal enum SslErrorCode
{
SSL_ERROR_NONE = 0,
SSL_ERROR_SSL = 1,
SSL_ERROR_WANT_READ = 2,
SSL_ERROR_WANT_WRITE = 3,
SSL_ERROR_SYSCALL = 5,
SSL_ERROR_ZERO_RETURN = 6,
// NOTE: this SslErrorCode value doesn't exist in OpenSSL, but
// we use it to distinguish when a renegotiation is pending.
// Choosing an arbitrarily large value that shouldn't conflict
// with any actual OpenSSL error codes
SSL_ERROR_RENEGOTIATE = 29304
}
}
}
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeSslHandle : SafeHandle
{
private SafeBioHandle _readBio;
private SafeBioHandle _writeBio;
private bool _isServer;
private bool _handshakeCompleted = false;
public bool IsServer
{
get { return _isServer; }
}
public SafeBioHandle InputBio
{
get
{
return _readBio;
}
}
public SafeBioHandle OutputBio
{
get
{
return _writeBio;
}
}
internal void MarkHandshakeCompleted()
{
_handshakeCompleted = true;
}
public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer)
{
SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio();
SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio();
SafeSslHandle handle = Interop.Ssl.SslCreate(context);
if (readBio.IsInvalid || writeBio.IsInvalid || handle.IsInvalid)
{
readBio.Dispose();
writeBio.Dispose();
handle.Dispose(); // will make IsInvalid==true if it's not already
return handle;
}
handle._isServer = isServer;
// SslSetBio will transfer ownership of the BIO handles to the SSL context
try
{
readBio.TransferOwnershipToParent(handle);
writeBio.TransferOwnershipToParent(handle);
handle._readBio = readBio;
handle._writeBio = writeBio;
Interop.Ssl.SslSetBio(handle, readBio, writeBio);
}
catch (Exception exc)
{
// The only way this should be able to happen without thread aborts is if we hit OOMs while
// manipulating the safe handles, in which case we may leak the bio handles.
Debug.Fail("Unexpected exception while transferring SafeBioHandle ownership to SafeSslHandle", exc.ToString());
throw;
}
if (isServer)
{
Interop.Ssl.SslSetAcceptState(handle);
}
else
{
Interop.Ssl.SslSetConnectState(handle);
}
return handle;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_readBio?.Dispose();
_writeBio?.Dispose();
}
base.Dispose(disposing);
}
protected override bool ReleaseHandle()
{
if (_handshakeCompleted)
{
Disconnect();
}
IntPtr h = handle;
SetHandle(IntPtr.Zero);
Interop.Ssl.SslDestroy(h); // will free the handles underlying _readBio and _writeBio
return true;
}
private void Disconnect()
{
Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect");
int retVal = Interop.Ssl.SslShutdown(handle);
// Here, we are ignoring checking for <0 return values from Ssl_Shutdown,
// since the underlying memory bio is already disposed, we are not
// interested in reading or writing to it.
if (retVal == 0)
{
// Do a bi-directional shutdown.
retVal = Interop.Ssl.SslShutdown(handle);
}
}
private SafeSslHandle() : base(IntPtr.Zero, true)
{
}
internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
{
handle = validSslPointer;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Logging;
using QuantConnect.Securities;
using QuantConnect.Data.Market;
using QuantConnect.Tests.Engine;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
using QuantConnect.Tests.Engine.DataFeeds;
using QuantConnect.Brokerages.Backtesting;
using QuantConnect.Lean.Engine.TransactionHandlers;
namespace QuantConnect.Tests.Common.Securities
{
[TestFixture, Parallelizable(ParallelScope.All)]
public class FutureOptionMarginBuyingPowerModelTests
{
[Test]
public void MarginWithNoFutureOptionHoldings()
{
const decimal price = 2300m;
var time = new DateTime(2020, 10, 14);
var expDate = new DateTime(2021, 3, 19);
var tz = TimeZones.NewYork;
// For this symbol we dont have any history, but only one date and margins line
var ticker = QuantConnect.Securities.Futures.Indices.SP500EMini;
var future = Symbol.CreateFuture(ticker, Market.CME, expDate);
var symbol = Symbol.CreateOption(future, Market.CME, OptionStyle.American, OptionRight.Call, 2550m, new DateTime(2021, 3, 19));
var optionSecurity = new Option(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
optionSecurity.Underlying = new Future(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), future, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
optionSecurity.Underlying.SetMarketPrice(new Tick { Value = price, Time = time });
optionSecurity.Underlying.Holdings.SetHoldings(1.5m, 1);
var futureBuyingPowerModel = new FutureMarginModel(security: optionSecurity.Underlying);
var futureOptionBuyingPowerModel = new FuturesOptionsMarginModel(futureOption: optionSecurity);
// we don't hold FOPs!
Assert.AreEqual(0m, futureOptionBuyingPowerModel.GetMaintenanceMargin(optionSecurity));
Assert.AreNotEqual(0m, futureBuyingPowerModel.GetMaintenanceMargin(optionSecurity.Underlying));
Assert.AreNotEqual(0m, futureOptionBuyingPowerModel.GetInitialMarginRequirement(optionSecurity, 10));
}
[Test]
public void MarginWithFutureAndFutureOptionHoldings()
{
const decimal price = 2300m;
var time = new DateTime(2020, 10, 14);
var expDate = new DateTime(2021, 3, 19);
var tz = TimeZones.NewYork;
// For this symbol we dont have any history, but only one date and margins line
var ticker = QuantConnect.Securities.Futures.Indices.SP500EMini;
var future = Symbol.CreateFuture(ticker, Market.CME, expDate);
var symbol = Symbol.CreateOption(future, Market.CME, OptionStyle.American, OptionRight.Call, 2550m,
new DateTime(2021, 3, 19));
var optionSecurity = new Option(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
optionSecurity.Underlying = new Future(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), future, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
optionSecurity.Underlying.SetMarketPrice(new Tick {Value = price, Time = time});
optionSecurity.Holdings.SetHoldings(1.5m, 1);
optionSecurity.Underlying.Holdings.SetHoldings(1.5m, 1);
var futureOptionBuyingPowerModel = new FuturesOptionsMarginModel(futureOption: optionSecurity);
Assert.AreNotEqual(0m, futureOptionBuyingPowerModel.GetMaintenanceMargin(optionSecurity));
}
[Test]
public void MarginWithFutureOptionHoldings()
{
const decimal price = 2300m;
var time = new DateTime(2020, 10, 14);
var expDate = new DateTime(2021, 3, 19);
var tz = TimeZones.NewYork;
// For this symbol we dont have any history, but only one date and margins line
var ticker = QuantConnect.Securities.Futures.Indices.SP500EMini;
var future = Symbol.CreateFuture(ticker, Market.CME, expDate);
var symbol = Symbol.CreateOption(future, Market.CME, OptionStyle.American, OptionRight.Call, 2550m,
new DateTime(2021, 3, 19));
var optionSecurity = new Option(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
optionSecurity.Underlying = new Future(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), future, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
optionSecurity.Underlying.SetMarketPrice(new Tick { Value = price, Time = time });
optionSecurity.Holdings.SetHoldings(1.5m, 1);
var futureBuyingPowerModel = new FutureMarginModel(security: optionSecurity.Underlying);
var futureOptionBuyingPowerModel = new FuturesOptionsMarginModel(futureOption: optionSecurity);
Assert.AreNotEqual(0m, futureOptionBuyingPowerModel.GetMaintenanceMargin(optionSecurity));
Assert.AreEqual(0, futureBuyingPowerModel.GetMaintenanceMargin(optionSecurity.Underlying));
}
[Test]
public void OptionExerciseWhenFullyInvested()
{
var algorithm = new AlgorithmStub();
algorithm.SetFinishedWarmingUp();
var backtestingTransactionHandler = new BacktestingTransactionHandler();
var brokerage = new BacktestingBrokerage(algorithm);
algorithm.Transactions.SetOrderProcessor(backtestingTransactionHandler);
backtestingTransactionHandler.Initialize(algorithm, brokerage, new TestResultHandler());
const decimal price = 2600m;
var time = new DateTime(2020, 10, 14);
var expDate = new DateTime(2021, 3, 19);
// For this symbol we dont have any history, but only one date and margins line
var ticker = QuantConnect.Securities.Futures.Indices.SP500EMini;
var future = Symbol.CreateFuture(ticker, Market.CME, expDate);
var symbol = Symbol.CreateOption(future, Market.CME, OptionStyle.American, OptionRight.Call, 2550m,
new DateTime(2021, 3, 19));
var optionSecurity = algorithm.AddOptionContract(symbol);
optionSecurity.Underlying = algorithm.AddFutureContract(future);
optionSecurity.Underlying.SetMarketPrice(new Tick { Value = price, Time = time });
optionSecurity.SetMarketPrice(new Tick { Value = 150, Time = time });
optionSecurity.Holdings.SetHoldings(1.5m, 10);
var ticket = algorithm.ExerciseOption(optionSecurity.Symbol, 10, true);
Assert.AreEqual(OrderStatus.Filled, ticket.Status);
}
[Test]
public void MarginRequirementsAreSetCorrectly()
{
var expDate = new DateTime(2021, 3, 19);
var tz = TimeZones.NewYork;
// For this symbol we dont have any history, but only one date and margins line
var ticker = QuantConnect.Securities.Futures.Indices.SP500EMini;
var future = Symbol.CreateFuture(ticker, Market.CME, expDate);
var symbol = Symbol.CreateOption(future, Market.CME, OptionStyle.American, OptionRight.Call, 2550m,
new DateTime(2021, 3, 19));
var futureSecurity = new Future(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), future, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
var optionSecurity = new QuantConnect.Securities.FutureOption.FutureOption(symbol,
SecurityExchangeHours.AlwaysOpen(tz),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache(),
futureSecurity
);
var futureMarginModel = new FuturesOptionsMarginModel(futureOption: optionSecurity);
optionSecurity.Underlying.SetMarketPrice(new Tick { Value = 1500, Time = new DateTime(2001, 01, 07) });
var initialIntradayMarginRequirement = futureMarginModel.InitialIntradayMarginRequirement;
var maintenanceIntradayMarginRequirement = futureMarginModel.MaintenanceIntradayMarginRequirement;
var initialOvernightMarginRequirement = futureMarginModel.MaintenanceOvernightMarginRequirement;
var maintenanceOvernightMarginRequirement = futureMarginModel.InitialOvernightMarginRequirement;
Assert.AreNotEqual(0, initialIntradayMarginRequirement);
Assert.AreNotEqual(0, maintenanceIntradayMarginRequirement);
Assert.AreNotEqual(0, initialOvernightMarginRequirement);
Assert.AreNotEqual(0, maintenanceOvernightMarginRequirement);
}
// Long Call initial
[TestCase(10, 70000, OptionRight.Call, PositionSide.Long, 59375)]
[TestCase(23.5, 69000, OptionRight.Call, PositionSide.Long, 59375)]
[TestCase(30.5, 68000, OptionRight.Call, PositionSide.Long, 59375)]
[TestCase(55, 50000, OptionRight.Call, PositionSide.Long, 59375)]
[TestCase(66, 30000, OptionRight.Call, PositionSide.Long, 59375)]
[TestCase(72, 17000, OptionRight.Call, PositionSide.Long, 59375)]
[TestCase(87, 3700, OptionRight.Call, PositionSide.Long, 59375)]
[TestCase(108.5, 1000, OptionRight.Call, PositionSide.Long, 59375)]
[TestCase(125, 570, OptionRight.Call, PositionSide.Long, 59375)]
[TestCase(1000, 0, OptionRight.Call, PositionSide.Long, 59375)]
// Long Call maintenance
[TestCase(10, 56000, OptionRight.Call, PositionSide.Long, 47500)]
[TestCase(23.5, 55000, OptionRight.Call, PositionSide.Long, 47500)]
[TestCase(30.5, 54000, OptionRight.Call, PositionSide.Long, 47500)]
[TestCase(55, 40000, OptionRight.Call, PositionSide.Long, 47500)]
[TestCase(66, 24000, OptionRight.Call, PositionSide.Long, 47500)]
[TestCase(72, 14000, OptionRight.Call, PositionSide.Long, 47500)]
[TestCase(87, 3600, OptionRight.Call, PositionSide.Long, 47500)]
[TestCase(108.5, 1000, OptionRight.Call, PositionSide.Long, 47500)]
[TestCase(125, 540, OptionRight.Call, PositionSide.Long, 47500)]
[TestCase(1000, 0, OptionRight.Call, PositionSide.Long, 47500)]
// Short Call initial
[TestCase(10, 59400, OptionRight.Call, PositionSide.Short, 59375)]
[TestCase(23.5, 59680, OptionRight.Call, PositionSide.Short, 59375)]
[TestCase(30.5, 59750, OptionRight.Call, PositionSide.Short, 59375)]
[TestCase(55, 56712, OptionRight.Call, PositionSide.Short, 59375)]
[TestCase(66, 48134, OptionRight.Call, PositionSide.Short, 59375)]
[TestCase(72, 43492, OptionRight.Call, PositionSide.Short, 59375)]
[TestCase(87, 28960, OptionRight.Call, PositionSide.Short, 59375)]
[TestCase(108.5, 11373, OptionRight.Call, PositionSide.Short, 59375)]
[TestCase(125, 3900, OptionRight.Call, PositionSide.Short, 59375)]
[TestCase(1000, 0, OptionRight.Call, PositionSide.Short, 59375)]
// Long Put initial
[TestCase(10, 45, OptionRight.Put, PositionSide.Long, 59375)]
[TestCase(18, 171, OptionRight.Put, PositionSide.Long, 59375)]
[TestCase(26.5, 537, OptionRight.Put, PositionSide.Long, 59375)]
[TestCase(37.5, 1920, OptionRight.Put, PositionSide.Long, 59375)]
[TestCase(47.5, 6653, OptionRight.Put, PositionSide.Long, 59375)]
[TestCase(69.5, 48637, OptionRight.Put, PositionSide.Long, 59375)]
[TestCase(83, 59201, OptionRight.Put, PositionSide.Long, 59375)]
[TestCase(108, 60000, OptionRight.Put, PositionSide.Long, 59375)]
[TestCase(152, 59475, OptionRight.Put, PositionSide.Long, 59375)]
// Long Put maintenance
[TestCase(10, 45, OptionRight.Put, PositionSide.Long, 47500)]
[TestCase(18, 171, OptionRight.Put, PositionSide.Long, 47500)]
[TestCase(26.5, 537, OptionRight.Put, PositionSide.Long, 47500)]
[TestCase(37.5, 1920, OptionRight.Put, PositionSide.Long, 47500)]
[TestCase(47.5, 6653, OptionRight.Put, PositionSide.Long, 47500)]
[TestCase(69.5, 38910, OptionRight.Put, PositionSide.Long, 47500)]
[TestCase(83, 47361, OptionRight.Put, PositionSide.Long, 47500)]
[TestCase(108, 48000, OptionRight.Put, PositionSide.Long, 47500)]
[TestCase(152, 47580, OptionRight.Put, PositionSide.Long, 47500)]
// Short Put initial
[TestCase(10, 23729, OptionRight.Put, PositionSide.Short, 59375)]
[TestCase(18, 33859, OptionRight.Put, PositionSide.Short, 59375)]
[TestCase(26.5, 40000, OptionRight.Put, PositionSide.Short, 59375)]
[TestCase(37.5, 52714, OptionRight.Put, PositionSide.Short, 59375)]
[TestCase(47.5, 58414, OptionRight.Put, PositionSide.Short, 59375)]
[TestCase(69.5, 72647, OptionRight.Put, PositionSide.Short, 59375)]
[TestCase(83, 73160, OptionRight.Put, PositionSide.Short, 59375)]
[TestCase(108, 71782, OptionRight.Put, PositionSide.Short, 59375)]
[TestCase(152, 70637, OptionRight.Put, PositionSide.Short, 59375)]
public void MarginRequirementCrudeOil(decimal strike, double expected, OptionRight optionRight, PositionSide positionSide, decimal underlyingRequirement)
{
var tz = TimeZones.NewYork;
var expDate = new DateTime(2021, 3, 19);
// For this symbol we dont have any history, but only one date and margins line
var ticker = QuantConnect.Securities.Futures.Energies.CrudeOilWTI;
var future = Symbol.CreateFuture(ticker, Market.NYMEX, expDate);
var symbol = Symbol.CreateOption(future, Market.NYMEX, OptionStyle.American, optionRight, strike,
new DateTime(2021, 3, 19));
var futureSecurity = new Future(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), future, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
var optionSecurity = new QuantConnect.Securities.FutureOption.FutureOption(symbol,
SecurityExchangeHours.AlwaysOpen(tz),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache(),
futureSecurity
);
optionSecurity.Underlying.SetMarketPrice(new Tick { Value = 60, Time = new DateTime(2001, 01, 07) });
var marginRequirement = FuturesOptionsMarginModel.GetMarginRequirement(optionSecurity, underlyingRequirement, positionSide);
Log.Debug($"Side {positionSide}. Right {optionRight}. Strike {strike}. Margin: {marginRequirement}");
Assert.AreEqual(expected, marginRequirement, (double)underlyingRequirement * 0.30d);
}
// Long Call initial
[TestCase(1300, 154000, OptionRight.Call, PositionSide.Long, 112729)]
[TestCase(1755, 97000, OptionRight.Call, PositionSide.Long, 112729)]
[TestCase(1805, 84000, OptionRight.Call, PositionSide.Long, 112729)]
[TestCase(1900, 55000, OptionRight.Call, PositionSide.Long, 112729)]
[TestCase(2040, 24000, OptionRight.Call, PositionSide.Long, 112729)]
[TestCase(2100, 16000, OptionRight.Call, PositionSide.Long, 112729)]
[TestCase(2295, 5000, OptionRight.Call, PositionSide.Long, 112729)]
[TestCase(3000, 740, OptionRight.Call, PositionSide.Long, 112729)]
[TestCase(4000, 180, OptionRight.Call, PositionSide.Long, 112729)]
public void MarginRequirementGold(decimal strike, double expected, OptionRight optionRight, PositionSide positionSide, decimal underlyingRequirement)
{
var tz = TimeZones.NewYork;
var expDate = new DateTime(2021, 3, 19);
// For this symbol we dont have any history, but only one date and margins line
var ticker = QuantConnect.Securities.Futures.Metals.Gold;
var future = Symbol.CreateFuture(ticker, Market.COMEX, expDate);
var symbol = Symbol.CreateOption(future, Market.COMEX, OptionStyle.American, optionRight, strike,
new DateTime(2021, 3, 19));
var futureSecurity = new Future(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), future, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
var optionSecurity = new QuantConnect.Securities.FutureOption.FutureOption(symbol,
SecurityExchangeHours.AlwaysOpen(tz),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache(),
futureSecurity
);
optionSecurity.Underlying.SetMarketPrice(new Tick { Value = 1887, Time = new DateTime(2001, 01, 07) });
var marginRequirement = FuturesOptionsMarginModel.GetMarginRequirement(optionSecurity, underlyingRequirement, positionSide);
Log.Debug($"Side {positionSide}. Right {optionRight}. Strike {strike}. Margin: {marginRequirement}");
Assert.AreEqual(expected, marginRequirement, (double)underlyingRequirement * 0.30d);
}
// Long Call initial
[TestCase(2200, 16456, OptionRight.Call, PositionSide.Long, 15632)]
[TestCase(3200, 15582, OptionRight.Call, PositionSide.Long, 15632)]
[TestCase(3500, 14775, OptionRight.Call, PositionSide.Long, 15632)]
[TestCase(3570, 14310, OptionRight.Call, PositionSide.Long, 15632)]
[TestCase(4190, 7128, OptionRight.Call, PositionSide.Long, 15632)]
[TestCase(4370, 4089, OptionRight.Call, PositionSide.Long, 15632)]
[TestCase(4900, 233, OptionRight.Call, PositionSide.Long, 15632)]
// Short Call initial
[TestCase(2200, 17069, OptionRight.Call, PositionSide.Short, 15632)]
[TestCase(3200, 16716, OptionRight.Call, PositionSide.Short, 15632)]
[TestCase(3500, 16409, OptionRight.Call, PositionSide.Short, 15632)]
[TestCase(3570, 16222, OptionRight.Call, PositionSide.Short, 15632)]
[TestCase(4190, 14429, OptionRight.Call, PositionSide.Short, 15632)]
[TestCase(4370, 13003, OptionRight.Call, PositionSide.Short, 15632)]
[TestCase(4900, 6528, OptionRight.Call, PositionSide.Short, 15632)]
public void MarginRequirementEs(decimal strike, double expected, OptionRight optionRight, PositionSide positionSide, decimal underlyingRequirement)
{
var tz = TimeZones.NewYork;
var expDate = new DateTime(2021, 3, 19);
// For this symbol we dont have any history, but only one date and margins line
var ticker = QuantConnect.Securities.Futures.Indices.SP500EMini;
var future = Symbol.CreateFuture(ticker, Market.Globex, expDate);
var symbol = Symbol.CreateOption(future, Market.Globex, OptionStyle.American, optionRight, strike,
new DateTime(2021, 3, 19));
var futureSecurity = new Future(
SecurityExchangeHours.AlwaysOpen(tz),
new SubscriptionDataConfig(typeof(TradeBar), future, Resolution.Minute, tz, tz, true, false, false),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null
);
var optionSecurity = new QuantConnect.Securities.FutureOption.FutureOption(symbol,
SecurityExchangeHours.AlwaysOpen(tz),
new Cash(Currencies.USD, 0, 1m),
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache(),
futureSecurity
);
optionSecurity.Underlying.SetMarketPrice(new Tick { Value = 4172, Time = new DateTime(2001, 01, 07) });
var marginRequirement = FuturesOptionsMarginModel.GetMarginRequirement(optionSecurity, underlyingRequirement, positionSide);
Log.Debug($"Side {positionSide}. Right {optionRight}. Strike {strike}. Margin: {marginRequirement}");
Assert.AreEqual(expected, marginRequirement, (double)underlyingRequirement * 0.30d);
}
}
}
| |
namespace XenAdmin.TabPages
{
sealed partial class SnapshotsPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
ConnectionsManager.History.CollectionChanged -= History_CollectionChanged;
if(components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SnapshotsPage));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
this.GeneralTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.contentTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.panelPropertiesColumn = new System.Windows.Forms.Panel();
this.panelVMPP = new System.Windows.Forms.Panel();
this.linkLabelVMPPInfo = new System.Windows.Forms.LinkLabel();
this.labelVMPPInfo = new System.Windows.Forms.Label();
this.pictureBoxVMPPInfo = new System.Windows.Forms.PictureBox();
this.propertiesGroupBox = new System.Windows.Forms.GroupBox();
this.propertiesTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanelSimpleSelection = new System.Windows.Forms.TableLayoutPanel();
this.folderLabel = new System.Windows.Forms.Label();
this.sizeLabel = new System.Windows.Forms.Label();
this.tagsLabel = new System.Windows.Forms.Label();
this.descriptionLabel = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.sizeTitleLabel = new System.Windows.Forms.Label();
this.folderTitleLabel = new System.Windows.Forms.Label();
this.tagsTitleLabel = new System.Windows.Forms.Label();
this.customFieldTitle1 = new System.Windows.Forms.Label();
this.customFieldContent1 = new System.Windows.Forms.Label();
this.customFieldTitle2 = new System.Windows.Forms.Label();
this.customFieldContent2 = new System.Windows.Forms.Label();
this.labelModeTitle = new System.Windows.Forms.Label();
this.labelMode = new System.Windows.Forms.Label();
this.propertiesButton = new System.Windows.Forms.Button();
this.nameLabel = new System.Windows.Forms.Label();
this.shadowPanel1 = new XenAdmin.Controls.ShadowPanel();
this.screenshotPictureBox = new System.Windows.Forms.PictureBox();
this.viewPanel = new System.Windows.Forms.Panel();
this.snapshotTreeView = new XenAdmin.Controls.SnapshotTreeView(this.components);
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.newSnapshotButton = new System.Windows.Forms.Button();
this.toolTipContainerRevertButton = new XenAdmin.Controls.ToolTipContainer();
this.revertButton = new System.Windows.Forms.Button();
this.buttonView = new System.Windows.Forms.Button();
this.saveButton = new System.Windows.Forms.Button();
this.deleteButton = new System.Windows.Forms.Button();
this.chevronButton1 = new XenAdmin.Controls.ChevronButton();
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.TakeSnapshotToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.revertToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveVMToolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveVMToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveTemplateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.separatorDeleteToolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortByToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortByNameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortByCreatedOnToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortBySizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortByTypeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.sortToolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.propertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.columnType = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.columnName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.columnCreated = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.columnSize = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.columnTags = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDescription = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dateLabel = new System.Windows.Forms.Label();
this.tableLayoutPanelMultipleSelection = new System.Windows.Forms.TableLayoutPanel();
this.multipleSelectionTags = new System.Windows.Forms.Label();
this.multipleSelectionTotalSize = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.saveMenuStrip = new XenAdmin.Controls.NonReopeningContextMenuStrip(this.components);
this.saveAsVMToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.saveAsTemplateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportAsBackupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStripView = new XenAdmin.Controls.NonReopeningContextMenuStrip(this.components);
this.toolStripButtonListView = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripButtonTreeView = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparatorView = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItemScheduledSnapshots = new System.Windows.Forms.ToolStripMenuItem();
this.pageContainerPanel.SuspendLayout();
this.GeneralTableLayoutPanel.SuspendLayout();
this.contentTableLayoutPanel.SuspendLayout();
this.panelPropertiesColumn.SuspendLayout();
this.panelVMPP.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxVMPPInfo)).BeginInit();
this.propertiesGroupBox.SuspendLayout();
this.propertiesTableLayoutPanel.SuspendLayout();
this.tableLayoutPanelSimpleSelection.SuspendLayout();
this.shadowPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.screenshotPictureBox)).BeginInit();
this.viewPanel.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.toolTipContainerRevertButton.SuspendLayout();
this.contextMenuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.tableLayoutPanelMultipleSelection.SuspendLayout();
this.saveMenuStrip.SuspendLayout();
this.contextMenuStripView.SuspendLayout();
this.SuspendLayout();
//
// pageContainerPanel
//
this.pageContainerPanel.Controls.Add(this.GeneralTableLayoutPanel);
resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel");
//
// GeneralTableLayoutPanel
//
resources.ApplyResources(this.GeneralTableLayoutPanel, "GeneralTableLayoutPanel");
this.GeneralTableLayoutPanel.BackColor = System.Drawing.Color.Transparent;
this.GeneralTableLayoutPanel.Controls.Add(this.contentTableLayoutPanel, 0, 1);
this.GeneralTableLayoutPanel.Controls.Add(this.tableLayoutPanel2, 0, 0);
this.GeneralTableLayoutPanel.Name = "GeneralTableLayoutPanel";
//
// contentTableLayoutPanel
//
resources.ApplyResources(this.contentTableLayoutPanel, "contentTableLayoutPanel");
this.contentTableLayoutPanel.Controls.Add(this.panelPropertiesColumn, 1, 0);
this.contentTableLayoutPanel.Controls.Add(this.viewPanel, 0, 0);
this.contentTableLayoutPanel.Name = "contentTableLayoutPanel";
//
// panelPropertiesColumn
//
this.panelPropertiesColumn.Controls.Add(this.panelVMPP);
this.panelPropertiesColumn.Controls.Add(this.propertiesGroupBox);
resources.ApplyResources(this.panelPropertiesColumn, "panelPropertiesColumn");
this.panelPropertiesColumn.Name = "panelPropertiesColumn";
//
// panelVMPP
//
resources.ApplyResources(this.panelVMPP, "panelVMPP");
this.panelVMPP.Controls.Add(this.linkLabelVMPPInfo);
this.panelVMPP.Controls.Add(this.labelVMPPInfo);
this.panelVMPP.Controls.Add(this.pictureBoxVMPPInfo);
this.panelVMPP.Name = "panelVMPP";
//
// linkLabelVMPPInfo
//
resources.ApplyResources(this.linkLabelVMPPInfo, "linkLabelVMPPInfo");
this.linkLabelVMPPInfo.Name = "linkLabelVMPPInfo";
this.linkLabelVMPPInfo.TabStop = true;
this.linkLabelVMPPInfo.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelVMPPInfo_Click);
//
// labelVMPPInfo
//
resources.ApplyResources(this.labelVMPPInfo, "labelVMPPInfo");
this.labelVMPPInfo.AutoEllipsis = true;
this.labelVMPPInfo.Name = "labelVMPPInfo";
//
// pictureBoxVMPPInfo
//
this.pictureBoxVMPPInfo.Image = global::XenAdmin.Properties.Resources._000_Alert2_h32bit_16;
resources.ApplyResources(this.pictureBoxVMPPInfo, "pictureBoxVMPPInfo");
this.pictureBoxVMPPInfo.Name = "pictureBoxVMPPInfo";
this.pictureBoxVMPPInfo.TabStop = false;
//
// propertiesGroupBox
//
resources.ApplyResources(this.propertiesGroupBox, "propertiesGroupBox");
this.propertiesGroupBox.Controls.Add(this.propertiesTableLayoutPanel);
this.propertiesGroupBox.Name = "propertiesGroupBox";
this.propertiesGroupBox.TabStop = false;
//
// propertiesTableLayoutPanel
//
resources.ApplyResources(this.propertiesTableLayoutPanel, "propertiesTableLayoutPanel");
this.propertiesTableLayoutPanel.Controls.Add(this.tableLayoutPanelSimpleSelection, 0, 2);
this.propertiesTableLayoutPanel.Controls.Add(this.propertiesButton, 0, 3);
this.propertiesTableLayoutPanel.Controls.Add(this.nameLabel, 0, 1);
this.propertiesTableLayoutPanel.Controls.Add(this.shadowPanel1, 0, 0);
this.propertiesTableLayoutPanel.Name = "propertiesTableLayoutPanel";
//
// tableLayoutPanelSimpleSelection
//
resources.ApplyResources(this.tableLayoutPanelSimpleSelection, "tableLayoutPanelSimpleSelection");
this.tableLayoutPanelSimpleSelection.Controls.Add(this.folderLabel, 1, 4);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.sizeLabel, 1, 2);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.tagsLabel, 1, 3);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.descriptionLabel, 1, 0);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.sizeTitleLabel, 0, 2);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.folderTitleLabel, 0, 4);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.tagsTitleLabel, 0, 3);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.customFieldTitle1, 0, 5);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.customFieldContent1, 1, 5);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.customFieldTitle2, 0, 6);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.customFieldContent2, 1, 6);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.labelModeTitle, 0, 1);
this.tableLayoutPanelSimpleSelection.Controls.Add(this.labelMode, 1, 1);
this.tableLayoutPanelSimpleSelection.Name = "tableLayoutPanelSimpleSelection";
//
// folderLabel
//
this.folderLabel.AutoEllipsis = true;
resources.ApplyResources(this.folderLabel, "folderLabel");
this.folderLabel.Name = "folderLabel";
this.folderLabel.UseMnemonic = false;
//
// sizeLabel
//
resources.ApplyResources(this.sizeLabel, "sizeLabel");
this.sizeLabel.Name = "sizeLabel";
this.sizeLabel.UseMnemonic = false;
//
// tagsLabel
//
this.tagsLabel.AutoEllipsis = true;
resources.ApplyResources(this.tagsLabel, "tagsLabel");
this.tagsLabel.Name = "tagsLabel";
this.tagsLabel.UseMnemonic = false;
//
// descriptionLabel
//
this.descriptionLabel.AutoEllipsis = true;
resources.ApplyResources(this.descriptionLabel, "descriptionLabel");
this.descriptionLabel.Name = "descriptionLabel";
this.descriptionLabel.UseMnemonic = false;
//
// label1
//
this.label1.AutoEllipsis = true;
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
this.label1.UseMnemonic = false;
//
// sizeTitleLabel
//
resources.ApplyResources(this.sizeTitleLabel, "sizeTitleLabel");
this.sizeTitleLabel.Name = "sizeTitleLabel";
this.sizeTitleLabel.UseMnemonic = false;
//
// folderTitleLabel
//
resources.ApplyResources(this.folderTitleLabel, "folderTitleLabel");
this.folderTitleLabel.Name = "folderTitleLabel";
this.folderTitleLabel.UseMnemonic = false;
//
// tagsTitleLabel
//
resources.ApplyResources(this.tagsTitleLabel, "tagsTitleLabel");
this.tagsTitleLabel.Name = "tagsTitleLabel";
this.tagsTitleLabel.UseMnemonic = false;
//
// customFieldTitle1
//
this.customFieldTitle1.AutoEllipsis = true;
resources.ApplyResources(this.customFieldTitle1, "customFieldTitle1");
this.customFieldTitle1.Name = "customFieldTitle1";
this.customFieldTitle1.UseMnemonic = false;
//
// customFieldContent1
//
this.customFieldContent1.AutoEllipsis = true;
resources.ApplyResources(this.customFieldContent1, "customFieldContent1");
this.customFieldContent1.Name = "customFieldContent1";
this.customFieldContent1.UseMnemonic = false;
//
// customFieldTitle2
//
this.customFieldTitle2.AutoEllipsis = true;
resources.ApplyResources(this.customFieldTitle2, "customFieldTitle2");
this.customFieldTitle2.Name = "customFieldTitle2";
this.customFieldTitle2.UseMnemonic = false;
//
// customFieldContent2
//
this.customFieldContent2.AutoEllipsis = true;
resources.ApplyResources(this.customFieldContent2, "customFieldContent2");
this.customFieldContent2.Name = "customFieldContent2";
this.customFieldContent2.UseMnemonic = false;
//
// labelModeTitle
//
resources.ApplyResources(this.labelModeTitle, "labelModeTitle");
this.labelModeTitle.Name = "labelModeTitle";
this.labelModeTitle.UseMnemonic = false;
//
// labelMode
//
resources.ApplyResources(this.labelMode, "labelMode");
this.labelMode.Name = "labelMode";
//
// propertiesButton
//
resources.ApplyResources(this.propertiesButton, "propertiesButton");
this.propertiesButton.Name = "propertiesButton";
this.propertiesButton.UseVisualStyleBackColor = true;
this.propertiesButton.Click += new System.EventHandler(this.propertiesButton_Click);
//
// nameLabel
//
this.nameLabel.AutoEllipsis = true;
resources.ApplyResources(this.nameLabel, "nameLabel");
this.nameLabel.Name = "nameLabel";
this.nameLabel.UseMnemonic = false;
//
// shadowPanel1
//
resources.ApplyResources(this.shadowPanel1, "shadowPanel1");
this.shadowPanel1.BorderColor = System.Drawing.Color.Empty;
this.shadowPanel1.Controls.Add(this.screenshotPictureBox);
this.shadowPanel1.Name = "shadowPanel1";
this.shadowPanel1.PanelColor = System.Drawing.Color.Empty;
//
// screenshotPictureBox
//
this.screenshotPictureBox.Cursor = System.Windows.Forms.Cursors.Hand;
resources.ApplyResources(this.screenshotPictureBox, "screenshotPictureBox");
this.screenshotPictureBox.Name = "screenshotPictureBox";
this.screenshotPictureBox.TabStop = false;
this.screenshotPictureBox.Click += new System.EventHandler(this.screenshotPictureBox_Click);
//
// viewPanel
//
this.viewPanel.Controls.Add(this.snapshotTreeView);
resources.ApplyResources(this.viewPanel, "viewPanel");
this.viewPanel.Name = "viewPanel";
//
// snapshotTreeView
//
resources.ApplyResources(this.snapshotTreeView, "snapshotTreeView");
this.snapshotTreeView.AllowDrop = true;
this.snapshotTreeView.AutoArrange = false;
this.snapshotTreeView.BackgroundImageTiled = true;
this.snapshotTreeView.GridLines = true;
this.snapshotTreeView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.snapshotTreeView.HGap = 42;
this.snapshotTreeView.HideSelection = false;
this.snapshotTreeView.LinkLineColor = System.Drawing.SystemColors.ActiveBorder;
this.snapshotTreeView.Name = "snapshotTreeView";
this.snapshotTreeView.OwnerDraw = true;
this.snapshotTreeView.ShowGroups = false;
this.snapshotTreeView.ShowItemToolTips = true;
this.snapshotTreeView.TileSize = new System.Drawing.Size(80, 60);
this.snapshotTreeView.UseCompatibleStateImageBehavior = false;
this.snapshotTreeView.VGap = 50;
this.snapshotTreeView.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.snapshotTreeView_ItemDrag);
this.snapshotTreeView.SelectedIndexChanged += new System.EventHandler(this.view_SelectionChanged);
this.snapshotTreeView.DragDrop += new System.Windows.Forms.DragEventHandler(this.snapshotTreeView_DragDrop);
this.snapshotTreeView.DragEnter += new System.Windows.Forms.DragEventHandler(this.snapshotTreeView_DragEnter);
this.snapshotTreeView.DragOver += new System.Windows.Forms.DragEventHandler(this.snapshotTreeView_DragOver);
this.snapshotTreeView.Enter += new System.EventHandler(this.snapshotTreeView_Enter);
this.snapshotTreeView.Leave += new System.EventHandler(this.snapshotTreeView_Leave);
this.snapshotTreeView.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.snapshotTreeView1_MouseDoubleClick);
this.snapshotTreeView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.snapshotTreeView_MouseClick);
this.snapshotTreeView.MouseMove += new System.Windows.Forms.MouseEventHandler(this.snapshotTreeView_MouseMove);
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this.newSnapshotButton, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.toolTipContainerRevertButton, 1, 0);
this.tableLayoutPanel2.Controls.Add(this.buttonView, 4, 0);
this.tableLayoutPanel2.Controls.Add(this.saveButton, 2, 0);
this.tableLayoutPanel2.Controls.Add(this.deleteButton, 3, 0);
this.tableLayoutPanel2.Controls.Add(this.chevronButton1, 6, 0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// newSnapshotButton
//
resources.ApplyResources(this.newSnapshotButton, "newSnapshotButton");
this.newSnapshotButton.Name = "newSnapshotButton";
this.newSnapshotButton.UseVisualStyleBackColor = true;
this.newSnapshotButton.Click += new System.EventHandler(this.takeSnapshotToolStripButton_Click);
//
// toolTipContainerRevertButton
//
this.toolTipContainerRevertButton.Controls.Add(this.revertButton);
resources.ApplyResources(this.toolTipContainerRevertButton, "toolTipContainerRevertButton");
this.toolTipContainerRevertButton.Name = "toolTipContainerRevertButton";
this.toolTipContainerRevertButton.TabStop = true;
//
// revertButton
//
resources.ApplyResources(this.revertButton, "revertButton");
this.revertButton.Name = "revertButton";
this.revertButton.UseVisualStyleBackColor = true;
this.revertButton.Click += new System.EventHandler(this.revertButton_Click);
//
// buttonView
//
this.buttonView.Image = global::XenAdmin.Properties.Resources.expanded_triangle;
resources.ApplyResources(this.buttonView, "buttonView");
this.buttonView.Name = "buttonView";
this.buttonView.UseVisualStyleBackColor = true;
this.buttonView.Click += new System.EventHandler(this.button1_Click);
//
// saveButton
//
this.saveButton.Image = global::XenAdmin.Properties.Resources.expanded_triangle;
resources.ApplyResources(this.saveButton, "saveButton");
this.saveButton.Name = "saveButton";
this.saveButton.UseVisualStyleBackColor = true;
this.saveButton.Click += new System.EventHandler(this.saveButton_Click);
//
// deleteButton
//
resources.ApplyResources(this.deleteButton, "deleteButton");
this.deleteButton.Name = "deleteButton";
this.deleteButton.UseVisualStyleBackColor = true;
this.deleteButton.Click += new System.EventHandler(this.deleteButton_Click);
//
// chevronButton1
//
resources.ApplyResources(this.chevronButton1, "chevronButton1");
this.chevronButton1.Cursor = System.Windows.Forms.Cursors.Default;
this.chevronButton1.Image = ((System.Drawing.Image)(resources.GetObject("chevronButton1.Image")));
this.chevronButton1.Name = "chevronButton1";
this.chevronButton1.ButtonClick += new System.EventHandler(this.chevronButton1_ButtonClick);
this.chevronButton1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.chevronButton1_KeyDown);
//
// contextMenuStrip
//
this.contextMenuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.TakeSnapshotToolStripMenuItem,
this.revertToolStripMenuItem,
this.saveVMToolStripSeparator,
this.saveVMToolStripMenuItem,
this.saveTemplateToolStripMenuItem,
this.exportToolStripMenuItem,
this.separatorDeleteToolStripSeparator,
this.viewToolStripMenuItem,
this.sortByToolStripMenuItem,
this.sortToolStripSeparator,
this.deleteToolStripMenuItem,
this.propertiesToolStripMenuItem});
this.contextMenuStrip.Name = "contextMenuStrip1";
resources.ApplyResources(this.contextMenuStrip, "contextMenuStrip");
this.contextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip_Opening);
//
// TakeSnapshotToolStripMenuItem
//
this.TakeSnapshotToolStripMenuItem.Name = "TakeSnapshotToolStripMenuItem";
resources.ApplyResources(this.TakeSnapshotToolStripMenuItem, "TakeSnapshotToolStripMenuItem");
this.TakeSnapshotToolStripMenuItem.Click += new System.EventHandler(this.takeSnapshotToolStripButton_Click);
//
// revertToolStripMenuItem
//
this.revertToolStripMenuItem.Name = "revertToolStripMenuItem";
resources.ApplyResources(this.revertToolStripMenuItem, "revertToolStripMenuItem");
this.revertToolStripMenuItem.Click += new System.EventHandler(this.restoreToolStripButton_Click);
//
// saveVMToolStripSeparator
//
this.saveVMToolStripSeparator.Name = "saveVMToolStripSeparator";
resources.ApplyResources(this.saveVMToolStripSeparator, "saveVMToolStripSeparator");
//
// saveVMToolStripMenuItem
//
this.saveVMToolStripMenuItem.Name = "saveVMToolStripMenuItem";
resources.ApplyResources(this.saveVMToolStripMenuItem, "saveVMToolStripMenuItem");
this.saveVMToolStripMenuItem.Click += new System.EventHandler(this.saveAsAVirtualMachineToolStripMenuItem_Click);
//
// saveTemplateToolStripMenuItem
//
this.saveTemplateToolStripMenuItem.Name = "saveTemplateToolStripMenuItem";
resources.ApplyResources(this.saveTemplateToolStripMenuItem, "saveTemplateToolStripMenuItem");
this.saveTemplateToolStripMenuItem.Click += new System.EventHandler(this.saveAsATemplateToolStripMenuItem_Click);
//
// exportToolStripMenuItem
//
this.exportToolStripMenuItem.Name = "exportToolStripMenuItem";
resources.ApplyResources(this.exportToolStripMenuItem, "exportToolStripMenuItem");
this.exportToolStripMenuItem.Click += new System.EventHandler(this.exportSnapshotToolStripMenuItem_Click);
//
// separatorDeleteToolStripSeparator
//
this.separatorDeleteToolStripSeparator.Name = "separatorDeleteToolStripSeparator";
resources.ApplyResources(this.separatorDeleteToolStripSeparator, "separatorDeleteToolStripSeparator");
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
resources.ApplyResources(this.viewToolStripMenuItem, "viewToolStripMenuItem");
//
// sortByToolStripMenuItem
//
this.sortByToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.sortByNameToolStripMenuItem,
this.sortByCreatedOnToolStripMenuItem,
this.sortBySizeToolStripMenuItem,
this.sortByTypeToolStripMenuItem});
this.sortByToolStripMenuItem.Name = "sortByToolStripMenuItem";
resources.ApplyResources(this.sortByToolStripMenuItem, "sortByToolStripMenuItem");
//
// sortByNameToolStripMenuItem
//
this.sortByNameToolStripMenuItem.Name = "sortByNameToolStripMenuItem";
resources.ApplyResources(this.sortByNameToolStripMenuItem, "sortByNameToolStripMenuItem");
this.sortByNameToolStripMenuItem.Click += new System.EventHandler(this.sortByNameToolStripMenuItem_Click);
//
// sortByCreatedOnToolStripMenuItem
//
this.sortByCreatedOnToolStripMenuItem.Name = "sortByCreatedOnToolStripMenuItem";
resources.ApplyResources(this.sortByCreatedOnToolStripMenuItem, "sortByCreatedOnToolStripMenuItem");
this.sortByCreatedOnToolStripMenuItem.Click += new System.EventHandler(this.sortByCreatedOnToolStripMenuItem_Click);
//
// sortBySizeToolStripMenuItem
//
this.sortBySizeToolStripMenuItem.Name = "sortBySizeToolStripMenuItem";
resources.ApplyResources(this.sortBySizeToolStripMenuItem, "sortBySizeToolStripMenuItem");
this.sortBySizeToolStripMenuItem.Click += new System.EventHandler(this.sortBySizeToolStripMenuItem_Click);
//
// sortByTypeToolStripMenuItem
//
this.sortByTypeToolStripMenuItem.Name = "sortByTypeToolStripMenuItem";
resources.ApplyResources(this.sortByTypeToolStripMenuItem, "sortByTypeToolStripMenuItem");
this.sortByTypeToolStripMenuItem.Click += new System.EventHandler(this.sortByTypeToolStripMenuItem_Click);
//
// sortToolStripSeparator
//
this.sortToolStripSeparator.Name = "sortToolStripSeparator";
resources.ApplyResources(this.sortToolStripSeparator, "sortToolStripSeparator");
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem");
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripButton_Click);
//
// propertiesToolStripMenuItem
//
this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem";
resources.ApplyResources(this.propertiesToolStripMenuItem, "propertiesToolStripMenuItem");
this.propertiesToolStripMenuItem.Click += new System.EventHandler(this.propertiesButton_Click);
//
// dataGridView
//
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.AllowUserToOrderColumns = true;
this.dataGridView.AllowUserToResizeRows = false;
this.dataGridView.BackgroundColor = System.Drawing.Color.White;
this.dataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dataGridView.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.ControlDarkDark;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridView.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.columnType,
this.columnName,
this.columnCreated,
this.columnSize,
this.columnTags,
this.ColumnDescription});
resources.ApplyResources(this.dataGridView, "dataGridView");
this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true;
this.dataGridView.RowHeadersVisible = false;
this.dataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView.SelectionChanged += new System.EventHandler(this.view_SelectionChanged);
this.dataGridView.MouseClick += new System.Windows.Forms.MouseEventHandler(this.dataGridView_MouseClick);
//
// columnType
//
this.columnType.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
resources.ApplyResources(this.columnType, "columnType");
this.columnType.Name = "columnType";
this.columnType.ReadOnly = true;
this.columnType.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// columnName
//
this.columnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
resources.ApplyResources(this.columnName, "columnName");
this.columnName.Name = "columnName";
this.columnName.ReadOnly = true;
this.columnName.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// columnCreated
//
this.columnCreated.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
resources.ApplyResources(this.columnCreated, "columnCreated");
this.columnCreated.Name = "columnCreated";
this.columnCreated.ReadOnly = true;
this.columnCreated.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// columnSize
//
this.columnSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
this.columnSize.DefaultCellStyle = dataGridViewCellStyle2;
resources.ApplyResources(this.columnSize, "columnSize");
this.columnSize.Name = "columnSize";
this.columnSize.ReadOnly = true;
//
// columnTags
//
this.columnTags.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
resources.ApplyResources(this.columnTags, "columnTags");
this.columnTags.Name = "columnTags";
this.columnTags.ReadOnly = true;
this.columnTags.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// ColumnDescription
//
this.ColumnDescription.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.ColumnDescription, "ColumnDescription");
this.ColumnDescription.Name = "ColumnDescription";
this.ColumnDescription.ReadOnly = true;
this.ColumnDescription.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// dateLabel
//
resources.ApplyResources(this.dateLabel, "dateLabel");
this.dateLabel.Name = "dateLabel";
//
// tableLayoutPanelMultipleSelection
//
resources.ApplyResources(this.tableLayoutPanelMultipleSelection, "tableLayoutPanelMultipleSelection");
this.tableLayoutPanelMultipleSelection.Controls.Add(this.multipleSelectionTags, 1, 1);
this.tableLayoutPanelMultipleSelection.Controls.Add(this.multipleSelectionTotalSize, 1, 0);
this.tableLayoutPanelMultipleSelection.Controls.Add(this.label6, 0, 0);
this.tableLayoutPanelMultipleSelection.Controls.Add(this.label7, 0, 1);
this.tableLayoutPanelMultipleSelection.Name = "tableLayoutPanelMultipleSelection";
//
// multipleSelectionTags
//
resources.ApplyResources(this.multipleSelectionTags, "multipleSelectionTags");
this.multipleSelectionTags.Name = "multipleSelectionTags";
//
// multipleSelectionTotalSize
//
resources.ApplyResources(this.multipleSelectionTotalSize, "multipleSelectionTotalSize");
this.multipleSelectionTotalSize.Name = "multipleSelectionTotalSize";
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.Name = "label7";
//
// saveMenuStrip
//
this.saveMenuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
this.saveMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveAsVMToolStripMenuItem,
this.toolStripSeparator2,
this.saveAsTemplateToolStripMenuItem,
this.exportAsBackupToolStripMenuItem});
this.saveMenuStrip.Name = "saveMenuStrip";
resources.ApplyResources(this.saveMenuStrip, "saveMenuStrip");
//
// saveAsVMToolStripMenuItem
//
this.saveAsVMToolStripMenuItem.Name = "saveAsVMToolStripMenuItem";
resources.ApplyResources(this.saveAsVMToolStripMenuItem, "saveAsVMToolStripMenuItem");
this.saveAsVMToolStripMenuItem.Click += new System.EventHandler(this.toolStripMenuItem1_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// saveAsTemplateToolStripMenuItem
//
this.saveAsTemplateToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.saveAsTemplateToolStripMenuItem.Name = "saveAsTemplateToolStripMenuItem";
resources.ApplyResources(this.saveAsTemplateToolStripMenuItem, "saveAsTemplateToolStripMenuItem");
this.saveAsTemplateToolStripMenuItem.Click += new System.EventHandler(this.saveAsTemplateToolStripMenuItem_Click);
//
// exportAsBackupToolStripMenuItem
//
this.exportAsBackupToolStripMenuItem.Name = "exportAsBackupToolStripMenuItem";
resources.ApplyResources(this.exportAsBackupToolStripMenuItem, "exportAsBackupToolStripMenuItem");
this.exportAsBackupToolStripMenuItem.Click += new System.EventHandler(this.exportAsBackupToolStripMenuItem_Click);
//
// contextMenuStripView
//
this.contextMenuStripView.ImageScalingSize = new System.Drawing.Size(20, 20);
this.contextMenuStripView.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripButtonListView,
this.toolStripButtonTreeView,
this.toolStripSeparatorView,
this.toolStripMenuItemScheduledSnapshots});
this.contextMenuStripView.Name = "contextMenuStripView";
resources.ApplyResources(this.contextMenuStripView, "contextMenuStripView");
//
// toolStripButtonListView
//
this.toolStripButtonListView.Image = global::XenAdmin.Properties.Resources._000_ViewModeList_h32bit_16;
this.toolStripButtonListView.Name = "toolStripButtonListView";
resources.ApplyResources(this.toolStripButtonListView, "toolStripButtonListView");
this.toolStripButtonListView.Click += new System.EventHandler(this.gridToolStripMenuItem_Click);
//
// toolStripButtonTreeView
//
this.toolStripButtonTreeView.Image = global::XenAdmin.Properties.Resources._000_ViewModeTree_h32bit_16;
this.toolStripButtonTreeView.Name = "toolStripButtonTreeView";
resources.ApplyResources(this.toolStripButtonTreeView, "toolStripButtonTreeView");
this.toolStripButtonTreeView.Click += new System.EventHandler(this.treeToolStripMenuItem_Click);
//
// toolStripSeparatorView
//
this.toolStripSeparatorView.Name = "toolStripSeparatorView";
resources.ApplyResources(this.toolStripSeparatorView, "toolStripSeparatorView");
//
// toolStripMenuItemScheduledSnapshots
//
this.toolStripMenuItemScheduledSnapshots.Name = "toolStripMenuItemScheduledSnapshots";
resources.ApplyResources(this.toolStripMenuItemScheduledSnapshots, "toolStripMenuItemScheduledSnapshots");
this.toolStripMenuItemScheduledSnapshots.Click += new System.EventHandler(this.toolStripMenuItemScheduledSnapshots_Click);
//
// SnapshotsPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.DoubleBuffered = true;
this.Name = "SnapshotsPage";
this.Controls.SetChildIndex(this.pageContainerPanel, 0);
this.pageContainerPanel.ResumeLayout(false);
this.pageContainerPanel.PerformLayout();
this.GeneralTableLayoutPanel.ResumeLayout(false);
this.GeneralTableLayoutPanel.PerformLayout();
this.contentTableLayoutPanel.ResumeLayout(false);
this.panelPropertiesColumn.ResumeLayout(false);
this.panelPropertiesColumn.PerformLayout();
this.panelVMPP.ResumeLayout(false);
this.panelVMPP.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxVMPPInfo)).EndInit();
this.propertiesGroupBox.ResumeLayout(false);
this.propertiesGroupBox.PerformLayout();
this.propertiesTableLayoutPanel.ResumeLayout(false);
this.propertiesTableLayoutPanel.PerformLayout();
this.tableLayoutPanelSimpleSelection.ResumeLayout(false);
this.tableLayoutPanelSimpleSelection.PerformLayout();
this.shadowPanel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.screenshotPictureBox)).EndInit();
this.viewPanel.ResumeLayout(false);
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.toolTipContainerRevertButton.ResumeLayout(false);
this.contextMenuStrip.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.tableLayoutPanelMultipleSelection.ResumeLayout(false);
this.saveMenuStrip.ResumeLayout(false);
this.contextMenuStripView.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DataGridView dataGridView;
private System.Windows.Forms.TableLayoutPanel GeneralTableLayoutPanel;
private XenAdmin.Controls.SnapshotTreeView snapshotTreeView;
private System.Windows.Forms.Panel viewPanel;
private System.Windows.Forms.GroupBox propertiesGroupBox;
private System.Windows.Forms.TableLayoutPanel propertiesTableLayoutPanel;
private System.Windows.Forms.Label folderTitleLabel;
private System.Windows.Forms.Label tagsTitleLabel;
private System.Windows.Forms.Label sizeTitleLabel;
private System.Windows.Forms.Label dateLabel;
private System.Windows.Forms.Label descriptionLabel;
private System.Windows.Forms.Label nameLabel;
private System.Windows.Forms.Label sizeLabel;
private System.Windows.Forms.Button propertiesButton;
private System.Windows.Forms.Label folderLabel;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem revertToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem TakeSnapshotToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator separatorDeleteToolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem propertiesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator saveVMToolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem saveVMToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveTemplateToolStripMenuItem;
private System.Windows.Forms.Label tagsLabel;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sortByToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator sortToolStripSeparator;
private System.Windows.Forms.ToolStripMenuItem sortByNameToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sortByCreatedOnToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sortBySizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem sortByTypeToolStripMenuItem;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.PictureBox screenshotPictureBox;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelSimpleSelection;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelMultipleSelection;
private System.Windows.Forms.Label multipleSelectionTags;
private System.Windows.Forms.Label multipleSelectionTotalSize;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private XenAdmin.Controls.ShadowPanel shadowPanel1;
private System.Windows.Forms.TableLayoutPanel contentTableLayoutPanel;
private XenAdmin.Controls.NonReopeningContextMenuStrip saveMenuStrip;
private System.Windows.Forms.ToolStripMenuItem saveAsTemplateToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveAsVMToolStripMenuItem;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.ToolStripMenuItem exportAsBackupToolStripMenuItem;
private System.Windows.Forms.Button newSnapshotButton;
private System.Windows.Forms.Button revertButton;
private System.Windows.Forms.Button saveButton;
private System.Windows.Forms.Button deleteButton;
private System.Windows.Forms.Label customFieldTitle1;
private System.Windows.Forms.Label customFieldContent1;
private System.Windows.Forms.Label customFieldTitle2;
private System.Windows.Forms.Label customFieldContent2;
private XenAdmin.Controls.ToolTipContainer toolTipContainerRevertButton;
private System.Windows.Forms.Label labelModeTitle;
private System.Windows.Forms.Label labelMode;
private System.Windows.Forms.Panel panelPropertiesColumn;
private System.Windows.Forms.Panel panelVMPP;
private System.Windows.Forms.Label labelVMPPInfo;
private System.Windows.Forms.PictureBox pictureBoxVMPPInfo;
private System.Windows.Forms.LinkLabel linkLabelVMPPInfo;
private System.Windows.Forms.Button buttonView;
private XenAdmin.Controls.NonReopeningContextMenuStrip contextMenuStripView;
private System.Windows.Forms.ToolStripMenuItem toolStripButtonListView;
private System.Windows.Forms.ToolStripMenuItem toolStripButtonTreeView;
private System.Windows.Forms.ToolStripSeparator toolStripSeparatorView;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemScheduledSnapshots;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private XenAdmin.Controls.ChevronButton chevronButton1;
private System.Windows.Forms.DataGridViewTextBoxColumn columnType;
private System.Windows.Forms.DataGridViewTextBoxColumn columnName;
private System.Windows.Forms.DataGridViewTextBoxColumn columnCreated;
private System.Windows.Forms.DataGridViewTextBoxColumn columnSize;
private System.Windows.Forms.DataGridViewTextBoxColumn columnTags;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDescription;
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="SmtpTransport.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace System.Net.Mail
{
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Mime;
using System.Diagnostics;
internal enum SupportedAuth{
None = 0, Login = 1,
#if !FEATURE_PAL
NTLM = 2, GSSAPI = 4, WDigest = 8
#endif
};
internal class SmtpPooledStream:PooledStream{
internal bool previouslyUsed;
internal bool dsnEnabled; //delivery status notification
internal bool serverSupportsEai;
internal ICredentialsByHost creds;
internal SmtpPooledStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime) : base (connectionPool,lifetime,checkLifetime) {
}
// maximum line length in SMTP response is 76 so this is a bit more conservative
const int safeBufferLength = 80;
// Cleans up an open connection to an SMTP server by sending the QUIT
// response, reading the server's response, and disposing the base stream
protected override void Dispose(bool disposing)
{
if (Logging.On) {
Logging.Enter(Logging.Web, "SmtpPooledStream::Dispose #" + ValidationHelper.HashString(this));
}
if (disposing) {
if (this.NetworkStream.Connected) {
this.Write(SmtpCommands.Quit, 0, SmtpCommands.Quit.Length);
this.Flush();
// read the response - this is a formality since the connection is shut down
// immediately by the server so this data can safely be ignored but buffer
// must be read to ensure a FIN is sent instead of a RST
byte[] buffer = new byte[safeBufferLength];
int result = this.Read(buffer, 0, safeBufferLength);
}
}
base.Dispose(disposing);
if (Logging.On) {
Logging.Exit(Logging.Web, "SmtpPooledStream::Dispose #" + ValidationHelper.HashString(this));
}
}
}
internal class SmtpTransport
{
internal const int DefaultPort = 25;
ISmtpAuthenticationModule[] authenticationModules;
SmtpConnection connection;
SmtpClient client;
ICredentialsByHost credentials;
int timeout = 100000; // seconds
ArrayList failedRecipientExceptions = new ArrayList();
bool m_IdentityRequired;
bool enableSsl = false;
X509CertificateCollection clientCertificates = null;
ServicePoint lastUsedServicePoint;
internal SmtpTransport(SmtpClient client) : this(client, SmtpAuthenticationManager.GetModules()) {
}
internal SmtpTransport(SmtpClient client, ISmtpAuthenticationModule[] authenticationModules)
{
this.client = client;
if (authenticationModules == null)
{
throw new ArgumentNullException("authenticationModules");
}
this.authenticationModules = authenticationModules;
}
internal ICredentialsByHost Credentials
{
get
{
return credentials;
}
set
{
credentials = value;
}
}
internal bool IdentityRequired
{
get
{
return m_IdentityRequired;
}
set
{
m_IdentityRequired = value;
}
}
internal bool IsConnected
{
get
{
return connection != null && connection.IsConnected;
}
}
internal int Timeout
{
get
{
return timeout;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
timeout = value;
}
}
internal bool EnableSsl
{
get
{
return enableSsl;
}
set
{
#if !FEATURE_PAL
enableSsl = value;
#else
throw new NotImplementedException("ROTORTODO");
#endif
}
}
internal X509CertificateCollection ClientCertificates
{
get {
if (clientCertificates == null) {
clientCertificates = new X509CertificateCollection();
}
return clientCertificates;
}
}
internal bool ServerSupportsEai
{
get { return connection != null && connection.ServerSupportsEai; }
}
// check to see if we're using a different servicepoint than the last
// servicepoint used to get a connectionpool
//
// preconditions: servicePoint must have valid host and port (checked in SmtpClient)
//
// postconditions: if servicePoint is different than the last servicePoint used by this object,
// the connection pool for the previous servicepoint will be cleaned up and servicePoint will be
// cached to identify if it has changed in future uses of this SmtpTransport object
private void UpdateServicePoint(ServicePoint servicePoint)
{
if (lastUsedServicePoint == null) {
lastUsedServicePoint = servicePoint;
}
else if (lastUsedServicePoint.Host != servicePoint.Host
|| lastUsedServicePoint.Port != servicePoint.Port) {
ConnectionPoolManager.CleanupConnectionPool(servicePoint, "");
lastUsedServicePoint = servicePoint;
}
}
internal void GetConnection(ServicePoint servicePoint)
{
try {
Debug.Assert(servicePoint != null, "no ServicePoint provided by SmtpClient");
// check to see if we have a different connection than last time
UpdateServicePoint(servicePoint);
connection = new SmtpConnection(this, client, credentials, authenticationModules);
connection.Timeout = timeout;
if(Logging.On)Logging.Associate(Logging.Web, this, connection);
if (EnableSsl)
{
connection.EnableSsl = true;
connection.ClientCertificates = ClientCertificates;
}
connection.GetConnection(servicePoint);
}
finally {
}
}
internal IAsyncResult BeginGetConnection(ServicePoint servicePoint, ContextAwareResult outerResult, AsyncCallback callback, object state)
{
GlobalLog.Enter("SmtpTransport#" + ValidationHelper.HashString(this) + "::BeginConnect");
IAsyncResult result = null;
try{
UpdateServicePoint(servicePoint);
connection = new SmtpConnection(this, client, credentials, authenticationModules);
connection.Timeout = timeout;
if(Logging.On)Logging.Associate(Logging.Web, this, connection);
if (EnableSsl)
{
connection.EnableSsl = true;
connection.ClientCertificates = ClientCertificates;
}
result = connection.BeginGetConnection(servicePoint, outerResult, callback, state);
}
catch(Exception innerException){
throw new SmtpException(SR.GetString(SR.MailHostNotFound), innerException);
}
GlobalLog.Leave("SmtpTransport#" + ValidationHelper.HashString(this) + "::BeginConnect [....] Completion");
return result;
}
internal void EndGetConnection(IAsyncResult result)
{
GlobalLog.Enter("SmtpTransport#" + ValidationHelper.HashString(this) + "::EndGetConnection");
try {
connection.EndGetConnection(result);
}
finally {
GlobalLog.Leave("SmtpTransport#" + ValidationHelper.HashString(this) + "::EndConnect");
}
}
internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients,
string deliveryNotify, bool allowUnicode, AsyncCallback callback, object state)
{
if (sender == null)
{
throw new ArgumentNullException("sender");
}
if (recipients == null)
{
throw new ArgumentNullException("recipients");
}
GlobalLog.Assert(recipients.Count > 0, "SmtpTransport::BeginSendMail()|recepients.Count <= 0");
SendMailAsyncResult result = new SendMailAsyncResult(connection, sender, recipients,
allowUnicode, connection.DSNEnabled ? deliveryNotify : null,
callback, state);
result.Send();
return result;
}
internal void ReleaseConnection() {
if(connection != null){
connection.ReleaseConnection();
}
}
internal void Abort() {
if(connection != null){
connection.Abort();
}
}
internal MailWriter EndSendMail(IAsyncResult result)
{
try {
return SendMailAsyncResult.End(result);
}
finally {
}
}
internal MailWriter SendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify,
bool allowUnicode, out SmtpFailedRecipientException exception)
{
if (sender == null)
{
throw new ArgumentNullException("sender");
}
if (recipients == null)
{
throw new ArgumentNullException("recipients");
}
GlobalLog.Assert(recipients.Count > 0, "SmtpTransport::SendMail()|recepients.Count <= 0");
MailCommand.Send(connection, SmtpCommands.Mail, sender, allowUnicode);
failedRecipientExceptions.Clear();
exception = null;
string response;
foreach (MailAddress address in recipients) {
string smtpAddress = address.GetSmtpAddress(allowUnicode);
string to = smtpAddress + (connection.DSNEnabled ? deliveryNotify : String.Empty);
if (!RecipientCommand.Send(connection, to, out response)) {
failedRecipientExceptions.Add(
new SmtpFailedRecipientException(connection.Reader.StatusCode, smtpAddress, response));
}
}
if (failedRecipientExceptions.Count > 0)
{
if (failedRecipientExceptions.Count == 1)
{
exception = (SmtpFailedRecipientException) failedRecipientExceptions[0];
}
else
{
exception = new SmtpFailedRecipientsException(failedRecipientExceptions, failedRecipientExceptions.Count == recipients.Count);
}
if (failedRecipientExceptions.Count == recipients.Count){
exception.fatal = true;
throw exception;
}
}
DataCommand.Send(connection);
return new MailWriter(connection.GetClosableStream());
}
internal void CloseIdleConnections(ServicePoint servicePoint)
{
ConnectionPoolManager.CleanupConnectionPool(servicePoint, "");
}
}
class SendMailAsyncResult : LazyAsyncResult
{
SmtpConnection connection;
MailAddress from;
string deliveryNotify;
static AsyncCallback sendMailFromCompleted = new AsyncCallback(SendMailFromCompleted);
static AsyncCallback sendToCollectionCompleted = new AsyncCallback(SendToCollectionCompleted);
static AsyncCallback sendDataCompleted = new AsyncCallback(SendDataCompleted);
ArrayList failedRecipientExceptions = new ArrayList();
Stream stream;
MailAddressCollection toCollection;
int toIndex;
private bool allowUnicode;
internal SendMailAsyncResult(SmtpConnection connection, MailAddress from, MailAddressCollection toCollection,
bool allowUnicode, string deliveryNotify, AsyncCallback callback, object state)
: base(null, state, callback)
{
this.toCollection = toCollection;
this.connection = connection;
this.from = from;
this.deliveryNotify = deliveryNotify;
this.allowUnicode = allowUnicode;
}
internal void Send(){
SendMailFrom();
}
internal static MailWriter End(IAsyncResult result)
{
SendMailAsyncResult thisPtr = (SendMailAsyncResult)result;
object sendMailResult = thisPtr.InternalWaitForCompletion();
// Note the difference between the singular and plural FailedRecipient exceptions.
// Only fail immediately if we couldn't send to any recipients.
if ((sendMailResult is Exception)
&& (!(sendMailResult is SmtpFailedRecipientException)
|| ((SmtpFailedRecipientException)sendMailResult).fatal))
{
throw (Exception)sendMailResult;
}
return new MailWriter(thisPtr.stream);
}
void SendMailFrom()
{
IAsyncResult result = MailCommand.BeginSend(connection, SmtpCommands.Mail, from, allowUnicode,
sendMailFromCompleted, this);
if (!result.CompletedSynchronously)
{
return;
}
MailCommand.EndSend(result);
SendToCollection();
}
static void SendMailFromCompleted(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState;
try
{
MailCommand.EndSend(result);
thisPtr.SendToCollection();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
void SendToCollection()
{
while (toIndex < toCollection.Count)
{
MultiAsyncResult result = (MultiAsyncResult)RecipientCommand.BeginSend(connection,
toCollection[toIndex++].GetSmtpAddress(allowUnicode) + deliveryNotify,
sendToCollectionCompleted, this);
if (!result.CompletedSynchronously)
{
return;
}
string response;
if (!RecipientCommand.EndSend(result, out response)){
failedRecipientExceptions.Add(new SmtpFailedRecipientException(connection.Reader.StatusCode,
toCollection[toIndex - 1].GetSmtpAddress(allowUnicode), response));
}
}
SendData();
}
static void SendToCollectionCompleted(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState;
try
{
string response;
if (!RecipientCommand.EndSend(result, out response))
{
thisPtr.failedRecipientExceptions.Add(
new SmtpFailedRecipientException(thisPtr.connection.Reader.StatusCode,
thisPtr.toCollection[thisPtr.toIndex - 1].GetSmtpAddress(thisPtr.allowUnicode),
response));
if (thisPtr.failedRecipientExceptions.Count == thisPtr.toCollection.Count)
{
SmtpFailedRecipientException exception = null;
if (thisPtr.toCollection.Count == 1)
{
exception = (SmtpFailedRecipientException)thisPtr.failedRecipientExceptions[0];
}
else
{
exception = new SmtpFailedRecipientsException(thisPtr.failedRecipientExceptions, true);
}
exception.fatal = true;
thisPtr.InvokeCallback(exception);
return;
}
}
thisPtr.SendToCollection();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
void SendData()
{
IAsyncResult result = DataCommand.BeginSend(connection, sendDataCompleted, this);
if (!result.CompletedSynchronously)
{
return;
}
DataCommand.EndSend(result);
stream = connection.GetClosableStream();
if (failedRecipientExceptions.Count > 1)
{
InvokeCallback(new SmtpFailedRecipientsException(failedRecipientExceptions, failedRecipientExceptions.Count == toCollection.Count));
}
else if (failedRecipientExceptions.Count == 1)
{
InvokeCallback(failedRecipientExceptions[0]);
}
else
{
InvokeCallback();
}
}
static void SendDataCompleted(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState;
try
{
DataCommand.EndSend(result);
thisPtr.stream = thisPtr.connection.GetClosableStream();
if (thisPtr.failedRecipientExceptions.Count > 1)
{
thisPtr.InvokeCallback(new SmtpFailedRecipientsException(thisPtr.failedRecipientExceptions, thisPtr.failedRecipientExceptions.Count == thisPtr.toCollection.Count));
}
else if (thisPtr.failedRecipientExceptions.Count == 1)
{
thisPtr.InvokeCallback(thisPtr.failedRecipientExceptions[0]);
}
else
{
thisPtr.InvokeCallback();
}
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
// Return the list of non-terminal failures (some recipients failed but not others).
internal SmtpFailedRecipientException GetFailedRecipientException()
{
if (failedRecipientExceptions.Count == 1)
{
return (SmtpFailedRecipientException)failedRecipientExceptions[0];
}
else if (failedRecipientExceptions.Count > 1)
{
// Aggregate exception, multiple failures
return new SmtpFailedRecipientsException(failedRecipientExceptions, false);
}
return null;
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Management.Automation.Internal;
using COM = System.Runtime.InteropServices.ComTypes;
namespace System.Management.Automation
{
/// <summary>
/// A Wrapper class for COM object's Type Information
/// </summary>
internal class ComTypeInfo
{
/// <summary>
/// Member variables.
/// </summary>
private Dictionary<String, ComProperty> _properties = null;
private Dictionary<String, ComMethod> _methods = null;
private COM.ITypeInfo _typeinfo = null;
private Guid _guid = Guid.Empty;
/// <summary>
/// Constructor
/// </summary>
/// <param name="info">ITypeInfo object being wrapped by this object</param>
internal ComTypeInfo(COM.ITypeInfo info)
{
_typeinfo = info;
_properties = new Dictionary<String, ComProperty>(StringComparer.OrdinalIgnoreCase);
_methods = new Dictionary<String, ComMethod>(StringComparer.OrdinalIgnoreCase);
if (_typeinfo != null)
{
Initialize();
}
}
/// <summary>
/// Collection of properties in the COM object.
/// </summary>
public Dictionary<String, ComProperty> Properties
{
get
{
return _properties;
}
}
/// <summary>
/// Collection of methods in the COM object.
/// </summary>
public Dictionary<String, ComMethod> Methods
{
get
{
return _methods;
}
}
/// <summary>
/// Returns the string of the GUID for the type information.
/// </summary>
public string Clsid
{
get
{
return _guid.ToString();
}
}
/// <summary>
/// Initializes the typeinfo object
/// </summary>
private void Initialize()
{
if (_typeinfo != null)
{
COM.TYPEATTR typeattr = GetTypeAttr(_typeinfo);
//Initialize the type information guid
_guid = typeattr.guid;
for (int i = 0; i < typeattr.cFuncs; i++)
{
COM.FUNCDESC funcdesc = GetFuncDesc(_typeinfo, i);
if ((funcdesc.wFuncFlags & 0x1) == 0x1)
{
// http://msdn.microsoft.com/en-us/library/ee488948.aspx
// FUNCFLAGS -- FUNCFLAG_FRESTRICTED = 0x1:
// Indicates that the function should not be accessible from macro languages.
// This flag is intended for system-level functions or functions that type browsers should not display.
//
// For IUnknown methods (AddRef, QueryInterface and Release) and IDispatch methods (GetTypeInfoCount, GetTypeInfo, GetIDsOfNames and Invoke)
// FUNCFLAG_FRESTRICTED (0x1) is set for the 'wFuncFlags' field
continue;
}
String strName = ComUtil.GetNameFromFuncDesc(_typeinfo, funcdesc);
switch (funcdesc.invkind)
{
case COM.INVOKEKIND.INVOKE_PROPERTYGET:
case COM.INVOKEKIND.INVOKE_PROPERTYPUT:
case COM.INVOKEKIND.INVOKE_PROPERTYPUTREF:
AddProperty(strName, funcdesc, i);
break;
case COM.INVOKEKIND.INVOKE_FUNC:
AddMethod(strName, i);
break;
}
}
}
}
/// <summary>
/// Get the typeinfo interface for the given comobject.
/// </summary>
/// <param name="comObject">reference to com object for which we are getting type information.</param>
/// <returns>ComTypeInfo object which wraps the ITypeInfo interface of the given COM object</returns>
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", Justification = "Code uses the out parameter of 'GetTypeInfo' to check if the call succeeded.")]
internal static ComTypeInfo GetDispatchTypeInfo(object comObject)
{
ComTypeInfo result = null;
IDispatch disp = comObject as IDispatch;
if (disp != null)
{
COM.ITypeInfo typeinfo = null;
disp.GetTypeInfo(0, 0, out typeinfo);
if (typeinfo != null)
{
COM.TYPEATTR typeattr = GetTypeAttr(typeinfo);
if ((typeattr.typekind == COM.TYPEKIND.TKIND_INTERFACE))
{
//We have typeinfo for custom interface. Get typeinfo for Dispatch interface.
typeinfo = GetDispatchTypeInfoFromCustomInterfaceTypeInfo(typeinfo);
}
if ((typeattr.typekind == COM.TYPEKIND.TKIND_COCLASS))
{
//We have typeinfo for the COClass. Find the default interface and get typeinfo for default interface.
typeinfo = GetDispatchTypeInfoFromCoClassTypeInfo(typeinfo);
}
result = new ComTypeInfo(typeinfo);
}
}
return result;
}
private void AddProperty(string strName, COM.FUNCDESC funcdesc, int index)
{
ComProperty prop;
if (!_properties.TryGetValue(strName, out prop))
{
prop = new ComProperty(_typeinfo, strName);
_properties[strName] = prop;
}
if (prop != null)
{
prop.UpdateFuncDesc(funcdesc, index);
}
}
private void AddMethod(string strName, int index)
{
ComMethod method;
if (!_methods.TryGetValue(strName, out method))
{
method = new ComMethod(_typeinfo, strName);
_methods[strName] = method;
}
if (method != null)
{
method.AddFuncDesc(index);
}
}
/// <summary>
/// Get TypeAttr for the given type information.
/// </summary>
/// <param name="typeinfo">reference to ITypeInfo from which to get TypeAttr</param>
/// <returns></returns>
[ArchitectureSensitive]
internal static COM.TYPEATTR GetTypeAttr(COM.ITypeInfo typeinfo)
{
IntPtr pTypeAttr;
typeinfo.GetTypeAttr(out pTypeAttr);
COM.TYPEATTR typeattr = ClrFacade.PtrToStructure<COM.TYPEATTR>(pTypeAttr);
typeinfo.ReleaseTypeAttr(pTypeAttr);
return typeattr;
}
/// <summary>
///
/// </summary>
/// <param name="typeinfo"></param>
/// <param name="index"></param>
/// <returns></returns>
[ArchitectureSensitive]
internal static COM.FUNCDESC GetFuncDesc(COM.ITypeInfo typeinfo, int index)
{
IntPtr pFuncDesc;
typeinfo.GetFuncDesc(index, out pFuncDesc);
COM.FUNCDESC funcdesc = ClrFacade.PtrToStructure<COM.FUNCDESC>(pFuncDesc);
typeinfo.ReleaseFuncDesc(pFuncDesc);
return funcdesc;
}
/// <summary>
///
/// </summary>
/// <param name="typeinfo"></param>
/// <returns></returns>
internal static COM.ITypeInfo GetDispatchTypeInfoFromCustomInterfaceTypeInfo(COM.ITypeInfo typeinfo)
{
int href;
COM.ITypeInfo dispinfo = null;
try
{
// We need the typeinfo for Dispatch Interface
typeinfo.GetRefTypeOfImplType(-1, out href);
typeinfo.GetRefTypeInfo(href, out dispinfo);
}
catch (COMException ce)
{
//check if the error code is TYPE_E_ELEMENTNOTFOUND.
//This error code is thrown when we can't IDispatch interface.
if (ce.HResult != ComUtil.TYPE_E_ELEMENTNOTFOUND)
{
//For other codes, rethrow the exception.
throw;
}
}
return dispinfo;
}
/// <summary>
/// Get the IDispatch Typeinfo from CoClass typeinfo.
/// </summary>
/// <param name="typeinfo">Reference to the type info to which the type descriptor belongs</param>
/// <returns>ITypeInfo reference to the Dispatch interface </returns>
internal static COM.ITypeInfo GetDispatchTypeInfoFromCoClassTypeInfo(COM.ITypeInfo typeinfo)
{
//Get the number of interfaces implemented by this CoClass.
COM.TYPEATTR typeattr = GetTypeAttr(typeinfo);
int count = typeattr.cImplTypes;
int href;
COM.ITypeInfo interfaceinfo = null;
//For each interface implemented by this coclass
for (int i = 0; i < count; i++)
{
//Get the type information?
typeinfo.GetRefTypeOfImplType(i, out href);
typeinfo.GetRefTypeInfo(href, out interfaceinfo);
typeattr = GetTypeAttr(interfaceinfo);
// Is this interface IDispatch compatible interface?
if (typeattr.typekind == COM.TYPEKIND.TKIND_DISPATCH)
{
return interfaceinfo;
}
//Nope. Is this a dual interface
if ((typeattr.wTypeFlags & COM.TYPEFLAGS.TYPEFLAG_FDUAL) != 0)
{
interfaceinfo = GetDispatchTypeInfoFromCustomInterfaceTypeInfo(interfaceinfo);
typeattr = GetTypeAttr(interfaceinfo);
if (typeattr.typekind == COM.TYPEKIND.TKIND_DISPATCH)
{
return interfaceinfo;
}
}
}
return null;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Schematic;
using ESRI.ArcGIS.SchematicControls;
using ESRI.ArcGIS.esriSystem;
using System.Windows.Forms;
using ESRI.ArcGIS.ArcMapUI;
using ESRI.ArcGIS.Display;
namespace CurrentDigitTool
{
internal static class CurrentTool
{
public static DigitTool.DigitTool currentDigit;
public static ESRI.ArcGIS.Framework.IDockableWindow currentDockableWindow;
public static DigitTool.DigitDockableWindow digitDockableWindow;
}
}
namespace DigitTool
{
public class DigitTool : ESRI.ArcGIS.Desktop.AddIns.Tool
{
ESRI.ArcGIS.Framework.IApplication m_app;
ESRI.ArcGIS.esriSystem.IExtension m_schematicExtension;
ISchematicLayer m_schematicLayer;
ISchematicLayer m_schematicLayerForLink;
ISchematicFeature m_schematicFeature1;
ISchematicFeature m_schematicFeature2;
INewLineFeedback m_linkFbk;
private string m_messageFromOK = "\n" + "Complete missing data and click on OK button";
private int m_x;
private int m_y;
public DigitDockableWindow m_dockableDigit;
private ESRI.ArcGIS.Framework.IDockableWindow m_dockableWindow;
private bool m_fromDeactivate = false;
private bool m_DeactivatedFromDock = false;
public DigitTool()
{
m_app = ArcMap.Application;
}
protected override void OnUpdate()
{
// the tool is enable only if the diagram is in memory
try
{
if (ArcMap.Application == null)
{
Enabled = false;
return;
}
SetTargetLayer();
if (m_schematicLayer == null)
{
Enabled = false;
return;
}
if (m_schematicLayer.IsEditingSchematicDiagram() == false)
{
Enabled = false;
if (m_dockableWindow != null)
m_dockableWindow.Show(false);
return;
}
ISchematicInMemoryDiagram inMemoryDiagram = m_schematicLayer.SchematicInMemoryDiagram;
if (inMemoryDiagram == null)
Enabled = false;
else
Enabled = true;
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
return;
}
protected override void OnMouseMove(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
{
try
{
if (m_schematicFeature1 != null)
{
ESRI.ArcGIS.ArcMapUI.IMxApplication mxApp = (ESRI.ArcGIS.ArcMapUI.IMxApplication)m_app;
if (mxApp == null)
return;
ESRI.ArcGIS.Display.IAppDisplay appDisplay = mxApp.Display;
if (appDisplay == null)
return;
IScreenDisplay screenDisplay = appDisplay.FocusScreen;
if (screenDisplay == null)
return;
//Move the Feedback to the current mouse location
IPoint pnt = screenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y);
if (pnt != null && m_linkFbk != null)
m_linkFbk.MoveTo(pnt);
}
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
return;
}
protected override void OnMouseUp(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg)
{
bool abortOperation = false;
ESRI.ArcGIS.Schematic.ISchematicOperation schematicOperation = null;
try
{
if (m_dockableDigit == null)
return;
if (arg != null)
{
m_x = arg.X;
m_y = arg.Y;
}
if (m_dockableWindow == null)
return;
if (m_dockableWindow.IsVisible() == false)
{
m_dockableWindow.Show(true);
}
ESRI.ArcGIS.SchematicControls.ISchematicTarget target = (ESRI.ArcGIS.SchematicControls.ISchematicTarget)m_schematicExtension;
if (target != null)
m_schematicLayer = target.SchematicTarget;
if (m_schematicLayer == null)
{
System.Windows.Forms.MessageBox.Show("No target Layer");
return;
}
ISchematicInMemoryDiagram inMemoryDiagram;
ISchematicInMemoryFeatureClass schematicInMemoryFeatureClass;
ISchematicInMemoryFeatureClassContainer schematicInMemoryFeatureClassContainer;
//Get the point
ESRI.ArcGIS.Geometry.Point point = new ESRI.ArcGIS.Geometry.Point();
ESRI.ArcGIS.ArcMapUI.IMxApplication mxApp;
ESRI.ArcGIS.Display.IAppDisplay appDisplay;
IScreenDisplay screenDisplay;
IDisplay display;
IDisplayTransformation transform;
ISpatialReference spatialReference;
inMemoryDiagram = m_schematicLayer.SchematicInMemoryDiagram;
schematicInMemoryFeatureClassContainer = (ISchematicInMemoryFeatureClassContainer)inMemoryDiagram;
if (schematicInMemoryFeatureClassContainer == null)
return;
mxApp = (ESRI.ArcGIS.ArcMapUI.IMxApplication)m_app;
if (mxApp == null)
return;
appDisplay = mxApp.Display;
if (appDisplay == null)
return;
screenDisplay = appDisplay.FocusScreen;
display = screenDisplay;
if (display == null)
return;
transform = display.DisplayTransformation;
if (transform == null)
return;
spatialReference = transform.SpatialReference;
WKSPoint mapPt = new WKSPoint();
ESRI.ArcGIS.Display.tagPOINT devPoint;
devPoint.x = m_x;
devPoint.y = m_y;
transform.TransformCoords(ref mapPt, ref devPoint, 1, 1); //'esriTransformToMap
point.SpatialReference = spatialReference;
point.Project(spatialReference);
point.X = mapPt.X;
point.Y = mapPt.Y;
schematicInMemoryFeatureClass = schematicInMemoryFeatureClassContainer.GetSchematicInMemoryFeatureClass(m_dockableDigit.FeatureClass());
if (schematicInMemoryFeatureClass == null)
{
System.Windows.Forms.MessageBox.Show("Invalid Type.");
return;
}
if (m_dockableDigit.CreateNode())
{
//TestMandatoryField
m_dockableDigit.btnOKPanel1.Visible = false;
if (m_dockableDigit.ValidateFields() == false)
{
m_dockableDigit.x(m_x);
m_dockableDigit.y(m_y);
System.Windows.Forms.MessageBox.Show(m_dockableDigit.ErrorProvider1.GetError(m_dockableDigit.btnOKPanel1) + m_messageFromOK);
return;
}
ESRI.ArcGIS.Geometry.IGeometry geometry;
ISchematicInMemoryFeature schematicInMemoryFeatureNode;
geometry = point;
schematicOperation = (ESRI.ArcGIS.Schematic.ISchematicOperation) new ESRI.ArcGIS.SchematicControls.SchematicOperation();
//digit operation is undo(redo)able we add it in the stack
IMxDocument doc = (IMxDocument)m_app.Document;
ESRI.ArcGIS.SystemUI.IOperationStack operationStack;
operationStack = doc.OperationStack;
operationStack.Do(schematicOperation);
schematicOperation.StartOperation("Digit", m_app, m_schematicLayer, true);
//do abort operation
abortOperation = true;
schematicInMemoryFeatureNode = schematicInMemoryFeatureClass.CreateSchematicInMemoryFeatureNode(geometry, "");
//schematicInMemoryFeatureNode.UpdateStatus = esriSchematicUpdateStatus.esriSchematicUpdateStatusNew; if we want the node deleted after update
schematicInMemoryFeatureNode.UpdateStatus = esriSchematicUpdateStatus.esriSchematicUpdateStatusLocked;
abortOperation = false;
schematicOperation.StopOperation();
ISchematicFeature schematicFeature = schematicInMemoryFeatureNode;
m_dockableDigit.FillValue(ref schematicFeature);
if (m_dockableDigit.AutoClear())
m_dockableDigit.SelectionChanged();
}
else
{
m_dockableDigit.btnOKPanel2.Visible = false;
//Get the Tolerance of ArcMap
Double tolerance;
IMxDocument mxDocument = (ESRI.ArcGIS.ArcMapUI.IMxDocument)m_app.Document;
ESRI.ArcGIS.esriSystem.WKSPoint point2 = new WKSPoint();
ESRI.ArcGIS.Display.tagPOINT devPt;
tolerance = mxDocument.SearchTolerancePixels;
devPt.x = (int)tolerance;
devPt.y = (int)tolerance;
transform.TransformCoords(ref point2, ref devPt, 1, 2);//2 <-> esriTransformSize 4 <-> esriTransformToMap
tolerance = point2.X * 5;//increase the tolerance value
IEnumSchematicFeature schematicFeatures = m_schematicLayer.GetSchematicFeaturesAtPoint(point, tolerance, false, true);
ISchematicFeature schematicFeatureSelected = null;
double distancetmp;
double distance = 0;
schematicFeatures.Reset();
if (schematicFeatures.Count <= 0)
return;
//pSchematicFeatures may contain several features, we are choosing the closest node.
ISchematicFeature schematicFeature2 = schematicFeatures.Next();
double dX;
double dY;
ISchematicInMemoryFeatureNode schematicInMemoryFeatureNode = null;
if (schematicFeature2 != null)
{
if (schematicFeature2.SchematicElementClass.SchematicElementType == ESRI.ArcGIS.Schematic.esriSchematicElementType.esriSchematicNodeType)
schematicInMemoryFeatureNode = (ISchematicInMemoryFeatureNode)schematicFeature2;
}
ISchematicInMemoryFeatureNodeGeometry schematicInMemoryFeatureNodeGeometry = (ISchematicInMemoryFeatureNodeGeometry)schematicInMemoryFeatureNode;
dX = schematicInMemoryFeatureNodeGeometry.Position.X;
dY = schematicInMemoryFeatureNodeGeometry.Position.Y;
schematicFeatureSelected = schematicFeature2;
distance = SquareDistance(dX - point.X, dY - point.Y);
while (schematicFeature2 != null)
{
//find the closest featureNode...
if (schematicInMemoryFeatureNode != null)
{
schematicInMemoryFeatureNodeGeometry = (ISchematicInMemoryFeatureNodeGeometry) schematicInMemoryFeatureNode;
if (schematicInMemoryFeatureNodeGeometry == null)
continue;
dX = schematicInMemoryFeatureNodeGeometry.Position.X;
dY = schematicInMemoryFeatureNodeGeometry.Position.Y;
distancetmp = SquareDistance(dX - point.X, dY - point.Y);
if (distancetmp < distance)
{
distance = distancetmp;
schematicFeatureSelected = schematicFeature2;
}
}
schematicFeature2 = schematicFeatures.Next();
if (schematicFeature2 != null)
{
if (schematicFeature2.SchematicElementClass.SchematicElementType == ESRI.ArcGIS.Schematic.esriSchematicElementType.esriSchematicNodeType)
schematicInMemoryFeatureNode = (ISchematicInMemoryFeatureNode)schematicFeature2;
}
}
if (schematicFeatureSelected == null)
return;
if (schematicFeatureSelected.SchematicElementClass.SchematicElementType != esriSchematicElementType.esriSchematicNodeType)
return;
if (m_schematicFeature1 == null)
{
m_schematicFeature1 = schematicFeatureSelected;
m_dockableDigit.SchematicFeature1(m_schematicFeature1);
if (!m_dockableDigit.CheckValidFeature(true))
{
m_schematicFeature1 = null;
m_dockableDigit.SchematicFeature1(m_schematicFeature1);
throw new Exception("Invalid starting node for this link type");
}
//Begin Feedback
m_linkFbk = new NewLineFeedback();
m_linkFbk.Display = screenDisplay;
//symbol
ISimpleLineSymbol sLnSym;
IRgbColor rGB = new RgbColor();
sLnSym = (ESRI.ArcGIS.Display.ISimpleLineSymbol)m_linkFbk.Symbol;
//Make a color
rGB.Red = 255;
rGB.Green = 0;
rGB.Blue = 0;
// Setup the symbol with color and style
sLnSym.Color = rGB;
m_linkFbk.Start(point);
//End Feedback
//To know if we are in the same diagram.
m_schematicLayerForLink = m_schematicLayer;
}
else
{
if (m_schematicLayerForLink != m_schematicLayer)
{
System.Windows.Forms.MessageBox.Show("wrong Target layer");
m_schematicLayerForLink = null;
EndFeedBack();
return;
}
m_schematicFeature2 = schematicFeatureSelected;
m_dockableDigit.SchematicFeature2(m_schematicFeature2);
//TestMandatoryField
if (m_dockableDigit.ValidateFields() == false)
{
m_dockableDigit.x(m_x);
m_dockableDigit.y(m_y);
System.Windows.Forms.MessageBox.Show(m_dockableDigit.ErrorProvider1.GetError(m_dockableDigit.btnOKPanel2) + m_messageFromOK);
return;
}
if (!m_dockableDigit.CheckValidFeature(false))
{
m_schematicFeature2 = null;
m_dockableDigit.SchematicFeature2(m_schematicFeature2);
throw new Exception("Invalid End node for this link type");
}
//CreateLink
ISchematicInMemoryFeature schematicInMemoryFeatureLink;
schematicOperation = (ESRI.ArcGIS.Schematic.ISchematicOperation) new ESRI.ArcGIS.SchematicControls.SchematicOperation();
//digit operation is undo(redo)able we add it in the stack
IMxDocument doc = (IMxDocument)m_app.Document;
ESRI.ArcGIS.SystemUI.IOperationStack operationStack;
operationStack = doc.OperationStack;
operationStack.Do(schematicOperation);
schematicOperation.StartOperation("Digit", m_app, m_schematicLayer, true);
//do abort operation
abortOperation = true;
schematicInMemoryFeatureLink = schematicInMemoryFeatureClass.CreateSchematicInMemoryFeatureLink((ESRI.ArcGIS.Schematic.ISchematicInMemoryFeatureNode)m_schematicFeature1, (ESRI.ArcGIS.Schematic.ISchematicInMemoryFeatureNode)m_schematicFeature2, "");
//schematicInMemoryFeatureLink.UpdateStatus = esriSchematicUpdateStatus.esriSchematicUpdateStatusNew; if we want the node deleted after update
schematicInMemoryFeatureLink.UpdateStatus = esriSchematicUpdateStatus.esriSchematicUpdateStatusLocked;
abortOperation = false;
schematicOperation.StopOperation();
ISchematicFeature schematicFeature = schematicInMemoryFeatureLink;
m_dockableDigit.FillValue(ref schematicFeature);
//End Feedback
EndFeedBack();
m_schematicLayerForLink = null;
if (m_dockableDigit.AutoClear())
m_dockableDigit.SelectionChanged();
}
}
//Refresh the view and viewer windows
RefreshView();
}
catch (System.Exception e)
{
if (abortOperation && (schematicOperation != null))
schematicOperation.AbortOperation();
EndFeedBack();
System.Windows.Forms.MessageBox.Show(e.Message);
}
return;
}
protected override bool OnDeactivate()
{
try
{
CurrentDigitTool.CurrentTool.currentDigit = null;
if (m_dockableWindow != null && !m_DeactivatedFromDock)
{
m_fromDeactivate = true;
m_dockableWindow.Dock(ESRI.ArcGIS.Framework.esriDockFlags.esriDockUnPinned);
m_dockableWindow.Show(false);
}
else
m_DeactivatedFromDock = false;
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
return true;
}
protected override void OnActivate()
{
try
{
this.Cursor = Cursors.Cross;
CurrentDigitTool.CurrentTool.currentDigit = this;
SetTargetLayer();
ESRI.ArcGIS.Framework.IDockableWindowManager dockWinMgr = ArcMap.DockableWindowManager;
UID u = new UID();
u.Value = "DigitTool_DockableWindowCS";
if (dockWinMgr == null)
return;
m_dockableWindow = dockWinMgr.GetDockableWindow(u);
if (m_dockableDigit == null)
m_dockableDigit = CurrentDigitTool.CurrentTool.digitDockableWindow;
if (m_dockableDigit != null)
m_dockableDigit.Init(m_schematicLayer);
m_dockableWindow.Show(true);
CurrentDigitTool.CurrentTool.currentDockableWindow = m_dockableWindow;
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
private void RefreshView()
{
IMxDocument mxDocument2 = (IMxDocument)m_app.Document;
if (mxDocument2 == null)
return;
IMap map = mxDocument2.FocusMap;
IActiveView activeView = (IActiveView)map;
if (activeView != null)
activeView.Refresh();
//refresh viewer window
IApplicationWindows applicationWindows = m_app as IApplicationWindows;
ISet mySet = applicationWindows.DataWindows;
if (mySet != null)
{
mySet.Reset();
IMapInsetWindow dataWindow = (IMapInsetWindow)mySet.Next();
while (dataWindow != null)
{
dataWindow.Refresh();
dataWindow = (IMapInsetWindow)mySet.Next();
}
}
}
public void EndFeedBack()
{
m_schematicFeature1 = null;
m_schematicFeature2 = null;
if (m_dockableDigit != null)
{
m_dockableDigit.SchematicFeature1(m_schematicFeature1);
m_dockableDigit.SchematicFeature2(m_schematicFeature2);
}
if (m_linkFbk != null)
{
m_linkFbk.Stop();
m_linkFbk = null;
}
}
public void SchematicFeature1(ISchematicFeature value)
{
m_schematicFeature1 = value;
return;
}
public void SchematicFeature2(ISchematicFeature value)
{
m_schematicFeature2 = value;
return;
}
public void DeactivatedFromDock(bool value)
{
m_DeactivatedFromDock = value;
}
public void FromDeactivate(bool value)
{
m_fromDeactivate = value;
}
public bool FromDeactivate()
{
return m_fromDeactivate;
}
public void MyMouseUp(int x, int y)
{
m_x = x;
m_y = y;
m_messageFromOK = "";
OnMouseUp(null);
m_messageFromOK = "\n" + "Complete missing data and click on OK button";
}
private double SquareDistance(double dx, double dy)
{
return (dx * dx + dy * dy);
}
private void SetTargetLayer()
{
try
{
if (m_schematicLayer == null)
{
IExtension extention = null;
IExtensionManager extensionManager;
extensionManager = (IExtensionManager)m_app;
extention = extensionManager.FindExtension("SchematicUI.SchematicExtension");
if (extention == null)
Enabled = false;
else
{
m_schematicExtension = extention;
ISchematicTarget target = m_schematicExtension as ISchematicTarget;
if (target != null)
m_schematicLayer = target.SchematicTarget;
}
}
}
catch (System.Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Ionic.Zip;
using Ionic.Zlib;
using Sitecore.Diagnostics.Base;
using JetBrains.Annotations;
namespace SIM.FileSystem
{
using Sitecore.Diagnostics.Logging;
using SIM.Extensions;
public class ZipProvider
{
#region Constants
private const long Kb = 1024;
private const long Mb = 1024 * Kb;
#endregion
#region Fields
private FileSystem FileSystem { get; }
#endregion
#region Constructors
public ZipProvider(FileSystem fileSystem)
{
FileSystem = fileSystem;
}
#endregion
#region Public methods
public virtual void CheckZip([NotNull] string packagePath)
{
Assert.ArgumentNotNullOrEmpty(packagePath, nameof(packagePath));
if (System.IO.File.Exists(packagePath))
{
try
{
using (ZipFile zip = new ZipFile(packagePath))
{
bool data = zip.Entries.FirstOrDefault(e => e.IsDirectory && e.FileName.Contains("/Data/")) != null;
bool databases = zip.Entries.FirstOrDefault(e => e.IsDirectory && e.FileName.Contains("/Databases/")) !=
null;
bool website = zip.Entries.FirstOrDefault(e => e.IsDirectory && e.FileName.Contains("/Website/")) != null;
if (!(data && databases && website))
{
throw new InvalidOperationException(
$"The \"{packagePath}\" archive isn't a Sitecore installation package.");
}
}
}
catch (ZipException)
{
throw new InvalidOperationException($"The \"{packagePath}\" installation package seems to be corrupted.");
}
}
}
public virtual void CreateZip(string path, string zipFileName, string ignore = null, int compressionLevel = 0)
{
CompressionLevel zipCompressionLevel;
if (typeof(CompressionLevel).IsEnumDefined(compressionLevel))
{
zipCompressionLevel = (CompressionLevel)compressionLevel;
}
else
{
zipCompressionLevel = CompressionLevel.None;
}
var zip = new ZipFile
{
CompressionLevel = zipCompressionLevel,
UseZip64WhenSaving = Zip64Option.AsNecessary
};
if (ignore == null)
{
zip.AddDirectory(path); // , relativePath);
}
else
{
Assert.IsTrue(!ignore.Contains('\\') && !ignore.Contains('/'), "Multi-level ignore is not supported for archiving");
foreach (var directory in Directory.GetDirectories(path))
{
var directoryName = new DirectoryInfo(directory).Name;
if (!directoryName.EqualsIgnoreCase(ignore))
{
zip.AddDirectory(directory, directoryName);
}
}
foreach (var file in Directory.GetFiles(path))
{
zip.AddFile(file, "/");
}
}
// zip.SaveProgress += this.OnSaveProgress;
zip.Save(zipFileName);
}
public virtual string GetFirstRootFolder(string packagePath)
{
if (System.IO.File.Exists(packagePath))
{
try
{
using (ZipFile zip = new ZipFile(packagePath))
{
var first = zip.EntryFileNames.First();
return first.Substring(0, first.IndexOf('/'));
}
}
catch (ZipException)
{
throw new InvalidOperationException($"The \"{packagePath}\" installation package seems to be corrupted.");
}
}
return null;
}
public virtual void UnpackZip([NotNull] string packagePath, [NotNull] string path,
[CanBeNull] string entriesPattern = null, int stepsCount = 1,
[CanBeNull] Action incrementProgress = null, bool skipErrors = false)
{
Assert.ArgumentNotNull(packagePath, nameof(packagePath));
Assert.ArgumentNotNull(path, nameof(path));
// TODO: comment this line when the progress bar is adjusted
incrementProgress = null;
bool hasResponse = incrementProgress != null;
if (System.IO.File.Exists(packagePath))
{
try
{
if (entriesPattern != null)
{
Log.Info(string.Format("Unzipping the {2} entries of the '{0}' archive to the '{1}' folder", packagePath, path, entriesPattern));
}
else
{
Log.Info($"Unzipping the '{packagePath}' archive to the '{path}' folder");
}
using (ZipFile zip = new ZipFile(packagePath))
{
var q = Math.Max(zip.Entries.Count / stepsCount, 1);
FileSystem.Directory.Ensure(path);
var i = 0;
ICollection<ZipEntry> entries = entriesPattern != null ? zip.SelectEntries(entriesPattern) : zip.Entries;
foreach (ZipEntry entry in entries)
{
try
{
entry.Extract(path, ExtractExistingFileAction.OverwriteSilently);
}
catch (IOException ex)
{
if (skipErrors)
{
Log.Error(ex, "Unpacking caused exception");
continue;
}
bool b = false;
foreach (string postFix in new[]
{
".tmp", ".PendingOverwrite"
})
{
var errorPath = Path.Combine(path, entry.FileName) + postFix;
if (System.IO.File.Exists(errorPath))
{
System.IO.File.Delete(errorPath);
b = true;
}
}
if (!b)
{
throw;
}
entry.Extract(path, ExtractExistingFileAction.OverwriteSilently);
}
catch (Exception ex)
{
if (skipErrors)
{
Log.Error(ex, "Unpacking caused exception");
continue;
}
}
if (hasResponse)
{
if (++i == q)
{
incrementProgress();
i = 0;
}
}
}
}
}
catch (ZipException)
{
throw new InvalidOperationException($"The \"{packagePath}\" package seems to be corrupted.");
}
}
}
public virtual void UnpackZipWithActualWebRootName([NotNull] string packagePath, [NotNull] string path, string webRootName, [CanBeNull] string entriesPattern = null, int stepsCount = 1, [CanBeNull] Action incrementProgress = null)
{
Assert.ArgumentNotNull(packagePath, nameof(packagePath));
Assert.ArgumentNotNull(path, nameof(path));
// TODO: comment this line when the progress bar is adjusted
incrementProgress = null;
var hasResponse = incrementProgress != null;
if (!System.IO.File.Exists(packagePath))
{
return;
}
try
{
if (entriesPattern != null)
{
Log.Info(string.Format("Unzipping the {2} entries of the '{0}' archive to the '{1}' folder", packagePath, path, entriesPattern));
}
else
{
Log.Info($"Unzipping the '{packagePath}' archive to the '{path}' folder");
}
using (var zip = new ZipFile(packagePath))
{
var q = Math.Max(zip.Entries.Count / stepsCount, 1);
FileSystem.Directory.Ensure(path);
var i = 0;
var entries = entriesPattern != null ? zip.SelectEntries(entriesPattern) : zip.Entries;
for (var j = 0; j < entries.Count(); j++)
{
try
{
if (entries.ElementAt(j).FileName.StartsWith("Website", true, CultureInfo.InvariantCulture))
{
entries.ElementAt(j).FileName = webRootName + entries.ElementAt(j).FileName.Substring(7);
}
entries.ElementAt(j).Extract(path, ExtractExistingFileAction.OverwriteSilently);
}
catch (IOException)
{
var b = false;
foreach (var postFix in new[]
{
".tmp", ".PendingOverwrite"
})
{
var errorPath = Path.Combine(path, entries.ElementAt(j).FileName) + postFix;
if (!System.IO.File.Exists(errorPath))
{
continue;
}
System.IO.File.Delete(errorPath);
b = true;
}
if (!b)
{
throw;
}
entries.ElementAt(j).Extract(path, ExtractExistingFileAction.OverwriteSilently);
}
if (!hasResponse)
{
continue;
}
if (++i != q)
{
continue;
}
incrementProgress();
i = 0;
}
}
}
catch (ZipException)
{
throw new InvalidOperationException($"The \"{packagePath}\" package seems to be corrupted.");
}
}
public virtual bool ZipContainsSingleFile(string packagePath, string innerFileName)
{
var fileInfo = new FileInfo(packagePath);
Assert.IsTrue(fileInfo.Exists, $"The {packagePath} file does not exist");
if (fileInfo.Length <= 22)
{
return false;
}
using (ZipFile zip = new ZipFile(packagePath))
{
if (zip.Entries.Count == 1 && zip.Entries.First().FileName == innerFileName)
{
return true;
}
}
return false;
}
public virtual string ZipUnpackFile(string pathToZip, string pathToUnpack, string fileName)
{
var zipToUnpack = pathToZip;
var unpackDirectory = pathToUnpack;
using (ZipFile zip = ZipFile.Read(zipToUnpack))
{
foreach (ZipEntry entry in zip)
{
string[] splittedFileName = entry.FileName.Split('/');
if (splittedFileName[splittedFileName.Length - 1] == fileName)
{
entry.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
return Path.Combine(pathToUnpack, fileName);
}
}
}
return string.Empty;
}
public virtual string ZipUnpackFolder(string pathToZip, string pathToUnpack, string folderName)
{
using (ZipFile zip1 = ZipFile.Read(pathToZip))
{
var selection = from e in zip1.Entries
where (e.FileName).StartsWith(folderName + "/") || (e.FileName).StartsWith(folderName + "\\")
select e;
Directory.CreateDirectory(pathToUnpack);
foreach (var e in selection)
{
if (e.UncompressedSize > 0)
{
e.Extract(pathToUnpack, ExtractExistingFileAction.OverwriteSilently);
}
else
{
new DirectoryInfo(Path.Combine(pathToUnpack, e.FileName.Trim("\\/".ToCharArray()))).Create();
}
}
}
return pathToUnpack.PathCombine(folderName);
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data{
/// <summary>
/// Strongly-typed collection for the VObservationExpansion class.
/// </summary>
[Serializable]
public partial class VObservationExpansionCollection : ReadOnlyList<VObservationExpansion, VObservationExpansionCollection>
{
public VObservationExpansionCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vObservationExpansion view.
/// </summary>
[Serializable]
public partial class VObservationExpansion : ReadOnlyRecord<VObservationExpansion>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("vObservationExpansion", TableType.View, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "ID";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = false;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = false;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarImportBatchID = new TableSchema.TableColumn(schema);
colvarImportBatchID.ColumnName = "ImportBatchID";
colvarImportBatchID.DataType = DbType.Guid;
colvarImportBatchID.MaxLength = 0;
colvarImportBatchID.AutoIncrement = false;
colvarImportBatchID.IsNullable = false;
colvarImportBatchID.IsPrimaryKey = false;
colvarImportBatchID.IsForeignKey = false;
colvarImportBatchID.IsReadOnly = false;
schema.Columns.Add(colvarImportBatchID);
TableSchema.TableColumn colvarImportBatchCode = new TableSchema.TableColumn(schema);
colvarImportBatchCode.ColumnName = "ImportBatchCode";
colvarImportBatchCode.DataType = DbType.Int32;
colvarImportBatchCode.MaxLength = 0;
colvarImportBatchCode.AutoIncrement = false;
colvarImportBatchCode.IsNullable = false;
colvarImportBatchCode.IsPrimaryKey = false;
colvarImportBatchCode.IsForeignKey = false;
colvarImportBatchCode.IsReadOnly = false;
schema.Columns.Add(colvarImportBatchCode);
TableSchema.TableColumn colvarImportBatchDate = new TableSchema.TableColumn(schema);
colvarImportBatchDate.ColumnName = "ImportBatchDate";
colvarImportBatchDate.DataType = DbType.DateTime;
colvarImportBatchDate.MaxLength = 0;
colvarImportBatchDate.AutoIncrement = false;
colvarImportBatchDate.IsNullable = false;
colvarImportBatchDate.IsPrimaryKey = false;
colvarImportBatchDate.IsForeignKey = false;
colvarImportBatchDate.IsReadOnly = false;
schema.Columns.Add(colvarImportBatchDate);
TableSchema.TableColumn colvarValueDate = new TableSchema.TableColumn(schema);
colvarValueDate.ColumnName = "ValueDate";
colvarValueDate.DataType = DbType.DateTime;
colvarValueDate.MaxLength = 0;
colvarValueDate.AutoIncrement = false;
colvarValueDate.IsNullable = false;
colvarValueDate.IsPrimaryKey = false;
colvarValueDate.IsForeignKey = false;
colvarValueDate.IsReadOnly = false;
schema.Columns.Add(colvarValueDate);
TableSchema.TableColumn colvarValueDay = new TableSchema.TableColumn(schema);
colvarValueDay.ColumnName = "ValueDay";
colvarValueDay.DataType = DbType.Date;
colvarValueDay.MaxLength = 0;
colvarValueDay.AutoIncrement = false;
colvarValueDay.IsNullable = true;
colvarValueDay.IsPrimaryKey = false;
colvarValueDay.IsForeignKey = false;
colvarValueDay.IsReadOnly = false;
schema.Columns.Add(colvarValueDay);
TableSchema.TableColumn colvarValueYear = new TableSchema.TableColumn(schema);
colvarValueYear.ColumnName = "ValueYear";
colvarValueYear.DataType = DbType.Int32;
colvarValueYear.MaxLength = 0;
colvarValueYear.AutoIncrement = false;
colvarValueYear.IsNullable = true;
colvarValueYear.IsPrimaryKey = false;
colvarValueYear.IsForeignKey = false;
colvarValueYear.IsReadOnly = false;
schema.Columns.Add(colvarValueYear);
TableSchema.TableColumn colvarValueDecade = new TableSchema.TableColumn(schema);
colvarValueDecade.ColumnName = "ValueDecade";
colvarValueDecade.DataType = DbType.Int32;
colvarValueDecade.MaxLength = 0;
colvarValueDecade.AutoIncrement = false;
colvarValueDecade.IsNullable = true;
colvarValueDecade.IsPrimaryKey = false;
colvarValueDecade.IsForeignKey = false;
colvarValueDecade.IsReadOnly = false;
schema.Columns.Add(colvarValueDecade);
TableSchema.TableColumn colvarRawValue = new TableSchema.TableColumn(schema);
colvarRawValue.ColumnName = "RawValue";
colvarRawValue.DataType = DbType.Double;
colvarRawValue.MaxLength = 0;
colvarRawValue.AutoIncrement = false;
colvarRawValue.IsNullable = true;
colvarRawValue.IsPrimaryKey = false;
colvarRawValue.IsForeignKey = false;
colvarRawValue.IsReadOnly = false;
schema.Columns.Add(colvarRawValue);
TableSchema.TableColumn colvarDataValue = new TableSchema.TableColumn(schema);
colvarDataValue.ColumnName = "DataValue";
colvarDataValue.DataType = DbType.Double;
colvarDataValue.MaxLength = 0;
colvarDataValue.AutoIncrement = false;
colvarDataValue.IsNullable = true;
colvarDataValue.IsPrimaryKey = false;
colvarDataValue.IsForeignKey = false;
colvarDataValue.IsReadOnly = false;
schema.Columns.Add(colvarDataValue);
TableSchema.TableColumn colvarTextValue = new TableSchema.TableColumn(schema);
colvarTextValue.ColumnName = "TextValue";
colvarTextValue.DataType = DbType.AnsiString;
colvarTextValue.MaxLength = 10;
colvarTextValue.AutoIncrement = false;
colvarTextValue.IsNullable = true;
colvarTextValue.IsPrimaryKey = false;
colvarTextValue.IsForeignKey = false;
colvarTextValue.IsReadOnly = false;
schema.Columns.Add(colvarTextValue);
TableSchema.TableColumn colvarComment = new TableSchema.TableColumn(schema);
colvarComment.ColumnName = "Comment";
colvarComment.DataType = DbType.AnsiString;
colvarComment.MaxLength = 250;
colvarComment.AutoIncrement = false;
colvarComment.IsNullable = true;
colvarComment.IsPrimaryKey = false;
colvarComment.IsForeignKey = false;
colvarComment.IsReadOnly = false;
schema.Columns.Add(colvarComment);
TableSchema.TableColumn colvarCorrelationID = new TableSchema.TableColumn(schema);
colvarCorrelationID.ColumnName = "CorrelationID";
colvarCorrelationID.DataType = DbType.Guid;
colvarCorrelationID.MaxLength = 0;
colvarCorrelationID.AutoIncrement = false;
colvarCorrelationID.IsNullable = true;
colvarCorrelationID.IsPrimaryKey = false;
colvarCorrelationID.IsForeignKey = false;
colvarCorrelationID.IsReadOnly = false;
schema.Columns.Add(colvarCorrelationID);
TableSchema.TableColumn colvarSiteID = new TableSchema.TableColumn(schema);
colvarSiteID.ColumnName = "SiteID";
colvarSiteID.DataType = DbType.Guid;
colvarSiteID.MaxLength = 0;
colvarSiteID.AutoIncrement = false;
colvarSiteID.IsNullable = false;
colvarSiteID.IsPrimaryKey = false;
colvarSiteID.IsForeignKey = false;
colvarSiteID.IsReadOnly = false;
schema.Columns.Add(colvarSiteID);
TableSchema.TableColumn colvarSiteCode = new TableSchema.TableColumn(schema);
colvarSiteCode.ColumnName = "SiteCode";
colvarSiteCode.DataType = DbType.AnsiString;
colvarSiteCode.MaxLength = 50;
colvarSiteCode.AutoIncrement = false;
colvarSiteCode.IsNullable = false;
colvarSiteCode.IsPrimaryKey = false;
colvarSiteCode.IsForeignKey = false;
colvarSiteCode.IsReadOnly = false;
schema.Columns.Add(colvarSiteCode);
TableSchema.TableColumn colvarSiteName = new TableSchema.TableColumn(schema);
colvarSiteName.ColumnName = "SiteName";
colvarSiteName.DataType = DbType.AnsiString;
colvarSiteName.MaxLength = 150;
colvarSiteName.AutoIncrement = false;
colvarSiteName.IsNullable = false;
colvarSiteName.IsPrimaryKey = false;
colvarSiteName.IsForeignKey = false;
colvarSiteName.IsReadOnly = false;
schema.Columns.Add(colvarSiteName);
TableSchema.TableColumn colvarSiteDescription = new TableSchema.TableColumn(schema);
colvarSiteDescription.ColumnName = "SiteDescription";
colvarSiteDescription.DataType = DbType.AnsiString;
colvarSiteDescription.MaxLength = 5000;
colvarSiteDescription.AutoIncrement = false;
colvarSiteDescription.IsNullable = true;
colvarSiteDescription.IsPrimaryKey = false;
colvarSiteDescription.IsForeignKey = false;
colvarSiteDescription.IsReadOnly = false;
schema.Columns.Add(colvarSiteDescription);
TableSchema.TableColumn colvarSiteUrl = new TableSchema.TableColumn(schema);
colvarSiteUrl.ColumnName = "SiteUrl";
colvarSiteUrl.DataType = DbType.AnsiString;
colvarSiteUrl.MaxLength = 250;
colvarSiteUrl.AutoIncrement = false;
colvarSiteUrl.IsNullable = true;
colvarSiteUrl.IsPrimaryKey = false;
colvarSiteUrl.IsForeignKey = false;
colvarSiteUrl.IsReadOnly = false;
schema.Columns.Add(colvarSiteUrl);
TableSchema.TableColumn colvarStationID = new TableSchema.TableColumn(schema);
colvarStationID.ColumnName = "StationID";
colvarStationID.DataType = DbType.Guid;
colvarStationID.MaxLength = 0;
colvarStationID.AutoIncrement = false;
colvarStationID.IsNullable = false;
colvarStationID.IsPrimaryKey = false;
colvarStationID.IsForeignKey = false;
colvarStationID.IsReadOnly = false;
schema.Columns.Add(colvarStationID);
TableSchema.TableColumn colvarStationCode = new TableSchema.TableColumn(schema);
colvarStationCode.ColumnName = "StationCode";
colvarStationCode.DataType = DbType.AnsiString;
colvarStationCode.MaxLength = 50;
colvarStationCode.AutoIncrement = false;
colvarStationCode.IsNullable = false;
colvarStationCode.IsPrimaryKey = false;
colvarStationCode.IsForeignKey = false;
colvarStationCode.IsReadOnly = false;
schema.Columns.Add(colvarStationCode);
TableSchema.TableColumn colvarStationName = new TableSchema.TableColumn(schema);
colvarStationName.ColumnName = "StationName";
colvarStationName.DataType = DbType.AnsiString;
colvarStationName.MaxLength = 150;
colvarStationName.AutoIncrement = false;
colvarStationName.IsNullable = false;
colvarStationName.IsPrimaryKey = false;
colvarStationName.IsForeignKey = false;
colvarStationName.IsReadOnly = false;
schema.Columns.Add(colvarStationName);
TableSchema.TableColumn colvarStationDescription = new TableSchema.TableColumn(schema);
colvarStationDescription.ColumnName = "StationDescription";
colvarStationDescription.DataType = DbType.AnsiString;
colvarStationDescription.MaxLength = 5000;
colvarStationDescription.AutoIncrement = false;
colvarStationDescription.IsNullable = true;
colvarStationDescription.IsPrimaryKey = false;
colvarStationDescription.IsForeignKey = false;
colvarStationDescription.IsReadOnly = false;
schema.Columns.Add(colvarStationDescription);
TableSchema.TableColumn colvarStationUrl = new TableSchema.TableColumn(schema);
colvarStationUrl.ColumnName = "StationUrl";
colvarStationUrl.DataType = DbType.AnsiString;
colvarStationUrl.MaxLength = 250;
colvarStationUrl.AutoIncrement = false;
colvarStationUrl.IsNullable = true;
colvarStationUrl.IsPrimaryKey = false;
colvarStationUrl.IsForeignKey = false;
colvarStationUrl.IsReadOnly = false;
schema.Columns.Add(colvarStationUrl);
TableSchema.TableColumn colvarInstrumentID = new TableSchema.TableColumn(schema);
colvarInstrumentID.ColumnName = "InstrumentID";
colvarInstrumentID.DataType = DbType.Guid;
colvarInstrumentID.MaxLength = 0;
colvarInstrumentID.AutoIncrement = false;
colvarInstrumentID.IsNullable = false;
colvarInstrumentID.IsPrimaryKey = false;
colvarInstrumentID.IsForeignKey = false;
colvarInstrumentID.IsReadOnly = false;
schema.Columns.Add(colvarInstrumentID);
TableSchema.TableColumn colvarInstrumentCode = new TableSchema.TableColumn(schema);
colvarInstrumentCode.ColumnName = "InstrumentCode";
colvarInstrumentCode.DataType = DbType.AnsiString;
colvarInstrumentCode.MaxLength = 50;
colvarInstrumentCode.AutoIncrement = false;
colvarInstrumentCode.IsNullable = false;
colvarInstrumentCode.IsPrimaryKey = false;
colvarInstrumentCode.IsForeignKey = false;
colvarInstrumentCode.IsReadOnly = false;
schema.Columns.Add(colvarInstrumentCode);
TableSchema.TableColumn colvarInstrumentName = new TableSchema.TableColumn(schema);
colvarInstrumentName.ColumnName = "InstrumentName";
colvarInstrumentName.DataType = DbType.AnsiString;
colvarInstrumentName.MaxLength = 150;
colvarInstrumentName.AutoIncrement = false;
colvarInstrumentName.IsNullable = false;
colvarInstrumentName.IsPrimaryKey = false;
colvarInstrumentName.IsForeignKey = false;
colvarInstrumentName.IsReadOnly = false;
schema.Columns.Add(colvarInstrumentName);
TableSchema.TableColumn colvarInstrumentDescription = new TableSchema.TableColumn(schema);
colvarInstrumentDescription.ColumnName = "InstrumentDescription";
colvarInstrumentDescription.DataType = DbType.AnsiString;
colvarInstrumentDescription.MaxLength = 5000;
colvarInstrumentDescription.AutoIncrement = false;
colvarInstrumentDescription.IsNullable = true;
colvarInstrumentDescription.IsPrimaryKey = false;
colvarInstrumentDescription.IsForeignKey = false;
colvarInstrumentDescription.IsReadOnly = false;
schema.Columns.Add(colvarInstrumentDescription);
TableSchema.TableColumn colvarInstrumentUrl = new TableSchema.TableColumn(schema);
colvarInstrumentUrl.ColumnName = "InstrumentUrl";
colvarInstrumentUrl.DataType = DbType.AnsiString;
colvarInstrumentUrl.MaxLength = 250;
colvarInstrumentUrl.AutoIncrement = false;
colvarInstrumentUrl.IsNullable = true;
colvarInstrumentUrl.IsPrimaryKey = false;
colvarInstrumentUrl.IsForeignKey = false;
colvarInstrumentUrl.IsReadOnly = false;
schema.Columns.Add(colvarInstrumentUrl);
TableSchema.TableColumn colvarSensorID = new TableSchema.TableColumn(schema);
colvarSensorID.ColumnName = "SensorID";
colvarSensorID.DataType = DbType.Guid;
colvarSensorID.MaxLength = 0;
colvarSensorID.AutoIncrement = false;
colvarSensorID.IsNullable = false;
colvarSensorID.IsPrimaryKey = false;
colvarSensorID.IsForeignKey = false;
colvarSensorID.IsReadOnly = false;
schema.Columns.Add(colvarSensorID);
TableSchema.TableColumn colvarSensorCode = new TableSchema.TableColumn(schema);
colvarSensorCode.ColumnName = "SensorCode";
colvarSensorCode.DataType = DbType.AnsiString;
colvarSensorCode.MaxLength = 75;
colvarSensorCode.AutoIncrement = false;
colvarSensorCode.IsNullable = false;
colvarSensorCode.IsPrimaryKey = false;
colvarSensorCode.IsForeignKey = false;
colvarSensorCode.IsReadOnly = false;
schema.Columns.Add(colvarSensorCode);
TableSchema.TableColumn colvarSensorName = new TableSchema.TableColumn(schema);
colvarSensorName.ColumnName = "SensorName";
colvarSensorName.DataType = DbType.AnsiString;
colvarSensorName.MaxLength = 150;
colvarSensorName.AutoIncrement = false;
colvarSensorName.IsNullable = false;
colvarSensorName.IsPrimaryKey = false;
colvarSensorName.IsForeignKey = false;
colvarSensorName.IsReadOnly = false;
schema.Columns.Add(colvarSensorName);
TableSchema.TableColumn colvarSensorDescription = new TableSchema.TableColumn(schema);
colvarSensorDescription.ColumnName = "SensorDescription";
colvarSensorDescription.DataType = DbType.AnsiString;
colvarSensorDescription.MaxLength = 5000;
colvarSensorDescription.AutoIncrement = false;
colvarSensorDescription.IsNullable = true;
colvarSensorDescription.IsPrimaryKey = false;
colvarSensorDescription.IsForeignKey = false;
colvarSensorDescription.IsReadOnly = false;
schema.Columns.Add(colvarSensorDescription);
TableSchema.TableColumn colvarSensorUrl = new TableSchema.TableColumn(schema);
colvarSensorUrl.ColumnName = "SensorUrl";
colvarSensorUrl.DataType = DbType.AnsiString;
colvarSensorUrl.MaxLength = 250;
colvarSensorUrl.AutoIncrement = false;
colvarSensorUrl.IsNullable = true;
colvarSensorUrl.IsPrimaryKey = false;
colvarSensorUrl.IsForeignKey = false;
colvarSensorUrl.IsReadOnly = false;
schema.Columns.Add(colvarSensorUrl);
TableSchema.TableColumn colvarLatitude = new TableSchema.TableColumn(schema);
colvarLatitude.ColumnName = "Latitude";
colvarLatitude.DataType = DbType.Double;
colvarLatitude.MaxLength = 0;
colvarLatitude.AutoIncrement = false;
colvarLatitude.IsNullable = true;
colvarLatitude.IsPrimaryKey = false;
colvarLatitude.IsForeignKey = false;
colvarLatitude.IsReadOnly = false;
schema.Columns.Add(colvarLatitude);
TableSchema.TableColumn colvarLongitude = new TableSchema.TableColumn(schema);
colvarLongitude.ColumnName = "Longitude";
colvarLongitude.DataType = DbType.Double;
colvarLongitude.MaxLength = 0;
colvarLongitude.AutoIncrement = false;
colvarLongitude.IsNullable = true;
colvarLongitude.IsPrimaryKey = false;
colvarLongitude.IsForeignKey = false;
colvarLongitude.IsReadOnly = false;
schema.Columns.Add(colvarLongitude);
TableSchema.TableColumn colvarElevation = new TableSchema.TableColumn(schema);
colvarElevation.ColumnName = "Elevation";
colvarElevation.DataType = DbType.Double;
colvarElevation.MaxLength = 0;
colvarElevation.AutoIncrement = false;
colvarElevation.IsNullable = true;
colvarElevation.IsPrimaryKey = false;
colvarElevation.IsForeignKey = false;
colvarElevation.IsReadOnly = false;
schema.Columns.Add(colvarElevation);
TableSchema.TableColumn colvarPhenomenonOfferingID = new TableSchema.TableColumn(schema);
colvarPhenomenonOfferingID.ColumnName = "PhenomenonOfferingID";
colvarPhenomenonOfferingID.DataType = DbType.Guid;
colvarPhenomenonOfferingID.MaxLength = 0;
colvarPhenomenonOfferingID.AutoIncrement = false;
colvarPhenomenonOfferingID.IsNullable = false;
colvarPhenomenonOfferingID.IsPrimaryKey = false;
colvarPhenomenonOfferingID.IsForeignKey = false;
colvarPhenomenonOfferingID.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonOfferingID);
TableSchema.TableColumn colvarPhenomenonID = new TableSchema.TableColumn(schema);
colvarPhenomenonID.ColumnName = "PhenomenonID";
colvarPhenomenonID.DataType = DbType.Guid;
colvarPhenomenonID.MaxLength = 0;
colvarPhenomenonID.AutoIncrement = false;
colvarPhenomenonID.IsNullable = false;
colvarPhenomenonID.IsPrimaryKey = false;
colvarPhenomenonID.IsForeignKey = false;
colvarPhenomenonID.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonID);
TableSchema.TableColumn colvarPhenomenonCode = new TableSchema.TableColumn(schema);
colvarPhenomenonCode.ColumnName = "PhenomenonCode";
colvarPhenomenonCode.DataType = DbType.AnsiString;
colvarPhenomenonCode.MaxLength = 50;
colvarPhenomenonCode.AutoIncrement = false;
colvarPhenomenonCode.IsNullable = false;
colvarPhenomenonCode.IsPrimaryKey = false;
colvarPhenomenonCode.IsForeignKey = false;
colvarPhenomenonCode.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonCode);
TableSchema.TableColumn colvarPhenomenonName = new TableSchema.TableColumn(schema);
colvarPhenomenonName.ColumnName = "PhenomenonName";
colvarPhenomenonName.DataType = DbType.AnsiString;
colvarPhenomenonName.MaxLength = 150;
colvarPhenomenonName.AutoIncrement = false;
colvarPhenomenonName.IsNullable = false;
colvarPhenomenonName.IsPrimaryKey = false;
colvarPhenomenonName.IsForeignKey = false;
colvarPhenomenonName.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonName);
TableSchema.TableColumn colvarPhenomenonDescription = new TableSchema.TableColumn(schema);
colvarPhenomenonDescription.ColumnName = "PhenomenonDescription";
colvarPhenomenonDescription.DataType = DbType.AnsiString;
colvarPhenomenonDescription.MaxLength = 5000;
colvarPhenomenonDescription.AutoIncrement = false;
colvarPhenomenonDescription.IsNullable = true;
colvarPhenomenonDescription.IsPrimaryKey = false;
colvarPhenomenonDescription.IsForeignKey = false;
colvarPhenomenonDescription.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonDescription);
TableSchema.TableColumn colvarPhenomenonUrl = new TableSchema.TableColumn(schema);
colvarPhenomenonUrl.ColumnName = "PhenomenonUrl";
colvarPhenomenonUrl.DataType = DbType.AnsiString;
colvarPhenomenonUrl.MaxLength = 250;
colvarPhenomenonUrl.AutoIncrement = false;
colvarPhenomenonUrl.IsNullable = true;
colvarPhenomenonUrl.IsPrimaryKey = false;
colvarPhenomenonUrl.IsForeignKey = false;
colvarPhenomenonUrl.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonUrl);
TableSchema.TableColumn colvarOfferingID = new TableSchema.TableColumn(schema);
colvarOfferingID.ColumnName = "OfferingID";
colvarOfferingID.DataType = DbType.Guid;
colvarOfferingID.MaxLength = 0;
colvarOfferingID.AutoIncrement = false;
colvarOfferingID.IsNullable = false;
colvarOfferingID.IsPrimaryKey = false;
colvarOfferingID.IsForeignKey = false;
colvarOfferingID.IsReadOnly = false;
schema.Columns.Add(colvarOfferingID);
TableSchema.TableColumn colvarOfferingCode = new TableSchema.TableColumn(schema);
colvarOfferingCode.ColumnName = "OfferingCode";
colvarOfferingCode.DataType = DbType.AnsiString;
colvarOfferingCode.MaxLength = 50;
colvarOfferingCode.AutoIncrement = false;
colvarOfferingCode.IsNullable = false;
colvarOfferingCode.IsPrimaryKey = false;
colvarOfferingCode.IsForeignKey = false;
colvarOfferingCode.IsReadOnly = false;
schema.Columns.Add(colvarOfferingCode);
TableSchema.TableColumn colvarOfferingName = new TableSchema.TableColumn(schema);
colvarOfferingName.ColumnName = "OfferingName";
colvarOfferingName.DataType = DbType.AnsiString;
colvarOfferingName.MaxLength = 150;
colvarOfferingName.AutoIncrement = false;
colvarOfferingName.IsNullable = false;
colvarOfferingName.IsPrimaryKey = false;
colvarOfferingName.IsForeignKey = false;
colvarOfferingName.IsReadOnly = false;
schema.Columns.Add(colvarOfferingName);
TableSchema.TableColumn colvarOfferingDescription = new TableSchema.TableColumn(schema);
colvarOfferingDescription.ColumnName = "OfferingDescription";
colvarOfferingDescription.DataType = DbType.AnsiString;
colvarOfferingDescription.MaxLength = 5000;
colvarOfferingDescription.AutoIncrement = false;
colvarOfferingDescription.IsNullable = true;
colvarOfferingDescription.IsPrimaryKey = false;
colvarOfferingDescription.IsForeignKey = false;
colvarOfferingDescription.IsReadOnly = false;
schema.Columns.Add(colvarOfferingDescription);
TableSchema.TableColumn colvarPhenomenonUOMID = new TableSchema.TableColumn(schema);
colvarPhenomenonUOMID.ColumnName = "PhenomenonUOMID";
colvarPhenomenonUOMID.DataType = DbType.Guid;
colvarPhenomenonUOMID.MaxLength = 0;
colvarPhenomenonUOMID.AutoIncrement = false;
colvarPhenomenonUOMID.IsNullable = false;
colvarPhenomenonUOMID.IsPrimaryKey = false;
colvarPhenomenonUOMID.IsForeignKey = false;
colvarPhenomenonUOMID.IsReadOnly = false;
schema.Columns.Add(colvarPhenomenonUOMID);
TableSchema.TableColumn colvarUnitOfMeasureID = new TableSchema.TableColumn(schema);
colvarUnitOfMeasureID.ColumnName = "UnitOfMeasureID";
colvarUnitOfMeasureID.DataType = DbType.Guid;
colvarUnitOfMeasureID.MaxLength = 0;
colvarUnitOfMeasureID.AutoIncrement = false;
colvarUnitOfMeasureID.IsNullable = false;
colvarUnitOfMeasureID.IsPrimaryKey = false;
colvarUnitOfMeasureID.IsForeignKey = false;
colvarUnitOfMeasureID.IsReadOnly = false;
schema.Columns.Add(colvarUnitOfMeasureID);
TableSchema.TableColumn colvarUnitOfMeasureCode = new TableSchema.TableColumn(schema);
colvarUnitOfMeasureCode.ColumnName = "UnitOfMeasureCode";
colvarUnitOfMeasureCode.DataType = DbType.AnsiString;
colvarUnitOfMeasureCode.MaxLength = 50;
colvarUnitOfMeasureCode.AutoIncrement = false;
colvarUnitOfMeasureCode.IsNullable = false;
colvarUnitOfMeasureCode.IsPrimaryKey = false;
colvarUnitOfMeasureCode.IsForeignKey = false;
colvarUnitOfMeasureCode.IsReadOnly = false;
schema.Columns.Add(colvarUnitOfMeasureCode);
TableSchema.TableColumn colvarUnitOfMeasureUnit = new TableSchema.TableColumn(schema);
colvarUnitOfMeasureUnit.ColumnName = "UnitOfMeasureUnit";
colvarUnitOfMeasureUnit.DataType = DbType.AnsiString;
colvarUnitOfMeasureUnit.MaxLength = 100;
colvarUnitOfMeasureUnit.AutoIncrement = false;
colvarUnitOfMeasureUnit.IsNullable = false;
colvarUnitOfMeasureUnit.IsPrimaryKey = false;
colvarUnitOfMeasureUnit.IsForeignKey = false;
colvarUnitOfMeasureUnit.IsReadOnly = false;
schema.Columns.Add(colvarUnitOfMeasureUnit);
TableSchema.TableColumn colvarUnitOfMeasureSymbol = new TableSchema.TableColumn(schema);
colvarUnitOfMeasureSymbol.ColumnName = "UnitOfMeasureSymbol";
colvarUnitOfMeasureSymbol.DataType = DbType.AnsiString;
colvarUnitOfMeasureSymbol.MaxLength = 20;
colvarUnitOfMeasureSymbol.AutoIncrement = false;
colvarUnitOfMeasureSymbol.IsNullable = false;
colvarUnitOfMeasureSymbol.IsPrimaryKey = false;
colvarUnitOfMeasureSymbol.IsForeignKey = false;
colvarUnitOfMeasureSymbol.IsReadOnly = false;
schema.Columns.Add(colvarUnitOfMeasureSymbol);
TableSchema.TableColumn colvarStatusID = new TableSchema.TableColumn(schema);
colvarStatusID.ColumnName = "StatusID";
colvarStatusID.DataType = DbType.Guid;
colvarStatusID.MaxLength = 0;
colvarStatusID.AutoIncrement = false;
colvarStatusID.IsNullable = true;
colvarStatusID.IsPrimaryKey = false;
colvarStatusID.IsForeignKey = false;
colvarStatusID.IsReadOnly = false;
schema.Columns.Add(colvarStatusID);
TableSchema.TableColumn colvarStatusCode = new TableSchema.TableColumn(schema);
colvarStatusCode.ColumnName = "StatusCode";
colvarStatusCode.DataType = DbType.AnsiString;
colvarStatusCode.MaxLength = 50;
colvarStatusCode.AutoIncrement = false;
colvarStatusCode.IsNullable = true;
colvarStatusCode.IsPrimaryKey = false;
colvarStatusCode.IsForeignKey = false;
colvarStatusCode.IsReadOnly = false;
schema.Columns.Add(colvarStatusCode);
TableSchema.TableColumn colvarStatusName = new TableSchema.TableColumn(schema);
colvarStatusName.ColumnName = "StatusName";
colvarStatusName.DataType = DbType.AnsiString;
colvarStatusName.MaxLength = 150;
colvarStatusName.AutoIncrement = false;
colvarStatusName.IsNullable = true;
colvarStatusName.IsPrimaryKey = false;
colvarStatusName.IsForeignKey = false;
colvarStatusName.IsReadOnly = false;
schema.Columns.Add(colvarStatusName);
TableSchema.TableColumn colvarStatusDescription = new TableSchema.TableColumn(schema);
colvarStatusDescription.ColumnName = "StatusDescription";
colvarStatusDescription.DataType = DbType.AnsiString;
colvarStatusDescription.MaxLength = 500;
colvarStatusDescription.AutoIncrement = false;
colvarStatusDescription.IsNullable = true;
colvarStatusDescription.IsPrimaryKey = false;
colvarStatusDescription.IsForeignKey = false;
colvarStatusDescription.IsReadOnly = false;
schema.Columns.Add(colvarStatusDescription);
TableSchema.TableColumn colvarStatusReasonID = new TableSchema.TableColumn(schema);
colvarStatusReasonID.ColumnName = "StatusReasonID";
colvarStatusReasonID.DataType = DbType.Guid;
colvarStatusReasonID.MaxLength = 0;
colvarStatusReasonID.AutoIncrement = false;
colvarStatusReasonID.IsNullable = true;
colvarStatusReasonID.IsPrimaryKey = false;
colvarStatusReasonID.IsForeignKey = false;
colvarStatusReasonID.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonID);
TableSchema.TableColumn colvarStatusReasonCode = new TableSchema.TableColumn(schema);
colvarStatusReasonCode.ColumnName = "StatusReasonCode";
colvarStatusReasonCode.DataType = DbType.AnsiString;
colvarStatusReasonCode.MaxLength = 50;
colvarStatusReasonCode.AutoIncrement = false;
colvarStatusReasonCode.IsNullable = true;
colvarStatusReasonCode.IsPrimaryKey = false;
colvarStatusReasonCode.IsForeignKey = false;
colvarStatusReasonCode.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonCode);
TableSchema.TableColumn colvarStatusReasonName = new TableSchema.TableColumn(schema);
colvarStatusReasonName.ColumnName = "StatusReasonName";
colvarStatusReasonName.DataType = DbType.AnsiString;
colvarStatusReasonName.MaxLength = 150;
colvarStatusReasonName.AutoIncrement = false;
colvarStatusReasonName.IsNullable = true;
colvarStatusReasonName.IsPrimaryKey = false;
colvarStatusReasonName.IsForeignKey = false;
colvarStatusReasonName.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonName);
TableSchema.TableColumn colvarStatusReasonDescription = new TableSchema.TableColumn(schema);
colvarStatusReasonDescription.ColumnName = "StatusReasonDescription";
colvarStatusReasonDescription.DataType = DbType.AnsiString;
colvarStatusReasonDescription.MaxLength = 500;
colvarStatusReasonDescription.AutoIncrement = false;
colvarStatusReasonDescription.IsNullable = true;
colvarStatusReasonDescription.IsPrimaryKey = false;
colvarStatusReasonDescription.IsForeignKey = false;
colvarStatusReasonDescription.IsReadOnly = false;
schema.Columns.Add(colvarStatusReasonDescription);
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = false;
colvarUserId.IsReadOnly = false;
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarAddedDate = new TableSchema.TableColumn(schema);
colvarAddedDate.ColumnName = "AddedDate";
colvarAddedDate.DataType = DbType.DateTime;
colvarAddedDate.MaxLength = 0;
colvarAddedDate.AutoIncrement = false;
colvarAddedDate.IsNullable = false;
colvarAddedDate.IsPrimaryKey = false;
colvarAddedDate.IsForeignKey = false;
colvarAddedDate.IsReadOnly = false;
schema.Columns.Add(colvarAddedDate);
TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema);
colvarAddedAt.ColumnName = "AddedAt";
colvarAddedAt.DataType = DbType.DateTime;
colvarAddedAt.MaxLength = 0;
colvarAddedAt.AutoIncrement = false;
colvarAddedAt.IsNullable = true;
colvarAddedAt.IsPrimaryKey = false;
colvarAddedAt.IsForeignKey = false;
colvarAddedAt.IsReadOnly = false;
schema.Columns.Add(colvarAddedAt);
TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema);
colvarUpdatedAt.ColumnName = "UpdatedAt";
colvarUpdatedAt.DataType = DbType.DateTime;
colvarUpdatedAt.MaxLength = 0;
colvarUpdatedAt.AutoIncrement = false;
colvarUpdatedAt.IsNullable = true;
colvarUpdatedAt.IsPrimaryKey = false;
colvarUpdatedAt.IsForeignKey = false;
colvarUpdatedAt.IsReadOnly = false;
schema.Columns.Add(colvarUpdatedAt);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("vObservationExpansion",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VObservationExpansion()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VObservationExpansion(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VObservationExpansion(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VObservationExpansion(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get
{
return GetColumnValue<int>("ID");
}
set
{
SetColumnValue("ID", value);
}
}
[XmlAttribute("ImportBatchID")]
[Bindable(true)]
public Guid ImportBatchID
{
get
{
return GetColumnValue<Guid>("ImportBatchID");
}
set
{
SetColumnValue("ImportBatchID", value);
}
}
[XmlAttribute("ImportBatchCode")]
[Bindable(true)]
public int ImportBatchCode
{
get
{
return GetColumnValue<int>("ImportBatchCode");
}
set
{
SetColumnValue("ImportBatchCode", value);
}
}
[XmlAttribute("ImportBatchDate")]
[Bindable(true)]
public DateTime ImportBatchDate
{
get
{
return GetColumnValue<DateTime>("ImportBatchDate");
}
set
{
SetColumnValue("ImportBatchDate", value);
}
}
[XmlAttribute("ValueDate")]
[Bindable(true)]
public DateTime ValueDate
{
get
{
return GetColumnValue<DateTime>("ValueDate");
}
set
{
SetColumnValue("ValueDate", value);
}
}
[XmlAttribute("ValueDay")]
[Bindable(true)]
public DateTime? ValueDay
{
get
{
return GetColumnValue<DateTime?>("ValueDay");
}
set
{
SetColumnValue("ValueDay", value);
}
}
[XmlAttribute("ValueYear")]
[Bindable(true)]
public int? ValueYear
{
get
{
return GetColumnValue<int?>("ValueYear");
}
set
{
SetColumnValue("ValueYear", value);
}
}
[XmlAttribute("ValueDecade")]
[Bindable(true)]
public int? ValueDecade
{
get
{
return GetColumnValue<int?>("ValueDecade");
}
set
{
SetColumnValue("ValueDecade", value);
}
}
[XmlAttribute("RawValue")]
[Bindable(true)]
public double? RawValue
{
get
{
return GetColumnValue<double?>("RawValue");
}
set
{
SetColumnValue("RawValue", value);
}
}
[XmlAttribute("DataValue")]
[Bindable(true)]
public double? DataValue
{
get
{
return GetColumnValue<double?>("DataValue");
}
set
{
SetColumnValue("DataValue", value);
}
}
[XmlAttribute("TextValue")]
[Bindable(true)]
public string TextValue
{
get
{
return GetColumnValue<string>("TextValue");
}
set
{
SetColumnValue("TextValue", value);
}
}
[XmlAttribute("Comment")]
[Bindable(true)]
public string Comment
{
get
{
return GetColumnValue<string>("Comment");
}
set
{
SetColumnValue("Comment", value);
}
}
[XmlAttribute("CorrelationID")]
[Bindable(true)]
public Guid? CorrelationID
{
get
{
return GetColumnValue<Guid?>("CorrelationID");
}
set
{
SetColumnValue("CorrelationID", value);
}
}
[XmlAttribute("SiteID")]
[Bindable(true)]
public Guid SiteID
{
get
{
return GetColumnValue<Guid>("SiteID");
}
set
{
SetColumnValue("SiteID", value);
}
}
[XmlAttribute("SiteCode")]
[Bindable(true)]
public string SiteCode
{
get
{
return GetColumnValue<string>("SiteCode");
}
set
{
SetColumnValue("SiteCode", value);
}
}
[XmlAttribute("SiteName")]
[Bindable(true)]
public string SiteName
{
get
{
return GetColumnValue<string>("SiteName");
}
set
{
SetColumnValue("SiteName", value);
}
}
[XmlAttribute("SiteDescription")]
[Bindable(true)]
public string SiteDescription
{
get
{
return GetColumnValue<string>("SiteDescription");
}
set
{
SetColumnValue("SiteDescription", value);
}
}
[XmlAttribute("SiteUrl")]
[Bindable(true)]
public string SiteUrl
{
get
{
return GetColumnValue<string>("SiteUrl");
}
set
{
SetColumnValue("SiteUrl", value);
}
}
[XmlAttribute("StationID")]
[Bindable(true)]
public Guid StationID
{
get
{
return GetColumnValue<Guid>("StationID");
}
set
{
SetColumnValue("StationID", value);
}
}
[XmlAttribute("StationCode")]
[Bindable(true)]
public string StationCode
{
get
{
return GetColumnValue<string>("StationCode");
}
set
{
SetColumnValue("StationCode", value);
}
}
[XmlAttribute("StationName")]
[Bindable(true)]
public string StationName
{
get
{
return GetColumnValue<string>("StationName");
}
set
{
SetColumnValue("StationName", value);
}
}
[XmlAttribute("StationDescription")]
[Bindable(true)]
public string StationDescription
{
get
{
return GetColumnValue<string>("StationDescription");
}
set
{
SetColumnValue("StationDescription", value);
}
}
[XmlAttribute("StationUrl")]
[Bindable(true)]
public string StationUrl
{
get
{
return GetColumnValue<string>("StationUrl");
}
set
{
SetColumnValue("StationUrl", value);
}
}
[XmlAttribute("InstrumentID")]
[Bindable(true)]
public Guid InstrumentID
{
get
{
return GetColumnValue<Guid>("InstrumentID");
}
set
{
SetColumnValue("InstrumentID", value);
}
}
[XmlAttribute("InstrumentCode")]
[Bindable(true)]
public string InstrumentCode
{
get
{
return GetColumnValue<string>("InstrumentCode");
}
set
{
SetColumnValue("InstrumentCode", value);
}
}
[XmlAttribute("InstrumentName")]
[Bindable(true)]
public string InstrumentName
{
get
{
return GetColumnValue<string>("InstrumentName");
}
set
{
SetColumnValue("InstrumentName", value);
}
}
[XmlAttribute("InstrumentDescription")]
[Bindable(true)]
public string InstrumentDescription
{
get
{
return GetColumnValue<string>("InstrumentDescription");
}
set
{
SetColumnValue("InstrumentDescription", value);
}
}
[XmlAttribute("InstrumentUrl")]
[Bindable(true)]
public string InstrumentUrl
{
get
{
return GetColumnValue<string>("InstrumentUrl");
}
set
{
SetColumnValue("InstrumentUrl", value);
}
}
[XmlAttribute("SensorID")]
[Bindable(true)]
public Guid SensorID
{
get
{
return GetColumnValue<Guid>("SensorID");
}
set
{
SetColumnValue("SensorID", value);
}
}
[XmlAttribute("SensorCode")]
[Bindable(true)]
public string SensorCode
{
get
{
return GetColumnValue<string>("SensorCode");
}
set
{
SetColumnValue("SensorCode", value);
}
}
[XmlAttribute("SensorName")]
[Bindable(true)]
public string SensorName
{
get
{
return GetColumnValue<string>("SensorName");
}
set
{
SetColumnValue("SensorName", value);
}
}
[XmlAttribute("SensorDescription")]
[Bindable(true)]
public string SensorDescription
{
get
{
return GetColumnValue<string>("SensorDescription");
}
set
{
SetColumnValue("SensorDescription", value);
}
}
[XmlAttribute("SensorUrl")]
[Bindable(true)]
public string SensorUrl
{
get
{
return GetColumnValue<string>("SensorUrl");
}
set
{
SetColumnValue("SensorUrl", value);
}
}
[XmlAttribute("Latitude")]
[Bindable(true)]
public double? Latitude
{
get
{
return GetColumnValue<double?>("Latitude");
}
set
{
SetColumnValue("Latitude", value);
}
}
[XmlAttribute("Longitude")]
[Bindable(true)]
public double? Longitude
{
get
{
return GetColumnValue<double?>("Longitude");
}
set
{
SetColumnValue("Longitude", value);
}
}
[XmlAttribute("Elevation")]
[Bindable(true)]
public double? Elevation
{
get
{
return GetColumnValue<double?>("Elevation");
}
set
{
SetColumnValue("Elevation", value);
}
}
[XmlAttribute("PhenomenonOfferingID")]
[Bindable(true)]
public Guid PhenomenonOfferingID
{
get
{
return GetColumnValue<Guid>("PhenomenonOfferingID");
}
set
{
SetColumnValue("PhenomenonOfferingID", value);
}
}
[XmlAttribute("PhenomenonID")]
[Bindable(true)]
public Guid PhenomenonID
{
get
{
return GetColumnValue<Guid>("PhenomenonID");
}
set
{
SetColumnValue("PhenomenonID", value);
}
}
[XmlAttribute("PhenomenonCode")]
[Bindable(true)]
public string PhenomenonCode
{
get
{
return GetColumnValue<string>("PhenomenonCode");
}
set
{
SetColumnValue("PhenomenonCode", value);
}
}
[XmlAttribute("PhenomenonName")]
[Bindable(true)]
public string PhenomenonName
{
get
{
return GetColumnValue<string>("PhenomenonName");
}
set
{
SetColumnValue("PhenomenonName", value);
}
}
[XmlAttribute("PhenomenonDescription")]
[Bindable(true)]
public string PhenomenonDescription
{
get
{
return GetColumnValue<string>("PhenomenonDescription");
}
set
{
SetColumnValue("PhenomenonDescription", value);
}
}
[XmlAttribute("PhenomenonUrl")]
[Bindable(true)]
public string PhenomenonUrl
{
get
{
return GetColumnValue<string>("PhenomenonUrl");
}
set
{
SetColumnValue("PhenomenonUrl", value);
}
}
[XmlAttribute("OfferingID")]
[Bindable(true)]
public Guid OfferingID
{
get
{
return GetColumnValue<Guid>("OfferingID");
}
set
{
SetColumnValue("OfferingID", value);
}
}
[XmlAttribute("OfferingCode")]
[Bindable(true)]
public string OfferingCode
{
get
{
return GetColumnValue<string>("OfferingCode");
}
set
{
SetColumnValue("OfferingCode", value);
}
}
[XmlAttribute("OfferingName")]
[Bindable(true)]
public string OfferingName
{
get
{
return GetColumnValue<string>("OfferingName");
}
set
{
SetColumnValue("OfferingName", value);
}
}
[XmlAttribute("OfferingDescription")]
[Bindable(true)]
public string OfferingDescription
{
get
{
return GetColumnValue<string>("OfferingDescription");
}
set
{
SetColumnValue("OfferingDescription", value);
}
}
[XmlAttribute("PhenomenonUOMID")]
[Bindable(true)]
public Guid PhenomenonUOMID
{
get
{
return GetColumnValue<Guid>("PhenomenonUOMID");
}
set
{
SetColumnValue("PhenomenonUOMID", value);
}
}
[XmlAttribute("UnitOfMeasureID")]
[Bindable(true)]
public Guid UnitOfMeasureID
{
get
{
return GetColumnValue<Guid>("UnitOfMeasureID");
}
set
{
SetColumnValue("UnitOfMeasureID", value);
}
}
[XmlAttribute("UnitOfMeasureCode")]
[Bindable(true)]
public string UnitOfMeasureCode
{
get
{
return GetColumnValue<string>("UnitOfMeasureCode");
}
set
{
SetColumnValue("UnitOfMeasureCode", value);
}
}
[XmlAttribute("UnitOfMeasureUnit")]
[Bindable(true)]
public string UnitOfMeasureUnit
{
get
{
return GetColumnValue<string>("UnitOfMeasureUnit");
}
set
{
SetColumnValue("UnitOfMeasureUnit", value);
}
}
[XmlAttribute("UnitOfMeasureSymbol")]
[Bindable(true)]
public string UnitOfMeasureSymbol
{
get
{
return GetColumnValue<string>("UnitOfMeasureSymbol");
}
set
{
SetColumnValue("UnitOfMeasureSymbol", value);
}
}
[XmlAttribute("StatusID")]
[Bindable(true)]
public Guid? StatusID
{
get
{
return GetColumnValue<Guid?>("StatusID");
}
set
{
SetColumnValue("StatusID", value);
}
}
[XmlAttribute("StatusCode")]
[Bindable(true)]
public string StatusCode
{
get
{
return GetColumnValue<string>("StatusCode");
}
set
{
SetColumnValue("StatusCode", value);
}
}
[XmlAttribute("StatusName")]
[Bindable(true)]
public string StatusName
{
get
{
return GetColumnValue<string>("StatusName");
}
set
{
SetColumnValue("StatusName", value);
}
}
[XmlAttribute("StatusDescription")]
[Bindable(true)]
public string StatusDescription
{
get
{
return GetColumnValue<string>("StatusDescription");
}
set
{
SetColumnValue("StatusDescription", value);
}
}
[XmlAttribute("StatusReasonID")]
[Bindable(true)]
public Guid? StatusReasonID
{
get
{
return GetColumnValue<Guid?>("StatusReasonID");
}
set
{
SetColumnValue("StatusReasonID", value);
}
}
[XmlAttribute("StatusReasonCode")]
[Bindable(true)]
public string StatusReasonCode
{
get
{
return GetColumnValue<string>("StatusReasonCode");
}
set
{
SetColumnValue("StatusReasonCode", value);
}
}
[XmlAttribute("StatusReasonName")]
[Bindable(true)]
public string StatusReasonName
{
get
{
return GetColumnValue<string>("StatusReasonName");
}
set
{
SetColumnValue("StatusReasonName", value);
}
}
[XmlAttribute("StatusReasonDescription")]
[Bindable(true)]
public string StatusReasonDescription
{
get
{
return GetColumnValue<string>("StatusReasonDescription");
}
set
{
SetColumnValue("StatusReasonDescription", value);
}
}
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get
{
return GetColumnValue<Guid>("UserId");
}
set
{
SetColumnValue("UserId", value);
}
}
[XmlAttribute("AddedDate")]
[Bindable(true)]
public DateTime AddedDate
{
get
{
return GetColumnValue<DateTime>("AddedDate");
}
set
{
SetColumnValue("AddedDate", value);
}
}
[XmlAttribute("AddedAt")]
[Bindable(true)]
public DateTime? AddedAt
{
get
{
return GetColumnValue<DateTime?>("AddedAt");
}
set
{
SetColumnValue("AddedAt", value);
}
}
[XmlAttribute("UpdatedAt")]
[Bindable(true)]
public DateTime? UpdatedAt
{
get
{
return GetColumnValue<DateTime?>("UpdatedAt");
}
set
{
SetColumnValue("UpdatedAt", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"ID";
public static string ImportBatchID = @"ImportBatchID";
public static string ImportBatchCode = @"ImportBatchCode";
public static string ImportBatchDate = @"ImportBatchDate";
public static string ValueDate = @"ValueDate";
public static string ValueDay = @"ValueDay";
public static string ValueYear = @"ValueYear";
public static string ValueDecade = @"ValueDecade";
public static string RawValue = @"RawValue";
public static string DataValue = @"DataValue";
public static string TextValue = @"TextValue";
public static string Comment = @"Comment";
public static string CorrelationID = @"CorrelationID";
public static string SiteID = @"SiteID";
public static string SiteCode = @"SiteCode";
public static string SiteName = @"SiteName";
public static string SiteDescription = @"SiteDescription";
public static string SiteUrl = @"SiteUrl";
public static string StationID = @"StationID";
public static string StationCode = @"StationCode";
public static string StationName = @"StationName";
public static string StationDescription = @"StationDescription";
public static string StationUrl = @"StationUrl";
public static string InstrumentID = @"InstrumentID";
public static string InstrumentCode = @"InstrumentCode";
public static string InstrumentName = @"InstrumentName";
public static string InstrumentDescription = @"InstrumentDescription";
public static string InstrumentUrl = @"InstrumentUrl";
public static string SensorID = @"SensorID";
public static string SensorCode = @"SensorCode";
public static string SensorName = @"SensorName";
public static string SensorDescription = @"SensorDescription";
public static string SensorUrl = @"SensorUrl";
public static string Latitude = @"Latitude";
public static string Longitude = @"Longitude";
public static string Elevation = @"Elevation";
public static string PhenomenonOfferingID = @"PhenomenonOfferingID";
public static string PhenomenonID = @"PhenomenonID";
public static string PhenomenonCode = @"PhenomenonCode";
public static string PhenomenonName = @"PhenomenonName";
public static string PhenomenonDescription = @"PhenomenonDescription";
public static string PhenomenonUrl = @"PhenomenonUrl";
public static string OfferingID = @"OfferingID";
public static string OfferingCode = @"OfferingCode";
public static string OfferingName = @"OfferingName";
public static string OfferingDescription = @"OfferingDescription";
public static string PhenomenonUOMID = @"PhenomenonUOMID";
public static string UnitOfMeasureID = @"UnitOfMeasureID";
public static string UnitOfMeasureCode = @"UnitOfMeasureCode";
public static string UnitOfMeasureUnit = @"UnitOfMeasureUnit";
public static string UnitOfMeasureSymbol = @"UnitOfMeasureSymbol";
public static string StatusID = @"StatusID";
public static string StatusCode = @"StatusCode";
public static string StatusName = @"StatusName";
public static string StatusDescription = @"StatusDescription";
public static string StatusReasonID = @"StatusReasonID";
public static string StatusReasonCode = @"StatusReasonCode";
public static string StatusReasonName = @"StatusReasonName";
public static string StatusReasonDescription = @"StatusReasonDescription";
public static string UserId = @"UserId";
public static string AddedDate = @"AddedDate";
public static string AddedAt = @"AddedAt";
public static string UpdatedAt = @"UpdatedAt";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
/*
* Copyright (c) 2013-2014 Tobias Schulz
*
* Copying, redistribution and use of the source code in this file in source
* and binary forms, with or without modification, are permitted provided
* that the conditions of the MIT license are met.
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using OpenTK.Graphics.OpenGL;
using Platform;
using Primitives;
namespace Examples.TestGame3
{
public class TestGame : Game
{
private GraphicsDeviceManager Graphics;
public TestGame ()
{
Graphics = new GraphicsDeviceManager (this);
Graphics.PreferredBackBufferWidth = 600;
Graphics.PreferredBackBufferHeight = 480;
Graphics.IsFullScreen = false;
Graphics.ApplyChanges ();
IsMouseVisible = true;
Content.RootDirectory = SystemInfo.RelativeContentDirectory;
Window.Title = "Xna Test";
}
private Model model1;
private Model model2;
private Model model3;
private Cylinder cylinder1;
private Torus torus1;
private Matrix World;
private Matrix View;
private Matrix Projection;
private Effect shader3;
private Effect shader3_gl;
private Effect shader4;
private Effect currentShader;
private Texture2D texture;
private Vector3 position;
private Vector3 target;
protected override void LoadContent ()
{
model1 = Content.Load<Model>("Models/test");
model2 = Content.Load<Model>("Models/sphere");
model3 = Content.Load<Model>("Models/pipe-straight");
cylinder1 = new Cylinder (device: GraphicsDevice, height: 2f, diameter: 0.5f, tessellation: 64);
torus1 = new Torus (device: GraphicsDevice, diameter: 1.25f, thickness: 0.5f, tessellation: 64, circlePercent: 0.25f);
string shaderPath = SystemInfo.RelativeContentDirectory + "Shader/";
shader3 = new Effect (
graphicsDevice: GraphicsDevice,
effectCode: File.ReadAllBytes (shaderPath + "shader3.mgfx"),
effectName: "shader3"
);
// Write human-readable effect code to file
File.WriteAllText (shaderPath + "shader3.glfx_gen", shader3.EffectCode);
// Construct a new shader by loading the human-readable effect code
shader3_gl = new Effect (
graphicsDevice: GraphicsDevice,
effectCode: System.IO.File.ReadAllText (shaderPath + "shader3.glfx_gen"),
effectName: "shader3_gl"
);
// Construct a new shader by loading the human-readable effect code
shader4 = new Effect (
graphicsDevice: GraphicsDevice,
effectCode: System.IO.File.ReadAllText (shaderPath + "shader4.glfx"),
effectName: "shader4"
);
//shader3_gl = shader3 = null;
currentShader = shader3;
currentShader = shader3_gl;
currentShader = shader4;
string texturePath = SystemInfo.RelativeContentDirectory + "Textures/";
FileStream stream = new FileStream (texturePath + "texture1.png", FileMode.Open);
texture = Texture2D.FromStream (GraphicsDevice, stream);
position = (Vector3.Right + Vector3.Backward) * 15f;
target = Vector3.Zero;
Vector3 up = Vector3.Up;
float aspectRatio = Graphics.GraphicsDevice.Viewport.AspectRatio;
float nearPlane = 0.5f;
float farPlane = 1000.0f;
World = Matrix.Identity;
View = Matrix.CreateLookAt (position, target, up);
Projection = Matrix.CreatePerspectiveFieldOfView (MathHelper.ToRadians (60), aspectRatio, nearPlane, farPlane);
modelScale [0] = Vector3.One * 0.002f;
modelScale [1] = Vector3.One * 2f;
modelScale [2] = Vector3.One * 2f;
modelScale [3] = Vector3.One * 2f;
modelScale [4] = Vector3.One * 2f;
modelPositions [0] = (Vector3.Left + Vector3.Up) * 10f;
modelPositions [1] = (Vector3.Left + Vector3.Down) * 10f;
modelPositions [2] = (Vector3.Forward + Vector3.Up) * 10f;
modelPositions [3] = (Vector3.Forward + Vector3.Down) * 10f;
modelPositions [4] = Vector3.Zero;
}
static readonly int NUM_MODELS = 5;
Vector3[] modelScale = new Vector3 [NUM_MODELS];
Vector3[] modelPositions = new Vector3 [NUM_MODELS];
Vector3[] modelRotations = new Vector3 [NUM_MODELS];
Vector3[] modelDirections = new Vector3 [NUM_MODELS];
protected override void Draw (GameTime time)
{
GraphicsDevice.Clear (Color.Gray);
RotateModel (0);
modelRotations [4] = modelRotations [3] = modelRotations [2] = modelRotations [1] = modelRotations [0];
int index = 0;
SetShaderParameters (index);
RemapModel (model1, currentShader);
foreach (ModelMesh mesh in model1.Meshes)
{
mesh.Draw ();
}
++index;
SetShaderParameters (index);
RemapModel (model2, currentShader);
foreach (ModelMesh mesh in model2.Meshes)
{
mesh.Draw ();
}
++index;
SetShaderParameters (index);
RemapModel (model3, currentShader);
foreach (ModelMesh mesh in model3.Meshes)
{
mesh.Draw ();
}
++index;
SetShaderParameters (index);
cylinder1.Draw (currentShader);
++index;
SetShaderParameters (index);
torus1.Draw (currentShader);
}
void RotateModel (int i)
{
if (random.Next () % 100 == 0)
{
modelDirections [i] = new Vector3 (random.Next () % 201 - 100, random.Next () % 201 - 100, random.Next () % 201 - 100) / 200f / 15f;
}
modelRotations [i] += modelDirections [i];
if (modelRotations [i].Length () > 15)
{
modelDirections [i] = Vector3.Normalize (-modelRotations [i]) * modelDirections [i].Length ();
}
}
private void SetShaderParameters (int index)
{
Matrix modelWorld = Matrix.CreateScale (modelScale [index])
* Matrix.CreateFromYawPitchRoll (modelRotations [index].Y, modelRotations [index].X, modelRotations [index].Z)
* Matrix.CreateTranslation (modelPositions [index]);
try
{
currentShader.Parameters ["ModelTexture"].SetValue (texture);
}
catch (NullReferenceException)
{
}
currentShader.Parameters ["World"].SetValue (modelWorld * World);
currentShader.Parameters ["View"].SetValue (View);
currentShader.Parameters ["Projection"].SetValue (Projection);
Matrix worldInverseTransposeMatrix = Matrix.Transpose (Matrix.Invert (modelWorld * World));
currentShader.Parameters ["WorldInverseTranspose"].SetValue (worldInverseTransposeMatrix);
}
Random random = new Random ();
private void RemapModel (Model model, Effect effect)
{
foreach (ModelMesh mesh in model.Meshes)
{
foreach (ModelMeshPart part in mesh.MeshParts)
{
part.Effect = effect;
}
}
}
}
}
| |
/*
* Copyright 2002-2015 Drew Noakes
*
* Modified by Yakov Danilov <[email protected]> for Imazen LLC (Ported from Java to C#)
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
using System.IO;
using Sharpen;
namespace Com.Drew.Lang
{
/// <summary>
/// Base class for testing implementations of
/// <see cref="RandomAccessReader"/>
/// .
/// </summary>
/// <author>Drew Noakes https://drewnoakes.com</author>
public abstract class RandomAccessTestBase
{
protected internal abstract RandomAccessReader CreateReader(sbyte[] bytes);
[NUnit.Framework.Test]
public virtual void TestDefaultEndianness()
{
Sharpen.Tests.AreEqual(true, CreateReader(new sbyte[1]).IsMotorolaByteOrder());
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetInt8()
{
sbyte[] buffer = new sbyte[] { unchecked((int)(0x00)), unchecked((int)(0x01)), unchecked((sbyte)0x7F), unchecked((sbyte)0xFF) };
RandomAccessReader reader = CreateReader(buffer);
Sharpen.Tests.AreEqual(unchecked((sbyte)0), reader.GetInt8(0));
Sharpen.Tests.AreEqual(unchecked((sbyte)1), reader.GetInt8(1));
Sharpen.Tests.AreEqual(unchecked((sbyte)127), reader.GetInt8(2));
Sharpen.Tests.AreEqual(unchecked((sbyte)255), reader.GetInt8(3));
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetUInt8()
{
sbyte[] buffer = new sbyte[] { unchecked((int)(0x00)), unchecked((int)(0x01)), unchecked((sbyte)0x7F), unchecked((sbyte)0xFF) };
RandomAccessReader reader = CreateReader(buffer);
Sharpen.Tests.AreEqual(0, reader.GetUInt8(0));
Sharpen.Tests.AreEqual(1, reader.GetUInt8(1));
Sharpen.Tests.AreEqual(127, reader.GetUInt8(2));
Sharpen.Tests.AreEqual(255, reader.GetUInt8(3));
}
[NUnit.Framework.Test]
public virtual void TestGetUInt8_OutOfBounds()
{
try
{
RandomAccessReader reader = CreateReader(new sbyte[2]);
reader.GetUInt8(2);
NUnit.Framework.Assert.Fail("Exception expected");
}
catch (IOException ex)
{
Sharpen.Tests.AreEqual("Attempt to read from beyond end of underlying data source (requested index: 2, requested count: 1, max index: 1)", ex.Message);
}
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetInt16()
{
Sharpen.Tests.AreEqual(-1, CreateReader(new sbyte[] { unchecked((sbyte)0xff), unchecked((sbyte)0xff) }).GetInt16(0));
sbyte[] buffer = new sbyte[] { unchecked((int)(0x00)), unchecked((int)(0x01)), unchecked((sbyte)0x7F), unchecked((sbyte)0xFF) };
RandomAccessReader reader = CreateReader(buffer);
Sharpen.Tests.AreEqual((short)0x0001, reader.GetInt16(0));
Sharpen.Tests.AreEqual((short)0x017F, reader.GetInt16(1));
Sharpen.Tests.AreEqual((short)0x7FFF, reader.GetInt16(2));
reader.SetMotorolaByteOrder(false);
Sharpen.Tests.AreEqual((short)0x0100, reader.GetInt16(0));
Sharpen.Tests.AreEqual((short)0x7F01, reader.GetInt16(1));
Sharpen.Tests.AreEqual(unchecked((short)(0xFF7F)), reader.GetInt16(2));
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetUInt16()
{
sbyte[] buffer = new sbyte[] { unchecked((int)(0x00)), unchecked((int)(0x01)), unchecked((sbyte)0x7F), unchecked((sbyte)0xFF) };
RandomAccessReader reader = CreateReader(buffer);
Sharpen.Tests.AreEqual(unchecked((int)(0x0001)), reader.GetUInt16(0));
Sharpen.Tests.AreEqual(unchecked((int)(0x017F)), reader.GetUInt16(1));
Sharpen.Tests.AreEqual(unchecked((int)(0x7FFF)), reader.GetUInt16(2));
reader.SetMotorolaByteOrder(false);
Sharpen.Tests.AreEqual(unchecked((int)(0x0100)), reader.GetUInt16(0));
Sharpen.Tests.AreEqual(unchecked((int)(0x7F01)), reader.GetUInt16(1));
Sharpen.Tests.AreEqual(unchecked((int)(0xFF7F)), reader.GetUInt16(2));
}
[NUnit.Framework.Test]
public virtual void TestGetUInt16_OutOfBounds()
{
try
{
RandomAccessReader reader = CreateReader(new sbyte[2]);
reader.GetUInt16(1);
NUnit.Framework.Assert.Fail("Exception expected");
}
catch (IOException ex)
{
Sharpen.Tests.AreEqual("Attempt to read from beyond end of underlying data source (requested index: 1, requested count: 2, max index: 1)", ex.Message);
}
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetInt32()
{
Sharpen.Tests.AreEqual(-1, CreateReader(new sbyte[] { unchecked((sbyte)0xff), unchecked((sbyte)0xff), unchecked((sbyte)0xff), unchecked((sbyte)0xff) }).GetInt32(0));
sbyte[] buffer = new sbyte[] { unchecked((int)(0x00)), unchecked((int)(0x01)), unchecked((sbyte)0x7F), unchecked((sbyte)0xFF), unchecked((int)(0x02)), unchecked((int)(0x03)), unchecked((int)(0x04)) };
RandomAccessReader reader = CreateReader(buffer);
Sharpen.Tests.AreEqual(unchecked((int)(0x00017FFF)), reader.GetInt32(0));
Sharpen.Tests.AreEqual(unchecked((int)(0x017FFF02)), reader.GetInt32(1));
Sharpen.Tests.AreEqual(unchecked((int)(0x7FFF0203)), reader.GetInt32(2));
Sharpen.Tests.AreEqual(unchecked((int)(0xFF020304)), reader.GetInt32(3));
reader.SetMotorolaByteOrder(false);
Sharpen.Tests.AreEqual(unchecked((int)(0xFF7F0100)), reader.GetInt32(0));
Sharpen.Tests.AreEqual(unchecked((int)(0x02FF7F01)), reader.GetInt32(1));
Sharpen.Tests.AreEqual(unchecked((int)(0x0302FF7F)), reader.GetInt32(2));
Sharpen.Tests.AreEqual(unchecked((int)(0x040302FF)), reader.GetInt32(3));
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetUInt32()
{
Sharpen.Tests.AreEqual(4294967295L, CreateReader(new sbyte[] { unchecked((sbyte)0xff), unchecked((sbyte)0xff), unchecked((sbyte)0xff), unchecked((sbyte)0xff) }).GetUInt32(0));
sbyte[] buffer = new sbyte[] { unchecked((int)(0x00)), unchecked((int)(0x01)), unchecked((sbyte)0x7F), unchecked((sbyte)0xFF), unchecked((int)(0x02)), unchecked((int)(0x03)), unchecked((int)(0x04)) };
RandomAccessReader reader = CreateReader(buffer);
Sharpen.Tests.AreEqual(unchecked((long)(0x00017FFFL)), reader.GetUInt32(0));
Sharpen.Tests.AreEqual(unchecked((long)(0x017FFF02L)), reader.GetUInt32(1));
Sharpen.Tests.AreEqual(unchecked((long)(0x7FFF0203L)), reader.GetUInt32(2));
Sharpen.Tests.AreEqual(unchecked((long)(0xFF020304L)), reader.GetUInt32(3));
reader.SetMotorolaByteOrder(false);
Sharpen.Tests.AreEqual(4286513408L, reader.GetUInt32(0));
Sharpen.Tests.AreEqual(unchecked((long)(0x02FF7F01L)), reader.GetUInt32(1));
Sharpen.Tests.AreEqual(unchecked((long)(0x0302FF7FL)), reader.GetUInt32(2));
Sharpen.Tests.AreEqual(unchecked((long)(0x040302FFL)), reader.GetInt32(3));
}
[NUnit.Framework.Test]
public virtual void TestGetInt32_OutOfBounds()
{
try
{
RandomAccessReader reader = CreateReader(new sbyte[3]);
reader.GetInt32(0);
NUnit.Framework.Assert.Fail("Exception expected");
}
catch (IOException ex)
{
Sharpen.Tests.AreEqual("Attempt to read from beyond end of underlying data source (requested index: 0, requested count: 4, max index: 2)", ex.Message);
}
}
/// <exception cref="System.IO.IOException"/>
[NUnit.Framework.Test]
public virtual void TestGetInt64()
{
sbyte[] buffer = new sbyte[] { unchecked((int)(0x00)), unchecked((int)(0x01)), unchecked((int)(0x02)), unchecked((int)(0x03)), unchecked((int)(0x04)), unchecked((int)(0x05)), unchecked((int)(0x06)), unchecked((int)(0x07)), unchecked((sbyte)0xFF
) };
RandomAccessReader reader = CreateReader(buffer);
Sharpen.Tests.AreEqual(unchecked((long)(0x0001020304050607L)), reader.GetInt64(0));
Sharpen.Tests.AreEqual(unchecked((long)(0x01020304050607FFL)), reader.GetInt64(1));
reader.SetMotorolaByteOrder(false);
Sharpen.Tests.AreEqual(unchecked((long)(0x0706050403020100L)), reader.GetInt64(0));
Sharpen.Tests.AreEqual(unchecked((long)(0xFF07060504030201L)), reader.GetInt64(1));
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetInt64_OutOfBounds()
{
try
{
RandomAccessReader reader = CreateReader(new sbyte[7]);
reader.GetInt64(0);
NUnit.Framework.Assert.Fail("Exception expected");
}
catch (IOException ex)
{
Sharpen.Tests.AreEqual("Attempt to read from beyond end of underlying data source (requested index: 0, requested count: 8, max index: 6)", ex.Message);
}
try
{
RandomAccessReader reader = CreateReader(new sbyte[7]);
reader.GetInt64(-1);
NUnit.Framework.Assert.Fail("Exception expected");
}
catch (IOException ex)
{
Sharpen.Tests.AreEqual("Attempt to read from buffer using a negative index (-1)", ex.Message);
}
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetFloat32()
{
int nanBits = unchecked((int)(0x7fc00000));
Sharpen.Tests.IsTrue(float.IsNaN(Sharpen.Extensions.IntBitsToFloat(nanBits)));
sbyte[] buffer = new sbyte[] { unchecked((int)(0x7f)), unchecked((sbyte)0xc0), unchecked((int)(0x00)), unchecked((int)(0x00)) };
RandomAccessReader reader = CreateReader(buffer);
Sharpen.Tests.IsTrue(float.IsNaN(reader.GetFloat32(0)));
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetFloat64()
{
long nanBits = unchecked((long)(0xfff0000000000001L));
Sharpen.Tests.IsTrue(double.IsNaN(Sharpen.Extensions.LongBitsToDouble(nanBits)));
sbyte[] buffer = new sbyte[] { unchecked((sbyte)0xff), unchecked((sbyte)0xf0), unchecked((int)(0x00)), unchecked((int)(0x00)), unchecked((int)(0x00)), unchecked((int)(0x00)), unchecked((int)(0x00)), unchecked((int)(0x01)) };
RandomAccessReader reader = CreateReader(buffer);
Sharpen.Tests.IsTrue(double.IsNaN(reader.GetDouble64(0)));
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetNullTerminatedString()
{
sbyte[] bytes = new sbyte[] { unchecked((int)(0x41)), unchecked((int)(0x42)), unchecked((int)(0x43)), unchecked((int)(0x44)), unchecked((int)(0x00)), unchecked((int)(0x45)), unchecked((int)(0x46)), unchecked((int)(0x47)) };
RandomAccessReader reader = CreateReader(bytes);
Sharpen.Tests.AreEqual(string.Empty, reader.GetNullTerminatedString(0, 0));
Sharpen.Tests.AreEqual("A", reader.GetNullTerminatedString(0, 1));
Sharpen.Tests.AreEqual("AB", reader.GetNullTerminatedString(0, 2));
Sharpen.Tests.AreEqual("ABC", reader.GetNullTerminatedString(0, 3));
Sharpen.Tests.AreEqual("ABCD", reader.GetNullTerminatedString(0, 4));
Sharpen.Tests.AreEqual("ABCD", reader.GetNullTerminatedString(0, 5));
Sharpen.Tests.AreEqual("ABCD", reader.GetNullTerminatedString(0, 6));
Sharpen.Tests.AreEqual("BCD", reader.GetNullTerminatedString(1, 3));
Sharpen.Tests.AreEqual("BCD", reader.GetNullTerminatedString(1, 4));
Sharpen.Tests.AreEqual("BCD", reader.GetNullTerminatedString(1, 5));
Sharpen.Tests.AreEqual(string.Empty, reader.GetNullTerminatedString(4, 3));
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetString()
{
sbyte[] bytes = new sbyte[] { unchecked((int)(0x41)), unchecked((int)(0x42)), unchecked((int)(0x43)), unchecked((int)(0x44)), unchecked((int)(0x00)), unchecked((int)(0x45)), unchecked((int)(0x46)), unchecked((int)(0x47)) };
RandomAccessReader reader = CreateReader(bytes);
Sharpen.Tests.AreEqual(string.Empty, reader.GetString(0, 0));
Sharpen.Tests.AreEqual("A", reader.GetString(0, 1));
Sharpen.Tests.AreEqual("AB", reader.GetString(0, 2));
Sharpen.Tests.AreEqual("ABC", reader.GetString(0, 3));
Sharpen.Tests.AreEqual("ABCD", reader.GetString(0, 4));
Sharpen.Tests.AreEqual("ABCD\x0", reader.GetString(0, 5));
Sharpen.Tests.AreEqual("ABCD\x0000E", reader.GetString(0, 6));
Sharpen.Tests.AreEqual("BCD", reader.GetString(1, 3));
Sharpen.Tests.AreEqual("BCD\x0", reader.GetString(1, 4));
Sharpen.Tests.AreEqual("BCD\x0000E", reader.GetString(1, 5));
Sharpen.Tests.AreEqual("\x0000EF", reader.GetString(4, 3));
}
[NUnit.Framework.Test]
public virtual void TestIndexPlusCountExceedsIntMaxValue()
{
RandomAccessReader reader = CreateReader(new sbyte[10]);
try
{
reader.GetBytes(unchecked((int)(0x6FFFFFFF)), unchecked((int)(0x6FFFFFFF)));
}
catch (IOException e)
{
Sharpen.Tests.AreEqual("Number of requested bytes summed with starting index exceed maximum range of signed 32 bit integers (requested index: 1879048191, requested count: 1879048191)", e.Message);
}
}
[NUnit.Framework.Test]
public virtual void TestOverflowBoundsCalculation()
{
RandomAccessReader reader = CreateReader(new sbyte[10]);
try
{
reader.GetBytes(5, 10);
}
catch (IOException e)
{
Sharpen.Tests.AreEqual("Attempt to read from beyond end of underlying data source (requested index: 5, requested count: 10, max index: 9)", e.Message);
}
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetBytesEOF()
{
CreateReader(new sbyte[50]).GetBytes(0, 50);
RandomAccessReader reader = CreateReader(new sbyte[50]);
reader.GetBytes(25, 25);
try
{
CreateReader(new sbyte[50]).GetBytes(0, 51);
NUnit.Framework.Assert.Fail("Expecting exception");
}
catch (IOException)
{
}
}
/// <exception cref="System.Exception"/>
[NUnit.Framework.Test]
public virtual void TestGetInt8EOF()
{
CreateReader(new sbyte[1]).GetInt8(0);
RandomAccessReader reader = CreateReader(new sbyte[2]);
reader.GetInt8(0);
reader.GetInt8(1);
try
{
reader = CreateReader(new sbyte[1]);
reader.GetInt8(0);
reader.GetInt8(1);
NUnit.Framework.Assert.Fail("Expecting exception");
}
catch (IOException)
{
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute.Models
{
/// <summary>
/// A deployment that exists in the cloud service.
/// </summary>
public partial class DeploymentGetResponse : OperationResponse
{
private string _configuration;
/// <summary>
/// The configuration file of the deployment.
/// </summary>
public string Configuration
{
get { return this._configuration; }
set { this._configuration = value; }
}
private DateTime _createdTime;
/// <summary>
/// The time that the deployment was created.
/// </summary>
public DateTime CreatedTime
{
get { return this._createdTime; }
set { this._createdTime = value; }
}
private DeploymentSlot _deploymentSlot;
/// <summary>
/// The deployment environment in which this deployment is running.
/// </summary>
public DeploymentSlot DeploymentSlot
{
get { return this._deploymentSlot; }
set { this._deploymentSlot = value; }
}
private DnsSettings _dnsSettings;
/// <summary>
/// The custom DNS settings that are specified for deployment.
/// </summary>
public DnsSettings DnsSettings
{
get { return this._dnsSettings; }
set { this._dnsSettings = value; }
}
private IDictionary<string, string> _extendedProperties;
/// <summary>
/// Optional. Represents the name of an extended cloud service
/// property. Each extended property must have both a defined name and
/// value. You can have a maximum of 50 extended property name and
/// value pairs. The maximum length of the Name element is 64
/// characters, only alphanumeric characters and underscores are valid
/// in the name, and it must start with a letter. Attempting to use
/// other characters, starting with a non-letter character, or
/// entering a name that is identical to that of another extended
/// property owned by the same service, will result in a status code
/// 400 (Bad Request) error. Each extended property value has a
/// maximum length of 255 characters.
/// </summary>
public IDictionary<string, string> ExtendedProperties
{
get { return this._extendedProperties; }
set { this._extendedProperties = value; }
}
private ExtensionConfiguration _extensionConfiguration;
/// <summary>
/// Represents an extension that is added to the cloud service.
/// </summary>
public ExtensionConfiguration ExtensionConfiguration
{
get { return this._extensionConfiguration; }
set { this._extensionConfiguration = value; }
}
private string _label;
/// <summary>
/// The user supplied name of the deployment. This name can be used
/// identify the deployment for tracking purposes.
/// </summary>
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private DateTime _lastModifiedTime;
/// <summary>
/// The last time that the deployment was modified.
/// </summary>
public DateTime LastModifiedTime
{
get { return this._lastModifiedTime; }
set { this._lastModifiedTime = value; }
}
private bool _locked;
/// <summary>
/// Indicates whether the deployment is locked for new write
/// operations. True if the deployment is locked because an existing
/// operation is updating the deployment; otherwise false.
/// </summary>
public bool Locked
{
get { return this._locked; }
set { this._locked = value; }
}
private string _name;
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private PersistentVMDowntime _persistentVMDowntime;
/// <summary>
/// Specifies information about when the virtual machine has been
/// started and stopped.
/// </summary>
public PersistentVMDowntime PersistentVMDowntime
{
get { return this._persistentVMDowntime; }
set { this._persistentVMDowntime = value; }
}
private string _privateId;
/// <summary>
/// The unique identifier for this deployment.
/// </summary>
public string PrivateId
{
get { return this._privateId; }
set { this._privateId = value; }
}
private string _reservedIPName;
/// <summary>
/// Preview Only. The name of the Reserved IP that the deployment
/// belongs to.
/// </summary>
public string ReservedIPName
{
get { return this._reservedIPName; }
set { this._reservedIPName = value; }
}
private IList<RoleInstance> _roleInstances;
/// <summary>
/// The list of role instances in the deployment.
/// </summary>
public IList<RoleInstance> RoleInstances
{
get { return this._roleInstances; }
set { this._roleInstances = value; }
}
private IList<Role> _roles;
/// <summary>
/// The list of roles in the deployment.
/// </summary>
public IList<Role> Roles
{
get { return this._roles; }
set { this._roles = value; }
}
private string _rollbackAllowed;
/// <summary>
/// Indicates whether the Rollback Update Or Upgrade operation is
/// allowed at this time. True if the operation is allowed; otherwise
/// false.
/// </summary>
public string RollbackAllowed
{
get { return this._rollbackAllowed; }
set { this._rollbackAllowed = value; }
}
private string _sdkVersion;
/// <summary>
/// The version of the Windows Azure SDK that was used to generate the
/// .cspkg that created this deployment. The first two numerical
/// components of the returned version represent the version of the
/// SDK used to create the package.
/// </summary>
public string SdkVersion
{
get { return this._sdkVersion; }
set { this._sdkVersion = value; }
}
private DeploymentStatus _status;
/// <summary>
/// The status of the deployment.
/// </summary>
public DeploymentStatus Status
{
get { return this._status; }
set { this._status = value; }
}
private int _upgradeDomainCount;
/// <summary>
/// The number of upgrade domains available to this cloud service.
/// </summary>
public int UpgradeDomainCount
{
get { return this._upgradeDomainCount; }
set { this._upgradeDomainCount = value; }
}
private UpgradeStatus _upgradeStatus;
/// <summary>
/// Specifies information about an update occurring on the deployment.
/// </summary>
public UpgradeStatus UpgradeStatus
{
get { return this._upgradeStatus; }
set { this._upgradeStatus = value; }
}
private Uri _uri;
/// <summary>
/// The URL used to access the hosted service. For example, if the
/// service name is MyService you could access the access the service
/// by calling: http://MyService.cloudapp.net
/// </summary>
public Uri Uri
{
get { return this._uri; }
set { this._uri = value; }
}
private IList<VirtualIPAddress> _virtualIPAddresses;
/// <summary>
/// The virtual IP addresses that are specified for thedeployment.
/// </summary>
public IList<VirtualIPAddress> VirtualIPAddresses
{
get { return this._virtualIPAddresses; }
set { this._virtualIPAddresses = value; }
}
private string _virtualNetworkName;
/// <summary>
/// The name of the Virtual Network that the virtual machine connects
/// to.
/// </summary>
public string VirtualNetworkName
{
get { return this._virtualNetworkName; }
set { this._virtualNetworkName = value; }
}
/// <summary>
/// Initializes a new instance of the DeploymentGetResponse class.
/// </summary>
public DeploymentGetResponse()
{
this._extendedProperties = new Dictionary<string, string>();
this._roleInstances = new List<RoleInstance>();
this._roles = new List<Role>();
this._virtualIPAddresses = new List<VirtualIPAddress>();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FluentAssertions;
using P3Net.Kraken.ComponentModel;
using P3Net.Kraken.UnitTesting;
namespace Tests.P3Net.Kraken.ComponentModel
{
[TestClass]
public partial class DisposableCollectionTests : UnitTest
{
#region Ctor
[TestMethod]
public void Ctor_DefaultWorks ()
{
//Act
var target = new DisposableCollection();
//Assert
target.Should().BeEmpty();
}
[TestMethod]
public void Ctor_ValidListWorks ()
{
var expected = new List<IDisposable>() {
new TestDisposableObject(),
new TestDisposableObject(),
new TestDisposableObject()
};
//Act
var target = new DisposableCollection(expected);
//Assert
target.Should().ContainInOrder(expected);
}
[TestMethod]
public void Ctor_NullListIsEmpty ()
{
List<IDisposable> items = null;
//Act
var target = new DisposableCollection(items);
//Assert
target.Should().BeEmpty();
}
[TestMethod]
public void Ctor_EmptyListIsEmpty ()
{
var expected = new List<IDisposable>();
//Act
var target = new DisposableCollection(expected);
//Assert
target.Should().BeEmpty();
}
[TestMethod]
public void Ctor_ListWithNullsWorks ()
{
var expected = new List<IDisposable> {
new TestDisposableObject(),
null,
new TestDisposableObject()
};
//Act
var target = new DisposableCollection(expected);
//Assert - Can't use Contains because it doesn't like nulls
target[0].Should().Be(expected[0]);
target[1].Should().BeNull();
target[2].Should().Be(expected[2]);
}
#endregion
#region Clear
[TestMethod]
public void Clear_ObjectsAreDisposed ()
{
var expected = new TestDisposableObject();
var target = new DisposableCollection();
target.Add(expected);
//Act
target.Clear();
//Assert
expected.IsDisposed.Should().BeTrue();
}
[TestMethod]
public void Clear_ValidCollectionWithDisposedObjectsIsDisposed ()
{
var expected = new TestDisposableObject();
var target = new DisposableCollection();
target.Add(expected);
//Act
expected.Dispose();
target.Clear();
//Assert
expected.IsDisposed.Should().BeTrue();
}
[TestMethod]
public void Clear_ValidCollectionWithNoDisposeFlagIsNotDisposed ()
{
var expected = new TestDisposableObject();
var target = new DisposableCollection();
target.Add(expected);
//Act
target.Clear(false);
//Assert
expected.IsDisposed.Should().BeFalse();
}
#endregion
#region CreateAndAdd
[TestMethod]
public void CreateAndAdd_WithValue ()
{
var expected = new TestDisposableObject();
var target = new DisposableCollection();
var actual = target.CreateAndAdd(expected);
//Assert
actual.Should().Be(expected);
target.Should().HaveCount(1);
target.Should().Contain(expected);
}
[TestMethod]
public void CreateAndAdd_WithDelegate ()
{
var target = new DisposableCollection();
var actual = target.CreateAndAdd(() => new TestDisposableObject());
//Assert
target.Should().HaveCount(1);
target.Should().Contain(actual);
}
#endregion
#region Detach
[TestMethod]
public void Detach_DoesNotDispose ()
{
var target = new DisposableCollection();
var expected = new TestDisposableObject();
target.Add(expected);
//Act
var actual = target.Detach(expected);
//Assert
actual.Should().BeTrue();
expected.IsDisposed.Should().BeFalse();
}
#endregion
#region Dispose
[TestMethod]
public void Dispose_UsingDisposesObjects ()
{
var expected = new TestDisposableObject();
//Act
using (var target = new DisposableCollection())
{
target.Add(expected);
};
//Assert
expected.IsDisposed.Should().BeTrue();
}
[TestMethod]
public void Dispose_DoubleDisposeWorks ()
{
var expected = new TestDisposableObject();
//Act
using (var target = new DisposableCollection())
{
target.Add(expected);
target.Dispose();
};
//Assert
expected.IsDisposed.Should().BeTrue();
}
#endregion
#region Remove
[TestMethod]
public void Remove_DisposesOfItem ()
{
var target = new DisposableCollection();
var item = new TestDisposableObject();
//Act
target.Add(item);
var actual = target.Remove(item);
//Assert
actual.Should().BeTrue();
item.IsDisposed.Should().BeTrue();
}
#endregion
#region Set
[TestMethod]
public void ItemSet_DisposesOriginalItem ()
{
var target = new DisposableCollection();
var originalItem = new TestDisposableObject();
var newItem = new TestDisposableObject();
//Act
target.Add(originalItem);
target[0] = newItem;
//Assert
originalItem.IsDisposed.Should().BeTrue();
newItem.IsDisposed.Should().BeFalse();
}
#endregion
#region Private Members
private class TestDisposableObject : DisposableObject
{
public TestDisposableObject ()
{
m_id = Interlocked.Increment(ref s_lastId);
}
public int DisposeCount { get; private set; }
protected override void Dispose ( bool disposing )
{
DisposeCount += 1;
base.Dispose(disposing);
}
public override bool Equals ( object obj )
{
return m_id == ((TestDisposableObject)obj).m_id;
}
public override int GetHashCode ()
{
return m_id.GetHashCode();
}
private static int s_lastId = 0;
private int m_id;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests
{
private static DiagnosticResult GetCA3075DataTableReadXmlCSharpResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXml");
#pragma warning restore RS0030 // Do not used banned APIs
private static DiagnosticResult GetCA3075DataTableReadXmlBasicResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXml");
#pragma warning restore RS0030 // Do not used banned APIs
[Fact]
public async Task UseDataTableReadXmlShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.IO;
using System.Xml;
using System.Data;
namespace TestNamespace
{
public class UseXmlReaderForDataTableReadXml
{
public void TestMethod(Stream stream)
{
DataTable table = new DataTable();
table.ReadXml(stream);
}
}
}
",
GetCA3075DataTableReadXmlCSharpResultAt(13, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.IO
Imports System.Xml
Imports System.Data
Namespace TestNamespace
Public Class UseXmlReaderForDataTableReadXml
Public Sub TestMethod(stream As Stream)
Dim table As New DataTable()
table.ReadXml(stream)
End Sub
End Class
End Namespace",
GetCA3075DataTableReadXmlBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInGetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
public DataTable Test
{
get {
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
return dt;
}
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(11, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Public ReadOnly Property Test() As DataTable
Get
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
Return dt
End Get
End Property
End Class",
GetCA3075DataTableReadXmlBasicResultAt(9, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInSetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
DataTable privateDoc;
public DataTable GetDoc
{
set
{
if (value == null)
{
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
privateDoc = dt;
}
else
privateDoc = value;
}
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(15, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Private privateDoc As DataTable
Public WriteOnly Property GetDoc() As DataTable
Set
If value Is Nothing Then
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
privateDoc = dt
Else
privateDoc = value
End If
End Set
End Property
End Class",
GetCA3075DataTableReadXmlBasicResultAt(11, 17)
);
}
[Fact]
public async Task UseDataTableReadXmlInTryBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try
{
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
}
catch (Exception) { throw; }
finally { }
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(13, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInCatchBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception)
{
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
}
finally { }
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(14, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
Finally
End Try
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(11, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInFinallyBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Data;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally
{
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
}
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(15, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Data
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
End Try
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(13, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInAsyncAwaitShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Threading.Tasks;
using System.Data;
class TestClass
{
private async Task TestMethod()
{
await Task.Run(() => {
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
});
}
private async void TestMethod2()
{
await TestMethod();
}
}",
GetCA3075DataTableReadXmlCSharpResultAt(12, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Threading.Tasks
Imports System.Data
Class TestClass
Private Async Function TestMethod() As Task
Await Task.Run(Function()
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod()
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseDataTableReadXmlInDelegateShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Data;
class TestClass
{
delegate void Del();
Del d = delegate () {
var src = """";
DataTable dt = new DataTable();
dt.ReadXml(src);
};
}",
GetCA3075DataTableReadXmlCSharpResultAt(11, 9)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Data
Class TestClass
Private Delegate Sub Del()
Private d As Del = Sub()
Dim src = """"
Dim dt As New DataTable()
dt.ReadXml(src)
End Sub
End Class",
GetCA3075DataTableReadXmlBasicResultAt(10, 5)
);
}
[Fact]
public async Task UseDataTableReadXmlWithXmlReaderShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
using System.Data;
namespace TestNamespace
{
public class UseXmlReaderForDataTableReadXml
{
public void TestMethod(XmlReader reader)
{
DataTable table = new DataTable();
table.ReadXml(reader);
}
}
}
"
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Imports System.Data
Namespace TestNamespace
Public Class UseXmlReaderForDataTableReadXml
Public Sub TestMethod(reader As XmlReader)
Dim table As New DataTable()
table.ReadXml(reader)
End Sub
End Class
End Namespace");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// MonoTests.System.ComponentModel.ReferenceConverterTest
//
// Author:
// Ivan N. Zlatev <[email protected]>
//
// Copyright (C) 2008 Ivan N. Zlatev
//
//
// 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.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using Xunit;
namespace System.ComponentModel.Tests
{
public class ReferenceConverterTest : RemoteExecutorTestBase
{
class TestReferenceService : IReferenceService
{
private Dictionary<string, object> references;
public TestReferenceService()
{
references = new Dictionary<string, object>();
}
public void AddReference(string name, object reference)
{
references[name] = reference;
}
public void ClearReferences()
{
references.Clear();
}
public IComponent GetComponent(object reference)
{
return null;
}
public string GetName(object reference)
{
foreach (KeyValuePair<string, object> entry in references)
{
if (entry.Value == reference)
return entry.Key;
}
return null;
}
public object GetReference(string name)
{
if (!references.ContainsKey(name))
return null;
return references[name];
}
public object[] GetReferences()
{
object[] array = new object[references.Values.Count];
references.Values.CopyTo(array, 0);
return array;
}
public object[] GetReferences(Type baseType)
{
object[] references = GetReferences();
List<object> filtered = new List<object>();
foreach (object reference in references)
{
if (baseType.IsInstanceOfType(reference))
filtered.Add(reference);
}
return filtered.ToArray();
}
}
private class TestTypeDescriptorContext : ITypeDescriptorContext
{
private IReferenceService reference_service = null;
private IContainer container = null;
public TestTypeDescriptorContext()
{
}
public TestTypeDescriptorContext(IReferenceService referenceService)
{
reference_service = referenceService;
}
public IContainer Container
{
get { return container; }
set { container = value; }
}
public object Instance
{
get { return null; }
}
public PropertyDescriptor PropertyDescriptor
{
get { return null; }
}
public void OnComponentChanged()
{
}
public bool OnComponentChanging()
{
return true;
}
public object GetService(Type serviceType)
{
if (serviceType == typeof(IReferenceService))
return reference_service;
return null;
}
}
private interface ITestInterface
{
}
private class TestComponent : Component
{
}
[Fact]
public void CanConvertFrom()
{
ReferenceConverter converter = new ReferenceConverter(typeof(ITestInterface));
// without context
Assert.False(converter.CanConvertFrom(null, typeof(string)));
// with context
Assert.True(converter.CanConvertFrom(new TestTypeDescriptorContext(), typeof(string)));
}
[Fact]
public void ConvertFrom()
{
ReferenceConverter converter = new ReferenceConverter(typeof(ITestInterface));
string referenceName = "reference name";
// no context
Assert.Null(converter.ConvertFrom(null, null, referenceName));
TestComponent component = new TestComponent();
// context with IReferenceService
TestReferenceService referenceService = new TestReferenceService();
referenceService.AddReference(referenceName, component);
TestTypeDescriptorContext context = new TestTypeDescriptorContext(referenceService);
Assert.Same(component, converter.ConvertFrom(context, null, referenceName));
// context with Component without IReferenceService
Container container = new Container();
container.Add(component, referenceName);
context = new TestTypeDescriptorContext();
context.Container = container;
Assert.Same(component, converter.ConvertFrom(context, null, referenceName));
}
[Fact]
public void ConvertTo()
{
RemoteInvoke(() =>
{
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
ReferenceConverter remoteConverter = new ReferenceConverter(typeof(ITestInterface));
Assert.Equal("(none)", (string)remoteConverter.ConvertTo(null, null, null, typeof(string)));
}).Dispose();
ReferenceConverter converter = new ReferenceConverter(typeof(ITestInterface));
string referenceName = "reference name";
TestComponent component = new TestComponent();
// no context
Assert.Equal(string.Empty, (string)converter.ConvertTo(null, null, component, typeof(string)));
// context with IReferenceService
TestReferenceService referenceService = new TestReferenceService();
referenceService.AddReference(referenceName, component);
TestTypeDescriptorContext context = new TestTypeDescriptorContext(referenceService);
Assert.Equal(referenceName, (string)converter.ConvertTo(context, null, component, typeof(string)));
// context with Component without IReferenceService
Container container = new Container();
container.Add(component, referenceName);
context = new TestTypeDescriptorContext();
context.Container = container;
Assert.Equal(referenceName, (string)converter.ConvertTo(context, null, component, typeof(string)));
}
[Fact]
public void CanConvertTo()
{
ReferenceConverter converter = new ReferenceConverter(typeof(ITestInterface));
Assert.True(converter.CanConvertTo(new TestTypeDescriptorContext(), typeof(string)));
}
[Fact]
public void GetStandardValues()
{
ReferenceConverter converter = new ReferenceConverter(typeof(TestComponent));
TestComponent component1 = new TestComponent();
TestComponent component2 = new TestComponent();
TestReferenceService referenceService = new TestReferenceService();
referenceService.AddReference("reference name 1", component1);
referenceService.AddReference("reference name 2", component2);
ITypeDescriptorContext context = new TestTypeDescriptorContext(referenceService);
TypeConverter.StandardValuesCollection values = converter.GetStandardValues(context);
Assert.NotNull(values);
// 2 components + 1 null value
Assert.Equal(3, values.Count);
}
}
}
| |
// -- FILE ------------------------------------------------------------------
// name : TimeTool.cs
// project : Itenso Time Period
// created : Jani Giannoudis - 2011.02.18
// language : C# 4.0
// environment: .NET 2.0
// copyright : (c) 2011-2012 by Itenso GmbH, Switzerland
// --------------------------------------------------------------------------
using System;
using System.Globalization;
namespace Itenso.TimePeriod
{
// ------------------------------------------------------------------------
public static class TimeTool
{
#region Date and Time
// ----------------------------------------------------------------------
public static DateTime GetDate( DateTime dateTime )
{
return dateTime.Date;
} // GetDate
// ----------------------------------------------------------------------
public static DateTime SetDate( DateTime from, DateTime to )
{
return SetDate( from, to.Year, to.Month, to.Day );
} // SetDate
// ----------------------------------------------------------------------
public static DateTime SetDate( DateTime from, int year, int month = 1, int day = 1 )
{
return new DateTime( year, month, day, from.Hour, from.Minute, from.Second, from.Millisecond );
} // SetDate
// ----------------------------------------------------------------------
public static bool HasTimeOfDay( DateTime dateTime )
{
return dateTime.TimeOfDay > TimeSpan.Zero;
} // HasTimeOfDay
// ----------------------------------------------------------------------
public static DateTime SetTimeOfDay( DateTime from, DateTime to )
{
return SetTimeOfDay( from, to.Hour, to.Minute, to.Second, to.Millisecond );
} // SetTimeOfDay
// ----------------------------------------------------------------------
public static DateTime SetTimeOfDay( DateTime from, int hour = 0, int minute = 0, int second = 0, int millisecond = 0 )
{
return new DateTime( from.Year, from.Month, from.Day, hour, minute, second, millisecond );
} // SetTimeOfDay
#endregion
#region Year
// ----------------------------------------------------------------------
public static int GetYearOf( YearMonth yearBaseMonth, DateTime moment )
{
return GetYearOf( yearBaseMonth, moment.Year, moment.Month );
} // GetYearOf
// ----------------------------------------------------------------------
public static int GetYearOf( YearMonth yearBaseMonth, int year, int month )
{
return month >= (int)yearBaseMonth ? year : year - 1;
} // GetYearOf
#endregion
#region Halfyear
// ----------------------------------------------------------------------
public static void NextHalfyear( YearHalfyear startHalfyear, out int year, out YearHalfyear halfyear )
{
AddHalfyear( startHalfyear, 1, out year, out halfyear );
} // NextHalfyear
// ----------------------------------------------------------------------
public static void PreviousHalfyear( YearHalfyear startHalfyear, out int year, out YearHalfyear halfyear )
{
AddHalfyear( startHalfyear, -1, out year, out halfyear );
} // PreviousHalfyear
// ----------------------------------------------------------------------
public static void AddHalfyear( YearHalfyear startHalfyear, int count, out int year, out YearHalfyear halfyear )
{
AddHalfyear( 0, startHalfyear, count, out year, out halfyear );
} // AddHalfyear
// ----------------------------------------------------------------------
public static void AddHalfyear( int startYear, YearHalfyear startHalfyear, int count, out int year, out YearHalfyear halfyear )
{
int offsetYear = ( Math.Abs( count ) / TimeSpec.HalfyearsPerYear ) + 1;
int startHalfyearCount = ( ( startYear + offsetYear ) * TimeSpec.HalfyearsPerYear ) + ( (int)startHalfyear - 1 );
int targetHalfyearCount = startHalfyearCount + count;
year = ( targetHalfyearCount / TimeSpec.HalfyearsPerYear ) - offsetYear;
halfyear = (YearHalfyear)( ( targetHalfyearCount % TimeSpec.HalfyearsPerYear ) + 1 );
} // AddHalfyear
// ----------------------------------------------------------------------
public static YearHalfyear GetHalfyearOfMonth( YearMonth yearMonth )
{
return GetHalfyearOfMonth( TimeSpec.CalendarYearStartMonth, yearMonth );
} // GetHalfyearOfMonth
// ----------------------------------------------------------------------
public static YearHalfyear GetHalfyearOfMonth( YearMonth yearBaseMonth, YearMonth yearMonth )
{
int yearMonthIndex = (int)yearMonth - 1;
int yearStartMonthIndex = (int)yearBaseMonth - 1;
if ( yearMonthIndex < yearStartMonthIndex )
{
yearMonthIndex += TimeSpec.MonthsPerYear;
}
int deltaMonths = yearMonthIndex - yearStartMonthIndex;
return (YearHalfyear)( ( deltaMonths / TimeSpec.MonthsPerHalfyear ) + 1 );
} // GetHalfyearOfMonth
// ----------------------------------------------------------------------
public static YearMonth[] GetMonthsOfHalfyear( YearHalfyear yearHalfyear )
{
switch ( yearHalfyear )
{
case YearHalfyear.First:
return TimeSpec.FirstHalfyearMonths;
case YearHalfyear.Second:
return TimeSpec.SecondHalfyearMonths;
}
throw new InvalidOperationException( "invalid year halfyear " + yearHalfyear );
} // GetMonthsOfHalfyear
#endregion
#region Quarter
// ----------------------------------------------------------------------
public static void NextQuarter( YearQuarter startQuarter, out int year, out YearQuarter quarter )
{
AddQuarter( startQuarter, 1, out year, out quarter );
} // NextQuarter
// ----------------------------------------------------------------------
public static void PreviousQuarter( YearQuarter startQuarter, out int year, out YearQuarter quarter )
{
AddQuarter( startQuarter, -1, out year, out quarter );
} // PreviousQuarter
// ----------------------------------------------------------------------
public static void AddQuarter( YearQuarter startQuarter, int count, out int year, out YearQuarter quarter )
{
AddQuarter( 0, startQuarter, count, out year, out quarter );
} // AddQuarter
// ----------------------------------------------------------------------
public static void AddQuarter( int startYear, YearQuarter startQuarter, int count, out int year, out YearQuarter quarter )
{
int offsetYear = ( Math.Abs( count ) / TimeSpec.QuartersPerYear ) + 1;
int startQuarterCount = ( ( startYear + offsetYear ) * TimeSpec.QuartersPerYear ) + ( (int)startQuarter - 1 );
int targetQuarterCount = startQuarterCount + count;
year = ( targetQuarterCount / TimeSpec.QuartersPerYear ) - offsetYear;
quarter = (YearQuarter)( ( targetQuarterCount % TimeSpec.QuartersPerYear ) + 1 );
} // AddQuarter
// ----------------------------------------------------------------------
public static YearQuarter GetQuarterOfMonth( YearMonth yearMonth )
{
return GetQuarterOfMonth( TimeSpec.CalendarYearStartMonth, yearMonth );
} // GetQuarterOfMonth
// ----------------------------------------------------------------------
public static YearQuarter GetQuarterOfMonth( YearMonth yearBaseMonth, YearMonth yearMonth )
{
int yearMonthIndex = (int)yearMonth - 1;
int yearStartMonthIndex = (int)yearBaseMonth - 1;
if ( yearMonthIndex < yearStartMonthIndex )
{
yearMonthIndex += TimeSpec.MonthsPerYear;
}
int deltaMonths = yearMonthIndex - yearStartMonthIndex;
return (YearQuarter)( ( deltaMonths / TimeSpec.MonthsPerQuarter ) + 1 );
} // GetQuarterOfMonth
// ----------------------------------------------------------------------
public static YearMonth[] GetMonthsOfQuarter( YearQuarter yearQuarter )
{
switch ( yearQuarter )
{
case YearQuarter.First:
return TimeSpec.FirstQuarterMonths;
case YearQuarter.Second:
return TimeSpec.SecondQuarterMonths;
case YearQuarter.Third:
return TimeSpec.ThirdQuarterMonths;
case YearQuarter.Fourth:
return TimeSpec.FourthQuarterMonths;
}
throw new InvalidOperationException( "invalid year quarter " + yearQuarter );
} // GetMonthsOfQuarter
#endregion
#region Month
// ----------------------------------------------------------------------
public static void NextMonth( YearMonth startMonth, out int year, out YearMonth month )
{
AddMonth( startMonth, 1, out year, out month );
} // NextMonth
// ----------------------------------------------------------------------
public static void PreviousMonth( YearMonth startMonth, out int year, out YearMonth month )
{
AddMonth( startMonth, -1, out year, out month );
} // PreviousMonth
// ----------------------------------------------------------------------
public static void AddMonth( YearMonth startMonth, int count, out int year, out YearMonth month )
{
AddMonth( 0, startMonth, count, out year, out month );
} // AddMonth
// ----------------------------------------------------------------------
public static void AddMonth( int startYear, YearMonth startMonth, int count, out int year, out YearMonth month )
{
int offsetYear = ( Math.Abs( count ) / TimeSpec.MonthsPerYear ) + 1;
int startMonthCount = ( ( startYear + offsetYear ) * TimeSpec.MonthsPerYear ) + ( (int)startMonth - 1 );
int targetMonthCount = startMonthCount + count;
year = ( targetMonthCount / TimeSpec.MonthsPerYear ) - offsetYear;
month = (YearMonth)( ( targetMonthCount % TimeSpec.MonthsPerYear ) + 1 );
} // AddMonth
// ----------------------------------------------------------------------
public static int GetDaysInMonth( int year, int month )
{
DateTime firstDay = new DateTime( year, month, 1 );
return firstDay.AddMonths( 1 ).AddDays( -1 ).Day;
} // GetDaysInMonth
#endregion
#region Week
// ----------------------------------------------------------------------
public static DateTime GetStartOfWeek( DateTime time, DayOfWeek firstDayOfWeek )
{
DateTime currentDay = new DateTime( time.Year, time.Month, time.Day );
while ( currentDay.DayOfWeek != firstDayOfWeek )
{
currentDay = currentDay.AddDays( -1 );
}
return currentDay;
} // GetStartOfWeek
// ----------------------------------------------------------------------
public static void GetWeekOfYear( DateTime moment, CultureInfo culture, YearWeekType yearWeekType,
out int year, out int weekOfYear )
{
GetWeekOfYear( moment, culture, culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek, yearWeekType,
out year, out weekOfYear );
} // GetWeekOfYear
// ----------------------------------------------------------------------
public static void GetWeekOfYear( DateTime moment, CultureInfo culture,
CalendarWeekRule weekRule, DayOfWeek firstDayOfWeek, YearWeekType yearWeekType, out int year, out int weekOfYear )
{
if ( culture == null )
{
throw new ArgumentNullException( "culture" );
}
if ( yearWeekType == YearWeekType.Iso8601 && weekRule == CalendarWeekRule.FirstFourDayWeek )
{
// see http://blogs.msdn.com/b/shawnste/archive/2006/01/24/517178.aspx
DayOfWeek day = culture.Calendar.GetDayOfWeek( moment );
if ( day >= firstDayOfWeek && (int)day <= (int)( firstDayOfWeek + 2 ) % 7 )
{
moment = moment.AddDays( 3 );
}
}
weekOfYear = culture.Calendar.GetWeekOfYear( moment, weekRule, firstDayOfWeek );
year = moment.Year;
if ( weekOfYear >= 52 && moment.Month < 12 )
{
year--;
}
} // GetWeekOfYear
// ----------------------------------------------------------------------
public static int GetWeeksOfYear( int year, CultureInfo culture, YearWeekType yearWeekType )
{
return GetWeeksOfYear( year, culture, culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek, yearWeekType );
} // GetWeeksOfYear
// ----------------------------------------------------------------------
public static int GetWeeksOfYear( int year, CultureInfo culture,
CalendarWeekRule weekRule, DayOfWeek firstDayOfWeek, YearWeekType yearWeekType )
{
if ( culture == null )
{
throw new ArgumentNullException( "culture" );
}
int currentYear;
int currentWeek;
DateTime currentDay = new DateTime( year, 12, 31 );
GetWeekOfYear( currentDay, culture, weekRule, firstDayOfWeek, yearWeekType, out currentYear, out currentWeek );
while ( currentYear != year )
{
currentDay = currentDay.AddDays( -1 );
GetWeekOfYear( currentDay, culture, weekRule, firstDayOfWeek, yearWeekType, out currentYear, out currentWeek );
}
return currentWeek;
} // GetWeeksOfYear
// ----------------------------------------------------------------------
public static DateTime GetStartOfYearWeek( int year, int weekOfYear, CultureInfo culture, YearWeekType yearWeekType )
{
if ( culture == null )
{
throw new ArgumentNullException( "culture" );
}
return GetStartOfYearWeek( year, weekOfYear, culture,
culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek, yearWeekType );
} // GetStartOfYearWeek
// ----------------------------------------------------------------------
public static DateTime GetStartOfYearWeek( int year, int weekOfYear, CultureInfo culture,
CalendarWeekRule weekRule, DayOfWeek firstDayOfWeek, YearWeekType yearWeekType )
{
if ( culture == null )
{
throw new ArgumentNullException( "culture" );
}
if ( weekOfYear < 1 )
{
throw new ArgumentOutOfRangeException( "weekOfYear" );
}
DateTime dateTime = new DateTime( year, 1, 1 ).AddDays( weekOfYear * TimeSpec.DaysPerWeek );
int currentYear;
int currentWeek;
GetWeekOfYear( dateTime, culture, weekRule, firstDayOfWeek, yearWeekType, out currentYear, out currentWeek );
// end date of week
while ( currentWeek != weekOfYear )
{
dateTime = dateTime.AddDays( -1 );
GetWeekOfYear( dateTime, culture, weekRule, firstDayOfWeek, yearWeekType, out currentYear, out currentWeek );
}
// end of previous week
while ( currentWeek == weekOfYear )
{
dateTime = dateTime.AddDays( -1 );
GetWeekOfYear( dateTime, culture, weekRule, firstDayOfWeek, yearWeekType, out currentYear, out currentWeek );
}
return dateTime.AddDays( 1 );
} // GetStartOfYearWeek
#endregion
#region Day
// ----------------------------------------------------------------------
public static DateTime DayStart( DateTime dateTime )
{
return dateTime.Date;
} // DayStart
// ----------------------------------------------------------------------
public static DayOfWeek NextDay( DayOfWeek day )
{
return AddDays( day, 1 );
} // NextMonth
// ----------------------------------------------------------------------
public static DayOfWeek PreviousDay( DayOfWeek day )
{
return AddDays( day, -1 );
} // PreviousDay
// ----------------------------------------------------------------------
public static DayOfWeek AddDays( DayOfWeek day, int days )
{
if ( days == 0 )
{
return day;
}
int weeks = ( Math.Abs( days ) / TimeSpec.DaysPerWeek ) + 1;
int offset = weeks * TimeSpec.DaysPerWeek + (int)day;
int targetOffset = offset + days;
return (DayOfWeek)( targetOffset % TimeSpec.DaysPerWeek );
} // AddMonths
#endregion
} // class TimeTool
} // namespace Itenso.TimePeriod
// -- EOF -------------------------------------------------------------------
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// <copyright file="BuildTask_Tests.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>Tests for all Public BuildTask objects for the v9 Compatibility</summary>
//-----------------------------------------------------------------------
using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using NUnit.Framework;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.UnitTests;
namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility
{
/// <summary>
/// Test Fixture Class for the v9 Object Model Public Interface Compatibility Tests for the BuildTask Class.
/// </summary>
[TestFixture]
public sealed class BuildTask_Tests
{
#region Common Helpers
/// <summary>
/// Basic Project Contents with a Target 't' that contains 1 BuildTask 'Task' where
/// the BuildTask contains no parameters.
/// </summary>
private string ProjectContentsWithOneTask = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task />
</Target>
</Project>
");
/// <summary>
/// Engine that is used through out test class
/// </summary>
private Engine engine;
/// <summary>
/// Project that is used through out test class
/// </summary>
private Project project;
/// <summary>
/// MockLogger that is used through out test class
/// </summary>
private MockLogger logger;
/// <summary>
/// Creates the engine and parent object. Also registers the mock logger.
/// </summary>
[SetUp()]
public void Initialize()
{
ObjectModelHelpers.DeleteTempProjectDirectory();
engine = new Engine();
engine.DefaultToolsVersion = "4.0";
project = new Project(engine);
logger = new MockLogger();
project.ParentEngine.RegisterLogger(logger);
}
/// <summary>
/// Unloads projects and un-registers logger.
/// </summary>
[TearDown()]
public void Cleanup()
{
engine.UnloadProject(project);
engine.UnloadAllProjects();
engine.UnregisterAllLoggers();
ObjectModelHelpers.DeleteTempProjectDirectory();
}
#endregion
#region Condition Tests
/// <summary>
/// Tests BuildTask.Condition Get simple/basic case
/// </summary>
[Test]
public void ConditionGetSimple()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition=""'a' == 'b'"" >
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("'a' == 'b'", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Get when Condition is an empty string
/// </summary>
[Test]
public void ConditionGetEmptyString()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition="""" >
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals(String.Empty, task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Get when condition contains special characters
/// </summary>
[Test]
public void ConditionGetSpecialCharacters()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition=""%24%40%3b%5c%25"" >
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("%24%40%3b%5c%25", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Get from an imported project
/// </summary>
[Test]
public void ConditionGetFromImportedProject()
{
string importProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t2' >
<t2.Task Condition=""'a' == 'b'"" >
</t2.Task>
</Target>
</Project>
");
Project p = GetProjectThatImportsAnotherProject(importProjectContents, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task");
Assertion.AssertEquals("'a' == 'b'", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set when no previous exists
/// </summary>
[Test]
public void ConditionSetWhenNoPreviousConditionExists()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = "'t' == 'f'";
Assertion.AssertEquals("'t' == 'f'", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set when an existing condition exists, changing the condition
/// </summary>
[Test]
public void ConditionSetOverExistingCondition()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition=""'a' == 'b'"" >
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = "'c' == 'd'";
Assertion.AssertEquals("'c' == 'd'", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set to an empty string
/// </summary>
[Test]
public void ConditionSetToEmtpyString()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = String.Empty;
Assertion.AssertEquals(String.Empty, task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set to null
/// </summary>
[Test]
public void ConditionSetToNull()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = null;
Assertion.AssertEquals(String.Empty, task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set to Special Characters
/// </summary>
[Test]
public void ConditionSetToSpecialCharacters()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = "%24%40%3b%5c%25";
Assertion.AssertEquals("%24%40%3b%5c%25", task.Condition);
}
/// <summary>
/// Tests BuildTask.Condition Set on an Imported Project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void ConditionSetOnImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t3", "t3.Task3");
task.Condition = "true";
}
/// <summary>
/// Tests BuildTask.Condition Set, save to disk and verify
/// </summary>
[Test]
public void ConditionSaveProjectAfterSet()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.Condition = "'a' == 'b'";
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition=""'a' == 'b'"" />
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
#endregion
#region ContinueOnError Tests
/// <summary>
/// Tests BuildTask.ContinueOnError Get for all cases that would return true
/// </summary>
[Test]
public void ContinueOnErrorGetTrue()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task1 ContinueOnError='true' />
<Task2 ContinueOnError='True' />
<Task3 ContinueOnError='TRUE' />
<Task4 ContinueOnError='on' />
<Task5 ContinueOnError='yes' />
<Task6 ContinueOnError='!false' />
<Task7 ContinueOnError='!off' />
<Task8 ContinueOnError='!no' />
</Target>
</Project>
");
project.LoadXml(projectContents);
List<bool> continueOnErrorResults = GetListOfContinueOnErrorResultsFromSpecificProject(project);
Assertion.AssertEquals(true, continueOnErrorResults.TrueForAll(delegate(bool b) { return b; }));
}
/// <summary>
/// Tests BuildTask.ContinueOnError Get for all cases that would return false
/// </summary>
[Test]
public void ContinueOnErrorGetFalse()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task1 ContinueOnError='false' />
<Task2 ContinueOnError='False' />
<Task3 ContinueOnError='FALSE' />
<Task4 ContinueOnError='off' />
<Task5 ContinueOnError='no' />
<Task6 ContinueOnError='!true' />
<Task7 ContinueOnError='!on' />
<Task8 ContinueOnError='!yes' />
</Target>
</Project>
");
project.LoadXml(projectContents);
List<bool> continueOnErrorResults = GetListOfContinueOnErrorResultsFromSpecificProject(project);
Assertion.AssertEquals(true, continueOnErrorResults.TrueForAll(delegate(bool b) { return !b; }));
}
/// <summary>
/// Tests BuildTask.ContinueOnError Get when value is an empty string
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ContinueOnErrorGetEmptyString()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError.ToString();
}
/// <summary>
/// Tests BuildTask.ContinueOnError Get when value is something that won't return true or false - invalid
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ContinueOnErrorGetInvalid()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='a' />
</Target>
</Project>
"));
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError.ToString();
}
/// <summary>
/// Tests BuildTask.ContinueOnError Get of a BuildTask from an imported Project
/// </summary>
[Test]
public void ContinueOnErrorGetFromImportedProject()
{
string importProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t2' >
<t2.Task ContinueOnError='true' />
</Target>
</Project>
");
Project p = GetProjectThatImportsAnotherProject(importProjectContents, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task");
Assertion.AssertEquals(true, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set when no previous ContinueOnError value exists
/// </summary>
[Test]
public void ContinueOnErrorSetWhenNoContinueOnErrorExists()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = true;
Assertion.AssertEquals(true, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set when a ContinueOnError value exists (basically changing from true to false)
/// </summary>
[Test]
public void ContinueOnErrorSetWhenContinueOnErrorExists()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='true' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = false;
Assertion.AssertEquals(false, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set to true
/// </summary>
[Test]
public void ContinueOnErrorSetToTrue()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = true;
Assertion.AssertEquals(true, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set to false
/// </summary>
[Test]
public void ContinueOnErrorSetToFalse()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = false;
Assertion.AssertEquals(false, task.ContinueOnError);
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set on an imported project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void ContinueOnErrorSetOnImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task2");
task.ContinueOnError = true;
}
/// <summary>
/// Tests BuildTask.ContinueOnError Set, then save to disk and verify
/// </summary>
[Test]
public void ContinueOnErrorSaveProjectAfterSet()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.ContinueOnError = true;
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='true'/>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
#endregion
#region HostObject Tests
/// <summary>
/// Tests BuildTask.HostObject simple set and get with only one BuildTask
/// </summary>
[Test]
public void HostObjectSetGetOneTask()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<Message Text='t.message' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Message");
MockHostObject hostObject = new MockHostObject();
task.HostObject = hostObject;
Assertion.AssertSame(task.HostObject.ToString(), hostObject.ToString());
}
/// <summary>
/// Tests BuildTask.HostObject Set/Get with several BuildTasks
/// </summary>
[Test]
public void HostObjectSetGetMultipleTasks()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<Message Text='t.message' />
<MyTask />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task1 = GetSpecificBuildTask(project, "t", "Message");
BuildTask task2 = GetSpecificBuildTask(project, "t", "MyTask");
MockHostObject hostObject1 = new MockHostObject();
MockHostObject hostObject2 = new MockHostObject();
task1.HostObject = hostObject1;
task2.HostObject = hostObject2;
Assertion.AssertSame(task1.HostObject.ToString(), hostObject1.ToString());
Assertion.AssertSame(task2.HostObject.ToString(), hostObject2.ToString());
}
/// <summary>
/// Tests BuildTask.HostObject Get before the Object Reference is set to an instance of an object
/// </summary>
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void HostObjectGetBeforeObjectReferenceSet()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<Message Text='t.message' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Message");
task.HostObject.ToString();
}
#endregion
#region Name Tests
/// <summary>
/// Tests BuildTask.Name get when only one BuildTask exists
/// </summary>
[Test]
public void NameWithOneBuildTask()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("Task", task.Name);
}
/// <summary>
/// Tests BuildTask.Name get when several BuildTasks exist within the same target
/// </summary>
[Test]
public void NameWithSeveralBuildTasksInSameTarget()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task1 parameter='value' />
<Task2 parameter='value' />
<Task3 parameter='value' />
</Target>
</Project>
");
project.LoadXml(projectContents);
Assertion.AssertEquals("Task1", GetSpecificBuildTask(project, "t", "Task1").Name);
Assertion.AssertEquals("Task2", GetSpecificBuildTask(project, "t", "Task2").Name);
Assertion.AssertEquals("Task3", GetSpecificBuildTask(project, "t", "Task3").Name);
}
/// <summary>
/// Tests BuildTask.Name get when several BuildTasks exist within different targets
/// </summary>
[Test]
public void NameWithSeveralBuildTasksInDifferentTargets()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t1' >
<t1.Task1 parameter='value' />
</Target>
<Target Name='t2' >
<t2.Task1 parameter='value' />
</Target>
<Target Name='t3' >
<t3.Task2 parameter='value' />
</Target>
</Project>
");
project.LoadXml(projectContents);
Assertion.AssertEquals("t1.Task1", GetSpecificBuildTask(project, "t1", "t1.Task1").Name);
Assertion.AssertEquals("t2.Task1", GetSpecificBuildTask(project, "t2", "t2.Task1").Name);
Assertion.AssertEquals("t3.Task2", GetSpecificBuildTask(project, "t3", "t3.Task2").Name);
}
/// <summary>
/// Tests BuildTask.Name get when BuildTask comes from an imported Project
/// </summary>
[Test]
public void NameOfBuildTaskFromImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
Assertion.AssertEquals("t3.Task3", GetSpecificBuildTask(p, "t3", "t3.Task3").Name);
}
/// <summary>
/// Tests BuildTask.Name get when BuildTask was just created
/// </summary>
[Test]
public void NameOfBuildTaskOfANewlyCreatedBuildTask()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t1' />
</Project>
");
project.LoadXml(projectContents);
Target t = GetSpecificTargetFromProject(project, "t1", false);
BuildTask task = t.AddNewTask("Task");
task.SetParameterValue("parameter", "value");
Assertion.AssertEquals("Task", GetSpecificBuildTask(project, "t1", "Task").Name);
}
#endregion
#region Type Tests
/// <summary>
/// Tests BuildTask.Type when Task class exists (Message)
/// </summary>
[Test]
public void TypeTaskExists()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<Message Text='t.message' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Message");
Assertion.AssertEquals(0, String.Compare(task.Type.ToString(), "Microsoft.Build.Tasks.Message"));
}
/// <summary>
/// Tests BuildTask.Type when Task class doesn't exists (MyFooTask)
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void TypeTaskNotExists()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t'>
<MyFooTask />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "MyFooTask");
Type t = task.Type;
}
/// <summary>
/// Tests BuildTask.Type when BuildTask is null
/// </summary>
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void TypeTaskIsNull()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = null;
Type t = task.Type;
}
#endregion
#region AddOutputItem/AddOutputProperty Tests
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding a new OutputItem/OutputProperty when none exist
/// </summary>
[Test]
public void AddOutputItemPropertyWhenNoOutputItemsPropertyExist()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem("ip", "in");
task.AddOutputProperty("pp", "pn");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip' ItemName='in' />
<Output TaskParameter='pp' PropertyName='pn' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding a new OutputItem/OutputProperty when several exist
/// </summary>
[Test]
public void AddOutputItemPropertyWhenOutputItemsPropertiesExist()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip1' ItemName='in1' />
<Output TaskParameter='ip2' ItemName='in2' />
<Output TaskParameter='ip3' ItemName='in3' />
<Output TaskParameter='pp1' PropertyName='pn1' />
<Output TaskParameter='pp2' PropertyName='pn2' />
<Output TaskParameter='pp3' PropertyName='pn3' />
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem("ip4", "in4");
task.AddOutputProperty("pp4", "pn4");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip1' ItemName='in1' />
<Output TaskParameter='ip2' ItemName='in2' />
<Output TaskParameter='ip3' ItemName='in3' />
<Output TaskParameter='pp1' PropertyName='pn1' />
<Output TaskParameter='pp2' PropertyName='pn2' />
<Output TaskParameter='pp3' PropertyName='pn3' />
<Output TaskParameter='ip4' ItemName='in4' />
<Output TaskParameter='pp4' PropertyName='pn4' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding a new OutputItem/OutputProperty
/// with the same values as an existing OutputItem/OutputProperty
/// </summary>
[Test]
public void AddOutputItemPropertyWithSameValuesAsExistingOutputItemProperty()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip' ItemName='in' />
<Output TaskParameter='pp' PropertyName='pn' />
</Task>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem("ip", "in");
task.AddOutputProperty("pp", "pn");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='ip' ItemName='in' />
<Output TaskParameter='pp' PropertyName='pn' />
<Output TaskParameter='ip' ItemName='in' />
<Output TaskParameter='pp' PropertyName='pn' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding Empty Strings for the taskParameter and itemName/propertyName
/// </summary>
[Test]
public void AddOutputItemPropertyWithEmptyStrings()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem(String.Empty, String.Empty);
task.AddOutputProperty(String.Empty, String.Empty);
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='' ItemName='' />
<Output TaskParameter='' PropertyName='' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by adding nulls for the taskParameter and itemName/propertyName
/// </summary>
[Test]
public void AddOutputItemPropertyWithNulls()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem(null, null);
task.AddOutputProperty(null, null);
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='' ItemName='' />
<Output TaskParameter='' PropertyName='' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem/AddOutputProperty by passing in Special characters into the taskParameter and itemName/propertyName
/// </summary>
[Test]
public void AddOutputItemPropertyWithSpecialCharacters()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.AddOutputItem("%24%40%3b%5c%25", "%24%40%3b%5c%25");
task.AddOutputProperty("%24%40%3b%5c%25", "%24%40%3b%5c%25");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task>
<Output TaskParameter='%24%40%3b%5c%25' ItemName='%24%40%3b%5c%25' />
<Output TaskParameter='%24%40%3b%5c%25' PropertyName='%24%40%3b%5c%25' />
</Task>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.AddOutputItem by attempting to add an OutputItem to an imported Project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void AddOutputItemToImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task2");
task.AddOutputItem("p", "n");
}
/// <summary>
/// Tests BuildTask.AddOutputProperty by attempting to add an OutputProperty to an imported Project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void AddOutputPropertyToImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t2", "t2.Task2");
task.AddOutputProperty("p", "n");
}
#endregion
#region Execute Tests
/// <summary>
/// Tests BuildTask.Execute basic case where expected to be true
/// </summary>
[Test]
public void ExecuteExpectedTrue()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t1'>
<Message Text='t1.message' />
</Target>
<Target Name='t2'>
<Message Text='t2.message' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t2", "Message");
Assertion.AssertEquals(0, String.Compare(task.Type.ToString(), "Microsoft.Build.Tasks.Message", StringComparison.OrdinalIgnoreCase));
Assertion.AssertEquals(true, task.Execute());
Assertion.AssertEquals(true, logger.FullLog.Contains("t2.message"));
Assertion.AssertEquals(false, logger.FullLog.Contains("t1.message"));
}
/// <summary>
/// Tests BuildTask.Execute where the BuildTask is null
/// </summary>
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void ExecuteOnNullBuildTask()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = null;
task.Execute();
}
/// <summary>
/// Tests BuildTask.Execute where the BuildTask doesn't do anything
/// </summary>
[Test]
public void ExecuteOnTaskThatDoesNothing()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals(false, task.Execute());
Assertion.AssertEquals(true, logger.FullLog.Contains("MSB4036"));
}
/// <summary>
/// Tests BuildTask.Execute where Task comes from an Imported Project
/// </summary>
[Test]
public void ExecuteFromImportedProject()
{
string importProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t' >
<Message Text='t.message' />
</Target>
</Project>
");
string parentProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Import Project='import.proj' />
</Project>
");
Project p = GetProjectThatImportsAnotherProject(importProjectContents, parentProjectContents);
BuildTask task = GetSpecificBuildTask(p, "t", "Message");
Assertion.AssertEquals(true, task.Execute());
}
#endregion
#region GetParameterNames Tests
/// <summary>
/// Tests BuildTask.GetParameterNames when only one parameter exists on the BuildTask
/// </summary>
[Test]
public void GetParameterNamesOnlyOneParameterExists()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value'/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
string[] parameters = task.GetParameterNames();
Assertion.AssertEquals(1, parameters.Length);
Assertion.AssertEquals("parameter", parameters[0]);
}
/// <summary>
/// Tests BuildTask.GetParameterNames when no parameters exist on the BuildTask
/// </summary>
[Test]
public void GetParameterNamesNoParametersExist()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
string[] parameters = task.GetParameterNames();
Assertion.AssertEquals(0, parameters.Length);
}
/// <summary>
/// Tests BuildTask.GetParameterNames when several parameters exist on the BuildTask
/// </summary>
[Test]
public void GetParameterNamesLotsOfParametersExist()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task p1='v1' p2='v2' p3='v3' p4='v4' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
string[] parameters = task.GetParameterNames();
Assertion.AssertEquals(4, parameters.Length);
Assertion.AssertEquals("p1", parameters[0]);
Assertion.AssertEquals("p2", parameters[1]);
Assertion.AssertEquals("p3", parameters[2]);
Assertion.AssertEquals("p4", parameters[3]);
}
#endregion
#region GetParameterValue Tests
/// <summary>
/// Tests BuildTask.GetParameterValue on one BuildTask
/// </summary>
[Test]
public void GetParameterValueOneBuildTaskWithOneParameter()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value'/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("value", task.GetParameterValue("parameter"));
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is special characters
/// </summary>
[Test]
public void GetParameterValueWhenSpecialCharacters()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='%24%40%3b%5c%25'/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals("%24%40%3b%5c%25", task.GetParameterValue("parameter"));
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is an empty string
/// </summary>
[Test]
public void GetParameterValueWhenEmtpyString()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
Assertion.AssertEquals(String.Empty, task.GetParameterValue("parameter"));
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is the Special Task Attribute 'Condition'
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetParameterValueWhenSpecialTaskAttributeCondition()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task Condition='A' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.GetParameterValue("Condition");
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is the Special Task Attribute 'ContinueOnError'
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetParameterValueWhenSpecialTaskAttributeContinueOnError()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task ContinueOnError='true' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.GetParameterValue("ContinueOnError");
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value is the Special Task Attribute 'xmlns'
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void GetParameterValueWhenSpecialTaskAttributexmlns()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task xmlns='msbuildnamespace' />
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.GetParameterValue("xmlns");
}
/// <summary>
/// Tests BuildTask.GetParameterValue when parameter value comes from an imported Project
/// </summary>
[Test]
public void GetParameterValueFromImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t3", "t3.Task3");
Assertion.AssertEquals("value", task.GetParameterValue("parameter"));
}
#endregion
#region SetParameterValue Tests
/// <summary>
/// Tests BuildTask.SetParameterValue on one BuildTask, simple case
/// </summary>
[Test]
public void SetParameterValueSimple()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p", "v");
Assertion.AssertEquals("v", task.GetParameterValue("p"));
}
/// <summary>
/// Tests BuildTask.SetParameterValue to null
/// </summary>
[Test]
public void SetParameterValueToNull()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p", null);
Assertion.AssertEquals(String.Empty, task.GetParameterValue("p"));
}
/// <summary>
/// Tests BuildTask.SetParameterValue to an Empty String
/// </summary>
[Test]
public void SetParameterValueToEmptyString()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p", String.Empty);
Assertion.AssertEquals(String.Empty, task.GetParameterValue("p"));
}
/// <summary>
/// Tests BuildTask.SetParameterValue to special characters
/// </summary>
[Test]
public void SetParameterValueToSpecialCharacters()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p", "%24%40%3b%5c%25");
}
/// <summary>
/// Tests BuildTask.SetParameterValue to Special Task Attribute Condition
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SetParameterValueToSpecialTaskAttributeCondition()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("Condition", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue to Special Task Attribute ContinueOnError
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SetParameterValueToSpecialTaskAttributeContinueOnError()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("ContinueOnError", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue to Special Task Attribute xmlns
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SetParameterValueToSpecialTaskAttributexmlns()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("xmlns", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue on a BuildTask from an Imported Project
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void SetParameterValueOnBuildTaskFromImportedProject()
{
Project p = GetProjectThatImportsAnotherProject(null, null);
BuildTask task = GetSpecificBuildTask(p, "t3", "t3.Task3");
task.SetParameterValue("p", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue on a BuildTask parameter that already exists
/// </summary>
[Test]
public void SetParameterValueOnAnExistingParameter()
{
string projectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value'/>
</Target>
</Project>
");
project.LoadXml(projectContents);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("parameter", "new");
Assertion.AssertEquals("new", task.GetParameterValue("parameter"));
}
/// <summary>
/// Tests BuildTask.SetParameterValue, then save to disk and verify
/// </summary>
[Test]
public void SetParameterValueSaveProjectAfterSet()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("parameter", "value");
string expectedProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project xmlns='msbuildnamespace'>
<Target Name='t' >
<Task parameter='value'/>
</Target>
</Project>
");
SaveProjectToDiskAndCompareAgainstExpectedContents(project, expectedProjectContents);
}
/// <summary>
/// Tests BuildTask.SetParameterValue by setting the parameter name to an empty string
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void SetParameterValueWithParameterNameSetToEmptyString()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue(String.Empty, "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue by setting the parameter name to null
/// </summary>
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void SetParameterValueWithParameterNameSetToNull()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue(null, "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue by setting the parameter name to special characters
/// </summary>
[Test]
[ExpectedException(typeof(XmlException))]
public void SetParameterValueWithParameterNameSetToSpecialCharacters()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("%24%40%3b%5c%25", "v");
}
/// <summary>
/// Tests BuildTask.SetParameterValue with the Treat Parameter Value As Literal set to true/false
/// </summary>
[Test]
public void SetParameterValueTreatParameterValueAsLiteral()
{
project.LoadXml(ProjectContentsWithOneTask);
BuildTask task = GetSpecificBuildTask(project, "t", "Task");
task.SetParameterValue("p1", @"%*?@$();\", true);
task.SetParameterValue("p2", @"%*?@$();\", false);
Assertion.AssertEquals(@"%25%2a%3f%40%24%28%29%3b\", task.GetParameterValue("p1"));
Assertion.AssertEquals(@"%*?@$();\", task.GetParameterValue("p2"));
}
#endregion
#region Helpers
/// <summary>
/// Gets a list of all ContinueOnError results within your project
/// </summary>
/// <param name="p">Project</param>
/// <returns>List of bool results for all ContinueOnError BuildTasks within your project</returns>
private List<bool> GetListOfContinueOnErrorResultsFromSpecificProject(Project p)
{
List<bool> continueOnErrorResults = new List<bool>();
foreach (Target t in project.Targets)
{
foreach (BuildTask task in t)
{
continueOnErrorResults.Add(task.ContinueOnError);
}
}
return continueOnErrorResults;
}
/// <summary>
/// Gets the specified BuildTask from your specified Project and Target
/// </summary>
/// <param name="p">Project</param>
/// <param name="targetNameThatContainsBuildTask">Target that contains the BuildTask that you want</param>
/// <param name="buildTaskName">BuildTask name that you want</param>
/// <returns>The specified BuildTask</returns>
private BuildTask GetSpecificBuildTask(Project p, string targetNameThatContainsBuildTask, string buildTaskName)
{
foreach (Target t in p.Targets)
{
if (String.Equals(t.Name, targetNameThatContainsBuildTask, StringComparison.OrdinalIgnoreCase))
{
foreach (BuildTask task in t)
{
if (String.Equals(task.Name, buildTaskName, StringComparison.OrdinalIgnoreCase))
{
return task;
}
}
}
}
return null;
}
/// <summary>
/// Gets a specified Target from a Project
/// </summary>
/// <param name="p">Project</param>
/// <param name="nameOfTarget">Target name of the Target you want</param>
/// <param name="lastInstance">If you want the last instance of a target set to true</param>
/// <returns>Target requested. null if specific target isn't found</returns>
private Target GetSpecificTargetFromProject(Project p, string nameOfTarget, bool lastInstance)
{
Target target = null;
foreach (Target t in p.Targets)
{
if (String.Equals(t.Name, nameOfTarget, StringComparison.OrdinalIgnoreCase))
{
if (!lastInstance)
{
return t;
}
else
{
target = t;
}
}
}
return target;
}
/// <summary>
/// Saves a given Project to disk and compares what's saved to disk with expected contents. Assertion handled within
/// ObjectModelHelpers.CompareProjectContents.
/// </summary>
/// <param name="p">Project to save</param>
/// <param name="expectedProjectContents">The Project content that you expect</param>
private void SaveProjectToDiskAndCompareAgainstExpectedContents(Project p, string expectedProjectContents)
{
string savePath = Path.Combine(ObjectModelHelpers.TempProjectDir, "p.proj");
p.Save(savePath);
Engine e = new Engine();
Project savedProject = new Project(e);
savedProject.Load(savePath);
ObjectModelHelpers.CompareProjectContents(savedProject, expectedProjectContents);
ObjectModelHelpers.DeleteTempProjectDirectory();
}
/// <summary>
/// Gets a Project that imports another Project
/// </summary>
/// <param name="importProjectContents">Project Contents of the imported Project, to get default content, pass in an empty string</param>
/// <param name="parentProjectContents">Project Contents of the Parent Project, to get default content, pass in an empty string</param>
/// <returns>Project</returns>
private Project GetProjectThatImportsAnotherProject(string importProjectContents, string parentProjectContents)
{
if (String.IsNullOrEmpty(importProjectContents))
{
importProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t2' >
<t2.Task2 parameter='value' />
</Target>
<Target Name='t3' >
<t3.Task3 parameter='value' />
</Target>
</Project>
");
}
if (String.IsNullOrEmpty(parentProjectContents))
{
parentProjectContents = ObjectModelHelpers.CleanupFileContents(@"
<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<Target Name='t1'>
<t1.Task1 parameter='value' />
</Target>
<Import Project='import.proj' />
</Project>
");
}
ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", importProjectContents);
ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", parentProjectContents);
return ObjectModelHelpers.LoadProjectFileInTempProjectDirectory("main.proj", null);
}
/// <summary>
/// Un-registers the existing logger and registers a new copy.
/// We will use this when we do multiple builds so that we can safely
/// assert on log messages for that particular build.
/// </summary>
private void ResetLogger()
{
engine.UnregisterAllLoggers();
logger = new MockLogger();
project.ParentEngine.RegisterLogger(logger);
}
/// <summary>
/// MyHostObject class for testing BuildTask HostObject
/// </summary>
internal class MockHostObject : ITaskHost
{
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CssStyleCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI {
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Web.UI;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Permissions;
/// <devdoc>
/// <para>
/// The <see langword='CssStyleCollection'/>
/// class contains HTML
/// cascading-style sheets (CSS) inline style attributes. It automatically parses
/// and exposes CSS properties through a dictionary pattern API. Each CSS key can be
/// manipulated using a key/value indexed collection.
/// </para>
/// </devdoc>
public sealed class CssStyleCollection {
private static readonly Regex _styleAttribRegex = new Regex(
"\\G(\\s*(;\\s*)*" + // match leading semicolons and spaces
"(?<stylename>[^:]+?)" + // match stylename - chars up to the semicolon
"\\s*:\\s*" + // spaces, then the colon, then more spaces
"(?<styleval>[^;]*)" + // now match styleval
")*\\s*(;\\s*)*$", // match a trailing semicolon and trailing spaces
RegexOptions.Singleline |
RegexOptions.Multiline |
RegexOptions.ExplicitCapture);
private StateBag _state;
private string _style;
private IDictionary _table;
private IDictionary _intTable;
internal CssStyleCollection() : this(null) {
}
/*
* Constructs an CssStyleCollection given a StateBag.
*/
internal CssStyleCollection(StateBag state) {
_state = state;
}
/*
* Automatically adds new keys.
*/
/// <devdoc>
/// <para>
/// Gets or sets a specified CSS value.
/// </para>
/// </devdoc>
public string this[string key] {
get {
if (_table == null)
ParseString();
string value = (string)_table[key];
if (value == null) {
HtmlTextWriterStyle style = CssTextWriter.GetStyleKey(key);
if (style != (HtmlTextWriterStyle)(-1)) {
value = this[style];
}
}
return value;
}
set {
Add(key, value);
}
}
/// <devdoc>
/// Gets or sets the specified known CSS value.
/// </devdoc>
public string this[HtmlTextWriterStyle key] {
get {
if (_intTable == null) {
return null;
}
return (string)_intTable[(int)key];
}
set {
Add(key, value);
}
}
/*
* Returns a collection of keys.
*/
/// <devdoc>
/// <para>
/// Gets a collection of keys to all the styles in the
/// <see langword='CssStyleCollection'/>.
/// </para>
/// </devdoc>
public ICollection Keys {
get {
if (_table == null)
ParseString();
if (_intTable != null) {
// combine the keys into a single table. Note that to preserve existing
// behavior, we convert enum values into strings to maintain a homogeneous collection.
string[] keys = new string[_table.Count + _intTable.Count];
int i = 0;
foreach (string s in _table.Keys) {
keys[i] = s;
i++;
}
foreach (HtmlTextWriterStyle style in _intTable.Keys) {
keys[i] = CssTextWriter.GetStyleName(style);
i++;
}
return keys;
}
return _table.Keys;
}
}
/// <devdoc>
/// <para>
/// Gets the number of items in the <see langword='CssStyleCollection'/>.
/// </para>
/// </devdoc>
public int Count {
get {
if (_table == null)
ParseString();
return _table.Count + ((_intTable != null) ? _intTable.Count : 0);
}
}
public string Value {
get {
if (_state == null) {
if (_style == null) {
_style = BuildString();
}
return _style;
}
return(string)_state["style"];
}
set {
if (_state == null) {
_style = value;
}
else {
_state["style"] = value;
}
_table = null;
}
}
/// <devdoc>
/// <para>
/// Adds a style to the CssStyleCollection.
/// </para>
/// </devdoc>
public void Add(string key, string value) {
if (String.IsNullOrEmpty(key)) {
throw new ArgumentNullException("key");
}
if (_table == null)
ParseString();
_table[key] = value;
if (_intTable != null) {
// Remove from the other table to avoid duplicates.
HtmlTextWriterStyle style = CssTextWriter.GetStyleKey(key);
if (style != (HtmlTextWriterStyle)(-1)) {
_intTable.Remove(style);
}
}
if (_state != null) {
// keep style attribute synchronized
_state["style"] = BuildString();
}
_style = null;
}
public void Add(HtmlTextWriterStyle key, string value) {
if (_intTable == null) {
_intTable = new HybridDictionary();
}
_intTable[(int)key] = value;
string name = CssTextWriter.GetStyleName(key);
if (name.Length != 0) {
// Remove from the other table to avoid duplicates.
if (_table == null)
ParseString();
_table.Remove(name);
}
if (_state != null) {
// keep style attribute synchronized
_state["style"] = BuildString();
}
_style = null;
}
/// <devdoc>
/// <para>
/// Removes a style from the <see langword='CssStyleCollection'/>.
/// </para>
/// </devdoc>
public void Remove(string key) {
if (_table == null)
ParseString();
if (_table[key] != null) {
_table.Remove(key);
if (_state != null) {
// keep style attribute synchronized
_state["style"] = BuildString();
}
_style = null;
}
}
public void Remove(HtmlTextWriterStyle key) {
if (_intTable == null) {
return;
}
_intTable.Remove((int)key);
if (_state != null) {
// keep style attribute synchronized
_state["style"] = BuildString();
}
_style = null;
}
/// <devdoc>
/// <para>
/// Removes all styles from the <see langword='CssStyleCollection'/>.
/// </para>
/// </devdoc>
public void Clear() {
_table = null;
_intTable = null;
if (_state != null) {
_state.Remove("style");
}
_style = null;
}
/* BuildString
* Form the style string from data contained in the
* hash table
*/
private string BuildString() {
// if the tables are null, there is nothing to build
if (((_table == null) || (_table.Count == 0)) &&
((_intTable == null) || (_intTable.Count == 0))) {
return null;
}
StringWriter sw = new StringWriter();
CssTextWriter writer = new CssTextWriter(sw);
Render(writer);
return sw.ToString();
}
/* ParseString
* Parse the style string and fill the hash table with
* corresponding values.
*/
private void ParseString() {
// create a case-insensitive dictionary
_table = new HybridDictionary(true);
string s = (_state == null) ? _style : (string)_state["style"];
if (s != null) {
Match match;
if ((match = _styleAttribRegex.Match( s, 0)).Success) {
CaptureCollection stylenames = match.Groups["stylename"].Captures;
CaptureCollection stylevalues = match.Groups["styleval"].Captures;
for (int i = 0; i < stylenames.Count; i++) {
String styleName = stylenames[i].ToString();
String styleValue = stylevalues[i].ToString();
_table[styleName] = styleValue;
}
}
}
}
/// <devdoc>
/// Render out the attribute collection into a CSS TextWriter. This
/// effectively renders the value of an inline style attribute.
/// </devdoc>
internal void Render(CssTextWriter writer) {
if (_table != null && _table.Count > 0) {
foreach (DictionaryEntry entry in _table) {
writer.WriteAttribute((string)entry.Key, (string)entry.Value);
}
}
if (_intTable != null && _intTable.Count > 0) {
foreach (DictionaryEntry entry in _intTable) {
writer.WriteAttribute((HtmlTextWriterStyle)entry.Key, (string)entry.Value);
}
}
}
/// <devdoc>
/// Render out the attribute collection into a CSS TextWriter. This
/// effectively renders the value of an inline style attribute.
/// Used by a Style object to render out its CSS attributes into an HtmlTextWriter.
/// </devdoc>
internal void Render(HtmlTextWriter writer) {
if (_table != null && _table.Count > 0) {
foreach (DictionaryEntry entry in _table) {
writer.AddStyleAttribute((string)entry.Key, (string)entry.Value);
}
}
if (_intTable != null && _intTable.Count > 0) {
foreach (DictionaryEntry entry in _intTable) {
writer.AddStyleAttribute((HtmlTextWriterStyle)entry.Key, (string)entry.Value);
}
}
}
}
}
| |
using System.Diagnostics;
using System.Threading;
using Castle.Components.DictionaryAdapter;
using static Rafty.Infrastructure.Wait;
namespace Rafty.UnitTests
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Concensus;
using Concensus.Messages;
using Concensus.Node;
using Concensus.Peers;
using Microsoft.Extensions.Logging;
using Moq;
using Rafty.Concensus.States;
using Rafty.FiniteStateMachine;
using Rafty.Infrastructure;
using Rafty.Log;
using Shouldly;
using Xunit;
public class FollowerTests
{
private readonly IFiniteStateMachine _fsm;
private List<IPeer> _peers;
private readonly ILog _log;
private readonly IRandomDelay _random;
private INode _node;
private CurrentState _currentState;
private InMemorySettings _settings;
private IRules _rules;
private IPeersProvider _peersProvider;
private Mock<ILoggerFactory> _loggerFactory;
private Mock<ILogger> _logger;
public FollowerTests()
{
_logger = new Mock<ILogger>();
_loggerFactory = new Mock<ILoggerFactory>();
_loggerFactory.Setup(x => x.CreateLogger(It.IsAny<string>())).Returns(_logger.Object);
_rules = new Rules(_loggerFactory.Object, new NodeId(default(string)));
_settings = new InMemorySettingsBuilder().Build();
_random = new RandomDelay();
_log = new InMemoryLog();
_peers = new List<IPeer>();
_fsm = new InMemoryStateMachine();
_peersProvider = new InMemoryPeersProvider(_peers);
_currentState = new CurrentState(Guid.NewGuid().ToString(), 0, default(string), -1, -1, default(string));
_node = new NothingNode();
}
[Fact]
public void CommitIndexShouldBeInitialisedToMinusOne()
{
_node = new Node(_fsm, _log, _settings, _peersProvider, _loggerFactory.Object);
_node.Start(new NodeId(Guid.NewGuid().ToString()));
_node.State.CurrentState.CommitIndex.ShouldBe(0);
}
[Fact]
public void CurrentTermShouldBeInitialisedToZero()
{
_node = new Node(_fsm, _log, _settings, _peersProvider, _loggerFactory.Object);
_node.Start(new NodeId(Guid.NewGuid().ToString()));
_node.State.CurrentState.CurrentTerm.ShouldBe(0);
}
[Fact]
public void LastAppliedShouldBeInitialisedToZero()
{
_node = new Node(_fsm, _log, _settings, _peersProvider, _loggerFactory.Object);
_node.Start(new NodeId(Guid.NewGuid().ToString()));
_node.State.CurrentState.LastApplied.ShouldBe(0);
}
[Fact]
public void ShouldBecomeCandidateWhenFollowerReceivesTimeoutAndHasNotHeardFromLeader()
{
_node = new TestingNode();
var node = (TestingNode)_node;
node.SetState(new Follower(_currentState, _fsm, _log, _random, node, new InMemorySettingsBuilder().WithMinTimeout(0).WithMaxTimeout(0).Build(),_rules, _peers, _loggerFactory.Object));
var result = WaitFor(1000).Until(() => node.BecomeCandidateCount > 0);
result.ShouldBeTrue();
}
[Fact]
public void ShouldBecomeCandidateWhenFollowerReceivesTimeoutAndHasNotHeardFromLeaderSinceLastTimeout()
{
_node = new TestingNode();
var node = (TestingNode)_node;
node.SetState(new Follower(_currentState, _fsm, _log, _random, node, new InMemorySettingsBuilder().WithMinTimeout(0).WithMaxTimeout(0).Build(), _rules, _peers, _loggerFactory.Object));
_node.Handle(new AppendEntriesBuilder().WithTerm(1).WithLeaderCommitIndex(-1).Build());
var result = WaitFor(1000).Until(() => node.BecomeCandidateCount > 0);
result.ShouldBeTrue();
}
[Fact]
public void ShouldNotBecomeCandidateWhenFollowerReceivesTimeoutAndHasHeardFromLeader()
{
_node = new Node(_fsm, _log, _settings, _peersProvider, _loggerFactory.Object);
_node.Start(new NodeId(Guid.NewGuid().ToString()));
_node.State.ShouldBeOfType<Follower>();
_node.Handle(new AppendEntriesBuilder().WithTerm(1).WithLeaderCommitIndex(-1).Build());
_node.State.ShouldBeOfType<Follower>();
}
[Fact]
public void ShouldNotBecomeCandidateWhenFollowerReceivesTimeoutAndHasHeardFromLeaderSinceLastTimeout()
{
_node = new Node(_fsm, _log, _settings, _peersProvider, _loggerFactory.Object);
_node.Start(new NodeId(Guid.NewGuid().ToString()));
_node.State.ShouldBeOfType<Follower>();
_node.Handle(new AppendEntriesBuilder().WithTerm(1).WithLeaderCommitIndex(-1).Build());
_node.State.ShouldBeOfType<Follower>();
_node.Handle(new AppendEntriesBuilder().WithTerm(1).WithLeaderCommitIndex(-1).Build());
_node.State.ShouldBeOfType<Follower>();
}
[Fact]
public void ShouldStartAsFollower()
{
_node = new Node(_fsm, _log, _settings, _peersProvider, _loggerFactory.Object);
_node.Start(new NodeId(Guid.NewGuid().ToString()));
_node.State.ShouldBeOfType<Follower>();
}
[Fact]
public void VotedForShouldBeInitialisedToNone()
{
_node = new Node(_fsm, _log, _settings, _peersProvider, _loggerFactory.Object);
_node.Start(new NodeId(Guid.NewGuid().ToString()));
_node.State.CurrentState.VotedFor.ShouldBe(default(string));
}
[Fact]
public async Task ShouldUpdateVotedFor()
{
_node = new NothingNode();
_currentState = new CurrentState(Guid.NewGuid().ToString(), 0, default(string), 0, 0, default(string));
var follower = new Follower(_currentState, _fsm, _log, _random, _node, _settings, _rules, _peers, _loggerFactory.Object);
var requestVote = new RequestVoteBuilder().WithCandidateId(Guid.NewGuid().ToString()).WithLastLogIndex(1).Build();
var requestVoteResponse = await follower.Handle(requestVote);
requestVoteResponse.VoteGranted.ShouldBeTrue();
follower.CurrentState.VotedFor.ShouldBe(requestVote.CandidateId);
}
[Fact]
public async Task ShouldVoteForNewCandidateInAnotherTermsElection()
{
_node = new NothingNode();
_currentState = new CurrentState(Guid.NewGuid().ToString(), 0, default(string), 0, 0, default(string));
var follower = new Follower(_currentState, _fsm, _log, _random, _node, _settings,_rules, _peers, _loggerFactory.Object);
var requestVote = new RequestVoteBuilder().WithTerm(0).WithCandidateId(Guid.NewGuid().ToString()).WithLastLogIndex(1).Build();
var requestVoteResponse = await follower.Handle(requestVote);
follower.CurrentState.VotedFor.ShouldBe(requestVote.CandidateId);
requestVoteResponse.VoteGranted.ShouldBeTrue();
requestVote = new RequestVoteBuilder().WithTerm(1).WithCandidateId(Guid.NewGuid().ToString()).WithLastLogIndex(1).Build();
requestVoteResponse = await follower.Handle(requestVote);
requestVoteResponse.VoteGranted.ShouldBeTrue();
follower.CurrentState.VotedFor.ShouldBe(requestVote.CandidateId);
}
[Fact]
public async Task FollowerShouldForwardCommandToLeader()
{
_node = new NothingNode();
var leaderId = Guid.NewGuid().ToString();
var leader = new FakePeer(leaderId);
_peers = new List<IPeer>
{
leader
};
_currentState = new CurrentState(_currentState.Id, _currentState.CurrentTerm, _currentState.VotedFor, _currentState.CommitIndex, _currentState.LastApplied, leaderId);
var follower = new Follower(_currentState, _fsm, _log, _random, _node, _settings,_rules, _peers, _loggerFactory.Object);
var response = await follower.Accept(new FakeCommand());
response.ShouldBeOfType<OkResponse<FakeCommand>>();
leader.ReceivedCommands.ShouldBe(1);
}
[Fact]
public async Task FollowerShouldReturnRetryIfNoLeader()
{
_node = new NothingNode();
_currentState = new CurrentState(_currentState.Id, _currentState.CurrentTerm, _currentState.VotedFor, _currentState.CommitIndex, _currentState.LastApplied, _currentState.LeaderId);
var follower = new Follower(_currentState, _fsm, _log, _random, _node, _settings,_rules, _peers, _loggerFactory.Object);
var response = await follower.Accept(new FakeCommand());
var error = (ErrorResponse<FakeCommand>)response;
error.Error.ShouldBe("Please retry command later. Unable to find leader.");
}
[Fact]
public async Task FollowerShouldAppendNewEntries()
{
_currentState = new CurrentState(Guid.NewGuid().ToString(), 0, default(string), 0, 0, default(string));
var follower = new Follower(_currentState, _fsm, _log, _random, _node, _settings,_rules, _peers, _loggerFactory.Object);
var logEntry = new LogEntry(new FakeCommand(), typeof(FakeCommand), 1);
var appendEntries = new AppendEntriesBuilder().WithTerm(1).WithEntry(logEntry).Build();
var response = await follower.Handle(appendEntries);
response.Success.ShouldBeTrue();
response.Term.ShouldBe(1);
var inMemoryLog = (InMemoryLog)_log;
inMemoryLog.ExposedForTesting.Count.ShouldBe(1);
}
[Fact]
public async Task FollowerShouldNotAppendDuplicateEntry()
{
_node = new NothingNode();
_currentState = new CurrentState(Guid.NewGuid().ToString(), 0, default(string), 0, 0, default(string));
var follower = new Follower(_currentState, _fsm, _log, _random, _node, _settings,_rules, _peers, _loggerFactory.Object);
var logEntry = new LogEntry(new FakeCommand(), typeof(FakeCommand), 1);
var appendEntries = new AppendEntriesBuilder().WithPreviousLogIndex(1).WithPreviousLogTerm(1).WithTerm(1).WithEntry(logEntry).WithTerm(1).WithLeaderCommitIndex(1).Build();
var response = await follower.Handle(appendEntries);
response.Success.ShouldBeTrue();
response.Term.ShouldBe(1);
response = await follower.Handle(appendEntries);
response.Success.ShouldBeTrue();
response.Term.ShouldBe(1);
var inMemoryLog = (InMemoryLog)_log;
inMemoryLog.ExposedForTesting.Count.ShouldBe(1);
}
}
}
| |
// 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 XorUInt16()
{
var test = new SimpleBinaryOpTest__XorUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorUInt16
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(UInt16);
private const int Op2ElementCount = VectorSize / sizeof(UInt16);
private const int RetElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable;
static SimpleBinaryOpTest__XorUInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__XorUInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Xor(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Xor(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Xor(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorUInt16();
var result = Avx2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt16> left, Vector256<UInt16> right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
if ((ushort)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ushort)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Xor)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/***************************************************************************
* PodcastFeedPropertiesDialog.cs
*
* Written by Mike Urbanski <[email protected]>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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 Mono.Unix;
using Gtk;
using Pango;
using Migo.Syndication;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Podcasting.Data;
using Banshee.Gui.TrackEditor;
using Banshee.Collection.Gui;
using Banshee.ServiceStack;
namespace Banshee.Podcasting.Gui
{
internal class PodcastFeedPropertiesDialog : Dialog
{
PodcastSource source;
Feed feed;
Entry name_entry;
Frame header_image_frame;
Image header_image;
FakeTrackInfo fake_track = new FakeTrackInfo ();
CheckButton subscribed_check, download_check, archive_check;
private VBox main_box;
public PodcastFeedPropertiesDialog (PodcastSource source, Feed feed)
{
this.source = source;
this.feed = feed;
fake_track.Feed = feed;
Title = feed.Title;
HasSeparator = false;
BorderWidth = 12;
WidthRequest = 525;
//IconThemeUtils.SetWindowIcon (this);
BuildWindow ();
DefaultResponse = Gtk.ResponseType.Cancel;
ActionArea.Layout = Gtk.ButtonBoxStyle.End;
Response += OnResponse;
ShowAll ();
}
private FeedAutoDownload DownloadPref {
get { return download_check.Active ? FeedAutoDownload.All : FeedAutoDownload.None; }
set { download_check.Active = value != FeedAutoDownload.None; }
}
private int MaxItemCount {
get { return archive_check.Active ? 1 : 0; }
set { archive_check.Active = value > 0; }
}
private void BuildWindow()
{
VBox.Spacing = 12;
main_box = VBox;
var save_button = new Button ("gtk-save") { CanDefault = true };
name_entry = new Entry ();
name_entry.Text = feed.Title;
name_entry.Changed += delegate {
save_button.Sensitive = !String.IsNullOrEmpty (name_entry.Text);
};
subscribed_check = new CheckButton (Catalog.GetString ("Check periodically for new episodes")) {
TooltipText = Catalog.GetString ("If checked, Banshee will check every hour to see if this podcast has new episodes")
};
download_check = new CheckButton (Catalog.GetString ("Download new episodes"));
DownloadPref = feed.AutoDownload;
archive_check = new CheckButton (Catalog.GetString ("Archive all episodes except the newest one"));
MaxItemCount = (int)feed.MaxItemCount;
subscribed_check.Toggled += delegate {
download_check.Sensitive = archive_check.Sensitive = subscribed_check.Active;
};
subscribed_check.Active = feed.IsSubscribed;
download_check.Sensitive = archive_check.Sensitive = subscribed_check.Active;
var last_updated_text = new Label (feed.LastDownloadTime.ToString ("f")) {
Justify = Justification.Left,
Xalign = 0f
};
var feed_url_text = new Label () {
Text = feed.Url.ToString (),
Wrap = false,
Selectable = true,
Xalign = 0f,
Justify = Justification.Left,
Ellipsize = Pango.EllipsizeMode.End
};
string description_string = String.IsNullOrEmpty (feed.Description) ?
Catalog.GetString ("No description available") :
feed.Description;
var header_box = new HBox () { Spacing = 6 };
header_image_frame = new Frame ();
header_image = new Image ();
LoadCoverArt (fake_track);
header_image_frame.Add (
CoverArtEditor.For (header_image,
(x, y) => true,
() => fake_track,
() => LoadCoverArt (fake_track)
)
);
header_box.PackStart (header_image_frame, false, false, 0);
var table = new Hyena.Widgets.SimpleTable<int> ();
table.XOptions[0] = AttachOptions.Fill;
table.XOptions[1] = AttachOptions.Expand | AttachOptions.Fill;
table.AddRow (0, HeaderLabel (Catalog.GetString ("Name:")), name_entry);
table.AddRow (1, HeaderLabel (Catalog.GetString ("Website:")),
new Gtk.Alignment (0f, 0f, 0f, 0f) {
Child = new LinkButton (feed.Link, Catalog.GetString ("Visit")) {
Image = new Gtk.Image (Gtk.Stock.JumpTo, Gtk.IconSize.Button)
}
});
header_box.PackStart (table, true, true, 0);
main_box.PackStart (header_box, false, false, 0);
Add (Catalog.GetString ("Subscription Options"), subscribed_check, download_check, archive_check);
var details = new Banshee.Gui.TrackEditor.StatisticsPage ();
details.AddItem (Catalog.GetString ("Feed URL:"), feed_url_text.Text);
details.AddItem (Catalog.GetString ("Last Refreshed:"), last_updated_text.Text);
details.AddItem (Catalog.GetString ("Description:"), description_string, true);
details.AddItem (Catalog.GetString ("Category:"), feed.Category);
details.AddItem (Catalog.GetString ("Keywords:"), feed.Keywords);
details.AddItem (Catalog.GetString ("Copyright:"), feed.Copyright);
details.HeightRequest = 120;
Add (true, Catalog.GetString ("Details"), details);
AddActionWidget (new Button ("gtk-cancel") { CanDefault = true }, ResponseType.Cancel);
AddActionWidget (save_button, ResponseType.Ok);
}
private void Add (string header_txt, params Widget [] widgets)
{
Add (false, header_txt, widgets);
}
private Label HeaderLabel (string str)
{
return new Label () {
Markup = String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (str)),
Xalign = 0f
};
}
private void Add (bool filled, string header_txt, params Widget [] widgets)
{
var vbox = new VBox () { Spacing = 3 };
vbox.PackStart (HeaderLabel (header_txt), false, false, 0);
foreach (var child in widgets) {
var align = new Gtk.Alignment (0, 0, 1, 1) { LeftPadding = 12, Child = child };
vbox.PackStart (align, filled, filled, 0);
}
main_box.PackStart (vbox, filled, filled, 0);
}
private void OnResponse (object sender, ResponseArgs args)
{
if (args.ResponseId == Gtk.ResponseType.Ok) {
bool changed = false;
if (feed.IsSubscribed != subscribed_check.Active) {
feed.IsSubscribed = subscribed_check.Active;
changed = true;
}
if (feed.IsSubscribed) {
if (feed.AutoDownload != DownloadPref) {
feed.AutoDownload = DownloadPref;
changed = true;
}
if (feed.MaxItemCount != MaxItemCount) {
feed.MaxItemCount = MaxItemCount;
changed = true;
}
}
if (feed.Title != name_entry.Text) {
feed.Title = name_entry.Text;
source.Reload ();
changed = true;
}
if (changed) {
feed.Save ();
}
}
(sender as Dialog).Response -= OnResponse;
(sender as Dialog).Destroy();
}
void LoadCoverArt (TrackInfo current_track)
{
if (current_track == null || current_track.ArtworkId == null) {
SetDefaultCoverArt ();
return;
}
var artwork = ServiceManager.Get<ArtworkManager> ();
var cover_art = artwork.LookupScalePixbuf (current_track.ArtworkId, 64);
header_image.Clear ();
header_image.Pixbuf = cover_art;
if (cover_art == null) {
SetDefaultCoverArt ();
} else {
header_image_frame.ShadowType = ShadowType.In;
header_image.QueueDraw ();
}
}
void SetDefaultCoverArt ()
{
header_image.IconName = "podcast";
header_image.PixelSize = 64;
header_image_frame.ShadowType = ShadowType.In;
header_image.QueueDraw ();
}
class FakeTrackInfo : TrackInfo
{
public Feed Feed { get; set; }
public override string ArtworkId {
get { return Feed == null ? null : PodcastService.ArtworkIdFor (Feed); }
}
}
}
}
| |
/*
* 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.
*/
using System;
using Nini.Config;
using Aurora.Framework;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// Holds drip rates and maximum burst rates for throttling with hierarchical
/// token buckets. The maximum burst rates set here are hard limits and can
/// not be overridden by client requests
/// </summary>
public sealed class ThrottleRates
{
/// <summary>
/// Drip rate for asset packets
/// </summary>
public int Asset;
/// <summary>
/// Maximum burst rate for asset packets
/// </summary>
public int AssetLimit;
/// <summary>
/// Drip rate for AvatarInfo packets
/// </summary>
public int AvatarInfo;
/// <summary>
/// Burst rate for the parent token bucket
/// </summary>
public int AvatarInfoLimit;
/// <summary>
/// Drip rate for cloud packets
/// </summary>
public int Cloud;
/// <summary>
/// Maximum burst rate for cloud packets
/// </summary>
public int CloudLimit;
/// <summary>
/// Drip rate for terrain packets
/// </summary>
public int Land;
/// <summary>
/// Maximum burst rate for land packets
/// </summary>
public int LandLimit;
/// <summary>
/// Drip rate for resent packets
/// </summary>
public int Resend;
/// <summary>
/// Maximum burst rate for resent packets
/// </summary>
public int ResendLimit;
/// <summary>
/// Drip rate for state packets
/// </summary>
public int State;
/// <summary>
/// Maximum burst rate for state packets
/// </summary>
public int StateLimit;
/// <summary>
/// Drip rate for task packets
/// </summary>
public int Task;
/// <summary>
/// Maximum burst rate for task (state and transaction) packets
/// </summary>
public int TaskLimit;
/// <summary>
/// Drip rate for texture packets
/// </summary>
public int Texture;
/// <summary>
/// Maximum burst rate for texture packets
/// </summary>
public int TextureLimit;
/// <summary>
/// Drip rate for the parent token bucket
/// </summary>
public int Total;
/// <summary>
/// Burst rate for the parent token bucket
/// </summary>
public int TotalLimit;
/// <summary>
/// Drip rate for wind packets
/// </summary>
public int Wind;
/// <summary>
/// Maximum burst rate for wind packets
/// </summary>
public int WindLimit;
/// <summary>
/// Default constructor
/// </summary>
/// <param name = "config">Config source to load defaults from</param>
public ThrottleRates(IConfigSource config)
{
try
{
IConfig throttleConfig = config.Configs["ClientStack.LindenUDP"];
Resend = throttleConfig.GetInt("resend_default", 12500);
Land = throttleConfig.GetInt("land_default", 1000);
Wind = throttleConfig.GetInt("wind_default", 1000);
Cloud = throttleConfig.GetInt("cloud_default", 1000);
Task = throttleConfig.GetInt("task_default", 1000);
Texture = throttleConfig.GetInt("texture_default", 1000);
Asset = throttleConfig.GetInt("asset_default", 1000);
State = throttleConfig.GetInt("state_default", 1000);
AvatarInfo = throttleConfig.GetInt("avatar_info_default", 1000);
ResendLimit = throttleConfig.GetInt("resend_limit", 18750);
LandLimit = throttleConfig.GetInt("land_limit", 29750);
WindLimit = throttleConfig.GetInt("wind_limit", 18750);
CloudLimit = throttleConfig.GetInt("cloud_limit", 18750);
TaskLimit = throttleConfig.GetInt("task_limit", 18750);
TextureLimit = throttleConfig.GetInt("texture_limit", 55750);
AssetLimit = throttleConfig.GetInt("asset_limit", 27500);
StateLimit = throttleConfig.GetInt("state_limit", 37000);
AvatarInfoLimit = throttleConfig.GetInt("avatar_info_limit", 37000);
Total = throttleConfig.GetInt("client_throttle_max_bps", 0);
TotalLimit = Total;
}
catch (Exception)
{
}
}
public int GetRate(ThrottleOutPacketType type)
{
switch (type)
{
case ThrottleOutPacketType.Resend:
return Resend;
case ThrottleOutPacketType.Land:
return Land;
case ThrottleOutPacketType.Wind:
return Wind;
case ThrottleOutPacketType.Cloud:
return Cloud;
case ThrottleOutPacketType.Task:
return Task;
case ThrottleOutPacketType.Texture:
return Texture;
case ThrottleOutPacketType.Asset:
return Asset;
case ThrottleOutPacketType.State:
return State;
case ThrottleOutPacketType.AvatarInfo:
return AvatarInfo;
// case ThrottleOutPacketType.Unknown:
default:
return 0;
}
}
public int GetLimit(ThrottleOutPacketType type)
{
switch (type)
{
case ThrottleOutPacketType.Resend:
return ResendLimit;
case ThrottleOutPacketType.Land:
return LandLimit;
case ThrottleOutPacketType.Wind:
return WindLimit;
case ThrottleOutPacketType.Cloud:
return CloudLimit;
case ThrottleOutPacketType.Task:
return TaskLimit;
case ThrottleOutPacketType.Texture:
return TextureLimit;
case ThrottleOutPacketType.Asset:
return AssetLimit;
case ThrottleOutPacketType.State:
return StateLimit;
case ThrottleOutPacketType.AvatarInfo:
return AvatarInfoLimit;
// case ThrottleOutPacketType.Unknown:
default:
return 0;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Security;
using System.Windows.Input;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChangedEventArgs
[ComImport]
[Guid("4cf68d33-e3f2-4964-b85e-945b4f7e2f21")]
[WindowsRuntimeImport]
internal interface INotifyCollectionChangedEventArgs
{
NotifyCollectionChangedAction Action { get; }
IList NewItems { get; }
IList OldItems { get; }
int NewStartingIndex { get; }
int OldStartingIndex { get; }
}
// Local definition of Windows.UI.Xaml.Data.IPropertyChangedEventArgs
[ComImport]
[Guid("4f33a9a0-5cf4-47a4-b16f-d7faaf17457e")]
[WindowsRuntimeImport]
internal interface IPropertyChangedEventArgs
{
string PropertyName { get; }
}
// Local definition of Windows.UI.Xaml.Interop.INotifyCollectionChanged
[ComImport]
[Guid("28b167d5-1a31-465b-9b25-d5c3ae686c40")]
[WindowsRuntimeImport]
internal interface INotifyCollectionChanged_WinRT
{
EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value);
void remove_CollectionChanged(EventRegistrationToken token);
}
// Local definition of Windows.UI.Xaml.Data.INotifyPropertyChanged
[ComImport]
[Guid("cf75d69c-f2f4-486b-b302-bb4c09baebfa")]
[WindowsRuntimeImport]
internal interface INotifyPropertyChanged_WinRT
{
EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value);
void remove_PropertyChanged(EventRegistrationToken token);
}
// Local definition of Windows.UI.Xaml.Input.ICommand
[ComImport]
[Guid("e5af3542-ca67-4081-995b-709dd13792df")]
[WindowsRuntimeImport]
internal interface ICommand_WinRT
{
EventRegistrationToken add_CanExecuteChanged(EventHandler<object> value);
void remove_CanExecuteChanged(EventRegistrationToken token);
bool CanExecute(object parameter);
void Execute(object parameter);
}
// Local definition of Windows.UI.Xaml.Interop.NotifyCollectionChangedEventHandler
[Guid("ca10b37c-f382-4591-8557-5e24965279b0")]
[WindowsRuntimeImport]
internal delegate void NotifyCollectionChangedEventHandler_WinRT(object sender, NotifyCollectionChangedEventArgs e);
// Local definition of Windows.UI.Xaml.Data.PropertyChangedEventHandler
[Guid("50f19c16-0a22-4d8e-a089-1ea9951657d2")]
[WindowsRuntimeImport]
internal delegate void PropertyChangedEventHandler_WinRT(object sender, PropertyChangedEventArgs e);
internal static class NotifyCollectionChangedEventArgsMarshaler
{
// Extracts properties from a managed NotifyCollectionChangedEventArgs and passes them to
// a VM-implemented helper that creates a WinRT NotifyCollectionChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static IntPtr ConvertToNative(NotifyCollectionChangedEventArgs managedArgs)
{
if (managedArgs == null)
return IntPtr.Zero;
return System.StubHelpers.EventArgsMarshaler.CreateNativeNCCEventArgsInstance(
(int)managedArgs.Action,
managedArgs.NewItems,
managedArgs.OldItems,
managedArgs.NewStartingIndex,
managedArgs.OldStartingIndex);
}
// Extracts properties from a WinRT NotifyCollectionChangedEventArgs and creates a new
// managed NotifyCollectionChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static NotifyCollectionChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
{
if (nativeArgsIP == IntPtr.Zero)
return null;
object obj = System.StubHelpers.InterfaceMarshaler.ConvertToManagedWithoutUnboxing(nativeArgsIP);
INotifyCollectionChangedEventArgs nativeArgs = (INotifyCollectionChangedEventArgs)obj;
return CreateNotifyCollectionChangedEventArgs(
nativeArgs.Action,
nativeArgs.NewItems,
nativeArgs.OldItems,
nativeArgs.NewStartingIndex,
nativeArgs.OldStartingIndex);
}
internal static NotifyCollectionChangedEventArgs CreateNotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newStartingIndex, int oldStartingIndex)
{
switch (action)
{
case NotifyCollectionChangedAction.Add:
return new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex);
case NotifyCollectionChangedAction.Remove:
return new NotifyCollectionChangedEventArgs(action, oldItems, oldStartingIndex);
case NotifyCollectionChangedAction.Replace:
return new NotifyCollectionChangedEventArgs(action, newItems, oldItems, newStartingIndex);
case NotifyCollectionChangedAction.Move:
return new NotifyCollectionChangedEventArgs(action, newItems, newStartingIndex, oldStartingIndex);
case NotifyCollectionChangedAction.Reset:
return new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
default: throw new ArgumentException("Invalid action value: " + action);
}
}
}
internal static class PropertyChangedEventArgsMarshaler
{
// Extracts PropertyName from a managed PropertyChangedEventArgs and passes them to
// a VM-implemented helper that creates a WinRT PropertyChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static IntPtr ConvertToNative(PropertyChangedEventArgs managedArgs)
{
if (managedArgs == null)
return IntPtr.Zero;
return System.StubHelpers.EventArgsMarshaler.CreateNativePCEventArgsInstance(managedArgs.PropertyName);
}
// Extracts properties from a WinRT PropertyChangedEventArgs and creates a new
// managed PropertyChangedEventArgs instance.
// This method is called from IL stubs and needs to have its token stabilized.
internal static PropertyChangedEventArgs ConvertToManaged(IntPtr nativeArgsIP)
{
if (nativeArgsIP == IntPtr.Zero)
return null;
object obj = System.StubHelpers.InterfaceMarshaler.ConvertToManagedWithoutUnboxing(nativeArgsIP);
IPropertyChangedEventArgs nativeArgs = (IPropertyChangedEventArgs)obj;
return new PropertyChangedEventArgs(nativeArgs.PropertyName);
}
}
// This is a set of stub methods implementing the support for the managed INotifyCollectionChanged
// interface on WinRT objects that support the WinRT INotifyCollectionChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyCollectionChangedToManagedAdapter
{
private NotifyCollectionChangedToManagedAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
internal event NotifyCollectionChangedEventHandler CollectionChanged
{
// void CollectionChanged.add(NotifyCollectionChangedEventHandler)
add
{
INotifyCollectionChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyCollectionChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<NotifyCollectionChangedEventHandler, EventRegistrationToken> addMethod =
new Func<NotifyCollectionChangedEventHandler, EventRegistrationToken>(_this.add_CollectionChanged);
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CollectionChanged);
WindowsRuntimeMarshal.AddEventHandler<NotifyCollectionChangedEventHandler>(addMethod, removeMethod, value);
}
// void CollectionChanged.remove(NotifyCollectionChangedEventHandler)
remove
{
INotifyCollectionChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyCollectionChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CollectionChanged);
WindowsRuntimeMarshal.RemoveEventHandler<NotifyCollectionChangedEventHandler>(removeMethod, value);
}
}
}
// This is a set of stub methods implementing the support for the WinRT INotifyCollectionChanged
// interface on managed objects that support the managed INotifyCollectionChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyCollectionChangedToWinRTAdapter
{
private NotifyCollectionChangedToWinRTAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
// Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's
// separately, associated with the implementations using ConditionalWeakTable.
private static ConditionalWeakTable<INotifyCollectionChanged, EventRegistrationTokenTable<NotifyCollectionChangedEventHandler>> s_weakTable =
new ConditionalWeakTable<INotifyCollectionChanged, EventRegistrationTokenTable<NotifyCollectionChangedEventHandler>>();
// EventRegistrationToken CollectionChanged.add(NotifyCollectionChangedEventHandler value)
internal EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value)
{
INotifyCollectionChanged _this = JitHelpers.UnsafeCast<INotifyCollectionChanged>(this);
EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventRegistrationToken token = table.AddEventHandler(value);
_this.CollectionChanged += value;
return token;
}
// void CollectionChanged.remove(EventRegistrationToken token)
internal void remove_CollectionChanged(EventRegistrationToken token)
{
INotifyCollectionChanged _this = JitHelpers.UnsafeCast<INotifyCollectionChanged>(this);
EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
NotifyCollectionChangedEventHandler handler = table.ExtractHandler(token);
if (handler != null)
{
_this.CollectionChanged -= handler;
}
}
}
// This is a set of stub methods implementing the support for the managed INotifyPropertyChanged
// interface on WinRT objects that support the WinRT INotifyPropertyChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyPropertyChangedToManagedAdapter
{
private NotifyPropertyChangedToManagedAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
internal event PropertyChangedEventHandler PropertyChanged
{
// void PropertyChanged.add(PropertyChangedEventHandler)
add
{
INotifyPropertyChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyPropertyChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<PropertyChangedEventHandler, EventRegistrationToken> addMethod =
new Func<PropertyChangedEventHandler, EventRegistrationToken>(_this.add_PropertyChanged);
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_PropertyChanged);
WindowsRuntimeMarshal.AddEventHandler<PropertyChangedEventHandler>(addMethod, removeMethod, value);
}
// void PropertyChanged.remove(PropertyChangedEventHandler)
remove
{
INotifyPropertyChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyPropertyChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_PropertyChanged);
WindowsRuntimeMarshal.RemoveEventHandler<PropertyChangedEventHandler>(removeMethod, value);
}
}
}
// This is a set of stub methods implementing the support for the WinRT INotifyPropertyChanged
// interface on managed objects that support the managed INotifyPropertyChanged. Used by the interop
// mashaling infrastructure.
internal sealed class NotifyPropertyChangedToWinRTAdapter
{
private NotifyPropertyChangedToWinRTAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
// Since here the class can be an arbitrary implementation of INotifyCollectionChanged, we have to keep the EventRegistrationTokenTable's
// separately, associated with the implementations using ConditionalWeakTable.
private static ConditionalWeakTable<INotifyPropertyChanged, EventRegistrationTokenTable<PropertyChangedEventHandler>> s_weakTable =
new ConditionalWeakTable<INotifyPropertyChanged, EventRegistrationTokenTable<PropertyChangedEventHandler>>();
// EventRegistrationToken PropertyChanged.add(PropertyChangedEventHandler value)
internal EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value)
{
INotifyPropertyChanged _this = JitHelpers.UnsafeCast<INotifyPropertyChanged>(this);
EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventRegistrationToken token = table.AddEventHandler(value);
_this.PropertyChanged += value;
return token;
}
// void PropertyChanged.remove(EventRegistrationToken token)
internal void remove_PropertyChanged(EventRegistrationToken token)
{
INotifyPropertyChanged _this = JitHelpers.UnsafeCast<INotifyPropertyChanged>(this);
EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
PropertyChangedEventHandler handler = table.ExtractHandler(token);
if (handler != null)
{
_this.PropertyChanged -= handler;
}
}
}
// This is a set of stub methods implementing the support for the managed ICommand
// interface on WinRT objects that support the WinRT ICommand_WinRT.
// Used by the interop mashaling infrastructure.
// Instances of this are really RCWs of ICommand_WinRT (not ICommandToManagedAdapter or any ICommand).
internal sealed class ICommandToManagedAdapter /*: System.Windows.Input.ICommand*/
{
private static ConditionalWeakTable<EventHandler, EventHandler<object>> s_weakTable =
new ConditionalWeakTable<EventHandler, EventHandler<object>>();
private ICommandToManagedAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
private event EventHandler CanExecuteChanged
{
// void CanExecuteChanged.add(EventHandler)
add
{
ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<EventHandler<object>, EventRegistrationToken> addMethod =
new Func<EventHandler<object>, EventRegistrationToken>(_this.add_CanExecuteChanged);
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CanExecuteChanged);
// value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.AddEventHandler)
// expects an instance of EventHandler<object>. So we get/create a wrapper of value here.
EventHandler<object> handler_WinRT = s_weakTable.GetValue(value, ICommandAdapterHelpers.CreateWrapperHandler);
WindowsRuntimeMarshal.AddEventHandler<EventHandler<object>>(addMethod, removeMethod, handler_WinRT);
}
// void CanExecuteChanged.remove(EventHandler)
remove
{
ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
new Action<EventRegistrationToken>(_this.remove_CanExecuteChanged);
// value is of type System.EventHandler, but ICommand_WinRT (and thus WindowsRuntimeMarshal.RemoveEventHandler)
// expects an instance of EventHandler<object>. So we get/create a wrapper of value here.
// Also we do a value check rather than an instance check to ensure that different instances of the same delegates are treated equal.
EventHandler<object> handler_WinRT = ICommandAdapterHelpers.GetValueFromEquivalentKey(s_weakTable, value, ICommandAdapterHelpers.CreateWrapperHandler);
WindowsRuntimeMarshal.RemoveEventHandler<EventHandler<object>>(removeMethod, handler_WinRT);
}
}
private bool CanExecute(object parameter)
{
ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
return _this.CanExecute(parameter);
}
private void Execute(object parameter)
{
ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
_this.Execute(parameter);
}
}
// This is a set of stub methods implementing the support for the WinRT ICommand_WinRT
// interface on managed objects that support the managed ICommand interface.
// Used by the interop mashaling infrastructure.
// Instances of this are really CCWs of ICommand (not ICommandToWinRTAdapter or any ICommand_WinRT).
internal sealed class ICommandToWinRTAdapter /*: ICommand_WinRT*/
{
private ICommandToWinRTAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
// Since here the class can be an arbitrary implementation of ICommand, we have to keep the EventRegistrationTokenTable's
// separately, associated with the implementations using ConditionalWeakTable.
private static ConditionalWeakTable<ICommand, EventRegistrationTokenTable<EventHandler>> s_weakTable =
new ConditionalWeakTable<ICommand, EventRegistrationTokenTable<EventHandler>>();
// EventRegistrationToken PropertyChanged.add(EventHandler<object> value)
private EventRegistrationToken add_CanExecuteChanged(EventHandler<object> value)
{
ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventHandler handler = ICommandAdapterHelpers.CreateWrapperHandler(value);
EventRegistrationToken token = table.AddEventHandler(handler);
_this.CanExecuteChanged += handler;
return token;
}
// void PropertyChanged.remove(EventRegistrationToken token)
private void remove_CanExecuteChanged(EventRegistrationToken token)
{
ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventHandler handler = table.ExtractHandler(token);
if (handler != null)
{
_this.CanExecuteChanged -= handler;
}
}
private bool CanExecute(object parameter)
{
ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
return _this.CanExecute(parameter);
}
private void Execute(object parameter)
{
ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
_this.Execute(parameter);
}
}
// A couple of ICommand adapter helpers need to be transparent, and so are in their own type
internal static class ICommandAdapterHelpers
{
internal static EventHandler<object> CreateWrapperHandler(EventHandler handler)
{
// Check whether it is a round-tripping case i.e. the sender is of the type eventArgs,
// If so we use it else we pass EventArgs.Empty
return (object sender, object e) =>
{
EventArgs eventArgs = e as EventArgs;
handler(sender, (eventArgs == null ? System.EventArgs.Empty : eventArgs));
};
}
internal static EventHandler CreateWrapperHandler(EventHandler<object> handler)
{
return (object sender, EventArgs e) => handler(sender, e);
}
internal static EventHandler<object> GetValueFromEquivalentKey(
ConditionalWeakTable<EventHandler, EventHandler<object>> table,
EventHandler key,
ConditionalWeakTable<EventHandler, EventHandler<object>>.CreateValueCallback callback)
{
EventHandler<object> value;
// Find the key in the table using a value check rather than an instance check.
EventHandler existingKey = table.FindEquivalentKeyUnsafe(key, out value);
if (existingKey == null)
{
value = callback(key);
table.Add(key, value);
}
return value;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Activation.Diagnostics;
using System.ServiceModel.Channels;
using System.Threading;
class ListenerAdapter : ListenerAdapterBase
{
const string SiteRootPath = "/";
IActivationService activationService;
bool canDispatch;
// Double-checked locking pattern requires volatile for read/write synchronization
volatile bool isOpen;
AutoResetEvent wasConnected;
AutoResetEvent cleanupComplete;
AppManager appManager;
ManualResetEvent initCompleted;
Action<object> closeAllListenerChannelInstancesCallback;
Action<object> launchQueueInstanceCallback;
// CSDMain 190118
// We introduce this int to indicate the current closing status
int closingProcessStatus;
const int ClosingProcessUnBlocked = 0;
const int ClosingProcessBlocked = 1;
const int ClosingProcessUnBlockedByEventOnConfigManagerDisconnected = 2;
internal ListenerAdapter(IActivationService activationService)
: base(activationService.ProtocolName)
{
this.activationService = activationService;
appManager = new AppManager();
}
object ThisLock { get { return this; } }
internal bool CanDispatch { get { return canDispatch; } }
internal override void Open()
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::Open()");
if (!isOpen)
{
lock (ThisLock)
{
if (!isOpen)
{
initCompleted = new ManualResetEvent(false);
base.Open();
initCompleted.WaitOne();
initCompleted.Close();
initCompleted = null;
isOpen = true;
}
}
}
}
internal new void Close()
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::Close()");
if (isOpen)
{
lock (ThisLock)
{
if (isOpen)
{
isOpen = false;
// When calling Cleanup() in the g----ful case, we must wait for all
// OnApplicationPoolAllQueueInstancesStopped callbacks to fire before we can stop
cleanupComplete = new AutoResetEvent(false);
if (!Cleanup(true))
{
// CSDMain 190118
// When the Cleanup(true) returns false, it means we are requesting WAS to close all the existing worker
// process and give us a callback. So the current thread is blocked here.
// In two cases the thread can be unblocked:
// 1. onApplicationPoolAllQueueInstancesStopped function called. That means WAS finished its work and send
// us the notification. This is the normal case.
// 2. onConfigManagerDisconnected function called. That means there's something wrong with WAS and we should
// not wait for the onApplicationPoolAllQueueInstancesStopped call anymore.
Interlocked.Exchange(ref closingProcessStatus, ClosingProcessBlocked);
cleanupComplete.WaitOne(ListenerConstants.ServiceStopTimeout, false);
Interlocked.Exchange(ref closingProcessStatus, ClosingProcessUnBlocked);
}
// base.Close causes WebhostUnregisterProtocol to be called.
base.Close();
}
}
}
}
bool Cleanup(bool closeInstances)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::Cleanup()");
canDispatch = false;
bool completeSelf = true;
if (closeInstances)
{
List<App> existingApps = new List<App>();
List<App> removeApps = new List<App>();
List<App> delayRemoveApps = new List<App>();
lock (appManager)
{
if (appManager.AppsCount != 0)
{
// cleanup for activation service stop: tell WAS about it
existingApps.AddRange(appManager.Apps.Values);
foreach (App app in existingApps)
{
if (app.MessageQueue.HasStartedQueueInstances)
{
delayRemoveApps.Add(app);
}
else
{
removeApps.Add(app);
}
}
existingApps.Clear();
}
}
if (removeApps.Count != 0)
{
foreach (App app in removeApps)
{
RemoveApp(app);
}
}
if (delayRemoveApps.Count != 0)
{
foreach (App app in delayRemoveApps)
{
if (app.PendingAction != null)
{
app.PendingAction.MergeFromDeletedAction();
}
else
{
// Create a new action
app.SetPendingAction(AppAction.CreateDeletedAction());
CloseAllListenerChannelInstances(app);
}
}
completeSelf = false;
}
}
else
{
lock (appManager)
{
appManager.Clear();
}
}
return completeSelf;
}
void CloseAllListenerChannelInstances(App app)
{
int hresult = CloseAllListenerChannelInstances(app.AppPool.AppPoolId, app.MessageQueue.ListenerChannelContext.ListenerChannelId);
Debug.Print("ListenerAdapter[" + ProtocolName + "]::CloseAllListenerChannelInstances(" + app.AppKey + ") returned: " + hresult);
if (hresult == 0)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Information, ListenerTraceCode.WasCloseAllListenerChannelInstances, SR.GetString(SR.TraceCodeWasCloseAllListenerChannelInstances), this);
}
if (TD.WasCloseAllListenerChannelInstancesCompletedIsEnabled())
{
//WasWebHostAPI
TD.WasCloseAllListenerChannelInstancesCompleted(this.EventTraceActivity);
}
}
else
{
if (DiagnosticUtility.ShouldTraceError)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Error, ListenerTraceCode.WasWebHostAPIFailed, SR.GetString(SR.TraceCodeWasWebHostAPIFailed),
new StringTraceRecord("HRESULT", SR.GetString(SR.TraceCodeWasWebHostAPIFailed,
"WebhostCloseAllListenerChannelInstances", hresult.ToString(CultureInfo.CurrentCulture))), this, null);
}
if (TD.WasCloseAllListenerChannelInstancesFailedIsEnabled())
{
//WasWebHostAPIFailed
TD.WasCloseAllListenerChannelInstancesFailed(this.EventTraceActivity, hresult.ToString(CultureInfo.CurrentCulture));
}
}
}
protected override void OnApplicationAppPoolChanged(string appKey, string appPoolId)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationAppPoolChanged(" + appKey + ", " + appPoolId + ")");
try
{
App app = null;
lock (appManager)
{
// The app might have been removed due to the service shutdown.
if (!appManager.Apps.TryGetValue(appKey, out app))
{
return;
}
}
if (app.PendingAction != null)
{
app.PendingAction.MergeFromAppPoolChangedAction(appPoolId);
}
else
{
if (app.MessageQueue.HasStartedQueueInstances)
{
// Create a new action
app.SetPendingAction(AppAction.CreateAppPoolChangedAction(appPoolId));
ScheduleClosingListenerChannelInstances(app);
}
else
{
CompleteAppPoolChange(app, appPoolId);
}
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
internal void CompleteAppPoolChange(App app, string appPoolId)
{
lock (appManager)
{
AppPool appPool;
if (!appManager.AppPools.TryGetValue(appPoolId, out appPool))
{
// The AppPool has been removed
return;
}
if (appPool != app.AppPool)
{
app.AppPool.RemoveApp(app);
appPool.AddApp(app);
app.OnAppPoolChanged(appPool);
}
}
}
protected override void OnApplicationDeleted(string appKey)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationDeleted(" + appKey + ")");
try
{
App app = null;
lock (appManager)
{
// CSDMain 190118
// In some cases WAS will send us duplicated notification for the deletion of a same appKey
if (!appManager.Apps.ContainsKey(appKey))
{
return;
}
app = appManager.Apps[appKey];
}
if (app.PendingAction != null)
{
app.PendingAction.MergeFromDeletedAction();
}
else
{
if (app.MessageQueue.HasStartedQueueInstances)
{
// Creae a new action
app.SetPendingAction(AppAction.CreateDeletedAction());
ScheduleClosingListenerChannelInstances(app);
}
else
{
CompleteDeleteApp(app);
}
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
internal void CompleteDeleteApp(App app)
{
RemoveApp(app);
}
void CompleteAppSettingsChanged(App app)
{
if (app.PendingAction.AppPoolId != null)
{
CompleteAppPoolChange(app, app.PendingAction.AppPoolId);
}
if (app.PendingAction.Path != null)
{
app.Path = app.PendingAction.Path;
}
if (app.PendingAction.Bindings != null)
{
RegisterNewBindings(app, app.PendingAction.Bindings);
}
if (app.PendingAction.RequestsBlocked.HasValue)
{
app.SetRequestBlocked(app.PendingAction.RequestsBlocked.Value);
}
}
void RemoveApp(App app)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::RemoveApp(" + app.AppKey + ")");
lock (appManager)
{
// The App might have been deleted when the AppPool is deleted.
if (appManager.Apps.ContainsKey(app.AppKey))
{
appManager.DeleteApp(app, false);
}
}
}
protected override void OnApplicationBindingsChanged(string appKey, IntPtr bindingsMultiSz, int numberOfBindings)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationBindingsChanged(" + appKey + ")");
string[] bindings = null;
try
{
bindings = base.ParseBindings(bindingsMultiSz, numberOfBindings);
}
catch (ArgumentException exception)
{
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Error);
// Ignore the binding change if WAS provides wrong bindings.
return;
}
App app = null;
lock (appManager)
{
// The app might have been removed due to the service shutdown.
if (!appManager.Apps.TryGetValue(appKey, out app))
{
return;
}
}
try
{
if (app.PendingAction != null)
{
app.PendingAction.MergeFromBindingChangedAction(bindings);
}
else
{
if (app.MessageQueue.HasStartedQueueInstances)
{
app.SetPendingAction(AppAction.CreateBindingsChangedAction(bindings));
ScheduleClosingListenerChannelInstances(app);
}
else
{
RegisterNewBindings(app, bindings);
}
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
internal void RegisterNewBindings(App app, string[] bindings)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::RegisterNewBindings(" + app.AppKey + ")");
// we could be smart-er and leave the bindings that have not changed alone
app.MessageQueue.UnregisterAll();
bool success = RegisterBindings(app.MessageQueue, app.SiteId, bindings, app.Path);
app.OnInvalidBinding(!success);
}
protected override void OnApplicationCreated(string appKey, string path, int siteId, string appPoolId, IntPtr bindingsMultiSz, int numberOfBindings, bool requestsBlocked)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationCreated(" + appKey + ", " + path + ", " + siteId + ", " + appPoolId + ", " + requestsBlocked + ")");
string[] bindings = null;
try
{
bindings = base.ParseBindings(bindingsMultiSz, numberOfBindings);
}
catch (ArgumentException exception)
{
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Error);
// Ignore the app if WAS provides wrong bindings.
return;
}
try
{
bool found = true;
App app = null;
lock (appManager)
{
if (!appManager.Apps.TryGetValue(appKey, out app))
{
found = false;
app = appManager.CreateApp(appKey, path, siteId, appPoolId, requestsBlocked);
}
}
if (found)
{
Fx.Assert(app.PendingAction != null, "The app should be waiting for AllLCStopped notification.");
app.PendingAction.MergeFromCreatedAction(path, siteId, appPoolId, requestsBlocked, bindings);
}
else
{
CompleteAppCreation(app, bindings);
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
void CompleteAppCreation(App app, string[] bindings)
{
IActivatedMessageQueue queue = activationService.CreateQueue(this, app);
app.RegisterQueue(queue);
bool success = RegisterBindings(app.MessageQueue, app.SiteId, bindings, app.Path);
app.OnInvalidBinding(!success);
}
bool RegisterBindings(IActivatedMessageQueue queue, int siteId, string[] bindings, string path)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::RegisterBindings() bindings#: " + bindings.Length);
BaseUriWithWildcard[] baseAddresses = new BaseUriWithWildcard[bindings.Length];
// first make sure all the bindings are valid for this protocol
for (int i = 0; i < bindings.Length; i++)
{
string binding = bindings[i];
int index = binding.IndexOf(':');
string protocol = binding.Substring(0, index);
if (string.Compare(this.ProtocolName, protocol, StringComparison.OrdinalIgnoreCase) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.LAProtocolMismatch, protocol, path, this.ProtocolName)));
}
binding = binding.Substring(index + 1);
try
{
baseAddresses[i] = BaseUriWithWildcard.CreateHostedUri(ProtocolName, binding, path);
Debug.Print("ListenerAdapter[" + ProtocolName + "]::RegisterBindings() CreateUrlFromBinding(binding: " + binding + " path: " + path + ") returned baseAddress: " + baseAddresses[i]);
}
catch (UriFormatException exception)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::RegisterBindings() CreateUrlFromBinding(binding: " + binding + " path: " + path + ") failed with UriFormatException: " + exception.Message);
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Error);
// We only log the event for the site root.
if (string.Compare(path, SiteRootPath, StringComparison.OrdinalIgnoreCase) == 0)
{
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)EventLogCategory.ListenerAdapter,
(uint)EventLogEventId.BindingError,
protocol,
binding,
siteId.ToString(NumberFormatInfo.CurrentInfo),
bindings[i],
ListenerTraceUtility.CreateSourceString(this),
exception.ToString());
}
return false;
}
}
// now make sure all the bindings can be listened on or roll back
for (int i = 0; i < bindings.Length; i++)
{
ListenerExceptionStatus status = ListenerExceptionStatus.FailedToListen;
Exception exception = null;
try
{
status = queue.Register(baseAddresses[i]);
Debug.Print("ListenerAdapter[" + ProtocolName + "]::RegisterBindings() registering baseAddress: " + baseAddresses[i] + " with queue returned: " + status);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Error);
exception = ex;
}
if (status != ListenerExceptionStatus.Success)
{
// We only log the event for the site root.
if (string.Compare(path, SiteRootPath, StringComparison.OrdinalIgnoreCase) == 0)
{
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)EventLogCategory.ListenerAdapter,
(uint)EventLogEventId.LAFailedToListenForApp,
activationService.ActivationServiceName,
ProtocolName,
siteId.ToString(NumberFormatInfo.CurrentInfo),
baseAddresses[i].ToString(),
status.ToString(),
exception == null ? string.Empty : exception.ToString());
}
queue.UnregisterAll();
return false;
}
}
return true;
}
protected override void OnApplicationPoolAllQueueInstancesStopped(string appPoolId, int queueId)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationPoolAllQueueInstancesStopped(" + appPoolId + ", " + queueId + ")");
if (!isOpen)
{
if (closingProcessStatus != ClosingProcessBlocked)
{
// OnConfigManagerDisconnected was already called. We should just return.
return;
}
}
try
{
AppPool appPool = null;
lock (appManager)
{
if (!appManager.AppPools.TryGetValue(appPoolId, out appPool))
{
// Ignore this notification if we received OnApplicationPoolDeleted.
return;
}
}
IActivatedMessageQueue queue = activationService.FindQueue(queueId);
if (queue == null)
{
// This is the belated notification. Ignore it.
return;
}
Fx.Assert(queue.App.AppPool.AppPoolId == appPoolId, "OnApplicationPoolAllQueueInstancesStopped: unexpected pool id");
queue.OnQueueInstancesStopped();
App app = queue.App;
try
{
if (app.PendingAction.ActionType == AppActionType.Deleted)
{
CompleteDeleteApp(app);
SignalCleanupForNoApps();
}
else if (app.PendingAction.ActionType == AppActionType.SettingsChanged)
{
CompleteAppSettingsChanged(app);
}
}
finally
{
// Reset the action
app.SetPendingAction(null);
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
protected override void OnApplicationPoolCanLaunchQueueInstance(string appPoolId, int queueId)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationPoolCanLaunchQueueInstance(" + appPoolId + ", " + queueId + ")");
try
{
IActivatedMessageQueue queue = activationService.FindQueue(queueId);
if (queue != null)
{
if (queue.App.AppPool.AppPoolId != appPoolId)
{
throw Fx.AssertAndThrow("OnApplicationPoolCanLaunchQueueInstance: unexpected pool id");
}
ScheduleLaunchingQueueInstance(queue);
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
protected override void OnApplicationPoolCreated(string appPoolId, SecurityIdentifier sid)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationPoolCreated(" + appPoolId + ", " + sid + ")");
try
{
lock (appManager)
{
appManager.CreateAppPool(appPoolId, sid);
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
protected override void OnApplicationPoolDeleted(string appPoolId)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationPoolDeleted(" + appPoolId + ")");
try
{
lock (appManager)
{
appManager.DeleteAppPool(appPoolId);
}
SignalCleanupForNoApps();
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
protected override void OnApplicationPoolIdentityChanged(string appPoolId, SecurityIdentifier sid)
{
try
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationPoolIdentityChanged(" + appPoolId + ", " + sid + ")");
AppPool appPool = null;
lock (appManager)
{
if (!appManager.AppPools.TryGetValue(appPoolId, out appPool))
{
return;
}
appPool.SetIdentity(sid);
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
protected override void OnApplicationPoolStateChanged(string appPoolId, bool isEnabled)
{
try
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationPoolStateChanged(" + appPoolId + ", " + isEnabled + ")");
AppPool appPool = null;
lock (appManager)
{
if (!appManager.AppPools.TryGetValue(appPoolId, out appPool))
{
return;
}
appPool.SetEnabledState(isEnabled);
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
protected override void OnApplicationRequestsBlockedChanged(string appKey, bool requestsBlocked)
{
try
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnApplicationRequestsBlockedChanged(" + appKey + ", " + requestsBlocked + ")");
App app = null;
lock (appManager)
{
if (!appManager.Apps.TryGetValue(appKey, out app))
{
return;
}
}
if (app.PendingAction != null)
{
app.PendingAction.MergeFromRequestsBlockedAction(requestsBlocked);
}
else
{
app.SetRequestBlocked(requestsBlocked);
}
}
catch (Exception exception)
{
HandleUnknownError(exception);
}
}
protected override void OnConfigManagerConnected()
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnConfigManagerConnected()");
if (DiagnosticUtility.ShouldTraceInformation)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Information, ListenerTraceCode.WasConnected, SR.GetString(SR.TraceCodeWasConnected), this);
}
if (TD.WasConnectedIsEnabled())
{
TD.WasConnected(this.EventTraceActivity);
}
if (wasConnected != null)
{
wasConnected.Set();
}
}
protected override void OnConfigManagerDisconnected(int hresult)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnConfigManagerDisconnected(" + hresult + ") isOpen: " + isOpen);
if (!isOpen)
{
int currentClosingProcessStatus = Interlocked.CompareExchange(ref closingProcessStatus,
ClosingProcessUnBlockedByEventOnConfigManagerDisconnected,
ClosingProcessBlocked);
if (currentClosingProcessStatus == ClosingProcessBlocked)
{
// CSDMain 190118
// According to WAS team, if we receive this call before the call "OnApplicationPoolAllQueueInstancesStopped",
// then we will not receive the call "OnApplicationPoolAllQueueInstancesStopped" ever. So in this case we should
// do cleanup on our side directly.
Cleanup(false);
SignalCleanupForNoApps();
}
return;
}
if (TD.WasDisconnectedIsEnabled())
{
TD.WasDisconnected(this.EventTraceActivity);
}
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Warning,
(ushort)EventLogCategory.ListenerAdapter,
(uint)EventLogEventId.WasDisconnected,
hresult.ToString(CultureInfo.InvariantCulture));
// WAS has crashed.
Cleanup(false);
wasConnected = new AutoResetEvent(false);
ThreadPool.UnsafeRegisterWaitForSingleObject(wasConnected, Fx.ThunkCallback(new WaitOrTimerCallback(WasConnected)), null, ListenerConstants.WasConnectTimeout, true);
}
void WasConnected(object state, bool timedOut)
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::WasConnected() timedOut: " + timedOut);
if (timedOut)
{
// WAS didn't connect within the timeout give up waiting and stop
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Warning,
(ushort)EventLogCategory.ListenerAdapter,
(uint)EventLogEventId.WasConnectionTimedout);
if (TD.WasConnectionTimedoutIsEnabled())
{
TD.WasConnectionTimedout(this.EventTraceActivity);
}
activationService.StopService();
}
wasConnected.Close();
wasConnected = null;
}
protected override void OnConfigManagerInitializationCompleted()
{
Debug.Print("ListenerAdapter[" + ProtocolName + "]::OnConfigManagerInitializationCompleted()");
canDispatch = true;
ManualResetEvent initCompleted = this.initCompleted;
if (initCompleted != null)
{
initCompleted.Set();
}
}
internal bool OpenListenerChannelInstance(IActivatedMessageQueue queue)
{
byte[] queueBlob = queue.ListenerChannelContext.Dehydrate();
Debug.Print("ListenerAdapter[" + ProtocolName + "]::ListenerAdapter.OpenListenerChannelInstance(appPoolId:" + queue.App.AppPool.AppPoolId + " appKey:" + queue.ListenerChannelContext.AppKey + " queueId:" + queue.ListenerChannelContext.ListenerChannelId + ")");
int hresult = OpenListenerChannelInstance(queue.App.AppPool.AppPoolId, queue.ListenerChannelContext.ListenerChannelId, queueBlob);
if (hresult != 0)
{
if (DiagnosticUtility.ShouldTraceError)
{
ListenerTraceUtility.TraceEvent(TraceEventType.Error, ListenerTraceCode.WasWebHostAPIFailed, SR.GetString(SR.TraceCodeWasWebHostAPIFailed),
new StringTraceRecord("HRESULT", SR.GetString(SR.TraceCodeWasWebHostAPIFailed,
"WebhostOpenListenerChannelInstance", hresult.ToString(CultureInfo.CurrentCulture))), this, null);
}
if (TD.OpenListenerChannelInstanceFailedIsEnabled())
{
TD.OpenListenerChannelInstanceFailed(this.EventTraceActivity, hresult.ToString(CultureInfo.CurrentCulture));
}
return false;
}
return true;
}
void ScheduleClosingListenerChannelInstances(App app)
{
if (closeAllListenerChannelInstancesCallback == null)
{
closeAllListenerChannelInstancesCallback = new Action<object>(OnCloseAllListenerChannelInstances);
}
ActionItem.Schedule(closeAllListenerChannelInstancesCallback, app);
}
void OnCloseAllListenerChannelInstances(object state)
{
App app = state as App;
Fx.Assert(app != null, "OnCloseAllListenerChannelInstances: app is null");
CloseAllListenerChannelInstances(app);
}
void ScheduleLaunchingQueueInstance(IActivatedMessageQueue queue)
{
if (launchQueueInstanceCallback == null)
{
launchQueueInstanceCallback = new Action<object>(OnLaunchQueueInstance);
}
ActionItem.Schedule(launchQueueInstanceCallback, queue);
}
void OnLaunchQueueInstance(object state)
{
IActivatedMessageQueue queue = state as IActivatedMessageQueue;
Fx.Assert(queue != null, "OnLaunchQueueInstance: queue is null");
queue.LaunchQueueInstance();
}
void HandleUnknownError(Exception exception)
{
DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
(ushort)EventLogCategory.ListenerAdapter,
(uint)EventLogEventId.UnknownListenerAdapterError,
this.ProtocolName,
exception.ToString());
if (TD.FailFastExceptionIsEnabled())
{
TD.FailFastException(this.EventTraceActivity, exception);
}
// We cannot handle this exception and thus have to terminate the process.
DiagnosticUtility.InvokeFinalHandler(exception);
}
void SignalCleanupForNoApps()
{
if (this.cleanupComplete != null)
{
lock (appManager)
{
if (appManager.AppsCount == 0)
{
// on g----ful cleanup we need to unblock Close() when no app is left running
this.appManager.Clear();
this.cleanupComplete.Set();
}
}
}
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ICartonApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Create a carton
/// </summary>
/// <remarks>
/// Inserts a new carton using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be inserted.</param>
/// <returns>Carton</returns>
Carton AddCarton (Carton body);
/// <summary>
/// Create a carton
/// </summary>
/// <remarks>
/// Inserts a new carton using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be inserted.</param>
/// <returns>ApiResponse of Carton</returns>
ApiResponse<Carton> AddCartonWithHttpInfo (Carton body);
/// <summary>
/// Delete a carton
/// </summary>
/// <remarks>
/// Deletes the carton identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be deleted.</param>
/// <returns></returns>
void DeleteCarton (int? cartonId);
/// <summary>
/// Delete a carton
/// </summary>
/// <remarks>
/// Deletes the carton identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be deleted.</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> DeleteCartonWithHttpInfo (int? cartonId);
/// <summary>
/// Search cartons by filter
/// </summary>
/// <remarks>
/// Returns the list of cartons that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>List<Carton></returns>
List<Carton> GetCartonByFilter (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Search cartons by filter
/// </summary>
/// <remarks>
/// Returns the list of cartons that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>ApiResponse of List<Carton></returns>
ApiResponse<List<Carton>> GetCartonByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Get a carton by id
/// </summary>
/// <remarks>
/// Returns the carton identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be returned.</param>
/// <returns>Carton</returns>
Carton GetCartonById (int? cartonId);
/// <summary>
/// Get a carton by id
/// </summary>
/// <remarks>
/// Returns the carton identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be returned.</param>
/// <returns>ApiResponse of Carton</returns>
ApiResponse<Carton> GetCartonByIdWithHttpInfo (int? cartonId);
/// <summary>
/// Update a carton
/// </summary>
/// <remarks>
/// Updates an existing carton using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be updated.</param>
/// <returns></returns>
void UpdateCarton (Carton body);
/// <summary>
/// Update a carton
/// </summary>
/// <remarks>
/// Updates an existing carton using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be updated.</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> UpdateCartonWithHttpInfo (Carton body);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Create a carton
/// </summary>
/// <remarks>
/// Inserts a new carton using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be inserted.</param>
/// <returns>Task of Carton</returns>
System.Threading.Tasks.Task<Carton> AddCartonAsync (Carton body);
/// <summary>
/// Create a carton
/// </summary>
/// <remarks>
/// Inserts a new carton using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be inserted.</param>
/// <returns>Task of ApiResponse (Carton)</returns>
System.Threading.Tasks.Task<ApiResponse<Carton>> AddCartonAsyncWithHttpInfo (Carton body);
/// <summary>
/// Delete a carton
/// </summary>
/// <remarks>
/// Deletes the carton identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be deleted.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task DeleteCartonAsync (int? cartonId);
/// <summary>
/// Delete a carton
/// </summary>
/// <remarks>
/// Deletes the carton identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be deleted.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> DeleteCartonAsyncWithHttpInfo (int? cartonId);
/// <summary>
/// Search cartons by filter
/// </summary>
/// <remarks>
/// Returns the list of cartons that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of List<Carton></returns>
System.Threading.Tasks.Task<List<Carton>> GetCartonByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Search cartons by filter
/// </summary>
/// <remarks>
/// Returns the list of cartons that match the given filter.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of ApiResponse (List<Carton>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<Carton>>> GetCartonByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null);
/// <summary>
/// Get a carton by id
/// </summary>
/// <remarks>
/// Returns the carton identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be returned.</param>
/// <returns>Task of Carton</returns>
System.Threading.Tasks.Task<Carton> GetCartonByIdAsync (int? cartonId);
/// <summary>
/// Get a carton by id
/// </summary>
/// <remarks>
/// Returns the carton identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be returned.</param>
/// <returns>Task of ApiResponse (Carton)</returns>
System.Threading.Tasks.Task<ApiResponse<Carton>> GetCartonByIdAsyncWithHttpInfo (int? cartonId);
/// <summary>
/// Update a carton
/// </summary>
/// <remarks>
/// Updates an existing carton using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be updated.</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task UpdateCartonAsync (Carton body);
/// <summary>
/// Update a carton
/// </summary>
/// <remarks>
/// Updates an existing carton using the specified data.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be updated.</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> UpdateCartonAsyncWithHttpInfo (Carton body);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class CartonApi : ICartonApi
{
private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="CartonApi"/> class.
/// </summary>
/// <returns></returns>
public CartonApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="CartonApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public CartonApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Infoplus.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Create a carton Inserts a new carton using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be inserted.</param>
/// <returns>Carton</returns>
public Carton AddCarton (Carton body)
{
ApiResponse<Carton> localVarResponse = AddCartonWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Create a carton Inserts a new carton using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be inserted.</param>
/// <returns>ApiResponse of Carton</returns>
public ApiResponse< Carton > AddCartonWithHttpInfo (Carton body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling CartonApi->AddCarton");
var localVarPath = "/v1.0/carton";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("AddCarton", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Carton>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Carton) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Carton)));
}
/// <summary>
/// Create a carton Inserts a new carton using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be inserted.</param>
/// <returns>Task of Carton</returns>
public async System.Threading.Tasks.Task<Carton> AddCartonAsync (Carton body)
{
ApiResponse<Carton> localVarResponse = await AddCartonAsyncWithHttpInfo(body);
return localVarResponse.Data;
}
/// <summary>
/// Create a carton Inserts a new carton using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be inserted.</param>
/// <returns>Task of ApiResponse (Carton)</returns>
public async System.Threading.Tasks.Task<ApiResponse<Carton>> AddCartonAsyncWithHttpInfo (Carton body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling CartonApi->AddCarton");
var localVarPath = "/v1.0/carton";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("AddCarton", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Carton>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Carton) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Carton)));
}
/// <summary>
/// Delete a carton Deletes the carton identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be deleted.</param>
/// <returns></returns>
public void DeleteCarton (int? cartonId)
{
DeleteCartonWithHttpInfo(cartonId);
}
/// <summary>
/// Delete a carton Deletes the carton identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be deleted.</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> DeleteCartonWithHttpInfo (int? cartonId)
{
// verify the required parameter 'cartonId' is set
if (cartonId == null)
throw new ApiException(400, "Missing required parameter 'cartonId' when calling CartonApi->DeleteCarton");
var localVarPath = "/v1.0/carton/{cartonId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (cartonId != null) localVarPathParams.Add("cartonId", Configuration.ApiClient.ParameterToString(cartonId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeleteCarton", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Delete a carton Deletes the carton identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be deleted.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task DeleteCartonAsync (int? cartonId)
{
await DeleteCartonAsyncWithHttpInfo(cartonId);
}
/// <summary>
/// Delete a carton Deletes the carton identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be deleted.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteCartonAsyncWithHttpInfo (int? cartonId)
{
// verify the required parameter 'cartonId' is set
if (cartonId == null)
throw new ApiException(400, "Missing required parameter 'cartonId' when calling CartonApi->DeleteCarton");
var localVarPath = "/v1.0/carton/{cartonId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (cartonId != null) localVarPathParams.Add("cartonId", Configuration.ApiClient.ParameterToString(cartonId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("DeleteCarton", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Search cartons by filter Returns the list of cartons that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>List<Carton></returns>
public List<Carton> GetCartonByFilter (string filter = null, int? page = null, int? limit = null, string sort = null)
{
ApiResponse<List<Carton>> localVarResponse = GetCartonByFilterWithHttpInfo(filter, page, limit, sort);
return localVarResponse.Data;
}
/// <summary>
/// Search cartons by filter Returns the list of cartons that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>ApiResponse of List<Carton></returns>
public ApiResponse< List<Carton> > GetCartonByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null)
{
var localVarPath = "/v1.0/carton/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetCartonByFilter", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<Carton>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<Carton>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Carton>)));
}
/// <summary>
/// Search cartons by filter Returns the list of cartons that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of List<Carton></returns>
public async System.Threading.Tasks.Task<List<Carton>> GetCartonByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null)
{
ApiResponse<List<Carton>> localVarResponse = await GetCartonByFilterAsyncWithHttpInfo(filter, page, limit, sort);
return localVarResponse.Data;
}
/// <summary>
/// Search cartons by filter Returns the list of cartons that match the given filter.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="filter">Query string, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <param name="sort">Sort results by specified field. (optional)</param>
/// <returns>Task of ApiResponse (List<Carton>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<Carton>>> GetCartonByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null)
{
var localVarPath = "/v1.0/carton/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetCartonByFilter", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<Carton>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<Carton>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Carton>)));
}
/// <summary>
/// Get a carton by id Returns the carton identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be returned.</param>
/// <returns>Carton</returns>
public Carton GetCartonById (int? cartonId)
{
ApiResponse<Carton> localVarResponse = GetCartonByIdWithHttpInfo(cartonId);
return localVarResponse.Data;
}
/// <summary>
/// Get a carton by id Returns the carton identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be returned.</param>
/// <returns>ApiResponse of Carton</returns>
public ApiResponse< Carton > GetCartonByIdWithHttpInfo (int? cartonId)
{
// verify the required parameter 'cartonId' is set
if (cartonId == null)
throw new ApiException(400, "Missing required parameter 'cartonId' when calling CartonApi->GetCartonById");
var localVarPath = "/v1.0/carton/{cartonId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (cartonId != null) localVarPathParams.Add("cartonId", Configuration.ApiClient.ParameterToString(cartonId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetCartonById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Carton>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Carton) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Carton)));
}
/// <summary>
/// Get a carton by id Returns the carton identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be returned.</param>
/// <returns>Task of Carton</returns>
public async System.Threading.Tasks.Task<Carton> GetCartonByIdAsync (int? cartonId)
{
ApiResponse<Carton> localVarResponse = await GetCartonByIdAsyncWithHttpInfo(cartonId);
return localVarResponse.Data;
}
/// <summary>
/// Get a carton by id Returns the carton identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="cartonId">Id of the carton to be returned.</param>
/// <returns>Task of ApiResponse (Carton)</returns>
public async System.Threading.Tasks.Task<ApiResponse<Carton>> GetCartonByIdAsyncWithHttpInfo (int? cartonId)
{
// verify the required parameter 'cartonId' is set
if (cartonId == null)
throw new ApiException(400, "Missing required parameter 'cartonId' when calling CartonApi->GetCartonById");
var localVarPath = "/v1.0/carton/{cartonId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (cartonId != null) localVarPathParams.Add("cartonId", Configuration.ApiClient.ParameterToString(cartonId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetCartonById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Carton>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Carton) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Carton)));
}
/// <summary>
/// Update a carton Updates an existing carton using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be updated.</param>
/// <returns></returns>
public void UpdateCarton (Carton body)
{
UpdateCartonWithHttpInfo(body);
}
/// <summary>
/// Update a carton Updates an existing carton using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be updated.</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> UpdateCartonWithHttpInfo (Carton body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling CartonApi->UpdateCarton");
var localVarPath = "/v1.0/carton";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdateCarton", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Update a carton Updates an existing carton using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be updated.</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task UpdateCartonAsync (Carton body)
{
await UpdateCartonAsyncWithHttpInfo(body);
}
/// <summary>
/// Update a carton Updates an existing carton using the specified data.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="body">Carton to be updated.</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdateCartonAsyncWithHttpInfo (Carton body)
{
// verify the required parameter 'body' is set
if (body == null)
throw new ApiException(400, "Missing required parameter 'body' when calling CartonApi->UpdateCarton");
var localVarPath = "/v1.0/carton";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (body != null && body.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
}
else
{
localVarPostBody = body; // byte array
}
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("UpdateCarton", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
}
}
| |
//
// System.Double.cs
//
// Authors:
// Miguel de Icaza ([email protected])
// Bob Smith ([email protected])
// Marek Safar ([email protected])
//
// (C) Ximian, Inc. http://www.ximian.com
// (C) Bob Smith. http://www.thestuff.net
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright (C) 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
namespace System {
[Serializable]
[System.Runtime.InteropServices.ComVisible (true)]
public struct Double : IComparable, IFormattable, IConvertible, IComparable <double>, IEquatable <double>
{
public const double Epsilon = 4.9406564584124650e-324;
public const double MaxValue = 1.7976931348623157e308;
public const double MinValue = -1.7976931348623157e308;
public const double NaN = 0.0d / 0.0d;
public const double NegativeInfinity = -1.0d / 0.0d;
public const double PositiveInfinity = 1.0d / 0.0d;
internal double m_value;
public int CompareTo (object value)
{
if (value == null)
return 1;
if (!(value is System.Double))
throw new ArgumentException (Locale.GetText ("Value is not a System.Double"));
double dv = (double)value;
if (IsPositiveInfinity(m_value) && IsPositiveInfinity(dv))
return 0;
if (IsNegativeInfinity(m_value) && IsNegativeInfinity(dv))
return 0;
if (IsNaN(dv))
if (IsNaN(m_value))
return 0;
else
return 1;
if (IsNaN(m_value))
if (IsNaN(dv))
return 0;
else
return -1;
if (m_value > dv) return 1;
else if (m_value < dv) return -1;
else return 0;
}
public override bool Equals (object obj)
{
if (!(obj is System.Double))
return false;
double value = (double) obj;
if (IsNaN (value))
return IsNaN (m_value);
return (value == m_value);
}
public int CompareTo (double value)
{
if (IsPositiveInfinity(m_value) && IsPositiveInfinity(value))
return 0;
if (IsNegativeInfinity(m_value) && IsNegativeInfinity(value))
return 0;
if (IsNaN(value))
if (IsNaN(m_value))
return 0;
else
return 1;
if (IsNaN(m_value))
if (IsNaN(value))
return 0;
else
return -1;
if (m_value > value) return 1;
else if (m_value < value) return -1;
else return 0;
}
public bool Equals (double obj)
{
if (IsNaN (obj)) {
if (IsNaN(m_value))
return true;
else
return false;
}
return obj == m_value;
}
public override unsafe int GetHashCode ()
{
double d = m_value;
return (*((long*)&d)).GetHashCode ();
}
#if NET_4_0
public static bool operator==(double left, double right)
{
return left == right;
}
public static bool operator!=(double left, double right)
{
return left != right;
}
public static bool operator>(double left, double right)
{
return left > right;
}
public static bool operator>=(double left, double right)
{
return left >= right;
}
public static bool operator<(double left, double right)
{
return left < right;
}
public static bool operator<=(double left, double right)
{
return left <= right;
}
#endif
public static bool IsInfinity (double d)
{
return (d == PositiveInfinity || d == NegativeInfinity);
}
[ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
public static bool IsNaN (double d)
{
#pragma warning disable 1718
return (d != d);
#pragma warning restore
}
public static bool IsNegativeInfinity (double d)
{
return (d < 0.0d && (d == NegativeInfinity || d == PositiveInfinity));
}
public static bool IsPositiveInfinity (double d)
{
return (d > 0.0d && (d == NegativeInfinity || d == PositiveInfinity));
}
public static double Parse (string s)
{
return Parse (s, (NumberStyles.Float | NumberStyles.AllowThousands), null);
}
public static double Parse (string s, IFormatProvider provider)
{
return Parse (s, (NumberStyles.Float | NumberStyles.AllowThousands), provider);
}
public static double Parse (string s, NumberStyles style)
{
return Parse (s, style, null);
}
enum ParseState {
AllowSign = 1,
Digits = 2,
Decimal = 3,
ExponentSign = 4,
Exponent = 5,
ConsumeWhiteSpace = 6,
TrailingSymbols = 7,
Exit = 8
};
public static double Parse (string s, NumberStyles style, IFormatProvider provider)
{
Exception exc;
double result;
if (!Parse (s, style, provider, false, out result, out exc))
throw exc;
return result;
}
// FIXME: check if digits are group in correct numbers between the group separators
internal static bool Parse (string s, NumberStyles style, IFormatProvider provider, bool tryParse, out double result, out Exception exc)
{
result = 0;
exc = null;
if (s == null) {
if (!tryParse)
exc = new ArgumentNullException ("s");
return false;
}
if (s.Length == 0) {
if (!tryParse)
exc = new FormatException ();
return false;
}
// yes it's counter intuitive (buggy?) but even TryParse actually throws in this case
if ((style & NumberStyles.AllowHexSpecifier) != 0) {
string msg = Locale.GetText ("Double doesn't support parsing with '{0}'.", "AllowHexSpecifier");
throw new ArgumentException (msg);
}
if (style > NumberStyles.Any) {
if (!tryParse)
exc = new ArgumentException();
return false;
}
NumberFormatInfo format = NumberFormatInfo.GetInstance(provider);
if (format == null) throw new Exception("How did this happen?");
//
// validate and prepare string for C
//
int len = s.Length;
int didx = 0;
int sidx = 0;
char c;
bool allow_leading_white = (style & NumberStyles.AllowLeadingWhite) != 0;
bool allow_trailing_white = ((style & NumberStyles.AllowTrailingWhite) != 0);
if (allow_leading_white) {
while (sidx < len && Char.IsWhiteSpace (s [sidx]))
sidx++;
if (sidx == len) {
if (!tryParse)
exc = Int32.GetFormatException ();
return false;
}
}
int sEndPos = s.Length - 1;
if (allow_trailing_white)
while (Char.IsWhiteSpace (s [sEndPos]))
sEndPos--;
if (TryParseStringConstant (format.NaNSymbol, s, sidx, sEndPos)) {
result = double.NaN;
return true;
}
if (TryParseStringConstant (format.PositiveInfinitySymbol, s, sidx, sEndPos)) {
result = double.PositiveInfinity;
return true;
}
if (TryParseStringConstant (format.NegativeInfinitySymbol, s, sidx, sEndPos)) {
result = double.NegativeInfinity;
return true;
}
byte [] b = new byte [len + 1];
//
// Machine state
//
var state = ParseState.AllowSign;
//
// Setup
//
string decimal_separator = null;
string group_separator = null;
string currency_symbol = null;
int decimal_separator_len = 0;
int group_separator_len = 0;
int currency_symbol_len = 0;
if ((style & NumberStyles.AllowDecimalPoint) != 0){
decimal_separator = format.NumberDecimalSeparator;
decimal_separator_len = decimal_separator.Length;
}
if ((style & NumberStyles.AllowThousands) != 0){
group_separator = format.NumberGroupSeparator;
group_separator_len = group_separator.Length;
}
if ((style & NumberStyles.AllowCurrencySymbol) != 0){
currency_symbol = format.CurrencySymbol;
currency_symbol_len = currency_symbol.Length;
}
string positive = format.PositiveSign;
string negative = format.NegativeSign;
bool allow_trailing_parenthes = false;
for (; sidx < len; sidx++){
c = s [sidx];
if (c == '\0') {
sidx = len;
continue;
}
switch (state){
case ParseState.AllowSign:
if ((style & NumberStyles.AllowLeadingSign) != 0) {
if (c == positive [0] &&
s.Substring (sidx, positive.Length) == positive) {
state = ParseState.Digits;
sidx += positive.Length - 1;
continue;
}
if (c == negative [0] &&
s.Substring (sidx, negative.Length) == negative) {
state = ParseState.Digits;
b [didx++] = (byte)'-';
sidx += negative.Length - 1;
continue;
}
}
if ((style & NumberStyles.AllowParentheses) != 0 && c == '(') {
b [didx++] = (byte)'-';
state = ParseState.Digits;
allow_trailing_parenthes = true;
continue;
}
state = ParseState.Digits;
goto case ParseState.Digits;
case ParseState.Digits:
if (Char.IsDigit (c)) {
b [didx++] = (byte)c;
break;
}
if (c == 'e' || c == 'E')
goto case ParseState.Decimal;
if (allow_trailing_parenthes && c == ')') {
allow_trailing_parenthes = false;
state = ParseState.ConsumeWhiteSpace;
continue;
}
if (decimal_separator_len > 0 &&
decimal_separator [0] == c) {
if (String.CompareOrdinal (s, sidx, decimal_separator, 0, decimal_separator_len) == 0) {
b [didx++] = (byte)'.';
sidx += decimal_separator_len - 1;
state = ParseState.Decimal;
break;
}
}
if (group_separator_len > 0 &&
group_separator [0] == c) {
if (s.Substring (sidx, group_separator_len) ==
group_separator) {
sidx += group_separator_len - 1;
break;
}
}
if (currency_symbol_len > 0 &&
currency_symbol [0] == c) {
if (s.Substring (sidx, currency_symbol_len) ==
currency_symbol) {
sidx += currency_symbol_len - 1;
currency_symbol_len = 0;
break;
}
}
state = ParseState.TrailingSymbols;
goto case ParseState.TrailingSymbols;
case ParseState.Decimal:
if (Char.IsDigit (c)){
b [didx++] = (byte) c;
break;
}
if (c == 'e' || c == 'E'){
if ((style & NumberStyles.AllowExponent) == 0) {
if (!tryParse)
exc = new FormatException ("Unknown char: " + c);
return false;
}
b [didx++] = (byte) c;
state = ParseState.ExponentSign;
break;
}
state = ParseState.TrailingSymbols;
goto case ParseState.TrailingSymbols;
case ParseState.ExponentSign:
if (Char.IsDigit (c)){
state = ParseState.Exponent;
goto case ParseState.Exponent;
}
if (c == positive [0] &&
s.Substring (sidx, positive.Length) == positive){
state = ParseState.Digits;
sidx += positive.Length-1;
continue;
}
if (c == negative [0] &&
s.Substring (sidx, negative.Length) == negative){
state = ParseState.Digits;
b [didx++] = (byte) '-';
sidx += negative.Length-1;
continue;
}
goto case ParseState.ConsumeWhiteSpace;
case ParseState.Exponent:
if (Char.IsDigit (c)){
b [didx++] = (byte) c;
break;
}
state = ParseState.TrailingSymbols;
goto case ParseState.TrailingSymbols;
case ParseState.TrailingSymbols:
if ((style & NumberStyles.AllowTrailingSign) != 0) {
if (positive != null && c == positive [0] &&
s.Substring (sidx, positive.Length) == positive) {
state = ParseState.ConsumeWhiteSpace;
sidx += positive.Length - 1;
allow_trailing_parenthes = false;
positive = null;
continue;
}
if (negative != null && c == negative [0] &&
s.Substring (sidx, negative.Length) == negative) {
state = ParseState.ConsumeWhiteSpace;
Array.Copy (b, 0, b, 1, didx);
b [0] = (byte)'-';
++didx;
sidx += negative.Length - 1;
allow_trailing_parenthes = false;
negative = null;
continue;
}
}
if (currency_symbol_len > 0 &&
currency_symbol [0] == c) {
if (s.Substring (sidx, currency_symbol_len) ==
currency_symbol) {
sidx += currency_symbol_len - 1;
currency_symbol_len = 0;
break;
}
}
if (allow_trailing_white && Char.IsWhiteSpace (c)) {
break;
}
goto case ParseState.ConsumeWhiteSpace;
case ParseState.ConsumeWhiteSpace:
if (allow_trailing_parenthes && c == ')') {
allow_trailing_parenthes = false;
state = ParseState.ConsumeWhiteSpace;
break;
}
if (allow_trailing_white && Char.IsWhiteSpace (c)) {
state = ParseState.ConsumeWhiteSpace;
break;
}
if (!tryParse)
exc = new FormatException ("Unknown char");
return false;
}
if (state == ParseState.Exit)
break;
}
b [didx] = 0;
unsafe {
fixed (cpp::uint8_t* p = &b [0]){
double retVal;
if (!ParseImpl (p, out retVal)) {
if (!tryParse)
exc = Int32.GetFormatException ();
return false;
}
if (IsPositiveInfinity(retVal) || IsNegativeInfinity(retVal)) {
if (!tryParse)
exc = new OverflowException ();
return false;
}
result = retVal;
return true;
}
}
}
static bool TryParseStringConstant (string format, string s, int start, int end)
{
return end - start + 1 == format.Length && String.CompareOrdinal (format, 0, s, start, format.Length) == 0;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private static extern bool ParseImpl (cpp::uint8_t* byte_ptr, out double value);
public static bool TryParse (string s,
NumberStyles style,
IFormatProvider provider,
out double result)
{
Exception exc;
if (!Parse (s, style, provider, true, out result, out exc)) {
result = 0;
return false;
}
return true;
}
public static bool TryParse (string s, out double result)
{
return TryParse (s, NumberStyles.Any, null, out result);
}
public override string ToString ()
{
return NumberFormatter.NumberToString (m_value, null);
}
public string ToString (IFormatProvider provider)
{
return NumberFormatter.NumberToString (m_value, provider);
}
public string ToString (string format)
{
return ToString (format, null);
}
public string ToString (string format, IFormatProvider provider)
{
return NumberFormatter.NumberToString (format, m_value, provider);
}
// =========== IConvertible Methods =========== //
public TypeCode GetTypeCode ()
{
return TypeCode.Double;
}
object IConvertible.ToType (Type targetType, IFormatProvider provider)
{
if (targetType == null)
throw new ArgumentNullException ("targetType");
return System.Convert.ToType (m_value, targetType, provider, false);
}
bool IConvertible.ToBoolean (IFormatProvider provider)
{
return System.Convert.ToBoolean (m_value);
}
byte IConvertible.ToByte (IFormatProvider provider)
{
return System.Convert.ToByte (m_value);
}
char IConvertible.ToChar (IFormatProvider provider)
{
throw new InvalidCastException ();
}
DateTime IConvertible.ToDateTime (IFormatProvider provider)
{
throw new InvalidCastException ();
}
decimal IConvertible.ToDecimal (IFormatProvider provider)
{
return System.Convert.ToDecimal (m_value);
}
double IConvertible.ToDouble (IFormatProvider provider)
{
return System.Convert.ToDouble (m_value);
}
short IConvertible.ToInt16 (IFormatProvider provider)
{
return System.Convert.ToInt16 (m_value);
}
int IConvertible.ToInt32 (IFormatProvider provider)
{
return System.Convert.ToInt32 (m_value);
}
long IConvertible.ToInt64 (IFormatProvider provider)
{
return System.Convert.ToInt64 (m_value);
}
sbyte IConvertible.ToSByte (IFormatProvider provider)
{
return System.Convert.ToSByte (m_value);
}
float IConvertible.ToSingle (IFormatProvider provider)
{
return System.Convert.ToSingle (m_value);
}
ushort IConvertible.ToUInt16 (IFormatProvider provider)
{
return System.Convert.ToUInt16 (m_value);
}
uint IConvertible.ToUInt32 (IFormatProvider provider)
{
return System.Convert.ToUInt32 (m_value);
}
ulong IConvertible.ToUInt64 (IFormatProvider provider)
{
return System.Convert.ToUInt64 (m_value);
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using Inform;
using Xenosynth.Modules;
namespace Xenosynth.Web.UI {
/// <summary>
/// A CmsFile type.
/// </summary>
public class CmsFileType {
[MemberMapping(PrimaryKey=true, ColumnName="ID")]
private Guid _id;
[MemberMapping(ColumnName = "ModuleID")]
private Guid _moduleID;
[MemberMapping(ColumnName="Name", Length=50)]
private string _name;
[MemberMapping(ColumnName="Description", Length=250)]
private string _description;
[MemberMapping(ColumnName = "IsDirectory")]
private bool _isDirectory;
[MemberMapping(ColumnName = "IsVersioned")]
private bool _isVersioned;
[MemberMapping(ColumnName = "IsContentType")]
private bool _isContentType;
[MemberMapping(ColumnName="EditUrl", Length=250)]
private string _editUrl;
[MemberMapping(ColumnName = "CreateUrl", Length = 250)]
private string _createUrl;
[MemberMapping(ColumnName = "BrowseUrl", Length = 250)]
private string _browseUrl;
[MemberMapping(ColumnName = "DefaultAction")]
private Action _defaultAction;
/// <summary>
/// CmsFile admin actions.
/// </summary>
public enum Action {
Create = 1,
Edit = 2,
Browse = 3,
View = 4
}
/// <summary>
/// The unique identifier for the CmsFileType.
/// </summary>
public Guid ID {
get { return _id; }
}
/// <summary>
/// The module ID that creates this CmsFileType.
/// </summary>
public Guid ModuleID {
get { return _moduleID; }
}
/// <summary>
/// The registered module creates this CmsFileType belongs.
/// </summary>
public RegisteredModule Module {
get { return XenosynthContext.Current.Modules[ModuleID]; }
}
/// <summary>
/// Whether this CmsFileType is versioned.
/// </summary>
public bool IsVersioned {
get { return _isVersioned; }
}
/// <summary>
/// Whether this CmsFileType is a directory.
/// </summary>
public bool IsDirectory {
get { return _isDirectory; }
}
/// <summary>
/// The name of this CmsFileType.
/// </summary>
public string Name {
get { return _name; }
}
/// <summary>
/// A description of this CmsFileType.
/// </summary>
public string Description {
get { return _description; }
}
/// <summary>
/// The URL for the admin page to create this CmsFileType.
/// </summary>
public string CreateUrl {
get { return _createUrl; }
}
/// <summary>
/// The URL for the admin page to edit this CmsFileType.
/// </summary>
public string EditUrl {
get { return _editUrl; }
}
/// <summary>
/// The URL for the admin page to browse this CmsFileType.
/// </summary>
public string BrowseUrl {
get { return _browseUrl; }
}
/// <summary>
/// The URL for the admin page of the default action for this CmsFileType.
/// </summary>
public Action DefaultAction {
get { return _defaultAction; }
}
/// <summary>
/// The css class for this file in the admin.
/// </summary>
public string CssClass {
get {
if (_name != null) {
return _name.ToLower().Replace(" ", "");
} else {
return string.Empty;
}
}
}
/// <summary>
/// If this is a directory, the CmsFileTypes that are allowed.
/// </summary>
public IList AllowedFileTypes {
get { return FindAllowedTypes(this.ID); }
}
public CmsFileType() {
}
public CmsFileType(Guid id, Guid moduleID, String name, String description, bool isDirectory, String createUrl, String editUrl, String browseUrl) {
_id = id;
_moduleID = moduleID;
_name = name;
_description = description;
_isDirectory = isDirectory;
_createUrl = createUrl;
_editUrl = editUrl;
_browseUrl = browseUrl;
}
/// <summary>
/// Insert this CmsFileType in the database.
/// </summary>
public void Insert() {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
ds.Insert(this);
}
/// <summary>
/// Update this CmsFileType in the database.
/// </summary>
public void Update() {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
ds.Update(this);
}
/// <summary>
/// Delete this CmsFileType in the database.
/// </summary>
public void Delete() {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
ds.Delete(this);
}
/// <summary>
/// Find this CmsFileType by ID.
/// </summary>
public static CmsFileType FindByID(Guid id) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
return (CmsFileType)ds.FindByPrimaryKey(typeof(CmsFileType), id);
}
/// <summary>
/// Gets the list of CmsFileTypes that are allowed if this is a directory.
/// </summary>
/// <param name="fileTypeID">
/// A <see cref="Guid"/>
/// </param>
/// <returns>
/// A <see cref="IList"/>
/// </returns>
public static IList FindAllowedTypes(Guid fileTypeID) {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindCollectionCommand cmd = ds.CreateFindCollectionCommand(typeof(CmsFileType), "INNER JOIN CmsFileTypeAllowedTypes ON CmsFileTypes.ID = CmsFileTypeAllowedTypes.FileTypeID WHERE DirectoryTypeID = @DirectoryTypeID ORDER BY CmsFileTypeAllowedTypes.SortOrder");
cmd.CreateInputParameter("@DirectoryTypeID", fileTypeID);
return cmd.Execute();
}
/// <summary>
/// Finds all CmsFileTypes.
/// </summary>
/// <returns>
/// A <see cref="IList"/>
/// </returns>
public static IList FindAll() {
DataStore ds = DataStoreServices.GetDataStore("Xenosynth");
IFindCollectionCommand cmd = ds.CreateFindCollectionCommand(typeof(CmsFileType), "ORDER BY Name");
return cmd.Execute();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace InvestmentApi.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using FileHelpers;
namespace FileHelpersSamples
{
/// <summary>
/// Base class for the other forms.
/// has the banner bar and footer bar on it
/// </summary>
/// <remarks>
/// Has some logic for links and other things in here.
/// </remarks>
public class frmFather : Form
{
private PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox2;
private Panel panel1;
private LinkLabel linkLabel1;
private LinkLabel linkLabel2;
private PictureBox pictureBox3;
private System.Windows.Forms.LinkLabel linkLabel3;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
public frmFather()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing) {
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmFather));
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.panel1 = new System.Windows.Forms.Panel();
this.linkLabel3 = new System.Windows.Forms.LinkLabel();
this.linkLabel2 = new System.Windows.Forms.LinkLabel();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.pictureBox3 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Cursor = System.Windows.Forms.Cursors.Hand;
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(333, 51);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
//
// pictureBox2
//
this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image")));
this.pictureBox2.Location = new System.Drawing.Point(288, 0);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(512, 51);
this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox2.TabIndex = 1;
this.pictureBox2.TabStop = false;
//
// panel1
//
this.panel1.Controls.Add(this.linkLabel3);
this.panel1.Controls.Add(this.linkLabel2);
this.panel1.Controls.Add(this.linkLabel1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 358);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(592, 24);
this.panel1.TabIndex = 2;
this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);
//
// linkLabel3
//
this.linkLabel3.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.linkLabel3.BackColor = System.Drawing.Color.Transparent;
this.linkLabel3.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkLabel3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(150)))), ((int)(((byte)(50)))), ((int)(((byte)(0)))));
this.linkLabel3.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabel3.LinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(150)))), ((int)(((byte)(50)))), ((int)(((byte)(0)))));
this.linkLabel3.Location = new System.Drawing.Point(268, 4);
this.linkLabel3.Name = "linkLabel3";
this.linkLabel3.Size = new System.Drawing.Size(80, 16);
this.linkLabel3.TabIndex = 102;
this.linkLabel3.TabStop = true;
this.linkLabel3.Text = "Devoo Soft";
this.linkLabel3.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel3_LinkClicked);
//
// linkLabel2
//
this.linkLabel2.BackColor = System.Drawing.Color.Transparent;
this.linkLabel2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkLabel2.LinkBehavior = System.Windows.Forms.LinkBehavior.NeverUnderline;
this.linkLabel2.LinkColor = System.Drawing.Color.Black;
this.linkLabel2.Location = new System.Drawing.Point(2, 6);
this.linkLabel2.Name = "linkLabel2";
this.linkLabel2.Size = new System.Drawing.Size(158, 16);
this.linkLabel2.TabIndex = 100;
this.linkLabel2.TabStop = true;
this.linkLabel2.Text = "(c) 2005-07 to Marcos Meli";
this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
//
// linkLabel1
//
this.linkLabel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.linkLabel1.BackColor = System.Drawing.Color.Transparent;
this.linkLabel1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkLabel1.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabel1.LinkColor = System.Drawing.Color.Black;
this.linkLabel1.Location = new System.Drawing.Point(464, 6);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(136, 16);
this.linkLabel1.TabIndex = 101;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "www.filehelpers.net";
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// pictureBox3
//
this.pictureBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox3.Cursor = System.Windows.Forms.Cursors.Hand;
this.pictureBox3.Image = global::FileHelpersSamples.Properties.Resources.donate;
this.pictureBox3.Location = new System.Drawing.Point(339, 4);
this.pictureBox3.Name = "pictureBox3";
this.pictureBox3.Size = new System.Drawing.Size(85, 40);
this.pictureBox3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox3.TabIndex = 3;
this.pictureBox3.TabStop = false;
this.pictureBox3.Click += new System.EventHandler(this.pictureBox3_Click);
//
// frmFather
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(592, 382);
this.Controls.Add(this.pictureBox3);
this.Controls.Add(this.panel1);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.pictureBox2);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "frmFather";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "FileHelpers - Demos";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Color mColor1 = Color.FromArgb(30, 110, 175);
private Color mColor2 = Color.FromArgb(20, 50, 130);
protected override void OnPaint(PaintEventArgs e)
{
LinearGradientBrush b = new LinearGradientBrush(this.ClientRectangle,
// Color.FromArgb(120, 180, 250), Color.FromArgb(10, 35, 100), LinearGradientMode.ForwardDiagonal);
Color1,
Color2,
LinearGradientMode.BackwardDiagonal);
e.Graphics.FillRectangle(b, e.ClipRectangle);
b.Dispose();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
LinearGradientBrush b = new LinearGradientBrush(panel1.ClientRectangle,
SystemColors.Control,
Color.DarkGray,
LinearGradientMode.Vertical);
e.Graphics.FillRectangle(b, e.ClipRectangle);
e.Graphics.DrawLine(Pens.DimGray, 0, 0, panel1.Width, 0);
b.Dispose();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ProcessStartInfo info = new ProcessStartInfo("explorer", "\"http://www.filehelpers.net\"");
info.CreateNoWindow = false;
info.UseShellExecute = true;
Process.Start(info);
}
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ProcessStartInfo info = new ProcessStartInfo("explorer",
"https://github.com/MarcosMeli/FileHelpers/issues/new");
info.CreateNoWindow = true;
info.UseShellExecute = true;
Process.Start(info);
}
private DateTime mLastOpen = DateTime.Today.AddDays(-1);
private void pictureBox1_Click(object sender, EventArgs e)
{
if (DateTime.Now > mLastOpen.AddSeconds(10)) {
Process.Start("explorer", "\"http://www.filehelpers.net\"");
mLastOpen = DateTime.Now;
}
}
private void pictureBox3_Click(object sender, System.EventArgs e)
{
Process.Start("explorer", "\"http://www.filehelpers.net/donate/\"");
}
private bool mExitOnEsc = true;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (mExitOnEsc && keyData == Keys.Escape) {
this.Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void linkLabel3_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
ProcessStartInfo info = new ProcessStartInfo("explorer", "\"http://www.devoo.net\"");
Process.Start(info);
}
public bool ExitOnEsc
{
get { return mExitOnEsc; }
set { mExitOnEsc = value; }
}
public Color Color1
{
get { return mColor1; }
set
{
mColor1 = value;
this.Invalidate();
}
}
public Color Color2
{
get { return mColor2; }
set
{
mColor2 = value;
this.Invalidate();
}
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using NUnit.Util;
namespace NUnit.UiKit
{
/// <summary>
/// ConfigurationEditor form is designed for adding, deleting
/// and renaming configurations from a project.
/// </summary>
public class ConfigurationEditor : System.Windows.Forms.Form
{
#region Instance Variables
private NUnitProject project;
private int selectedIndex = -1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.ListBox configListBox;
private System.Windows.Forms.Button removeButton;
private System.Windows.Forms.Button renameButton;
private System.Windows.Forms.Button addButton;
private System.Windows.Forms.Button activeButton;
private System.Windows.Forms.HelpProvider helpProvider1;
private System.Windows.Forms.Button closeButton;
#endregion
#region Construction and Disposal
public ConfigurationEditor( NUnitProject project )
{
InitializeComponent();
this.project = project;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ConfigurationEditor));
this.configListBox = new System.Windows.Forms.ListBox();
this.removeButton = new System.Windows.Forms.Button();
this.renameButton = new System.Windows.Forms.Button();
this.closeButton = new System.Windows.Forms.Button();
this.addButton = new System.Windows.Forms.Button();
this.activeButton = new System.Windows.Forms.Button();
this.helpProvider1 = new System.Windows.Forms.HelpProvider();
this.SuspendLayout();
//
// configListBox
//
this.helpProvider1.SetHelpString(this.configListBox, "Selects the configuration to operate on.");
this.configListBox.ItemHeight = 16;
this.configListBox.Location = new System.Drawing.Point(8, 8);
this.configListBox.Name = "configListBox";
this.helpProvider1.SetShowHelp(this.configListBox, true);
this.configListBox.Size = new System.Drawing.Size(168, 212);
this.configListBox.TabIndex = 0;
this.configListBox.SelectedIndexChanged += new System.EventHandler(this.configListBox_SelectedIndexChanged);
//
// removeButton
//
this.helpProvider1.SetHelpString(this.removeButton, "Removes the selected configuration");
this.removeButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.removeButton.Location = new System.Drawing.Point(192, 8);
this.removeButton.Name = "removeButton";
this.helpProvider1.SetShowHelp(this.removeButton, true);
this.removeButton.Size = new System.Drawing.Size(96, 32);
this.removeButton.TabIndex = 1;
this.removeButton.Text = "&Remove";
this.removeButton.Click += new System.EventHandler(this.removeButton_Click);
//
// renameButton
//
this.helpProvider1.SetHelpString(this.renameButton, "Allows renaming the selected configuration");
this.renameButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.renameButton.Location = new System.Drawing.Point(192, 48);
this.renameButton.Name = "renameButton";
this.helpProvider1.SetShowHelp(this.renameButton, true);
this.renameButton.Size = new System.Drawing.Size(96, 32);
this.renameButton.TabIndex = 2;
this.renameButton.Text = "Re&name";
this.renameButton.Click += new System.EventHandler(this.renameButton_Click);
//
// closeButton
//
this.closeButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.helpProvider1.SetHelpString(this.closeButton, "Closes this dialog");
this.closeButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.closeButton.Location = new System.Drawing.Point(192, 216);
this.closeButton.Name = "closeButton";
this.helpProvider1.SetShowHelp(this.closeButton, true);
this.closeButton.Size = new System.Drawing.Size(96, 32);
this.closeButton.TabIndex = 4;
this.closeButton.Text = "Close";
this.closeButton.Click += new System.EventHandler(this.okButton_Click);
//
// addButton
//
this.helpProvider1.SetHelpString(this.addButton, "Allows adding a new configuration");
this.addButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.addButton.Location = new System.Drawing.Point(192, 88);
this.addButton.Name = "addButton";
this.helpProvider1.SetShowHelp(this.addButton, true);
this.addButton.Size = new System.Drawing.Size(96, 32);
this.addButton.TabIndex = 5;
this.addButton.Text = "&Add...";
this.addButton.Click += new System.EventHandler(this.addButton_Click);
//
// activeButton
//
this.helpProvider1.SetHelpString(this.activeButton, "Makes the selected configuration active");
this.activeButton.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.activeButton.Location = new System.Drawing.Point(192, 128);
this.activeButton.Name = "activeButton";
this.helpProvider1.SetShowHelp(this.activeButton, true);
this.activeButton.Size = new System.Drawing.Size(96, 32);
this.activeButton.TabIndex = 6;
this.activeButton.Text = "&Make Active";
this.activeButton.Click += new System.EventHandler(this.activeButton_Click);
//
// ConfigurationEditor
//
this.AcceptButton = this.closeButton;
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.CancelButton = this.closeButton;
this.ClientSize = new System.Drawing.Size(297, 267);
this.Controls.Add(this.activeButton);
this.Controls.Add(this.addButton);
this.Controls.Add(this.closeButton);
this.Controls.Add(this.renameButton);
this.Controls.Add(this.removeButton);
this.Controls.Add(this.configListBox);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.HelpButton = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ConfigurationEditor";
this.helpProvider1.SetShowHelp(this, false);
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "ConfigurationEditor";
this.Load += new System.EventHandler(this.ConfigurationEditor_Load);
this.ResumeLayout(false);
}
#endregion
#region UI Event Handlers
private void ConfigurationEditor_Load(object sender, System.EventArgs e)
{
FillListBox();
if ( configListBox.Items.Count > 0 )
configListBox.SelectedIndex = selectedIndex = 0;
}
private void removeButton_Click(object sender, System.EventArgs e)
{
if ( project.Configs.Count == 1 )
{
string msg = "Removing the last configuration will make the project unloadable until you add another configuration.\r\rAre you sure you want to remove the configuration?";
if( UserMessage.Ask( msg, "Remove Configuration" ) == DialogResult.No )
return;
}
project.Configs.RemoveAt( selectedIndex );
FillListBox();
}
private void renameButton_Click(object sender, System.EventArgs e)
{
RenameConfiguration( project.Configs[selectedIndex].Name );
}
private void addButton_Click(object sender, System.EventArgs e)
{
using( AddConfigurationDialog dlg = new AddConfigurationDialog( project ) )
{
this.Site.Container.Add( dlg );
if ( dlg.ShowDialog() == DialogResult.OK )
FillListBox();
}
}
private void activeButton_Click(object sender, System.EventArgs e)
{
project.SetActiveConfig( selectedIndex );
//AppUI.TestLoader.LoadConfig( project.Configs[selectedIndex].Name );
FillListBox();
}
private void okButton_Click(object sender, System.EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void configListBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
selectedIndex = configListBox.SelectedIndex;
activeButton.Enabled = selectedIndex >= 0 && project.Configs[selectedIndex].Name != project.ActiveConfigName;
renameButton.Enabled = addButton.Enabled = selectedIndex >= 0;
removeButton.Enabled = selectedIndex >= 0 && configListBox.Items.Count > 0;
}
#endregion
#region Helper Methods
private void RenameConfiguration( string oldName )
{
using( RenameConfigurationDialog dlg =
new RenameConfigurationDialog( project, oldName ) )
{
this.Site.Container.Add( dlg );
if ( dlg.ShowDialog() == DialogResult.OK )
{
project.Configs[oldName].Name = dlg.ConfigurationName;
FillListBox();
}
}
}
private void FillListBox()
{
configListBox.Items.Clear();
int count = 0;
foreach( ProjectConfig config in project.Configs )
{
string name = config.Name;
if ( name == project.ActiveConfigName )
name += " (active)";
configListBox.Items.Add( name );
count++;
}
if ( count > 0 )
{
if( selectedIndex >= count )
selectedIndex = count - 1;
configListBox.SelectedIndex = selectedIndex;
}
else selectedIndex = -1;
}
#endregion
}
}
| |
#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.Reflection;
using System.Globalization;
using System.Collections.Generic;
namespace System
{
public static partial class ParserEx
{
#region Registration
//private static readonly Type s_objectParserBuilderType = typeof(IObjectParserBuilder);
private static Dictionary<Type, object> s_objectParserProviders = null;
public interface IObjectParserBuilder
{
IObjectParser<TResult> Build<TResult>();
}
public interface IObjectParser
{
object Parse2(object value, object defaultValue, Nattrib attrib);
bool Validate(object value, Nattrib attrib);
}
public interface IObjectParser<TResult> : IObjectParser
{
TResult Parse(object value, TResult defaultValue, Nattrib attrib);
bool TryParse(object value, Nattrib attrib, out TResult validValue);
}
public static void RegisterObjectParser<T>(object objectParser) { RegisterObjectParser(typeof(T), objectParser); }
public static void RegisterObjectParser(Type key, object objectParser)
{
if (s_objectParserProviders == null)
s_objectParserProviders = new Dictionary<Type, object>();
s_objectParserProviders.Add(key, objectParser);
}
private static bool TryScanForObjectParser<TResult>(out Type key, out IObjectParser<TResult> objectParser)
{
key = null; objectParser = null; return false;
//var interfaces = type.FindInterfaces(((m, filterCriteria) => m == s_objectParserBuilderType), null);
//throw new NotImplementedException();
}
private static IObjectParser ScanForObjectParser(Type type)
{
if (s_objectParserProviders != null)
foreach (var objectParser2 in s_objectParserProviders)
if ((type == objectParser2.Key) || (type.IsSubclassOf(objectParser2.Key)))
return (objectParser2.Value as IObjectParser);
return null;
}
private static IObjectParser<TResult> ScanForObjectParser<TResult>(Type type)
{
if (s_objectParserProviders != null)
foreach (var objectParser2 in s_objectParserProviders)
if ((type == objectParser2.Key) || (type.IsSubclassOf(objectParser2.Key)))
return (objectParser2.Value as IObjectParser<TResult>);
Type key;
IObjectParser<TResult> objectParser;
if (TryScanForObjectParser<TResult>(out key, out objectParser))
{
RegisterObjectParser(key, objectParser);
return objectParser;
}
return null;
}
#endregion
internal static class ObjectParserDelegateFactory<T, TResult>
{
private static readonly Type s_type = typeof(T);
private static readonly MethodInfo s_tryParseMethodInfo = s_type.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, null, new Type[] { CoreExInternal.StringType, s_type.MakeByRefType() }, null);
public static readonly Func<object, TResult, Nattrib, TResult> Parse = CreateParser(s_type);
public static readonly Func<object, object, Nattrib, object> Parse2 = CreateParser2(s_type);
public static readonly TryFunc<object, Nattrib, TResult> TryParse = CreateTryParser(s_type);
public static readonly Func<object, Nattrib, bool> Validate = CreateValidator(s_type);
static ObjectParserDelegateFactory() { }
private static Func<object, TResult, Nattrib, TResult> CreateParser(Type type)
{
if (type == CoreExInternal.BoolType)
return (Func<object, TResult, Nattrib, TResult>)Delegate.CreateDelegate(typeof(Func<object, TResult, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("Parser_Bool", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.NBoolType)
return (Func<object, TResult, Nattrib, TResult>)Delegate.CreateDelegate(typeof(Func<object, TResult, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("Parser_NBool", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.DateTimeType)
return (Func<object, TResult, Nattrib, TResult>)Delegate.CreateDelegate(typeof(Func<object, TResult, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("Parser_DateTime", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.NDateTimeType)
return (Func<object, TResult, Nattrib, TResult>)Delegate.CreateDelegate(typeof(Func<object, TResult, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("Parser_NDateTime", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.DecimalType)
return (Func<object, TResult, Nattrib, TResult>)Delegate.CreateDelegate(typeof(Func<object, TResult, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("Parser_Decimal", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.NDecimalType)
return (Func<object, TResult, Nattrib, TResult>)Delegate.CreateDelegate(typeof(Func<object, TResult, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("Parser_NDecimal", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.Int32Type)
return (Func<object, TResult, Nattrib, TResult>)Delegate.CreateDelegate(typeof(Func<object, TResult, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("Parser_Int32", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.NInt32Type)
return (Func<object, TResult, Nattrib, TResult>)Delegate.CreateDelegate(typeof(Func<object, TResult, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("Parser_NInt32", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.StringType)
return (Func<object, TResult, Nattrib, TResult>)Delegate.CreateDelegate(typeof(Func<object, TResult, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("Parser_String", BindingFlags.NonPublic | BindingFlags.Static));
var parser = ScanForObjectParser<TResult>(type);
if (parser != null)
return parser.Parse;
//EnsureTryParseMethod();
if (s_tryParseMethodInfo != null)
return new Func<object, TResult, Nattrib, TResult>(Parser_Default);
return null;
}
private static Func<object, object, Nattrib, object> CreateParser2(Type type)
{
if ((type == CoreExInternal.BoolType) || (type == CoreExInternal.NBoolType))
return new Func<object, object, Nattrib, object>(Parser2_Bool);
if ((type == CoreExInternal.DateTimeType) || (type == CoreExInternal.NDateTimeType))
return new Func<object, object, Nattrib, object>(Parser2_DateTime);
if ((type == CoreExInternal.DecimalType) || (type == CoreExInternal.NDecimalType))
return new Func<object, object, Nattrib, object>(Parser2_Decimal);
if ((type == CoreExInternal.Int32Type) || (type == CoreExInternal.NInt32Type))
return new Func<object, object, Nattrib, object>(Parser2_Int32);
if (type == CoreExInternal.StringType)
return new Func<object, object, Nattrib, object>(Parser2_String);
var parser = ScanForObjectParser(type);
if (parser != null)
return parser.Parse2;
//EnsureTryParseMethod();
if (s_tryParseMethodInfo != null)
return new Func<object, object, Nattrib, object>(Parser2_Default);
return null;
}
private static TryFunc<object, Nattrib, TResult> CreateTryParser(Type type)
{
if (type == CoreExInternal.BoolType)
return (TryFunc<object, Nattrib, TResult>)Delegate.CreateDelegate(typeof(TryFunc<object, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("TryParser_Bool", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.NBoolType)
return (TryFunc<object, Nattrib, TResult>)Delegate.CreateDelegate(typeof(TryFunc<object, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("TryParser_NBool", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.DateTimeType)
return (TryFunc<object, Nattrib, TResult>)Delegate.CreateDelegate(typeof(TryFunc<object, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("TryParser_DateTime", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.NDateTimeType)
return (TryFunc<object, Nattrib, TResult>)Delegate.CreateDelegate(typeof(TryFunc<object, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("TryParser_NDateTime", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.DecimalType)
return (TryFunc<object, Nattrib, TResult>)Delegate.CreateDelegate(typeof(TryFunc<object, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("TryParser_Decimal", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.NDecimalType)
return (TryFunc<object, Nattrib, TResult>)Delegate.CreateDelegate(typeof(TryFunc<object, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("TryParser_NDecimal", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.Int32Type)
return (TryFunc<object, Nattrib, TResult>)Delegate.CreateDelegate(typeof(TryFunc<object, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("TryParser_Int32", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.NInt32Type)
return (TryFunc<object, Nattrib, TResult>)Delegate.CreateDelegate(typeof(TryFunc<object, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("TryParser_NInt32", BindingFlags.NonPublic | BindingFlags.Static));
if (type == CoreExInternal.StringType)
return (TryFunc<object, Nattrib, TResult>)Delegate.CreateDelegate(typeof(TryFunc<object, Nattrib, TResult>), typeof(ObjectParserDelegateFactory<T, TResult>).GetMethod("TryParser_String", BindingFlags.NonPublic | BindingFlags.Static));
var parser = ScanForObjectParser<TResult>(type);
if (parser != null)
return parser.TryParse;
//EnsureTryParseMethod();
if (s_tryParseMethodInfo != null)
return new TryFunc<object, Nattrib, TResult>(TryParser_Default);
return null;
}
private static Func<object, Nattrib, bool> CreateValidator(Type type)
{
if (type == CoreExInternal.BoolType)
return new Func<object, Nattrib, bool>(Validator_Bool);
else if (type == CoreExInternal.DateTimeType)
return new Func<object, Nattrib, bool>(Validator_DateTime);
else if (type == CoreExInternal.DecimalType)
return new Func<object, Nattrib, bool>(Validator_Decimal);
else if (type == CoreExInternal.Int32Type)
return new Func<object, Nattrib, bool>(Validator_Int32);
else if (type == CoreExInternal.StringType)
return new Func<object, Nattrib, bool>(Validator_String);
var parser = ScanForObjectParser(type);
if (parser != null)
return parser.Validate;
if (s_tryParseMethodInfo != null)
return new Func<object, Nattrib, bool>(Validator_Default);
return null;
}
private static void EnsureTryParseMethod()
{
if (s_tryParseMethodInfo == null)
throw new InvalidOperationException(string.Format("{0}::TypeParse method required for parsing", typeof(T).ToString()));
}
#region Default
private static TResult Parser_Default(object value, TResult defaultValue, Nattrib attrib)
{
if (value != null)
{
if (value is TResult)
return (TResult)value;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
var args = new object[] { text, default(TResult) };
if ((bool)s_tryParseMethodInfo.Invoke(null, BindingFlags.Default, null, args, null))
return (TResult)args[1];
}
}
return defaultValue;
}
private static object Parser2_Default(object value, object defaultValue, Nattrib attrib)
{
if (value != null)
{
if (value is TResult)
return value;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
var args = new object[] { text, default(TResult) };
if ((bool)s_tryParseMethodInfo.Invoke(null, BindingFlags.Default, null, args, null))
return (TResult)args[1];
}
}
return defaultValue;
}
private static bool TryParser_Default(object value, Nattrib attrib, out TResult validValue)
{
if (value != null)
{
if (value is TResult)
{
validValue = (TResult)value; return true;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
var args = new object[] { text, default(TResult) };
if ((bool)s_tryParseMethodInfo.Invoke(null, BindingFlags.Default, null, args, null))
{
validValue = (TResult)args[1]; return true;
}
}
}
validValue = default(TResult); return false;
}
private static bool Validator_Default(object value, Nattrib attrib)
{
if (value == null)
return false;
if (value is TResult)
return true;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
var args = new object[] { text, default(TResult) };
if ((bool)s_tryParseMethodInfo.Invoke(null, BindingFlags.Default, null, args, null))
return true;
}
return false;
}
#endregion
#region Bool
private static bool Parser_Bool(object value, bool defaultValue, Nattrib attrib)
{
if (value != null)
{
if (value is bool)
return (bool)value;
if (value is int)
{
switch ((int)value)
{
case 1:
return true;
case 0:
return false;
}
return defaultValue;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
switch (text.ToLowerInvariant())
{
case "1":
case "y":
case "true":
case "yes":
case "on":
return true;
case "0":
case "n":
case "false":
case "no":
case "off":
return false;
}
bool validValue;
if (bool.TryParse(text, out validValue))
return validValue;
}
}
return defaultValue;
}
private static bool? Parser_NBool(object value, bool? defaultValue, Nattrib attrib)
{
if (value != null)
{
if ((value is bool) || (value is bool?))
return (bool?)value;
if (value is int)
{
switch ((int)value)
{
case 1:
return true;
case 0:
return false;
}
return defaultValue;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
switch (text.ToLowerInvariant())
{
case "1":
case "y":
case "true":
case "yes":
case "on":
return true;
case "0":
case "n":
case "false":
case "no":
case "off":
return false;
}
bool validValue;
if (bool.TryParse(text, out validValue))
return validValue;
}
}
return defaultValue;
}
private static object Parser2_Bool(object value, object defaultValue, Nattrib attrib)
{
if (value != null)
{
if ((value is bool) || (value is bool?))
return value;
if (value is int)
{
switch ((int)value)
{
case 1:
return true;
case 0:
return false;
}
return defaultValue;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
switch (text.ToLowerInvariant())
{
case "1":
case "y":
case "true":
case "yes":
case "on":
return true;
case "0":
case "n":
case "false":
case "no":
case "off":
return false;
}
bool validValue;
if (bool.TryParse(text, out validValue))
return validValue;
}
}
return defaultValue;
}
private static bool TryParser_Bool(object value, Nattrib attrib, out bool validValue)
{
if (value != null)
{
if (value is bool)
{
validValue = (bool)value; return true;
}
if (value is int)
{
switch ((int)value)
{
case 1:
validValue = true; return true;
case 0:
validValue = false; return true;
}
validValue = default(bool); return false;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
switch (text.ToLowerInvariant())
{
case "1":
case "y":
case "true":
case "yes":
case "on":
validValue = true; return true;
case "0":
case "n":
case "false":
case "no":
case "off":
validValue = false; return true;
}
bool validValue2;
if (bool.TryParse(text, out validValue2))
{
validValue = validValue2; return true;
}
}
}
validValue = default(bool);
return false;
}
private static bool TryParser_NBool(object value, Nattrib attrib, out bool? validValue)
{
if (value != null)
{
if ((value is bool) || (value is bool?))
{
validValue = (bool?)value; return true;
}
if (value is int)
{
switch ((int)value)
{
case 1:
validValue = true; return true;
case 0:
validValue = false; return true;
}
validValue = null; return false;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
switch (text.ToLowerInvariant())
{
case "1":
case "y":
case "true":
case "yes":
case "on":
validValue = true; return true;
case "0":
case "n":
case "false":
case "no":
case "off":
validValue = false; return true;
}
bool validValue2;
if (bool.TryParse(text, out validValue2))
{
validValue = validValue2; return true;
}
}
}
validValue = null; return false;
}
private static bool Validator_Bool(object value, Nattrib attrib)
{
if (value != null)
{
if (value is bool)
return true;
if (value is int)
{
switch ((int)value)
{
case 1:
case 0:
return true;
}
return false;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
switch (text.ToLowerInvariant())
{
case "1":
case "y":
case "true":
case "yes":
case "on":
return true;
case "0":
case "n":
case "false":
case "no":
case "off":
return true;
}
bool validValue;
return bool.TryParse(text, out validValue);
}
}
return false;
}
#endregion
#region DateTime
private static DateTime Parser_DateTime(object value, DateTime defaultValue, Nattrib attrib)
{
if (value != null)
{
if (value is DateTime)
return (DateTime)value;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
DateTime validValue;
if (DateTime.TryParse(text, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out validValue))
return validValue;
}
}
return defaultValue;
}
private static DateTime? Parser_DateTime(object value, DateTime? defaultValue, Nattrib attrib)
{
if (value != null)
{
if ((value is DateTime) || (value is DateTime?))
return (DateTime?)value;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
DateTime validValue;
if (DateTime.TryParse(text, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out validValue))
return validValue;
}
}
return defaultValue;
}
private static object Parser2_DateTime(object value, object defaultValue, Nattrib attrib)
{
if (value != null)
{
if ((value is DateTime) || (value is DateTime?))
return value;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
DateTime validValue;
if (DateTime.TryParse(text, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out validValue))
return validValue;
}
}
return defaultValue;
}
private static bool TryParser_DateTime(object value, Nattrib attrib, out DateTime validValue)
{
if (value != null)
{
if (value is DateTime)
{
validValue = (DateTime)value; return true;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
DateTime validValue2;
if (DateTime.TryParse(text, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out validValue2))
{
validValue = validValue2; return true;
}
}
}
validValue = default(DateTime); return false;
}
private static bool TryParser_DateTime(object value, Nattrib attrib, out DateTime? validValue)
{
if (value != null)
{
if ((value is DateTime) || (value is DateTime?))
{
validValue = (DateTime?)value; return true;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
DateTime validValue2;
if (DateTime.TryParse(text, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out validValue2))
{
validValue = validValue2; return true;
}
}
}
validValue = null; return false;
}
private static bool Validator_DateTime(object value, Nattrib attrib)
{
if (value != null)
{
if (value is DateTime)
return true;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
DateTime validValue;
return DateTime.TryParse(text, out validValue);
}
}
return false;
}
#endregion
#region Decimal
private static decimal Parser_Decimal(object value, decimal defaultValue, Nattrib attrib)
{
if (value != null)
{
if (value is decimal)
return (decimal)value;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
decimal validValue;
if (decimal.TryParse(text, NumberStyles.Currency, null, out validValue))
return validValue;
}
}
return defaultValue;
}
private static decimal? Parser_NDecimal(object value, decimal? defaultValue, Nattrib attrib)
{
if (value != null)
{
if ((value is decimal) || (value is decimal?))
return (decimal?)value;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
decimal validValue;
if (decimal.TryParse(text, NumberStyles.Currency, null, out validValue))
return validValue;
}
}
return defaultValue;
}
private static object Parser2_Decimal(object value, object defaultValue, Nattrib attrib)
{
if (value != null)
{
if ((value is decimal) || (value is decimal?))
return value;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
decimal validValue;
if (decimal.TryParse(text, NumberStyles.Currency, null, out validValue))
return validValue;
}
}
return defaultValue;
}
private static bool TryParser_Decimal(object value, Nattrib attrib, out decimal validValue)
{
if (value != null)
{
if (value is decimal)
{
validValue = (decimal)value; return true;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
decimal validValue2;
if (decimal.TryParse(text, NumberStyles.Currency, null, out validValue2))
{
validValue = validValue2; return true;
}
}
}
validValue = default(decimal); return false;
}
private static bool TryParser_Decimal(object value, Nattrib attrib, out decimal? validValue)
{
if (value != null)
{
if ((value is decimal) || (value is decimal?))
{
validValue = (decimal?)value; return true;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
decimal validValue2;
if (decimal.TryParse(text, NumberStyles.Currency, null, out validValue2))
{
validValue = validValue2; return true;
}
}
}
validValue = null; return false;
}
private static bool Validator_Decimal(object value, Nattrib attrib)
{
if (value != null)
{
if (value is decimal)
return true;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
decimal validValue;
return decimal.TryParse(text, NumberStyles.Currency, null, out validValue);
}
}
return false;
}
#endregion
#region Int32
private static int Parser_Int32(object value, int defaultValue, Nattrib attrib)
{
if (value != null)
{
if (value is int)
return (int)value;
if (value is bool)
return (!(bool)value ? 0 : 1);
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
int validValue;
if (int.TryParse(text, out validValue))
return validValue;
}
}
return defaultValue;
}
private static int? Parser_NInt32(object value, int? defaultValue, Nattrib attrib)
{
if (value != null)
{
if ((value is int) || (value is int?))
return (int?)value;
if (value is bool)
return (!(bool)value ? 0 : 1);
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
int validValue;
if (int.TryParse(text, out validValue))
return validValue;
}
}
return defaultValue;
}
private static object Parser2_Int32(object value, object defaultValue, Nattrib attrib)
{
if (value == null)
{
if ((value is int) || (value is int?))
return value;
if (value is bool)
return (!(bool)value ? 0 : 1);
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
int validValue;
if (int.TryParse(text, out validValue))
return validValue;
}
}
return defaultValue;
}
private static bool TryParser_Int32(object value, Nattrib attrib, out int validValue)
{
if (value != null)
{
if (value is int)
{
validValue = (int)value; return true;
}
if (value is bool)
{
validValue = (!(bool)value ? 0 : 1); return true;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
int validValue2;
if (int.TryParse(text, out validValue2))
{
validValue = validValue2; return true;
}
}
}
validValue = default(int); return false;
}
private static bool TryParser_NInt32(object value, Nattrib attrib, out int? validValue)
{
if (value != null)
{
if ((value is int) || (value is int?))
{
validValue = (int?)value; return true;
}
if (value is bool)
{
validValue = (!(bool)value ? 0 : 1); return true;
}
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
int validValue2;
if (int.TryParse(text, out validValue2))
{
validValue = validValue2; return true;
}
}
}
validValue = null; return false;
}
private static bool Validator_Int32(object value, Nattrib attrib)
{
if (value != null)
{
if (value is int)
return true;
string text;
if (((text = (value as string)) != null) && (text.Length > 0))
{
int validValue;
return int.TryParse(text, out validValue);
}
}
return false;
}
#endregion
#region String
private static string Parser_String(object value, string defaultValue, Nattrib attrib)
{
if (value != null)
{
string text;
if (((text = (value as string)) != null) && ((text = text.Trim()).Length > 0))
return text;
}
return defaultValue;
}
private static object Parser2_String(object value, object defaultValue, Nattrib attrib)
{
if (value != null)
{
string text;
if (((text = (value as string)) != null) && ((text = text.Trim()).Length > 0))
return text;
}
return defaultValue;
}
private static bool TryParser_String(object value, Nattrib attrib, out string validValue)
{
if (value != null)
{
string text;
if (((text = (value as string)) != null) && ((text = text.Trim()).Length > 0))
{
validValue = text; return true;
}
}
validValue = default(string); return false;
}
private static bool Validator_String(object value, Nattrib attrib)
{
string text = (value as string);
return ((text != null) && (text.Trim().Length > 0));
}
#endregion
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudtrail-2013-11-01.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.CloudTrail.Model;
using Amazon.CloudTrail.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CloudTrail
{
/// <summary>
/// Implementation for accessing CloudTrail
///
/// AWS CloudTrail
/// <para>
/// This is the CloudTrail API Reference. It provides descriptions of actions, data types,
/// common parameters, and common errors for CloudTrail.
/// </para>
///
/// <para>
/// CloudTrail is a web service that records AWS API calls for your AWS account and delivers
/// log files to an Amazon S3 bucket. The recorded information includes the identity of
/// the user, the start time of the AWS API call, the source IP address, the request parameters,
/// and the response elements returned by the service.
/// </para>
/// <note> As an alternative to using the API, you can use one of the AWS SDKs, which
/// consist of libraries and sample code for various programming languages and platforms
/// (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient way to create
/// programmatic access to AWSCloudTrail. For example, the SDKs take care of cryptographically
/// signing requests, managing errors, and retrying requests automatically. For information
/// about the AWS SDKs, including how to download and install them, see the <a href="http://aws.amazon.com/tools/">Tools
/// for Amazon Web Services page</a>. </note>
/// <para>
/// See the CloudTrail User Guide for information about the data that is included with
/// each AWS API call listed in the log files.
/// </para>
/// </summary>
public partial class AmazonCloudTrailClient : AmazonServiceClient, IAmazonCloudTrail
{
#region Constructors
/// <summary>
/// Constructs AmazonCloudTrailClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonCloudTrailClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCloudTrailConfig()) { }
/// <summary>
/// Constructs AmazonCloudTrailClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonCloudTrailConfig{RegionEndpoint = region}) { }
/// <summary>
/// Constructs AmazonCloudTrailClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSProfileName" value="AWS Default"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(AmazonCloudTrailConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config) { }
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonCloudTrailClient(AWSCredentials credentials)
: this(credentials, new AmazonCloudTrailConfig())
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonCloudTrailConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Credentials and an
/// AmazonCloudTrailClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(AWSCredentials credentials, AmazonCloudTrailConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudTrailConfig())
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudTrailConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudTrailClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCloudTrailConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudTrailConfig())
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudTrailConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudTrailClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCloudTrailConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateTrail
/// <summary>
/// From the command line, use <code>create-subscription</code>.
///
///
/// <para>
/// Creates a trail that specifies the settings for delivery of log data to an Amazon
/// S3 bucket.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the CreateTrail service method.</param>
///
/// <returns>The response from the CreateTrail service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.CloudWatchLogsDeliveryUnavailableException">
/// Cannot set a CloudWatch Logs delivery for this region.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientS3BucketPolicyException">
/// This exception is thrown when the policy on the S3 bucket is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientSnsTopicPolicyException">
/// This exception is thrown when the policy on the SNS topic is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsLogGroupArnException">
/// This exception is thrown when the provided CloudWatch log group is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsRoleArnException">
/// This exception is thrown when the provided role is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3BucketNameException">
/// This exception is thrown when the provided S3 bucket name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3PrefixException">
/// This exception is thrown when the provided S3 prefix is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidSnsTopicNameException">
/// This exception is thrown when the provided SNS topic name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.MaximumNumberOfTrailsExceededException">
/// This exception is thrown when the maximum number of trails is reached.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.S3BucketDoesNotExistException">
/// This exception is thrown when the specified S3 bucket does not exist.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailAlreadyExistsException">
/// This exception is thrown when the specified trail already exists.
/// </exception>
public CreateTrailResponse CreateTrail(CreateTrailRequest request)
{
var marshaller = new CreateTrailRequestMarshaller();
var unmarshaller = CreateTrailResponseUnmarshaller.Instance;
return Invoke<CreateTrailRequest,CreateTrailResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateTrail operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateTrailResponse> CreateTrailAsync(CreateTrailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateTrailRequestMarshaller();
var unmarshaller = CreateTrailResponseUnmarshaller.Instance;
return InvokeAsync<CreateTrailRequest,CreateTrailResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteTrail
/// <summary>
/// Deletes a trail.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DeleteTrail service method.</param>
///
/// <returns>The response from the DeleteTrail service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public DeleteTrailResponse DeleteTrail(DeleteTrailRequest request)
{
var marshaller = new DeleteTrailRequestMarshaller();
var unmarshaller = DeleteTrailResponseUnmarshaller.Instance;
return Invoke<DeleteTrailRequest,DeleteTrailResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteTrail operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteTrailResponse> DeleteTrailAsync(DeleteTrailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteTrailRequestMarshaller();
var unmarshaller = DeleteTrailResponseUnmarshaller.Instance;
return InvokeAsync<DeleteTrailRequest,DeleteTrailResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeTrails
/// <summary>
/// Retrieves settings for the trail associated with the current region for your account.
/// </summary>
///
/// <returns>The response from the DescribeTrails service method, as returned by CloudTrail.</returns>
public DescribeTrailsResponse DescribeTrails()
{
return DescribeTrails(new DescribeTrailsRequest());
}
/// <summary>
/// Retrieves settings for the trail associated with the current region for your account.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the DescribeTrails service method.</param>
///
/// <returns>The response from the DescribeTrails service method, as returned by CloudTrail.</returns>
public DescribeTrailsResponse DescribeTrails(DescribeTrailsRequest request)
{
var marshaller = new DescribeTrailsRequestMarshaller();
var unmarshaller = DescribeTrailsResponseUnmarshaller.Instance;
return Invoke<DescribeTrailsRequest,DescribeTrailsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Retrieves settings for the trail associated with the current region for your account.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeTrails service method, as returned by CloudTrail.</returns>
public Task<DescribeTrailsResponse> DescribeTrailsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return DescribeTrailsAsync(new DescribeTrailsRequest(), cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeTrails operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTrails operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeTrailsResponse> DescribeTrailsAsync(DescribeTrailsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeTrailsRequestMarshaller();
var unmarshaller = DescribeTrailsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeTrailsRequest,DescribeTrailsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetTrailStatus
/// <summary>
/// Returns a JSON-formatted list of information about the specified trail. Fields include
/// information on delivery errors, Amazon SNS and Amazon S3 errors, and start and stop
/// logging times for each trail.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the GetTrailStatus service method.</param>
///
/// <returns>The response from the GetTrailStatus service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public GetTrailStatusResponse GetTrailStatus(GetTrailStatusRequest request)
{
var marshaller = new GetTrailStatusRequestMarshaller();
var unmarshaller = GetTrailStatusResponseUnmarshaller.Instance;
return Invoke<GetTrailStatusRequest,GetTrailStatusResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetTrailStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTrailStatus operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetTrailStatusResponse> GetTrailStatusAsync(GetTrailStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetTrailStatusRequestMarshaller();
var unmarshaller = GetTrailStatusResponseUnmarshaller.Instance;
return InvokeAsync<GetTrailStatusRequest,GetTrailStatusResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region LookupEvents
/// <summary>
/// Looks up API activity events captured by CloudTrail that create, update, or delete
/// resources in your account. Events for a region can be looked up for the times in which
/// you had CloudTrail turned on in that region during the last seven days. Lookup supports
/// five different attributes: time range (defined by a start time and end time), user
/// name, event name, resource type, and resource name. All attributes are optional. The
/// maximum number of attributes that can be specified in any one lookup request are time
/// range and one other attribute. The default number of results returned is 10, with
/// a maximum of 50 possible. The response includes a token that you can use to get the
/// next page of results. The rate of lookup requests is limited to one per second per
/// account.
///
/// <important>Events that occurred during the selected time range will not be available
/// for lookup if CloudTrail logging was not enabled when the events occurred.</important>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the LookupEvents service method.</param>
///
/// <returns>The response from the LookupEvents service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidLookupAttributesException">
/// Occurs when an invalid lookup attribute is specified.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidMaxResultsException">
/// This exception is thrown if the limit specified is invalid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidNextTokenException">
/// Invalid token or token that was previously used in a request with different parameters.
/// This exception is thrown if the token is invalid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTimeRangeException">
/// Occurs if the timestamp values are invalid. Either the start time occurs after the
/// end time or the time range is outside the range of possible values.
/// </exception>
public LookupEventsResponse LookupEvents(LookupEventsRequest request)
{
var marshaller = new LookupEventsRequestMarshaller();
var unmarshaller = LookupEventsResponseUnmarshaller.Instance;
return Invoke<LookupEventsRequest,LookupEventsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the LookupEvents operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the LookupEvents operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<LookupEventsResponse> LookupEventsAsync(LookupEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new LookupEventsRequestMarshaller();
var unmarshaller = LookupEventsResponseUnmarshaller.Instance;
return InvokeAsync<LookupEventsRequest,LookupEventsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region StartLogging
/// <summary>
/// Starts the recording of AWS API calls and log file delivery for a trail.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StartLogging service method.</param>
///
/// <returns>The response from the StartLogging service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public StartLoggingResponse StartLogging(StartLoggingRequest request)
{
var marshaller = new StartLoggingRequestMarshaller();
var unmarshaller = StartLoggingResponseUnmarshaller.Instance;
return Invoke<StartLoggingRequest,StartLoggingResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the StartLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartLogging operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<StartLoggingResponse> StartLoggingAsync(StartLoggingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new StartLoggingRequestMarshaller();
var unmarshaller = StartLoggingResponseUnmarshaller.Instance;
return InvokeAsync<StartLoggingRequest,StartLoggingResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region StopLogging
/// <summary>
/// Suspends the recording of AWS API calls and log file delivery for the specified trail.
/// Under most circumstances, there is no need to use this action. You can update a trail
/// without stopping it first. This action is the only way to stop recording.
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the StopLogging service method.</param>
///
/// <returns>The response from the StopLogging service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public StopLoggingResponse StopLogging(StopLoggingRequest request)
{
var marshaller = new StopLoggingRequestMarshaller();
var unmarshaller = StopLoggingResponseUnmarshaller.Instance;
return Invoke<StopLoggingRequest,StopLoggingResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the StopLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StopLogging operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<StopLoggingResponse> StopLoggingAsync(StopLoggingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new StopLoggingRequestMarshaller();
var unmarshaller = StopLoggingResponseUnmarshaller.Instance;
return InvokeAsync<StopLoggingRequest,StopLoggingResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region UpdateTrail
/// <summary>
/// From the command line, use <code>update-subscription</code>.
///
///
/// <para>
/// Updates the settings that specify delivery of log files. Changes to a trail do not
/// require stopping the CloudTrail service. Use this action to designate an existing
/// bucket for log delivery. If the existing bucket has previously been a target for CloudTrail
/// log files, an IAM policy exists for the bucket.
/// </para>
/// </summary>
/// <param name="request">Container for the necessary parameters to execute the UpdateTrail service method.</param>
///
/// <returns>The response from the UpdateTrail service method, as returned by CloudTrail.</returns>
/// <exception cref="Amazon.CloudTrail.Model.CloudWatchLogsDeliveryUnavailableException">
/// Cannot set a CloudWatch Logs delivery for this region.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientS3BucketPolicyException">
/// This exception is thrown when the policy on the S3 bucket is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InsufficientSnsTopicPolicyException">
/// This exception is thrown when the policy on the SNS topic is not sufficient.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsLogGroupArnException">
/// This exception is thrown when the provided CloudWatch log group is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidCloudWatchLogsRoleArnException">
/// This exception is thrown when the provided role is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3BucketNameException">
/// This exception is thrown when the provided S3 bucket name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidS3PrefixException">
/// This exception is thrown when the provided S3 prefix is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidSnsTopicNameException">
/// This exception is thrown when the provided SNS topic name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.InvalidTrailNameException">
/// This exception is thrown when the provided trail name is not valid.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.S3BucketDoesNotExistException">
/// This exception is thrown when the specified S3 bucket does not exist.
/// </exception>
/// <exception cref="Amazon.CloudTrail.Model.TrailNotFoundException">
/// This exception is thrown when the trail with the given name is not found.
/// </exception>
public UpdateTrailResponse UpdateTrail(UpdateTrailRequest request)
{
var marshaller = new UpdateTrailRequestMarshaller();
var unmarshaller = UpdateTrailResponseUnmarshaller.Instance;
return Invoke<UpdateTrailRequest,UpdateTrailResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateTrail operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<UpdateTrailResponse> UpdateTrailAsync(UpdateTrailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new UpdateTrailRequestMarshaller();
var unmarshaller = UpdateTrailResponseUnmarshaller.Instance;
return InvokeAsync<UpdateTrailRequest,UpdateTrailResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.Parallel;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
[ParallelFixture]
public class ClassKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEmptyStatement()
{
VerifyAbsence(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCompilationUnit()
{
VerifyKeyword(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterExtern()
{
VerifyKeyword(
@"extern alias Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterUsing()
{
VerifyKeyword(
@"using Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNamespace()
{
VerifyKeyword(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterTypeDeclaration()
{
VerifyKeyword(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateDeclaration()
{
VerifyKeyword(
@"delegate void Foo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethod()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterField()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProperty()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing()
{
VerifyAbsence(SourceCodeKind.Regular,
@"$$
using Foo;");
}
[Fact(Skip = "528041"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$
using Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAssemblyAttribute()
{
VerifyKeyword(
@"[assembly: foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterRootAttribute()
{
VerifyKeyword(
@"[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideStruct()
{
VerifyKeyword(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInsideInterface()
{
VerifyAbsence(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPartial()
{
VerifyKeyword(
@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAbstract()
{
VerifyKeyword(
@"abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInternal()
{
VerifyKeyword(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStaticPublic()
{
VerifyKeyword(
@"static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPublicStatic()
{
VerifyKeyword(
@"public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterInvalidPublic()
{
VerifyAbsence(@"virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPublic()
{
VerifyKeyword(
@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPrivate()
{
VerifyKeyword(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProtected()
{
VerifyKeyword(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterSealed()
{
VerifyKeyword(
@"sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStatic()
{
VerifyKeyword(
@"static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStaticInUsingDirective()
{
VerifyAbsence(
@"using static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass()
{
VerifyAbsence(@"class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBetweenUsings()
{
VerifyAbsence(AddInsideMethod(
@"using Foo;
$$
using Bar;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClassTypeParameterConstraint()
{
VerifyKeyword(
@"class C<T> where T : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClassTypeParameterConstraint2()
{
VerifyKeyword(
@"class C<T>
where T : $$
where U : U");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodTypeParameterConstraint()
{
VerifyKeyword(
@"class C {
void Foo<T>()
where T : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethodTypeParameterConstraint2()
{
VerifyKeyword(
@"class C {
void Foo<T>()
where T : $$
where U : T");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNew()
{
VerifyKeyword(
@"class C {
new $$");
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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.
// -----------------------------------------------------------------------------
// The following code is a port of XNA StockEffects http://xbox.create.msdn.com/en-US/education/catalog/sample/stock_effects
// -----------------------------------------------------------------------------
// Microsoft Public License (Ms-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law.
// A "contribution" is the original software, or any additions or changes to
// the software.
// A "contributor" is any person that distributes its contribution under this
// license.
// "Licensed patents" are a contributor's patent claims that read directly on
// its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor grants
// you a non-exclusive, worldwide, royalty-free copyright license to reproduce
// its contribution, prepare derivative works of its contribution, and
// distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license
// conditions and limitations in section 3, each contributor grants you a
// non-exclusive, worldwide, royalty-free license under its licensed patents to
// make, have made, use, sell, offer for sale, import, and/or otherwise dispose
// of its contribution in the software or derivative works of the contribution
// in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any
// contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present in the
// software.
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the software
// in compiled or object code form, you may only do so under a license that
// complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You may
// have additional consumer rights under your local laws which this license
// cannot change. To the extent permitted under your local laws, the
// contributors exclude the implied warranties of merchantability, fitness for a
// particular purpose and non-infringement.
//-----------------------------------------------------------------------------
// SkinnedEffect.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using SharpDX.Mathematics;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Built-in effect for rendering skinned character models.
/// </summary>
public partial class SkinnedEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog
{
public const int MaxBones = 72;
#region Effect Parameters
EffectParameter textureParam;
EffectParameter diffuseColorParam;
EffectParameter emissiveColorParam;
EffectParameter specularColorParam;
EffectParameter specularPowerParam;
EffectParameter eyePositionParam;
EffectParameter fogColorParam;
EffectParameter fogVectorParam;
EffectParameter worldParam;
EffectParameter worldInverseTransposeParam;
EffectParameter worldViewProjParam;
EffectParameter bonesParam;
EffectPass shaderPass;
#endregion
#region Fields
bool preferPerPixelLighting;
bool oneLight;
bool fogEnabled;
Matrix world = Matrix.Identity;
Matrix view = Matrix.Identity;
Matrix projection = Matrix.Identity;
Matrix worldView;
Vector4 diffuseColor = Vector4.One;
Vector3 emissiveColor = Vector3.Zero;
Vector3 ambientLightColor = Vector3.Zero;
float alpha = 1;
DirectionalLight light0;
DirectionalLight light1;
DirectionalLight light2;
float fogStart = 0;
float fogEnd = 1;
int weightsPerVertex = 4;
EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the world matrix.
/// </summary>
public Matrix World
{
get { return world; }
set
{
world = value;
dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the view matrix.
/// </summary>
public Matrix View
{
get { return view; }
set
{
view = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the projection matrix.
/// </summary>
public Matrix Projection
{
get { return projection; }
set
{
projection = value;
dirtyFlags |= EffectDirtyFlags.WorldViewProj;
}
}
/// <summary>
/// Gets or sets the material diffuse color (range 0 to 1).
/// </summary>
public Vector4 DiffuseColor
{
get { return diffuseColor; }
set
{
diffuseColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material emissive color (range 0 to 1).
/// </summary>
public Vector3 EmissiveColor
{
get { return emissiveColor; }
set
{
emissiveColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the material specular color (range 0 to 1).
/// </summary>
public Vector3 SpecularColor
{
get { return specularColorParam.GetValue<Vector3>(); }
set { specularColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the material specular power.
/// </summary>
public float SpecularPower
{
get { return specularPowerParam.GetValue<float>(); }
set { specularPowerParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the material alpha.
/// </summary>
public float Alpha
{
get { return alpha; }
set
{
alpha = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets or sets the per-pixel lighting prefer flag.
/// </summary>
public bool PreferPerPixelLighting
{
get { return preferPerPixelLighting; }
set
{
if (preferPerPixelLighting != value)
{
preferPerPixelLighting = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
}
/// <summary>
/// Gets or sets the ambient light color (range 0 to 1).
/// </summary>
public Vector3 AmbientLightColor
{
get { return ambientLightColor; }
set
{
ambientLightColor = value;
dirtyFlags |= EffectDirtyFlags.MaterialColor;
}
}
/// <summary>
/// Gets the first directional light.
/// </summary>
public DirectionalLight DirectionalLight0 { get { return light0; } }
/// <summary>
/// Gets the second directional light.
/// </summary>
public DirectionalLight DirectionalLight1 { get { return light1; } }
/// <summary>
/// Gets the third directional light.
/// </summary>
public DirectionalLight DirectionalLight2 { get { return light2; } }
/// <summary>
/// Gets or sets the fog enable flag.
/// </summary>
public bool FogEnabled
{
get { return fogEnabled; }
set
{
if (fogEnabled != value)
{
fogEnabled = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable;
}
}
}
/// <summary>
/// Gets or sets the fog start distance.
/// </summary>
public float FogStart
{
get { return fogStart; }
set
{
fogStart = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog end distance.
/// </summary>
public float FogEnd
{
get { return fogEnd; }
set
{
fogEnd = value;
dirtyFlags |= EffectDirtyFlags.Fog;
}
}
/// <summary>
/// Gets or sets the fog color.
/// </summary>
public Vector3 FogColor
{
get { return fogColorParam.GetValue<Vector3>(); }
set { fogColorParam.SetValue(value); }
}
/// <summary>
/// Gets or sets the current texture.
/// </summary>
public Texture2D Texture
{
get { return textureParam.GetResource<Texture2D>(); }
set { textureParam.SetResource(value); }
}
/// <summary>
/// Gets or sets the number of skinning weights to evaluate for each vertex (1, 2, or 4).
/// </summary>
public int WeightsPerVertex
{
get { return weightsPerVertex; }
set
{
if ((value != 1) &&
(value != 2) &&
(value != 4))
{
throw new ArgumentOutOfRangeException("value");
}
weightsPerVertex = value;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
}
/// <summary>
/// Sets an array of skinning bone transform matrices.
/// </summary>
public void SetBoneTransforms(Matrix[] boneTransforms)
{
if ((boneTransforms == null) || (boneTransforms.Length == 0))
throw new ArgumentNullException("boneTransforms");
if (boneTransforms.Length > MaxBones)
throw new ArgumentException();
bonesParam.SetValue(boneTransforms);
}
/// <summary>
/// Gets a copy of the current skinning bone transform matrices.
/// </summary>
public Matrix[] GetBoneTransforms(int count)
{
if (count <= 0 || count > MaxBones)
throw new ArgumentOutOfRangeException("count");
var bones = bonesParam.GetMatrixArray(count);
// Convert matrices from 43 to 44 format.
for (int i = 0; i < bones.Length; i++)
{
bones[i].M44 = 1;
}
return bones;
}
/// <summary>
/// This effect requires lighting, so we explicitly implement
/// IEffectLights.LightingEnabled, and do not allow turning it off.
/// </summary>
bool IEffectLights.LightingEnabled
{
get { return true; }
set { if (!value) throw new NotSupportedException("SkinnedEffect does not support setting LightingEnabled to false."); }
}
#endregion
#region Methods
private const string SkinnedEffectName = "Toolkit::SkinnedEffect";
/// <summary>
/// Creates a new SkinnedEffect with default parameter settings.
/// </summary>
public SkinnedEffect(GraphicsDevice device) : this(device, device.DefaultEffectPool)
{
}
/// <summary>
/// Creates a new SkinnedEffect with default parameter settings from a specified <see cref="EffectPool"/>.
/// </summary>
public SkinnedEffect(GraphicsDevice device, EffectPool pool)
: base(device, effectBytecode, pool)
{
DirectionalLight0.Enabled = true;
SpecularColor = Vector3.One;
SpecularPower = 16;
var identityBones = new Matrix[MaxBones];
for (int i = 0; i < MaxBones; i++)
{
identityBones[i] = Matrix.Identity;
}
SetBoneTransforms(identityBones);
}
protected override void Initialize()
{
textureParam = Parameters["Texture"];
diffuseColorParam = Parameters["DiffuseColor"];
emissiveColorParam = Parameters["EmissiveColor"];
specularColorParam = Parameters["SpecularColor"];
specularPowerParam = Parameters["SpecularPower"];
eyePositionParam = Parameters["EyePosition"];
fogColorParam = Parameters["FogColor"];
fogVectorParam = Parameters["FogVector"];
worldParam = Parameters["World"];
worldInverseTransposeParam = Parameters["WorldInverseTranspose"];
worldViewProjParam = Parameters["WorldViewProj"];
bonesParam = Parameters["Bones"];
light0 = new DirectionalLight(Parameters["DirLight0Direction"],
Parameters["DirLight0DiffuseColor"],
Parameters["DirLight0SpecularColor"],
null);
light1 = new DirectionalLight(Parameters["DirLight1Direction"],
Parameters["DirLight1DiffuseColor"],
Parameters["DirLight1SpecularColor"],
null);
light2 = new DirectionalLight(Parameters["DirLight2Direction"],
Parameters["DirLight2DiffuseColor"],
Parameters["DirLight2SpecularColor"],
null);
}
///// <summary>
///// Creates a new SkinnedEffect by cloning parameter settings from an existing instance.
///// </summary>
//protected SkinnedEffect(SkinnedEffect cloneSource)
// : base(cloneSource)
//{
// CacheEffectParameters(cloneSource);
// preferPerPixelLighting = cloneSource.preferPerPixelLighting;
// fogEnabled = cloneSource.fogEnabled;
// world = cloneSource.world;
// view = cloneSource.view;
// projection = cloneSource.projection;
// diffuseColor = cloneSource.diffuseColor;
// emissiveColor = cloneSource.emissiveColor;
// ambientLightColor = cloneSource.ambientLightColor;
// alpha = cloneSource.alpha;
// fogStart = cloneSource.fogStart;
// fogEnd = cloneSource.fogEnd;
// weightsPerVertex = cloneSource.weightsPerVertex;
//}
///// <summary>
///// Creates a clone of the current SkinnedEffect instance.
///// </summary>
//public override Effect Clone()
//{
// return new SkinnedEffect(this);
//}
/// <summary>
/// Sets up the standard key/fill/back lighting rig.
/// </summary>
public void EnableDefaultLighting()
{
AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2);
}
/// <summary>
/// Lazily computes derived parameter values immediately before applying the effect.
/// </summary>
protected internal override EffectPass OnApply(EffectPass pass)
{
// Recompute the world+view+projection matrix or fog vector?
dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam);
// Recompute the world inverse transpose and eye position?
dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam);
// Recompute the diffuse/emissive/alpha material color parameters?
if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0)
{
EffectHelpers.SetMaterialColor(true, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam);
dirtyFlags &= ~EffectDirtyFlags.MaterialColor;
}
// Check if we can use the only-bother-with-the-first-light shader optimization.
bool newOneLight = !light1.Enabled && !light2.Enabled;
if (oneLight != newOneLight)
{
oneLight = newOneLight;
dirtyFlags |= EffectDirtyFlags.ShaderIndex;
}
// Recompute the shader index?
if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0)
{
int shaderIndex = 0;
if (!fogEnabled)
shaderIndex += 1;
if (weightsPerVertex == 2)
shaderIndex += 2;
else if (weightsPerVertex == 4)
shaderIndex += 4;
if (preferPerPixelLighting)
shaderIndex += 12;
else if (oneLight)
shaderIndex += 6;
shaderPass = pass.SubPasses[shaderIndex];
dirtyFlags &= ~EffectDirtyFlags.ShaderIndex;
}
return base.OnApply(shaderPass);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for the ProjectOnErrorElement class.</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Shared;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Tests for the ProjectOnErrorElement class
/// </summary>
[TestClass]
public class ProjectOnErrorElement_Tests
{
/// <summary>
/// Read a target containing only OnError
/// </summary>
[TestMethod]
public void ReadTargetOnlyContainingOnError()
{
ProjectOnErrorElement onError = GetOnError();
Assert.AreEqual("t", onError.ExecuteTargetsAttribute);
Assert.AreEqual("c", onError.Condition);
}
/// <summary>
/// Read a target with two onerrors, and some tasks
/// </summary>
[TestMethod]
public void ReadTargetTwoOnErrors()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1/>
<t2/>
<OnError ExecuteTargets='1'/>
<OnError ExecuteTargets='2'/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
var onErrors = Helpers.MakeList(target.OnErrors);
ProjectOnErrorElement onError1 = onErrors[0];
ProjectOnErrorElement onError2 = onErrors[1];
Assert.AreEqual("1", onError1.ExecuteTargetsAttribute);
Assert.AreEqual("2", onError2.ExecuteTargetsAttribute);
}
/// <summary>
/// Read onerror with no executetargets attribute
/// </summary>
/// <remarks>
/// This was accidentally allowed in 2.0/3.5 but it should be an error now.
/// </remarks>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadMissingExecuteTargets()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children);
Assert.AreEqual(String.Empty, onError.ExecuteTargetsAttribute);
}
/// <summary>
/// Read onerror with empty executetargets attribute
/// </summary>
/// <remarks>
/// This was accidentally allowed in 2.0/3.5 but it should be an error now.
/// </remarks>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadEmptyExecuteTargets()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets=''/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children);
Assert.AreEqual(String.Empty, onError.ExecuteTargetsAttribute);
}
/// <summary>
/// Read onerror with invalid attribute
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidUnexpectedAttribute()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t' XX='YY'/>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read onerror with invalid child element
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidUnexpectedChild()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t'>
<X/>
</OnError>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read onerror before task
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidBeforeTask()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t'/>
<t/>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read onerror before task
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidBeforePropertyGroup()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t'/>
<PropertyGroup/>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read onerror before task
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidBeforeItemGroup()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t'/>
<ItemGroup/>
</Target>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Set ExecuteTargets
/// </summary>
[TestMethod]
public void SetExecuteTargetsValid()
{
ProjectOnErrorElement onError = GetOnError();
onError.ExecuteTargetsAttribute = "t2";
Assert.AreEqual("t2", onError.ExecuteTargetsAttribute);
}
/// <summary>
/// Set ExecuteTargets to null
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SetInvalidExecuteTargetsNull()
{
ProjectOnErrorElement onError = GetOnError();
onError.ExecuteTargetsAttribute = null;
}
/// <summary>
/// Set ExecuteTargets to empty string
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SetInvalidExecuteTargetsEmpty()
{
ProjectOnErrorElement onError = GetOnError();
onError.ExecuteTargetsAttribute = String.Empty;
}
/// <summary>
/// Set on error condition
/// </summary>
[TestMethod]
public void SetCondition()
{
ProjectRootElement project = ProjectRootElement.Create();
ProjectTargetElement target = project.AddTarget("t");
ProjectOnErrorElement onError = project.CreateOnErrorElement("et");
target.AppendChild(onError);
Helpers.ClearDirtyFlag(project);
onError.Condition = "c";
Assert.AreEqual("c", onError.Condition);
Assert.AreEqual(true, project.HasUnsavedChanges);
}
/// <summary>
/// Set on error executetargets value
/// </summary>
[TestMethod]
public void SetExecuteTargets()
{
ProjectRootElement project = ProjectRootElement.Create();
ProjectTargetElement target = project.AddTarget("t");
ProjectOnErrorElement onError = project.CreateOnErrorElement("et");
target.AppendChild(onError);
Helpers.ClearDirtyFlag(project);
onError.ExecuteTargetsAttribute = "et2";
Assert.AreEqual("et2", onError.ExecuteTargetsAttribute);
Assert.AreEqual(true, project.HasUnsavedChanges);
}
/// <summary>
/// Get a basic ProjectOnErrorElement
/// </summary>
private static ProjectOnErrorElement GetOnError()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<OnError ExecuteTargets='t' Condition='c'/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children);
return onError;
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
namespace Microsoft.Extensions.Caching.StackExchangeRedis
{
/// <summary>
/// Distributed cache implementation using Redis.
/// <para>Uses <c>StackExchange.Redis</c> as the Redis client.</para>
/// </summary>
public class RedisCache : IDistributedCache, IDisposable
{
// KEYS[1] = = key
// ARGV[1] = absolute-expiration - ticks as long (-1 for none)
// ARGV[2] = sliding-expiration - ticks as long (-1 for none)
// ARGV[3] = relative-expiration (long, in seconds, -1 for none) - Min(absolute-expiration - Now, sliding-expiration)
// ARGV[4] = data - byte[]
// this order should not change LUA script depends on it
private const string SetScript = (@"
redis.call('HSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4])
if ARGV[3] ~= '-1' then
redis.call('EXPIRE', KEYS[1], ARGV[3])
end
return 1");
private const string AbsoluteExpirationKey = "absexp";
private const string SlidingExpirationKey = "sldexp";
private const string DataKey = "data";
private const long NotPresent = -1;
private volatile IConnectionMultiplexer _connection;
private IDatabase _cache;
private bool _disposed;
private readonly RedisCacheOptions _options;
private readonly string _instance;
private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(initialCount: 1, maxCount: 1);
/// <summary>
/// Initializes a new instance of <see cref="RedisCache"/>.
/// </summary>
/// <param name="optionsAccessor">The configuration options.</param>
public RedisCache(IOptions<RedisCacheOptions> optionsAccessor)
{
if (optionsAccessor == null)
{
throw new ArgumentNullException(nameof(optionsAccessor));
}
_options = optionsAccessor.Value;
// This allows partitioning a single backend cache for use with multiple apps/services.
_instance = _options.InstanceName ?? string.Empty;
}
/// <inheritdoc />
public byte[] Get(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return GetAndRefresh(key, getData: true);
}
/// <inheritdoc />
public async Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
return await GetAndRefreshAsync(key, getData: true, token: token).ConfigureAwait(false);
}
/// <inheritdoc />
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
Connect();
var creationTime = DateTimeOffset.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(creationTime, options);
var result = _cache.ScriptEvaluate(SetScript, new RedisKey[] { _instance + key },
new RedisValue[]
{
absoluteExpiration?.Ticks ?? NotPresent,
options.SlidingExpiration?.Ticks ?? NotPresent,
GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? NotPresent,
value
});
}
/// <inheritdoc />
public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
token.ThrowIfCancellationRequested();
await ConnectAsync(token).ConfigureAwait(false);
var creationTime = DateTimeOffset.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(creationTime, options);
await _cache.ScriptEvaluateAsync(SetScript, new RedisKey[] { _instance + key },
new RedisValue[]
{
absoluteExpiration?.Ticks ?? NotPresent,
options.SlidingExpiration?.Ticks ?? NotPresent,
GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? NotPresent,
value
}).ConfigureAwait(false);
}
/// <inheritdoc />
public void Refresh(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
GetAndRefresh(key, getData: false);
}
/// <inheritdoc />
public async Task RefreshAsync(string key, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
await GetAndRefreshAsync(key, getData: false, token: token).ConfigureAwait(false);
}
private void Connect()
{
CheckDisposed();
if (_cache != null)
{
return;
}
_connectionLock.Wait();
try
{
if (_cache == null)
{
if(_options.ConnectionMultiplexerFactory == null)
{
if (_options.ConfigurationOptions is not null)
{
_connection = ConnectionMultiplexer.Connect(_options.ConfigurationOptions);
}
else
{
_connection = ConnectionMultiplexer.Connect(_options.Configuration);
}
}
else
{
_connection = _options.ConnectionMultiplexerFactory().GetAwaiter().GetResult();
}
TryRegisterProfiler();
_cache = _connection.GetDatabase();
}
}
finally
{
_connectionLock.Release();
}
}
private async Task ConnectAsync(CancellationToken token = default(CancellationToken))
{
CheckDisposed();
token.ThrowIfCancellationRequested();
if (_cache != null)
{
return;
}
await _connectionLock.WaitAsync(token).ConfigureAwait(false);
try
{
if (_cache == null)
{
if(_options.ConnectionMultiplexerFactory is null)
{
if (_options.ConfigurationOptions is not null)
{
_connection = await ConnectionMultiplexer.ConnectAsync(_options.ConfigurationOptions).ConfigureAwait(false);
}
else
{
_connection = await ConnectionMultiplexer.ConnectAsync(_options.Configuration).ConfigureAwait(false);
}
}
else
{
_connection = await _options.ConnectionMultiplexerFactory();
}
TryRegisterProfiler();
_cache = _connection.GetDatabase();
}
}
finally
{
_connectionLock.Release();
}
}
private void TryRegisterProfiler()
{
if (_connection != null && _options.ProfilingSession != null)
{
_connection.RegisterProfiler(_options.ProfilingSession);
}
}
private byte[] GetAndRefresh(string key, bool getData)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
Connect();
// This also resets the LRU status as desired.
// TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
RedisValue[] results;
if (getData)
{
results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey);
}
else
{
results = _cache.HashMemberGet(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey);
}
// TODO: Error handling
if (results.Length >= 2)
{
MapMetadata(results, out DateTimeOffset? absExpr, out TimeSpan? sldExpr);
Refresh(key, absExpr, sldExpr);
}
if (results.Length >= 3 && results[2].HasValue)
{
return results[2];
}
return null;
}
private async Task<byte[]> GetAndRefreshAsync(string key, bool getData, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
await ConnectAsync(token).ConfigureAwait(false);
// This also resets the LRU status as desired.
// TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
RedisValue[] results;
if (getData)
{
results = await _cache.HashMemberGetAsync(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey).ConfigureAwait(false);
}
else
{
results = await _cache.HashMemberGetAsync(_instance + key, AbsoluteExpirationKey, SlidingExpirationKey).ConfigureAwait(false);
}
// TODO: Error handling
if (results.Length >= 2)
{
MapMetadata(results, out DateTimeOffset? absExpr, out TimeSpan? sldExpr);
await RefreshAsync(key, absExpr, sldExpr, token).ConfigureAwait(false);
}
if (results.Length >= 3 && results[2].HasValue)
{
return results[2];
}
return null;
}
/// <inheritdoc />
public void Remove(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
Connect();
_cache.KeyDelete(_instance + key);
// TODO: Error handling
}
/// <inheritdoc />
public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
await ConnectAsync(token).ConfigureAwait(false);
await _cache.KeyDeleteAsync(_instance + key).ConfigureAwait(false);
// TODO: Error handling
}
private void MapMetadata(RedisValue[] results, out DateTimeOffset? absoluteExpiration, out TimeSpan? slidingExpiration)
{
absoluteExpiration = null;
slidingExpiration = null;
var absoluteExpirationTicks = (long?)results[0];
if (absoluteExpirationTicks.HasValue && absoluteExpirationTicks.Value != NotPresent)
{
absoluteExpiration = new DateTimeOffset(absoluteExpirationTicks.Value, TimeSpan.Zero);
}
var slidingExpirationTicks = (long?)results[1];
if (slidingExpirationTicks.HasValue && slidingExpirationTicks.Value != NotPresent)
{
slidingExpiration = new TimeSpan(slidingExpirationTicks.Value);
}
}
private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
// Note Refresh has no effect if there is just an absolute expiration (or neither).
TimeSpan? expr = null;
if (sldExpr.HasValue)
{
if (absExpr.HasValue)
{
var relExpr = absExpr.Value - DateTimeOffset.Now;
expr = relExpr <= sldExpr.Value ? relExpr : sldExpr;
}
else
{
expr = sldExpr;
}
_cache.KeyExpire(_instance + key, expr);
// TODO: Error handling
}
}
private async Task RefreshAsync(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
// Note Refresh has no effect if there is just an absolute expiration (or neither).
TimeSpan? expr = null;
if (sldExpr.HasValue)
{
if (absExpr.HasValue)
{
var relExpr = absExpr.Value - DateTimeOffset.Now;
expr = relExpr <= sldExpr.Value ? relExpr : sldExpr;
}
else
{
expr = sldExpr;
}
await _cache.KeyExpireAsync(_instance + key, expr).ConfigureAwait(false);
// TODO: Error handling
}
}
private static long? GetExpirationInSeconds(DateTimeOffset creationTime, DateTimeOffset? absoluteExpiration, DistributedCacheEntryOptions options)
{
if (absoluteExpiration.HasValue && options.SlidingExpiration.HasValue)
{
return (long)Math.Min(
(absoluteExpiration.Value - creationTime).TotalSeconds,
options.SlidingExpiration.Value.TotalSeconds);
}
else if (absoluteExpiration.HasValue)
{
return (long)(absoluteExpiration.Value - creationTime).TotalSeconds;
}
else if (options.SlidingExpiration.HasValue)
{
return (long)options.SlidingExpiration.Value.TotalSeconds;
}
return null;
}
private static DateTimeOffset? GetAbsoluteExpiration(DateTimeOffset creationTime, DistributedCacheEntryOptions options)
{
if (options.AbsoluteExpiration.HasValue && options.AbsoluteExpiration <= creationTime)
{
throw new ArgumentOutOfRangeException(
nameof(DistributedCacheEntryOptions.AbsoluteExpiration),
options.AbsoluteExpiration.Value,
"The absolute expiration value must be in the future.");
}
if (options.AbsoluteExpirationRelativeToNow.HasValue)
{
return creationTime + options.AbsoluteExpirationRelativeToNow;
}
return options.AbsoluteExpiration;
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_connection?.Close();
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
}
}
| |
//
// $Id: GraphForm.cs 2321 2010-10-21 20:26:30Z chambm $
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2009 Vanderbilt University - Nashville, TN 37232
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using DigitalRune.Windows.Docking;
using pwiz.MSGraph;
using ZedGraph;
using System.Diagnostics;
using System.Linq;
using pwiz.Common.Collections;
using SpyTools;
namespace seems
{
public partial class HeatmapForm : DockableForm
{
public pwiz.MSGraph.MSGraphControl ZedGraphControl { get { return msGraphControl; } }
private class BoundingBox
{
public double MinX { get; set; }
public double MinY { get; set; }
public double MaxX { get; set; }
public double MaxY { get; set; }
}
private struct MobilityBin
{
public MobilityBin(double ionMobility, int binIndex) : this()
{
IonMobility = ionMobility;
BinIndex = binIndex;
}
public double IonMobility { get; private set; }
public int BinIndex { get; private set; }
}
private class ChromatogramControl : IMSGraphItemExtended
{
public ChromatogramControl(ManagedDataSource source, int targetMsLevel, GraphPane graphPane)
{
Title = String.Format("TIC Chromatogram (ms{0})", targetMsLevel);
var dgv = source.SpectrumListForm.GridView;
var scanTimeColumn = dgv.Columns["ScanTime"];
var ticColumn = dgv.Columns["TotalIonCurrent"];
var msLevelColumn = dgv.Columns["MsLevel"];
IntensityByScanTime = new SortedList<double, double>(dgv.RowCount / 200);
for (int i = 0; i < dgv.RowCount; ++i)
{
int msLevel = (int) dgv[msLevelColumn.Index, i].Value;
if (targetMsLevel != msLevel)
continue;
double scanTime = (double) dgv[scanTimeColumn.Index, i].Value;
double intensity = (double) dgv[ticColumn.Index, i].Value;
if (!IntensityByScanTime.ContainsKey(scanTime))
IntensityByScanTime[scanTime] = intensity;
else
IntensityByScanTime[scanTime] += intensity;
}
Points = new PointPairList(IntensityByScanTime.Keys, IntensityByScanTime.Values);
Source = source;
MsLevel = targetMsLevel;
GraphPane = graphPane;
SelectedTime = 0;
}
public MSGraphItemType GraphItemType { get {return MSGraphItemType.chromatogram;} }
public MSGraphItemDrawMethod GraphItemDrawMethod { get {return MSGraphItemDrawMethod.line;} }
public string Title { get; private set; }
public Color Color { get { return Color.Gray; } }
public float LineWidth { get { return ZedGraph.LineBase.Default.Width; } }
public void CustomizeXAxis(Axis axis)
{
axis.Title.IsVisible = false;
}
public void CustomizeYAxis(Axis axis)
{
axis.Title.FontSpec.Family = "Arial";
axis.Title.FontSpec.Size = 14;
axis.Color = axis.Title.FontSpec.FontColor = Color.Black;
axis.Title.FontSpec.Border.IsVisible = false;
axis.Title.Text = "Intensity";
}
public PointAnnotation AnnotatePoint(PointPair point)
{
return new PointAnnotation();
}
public void AddAnnotations(MSGraphPane graphPane, Graphics g, MSPointList pointList, GraphObjList annotations)
{
}
public void CustomizeCurve(CurveItem curveItem)
{
var line = curveItem as LineItem;
if (line != null) line.Symbol = new Symbol(SymbolType.Circle, Color) { Fill = new Fill(new SolidBrush(Color)) };
}
public void AddPreCurveAnnotations(MSGraphPane graphPane, Graphics g, MSPointList pointList, GraphObjList annotations)
{
}
public void SelectTime(double scanTime)
{
int index = IntensityByScanTime.IndexOfKey(scanTime);
if (index < 0)
throw new ArgumentOutOfRangeException("scanTime", "time point not found in chromatogram");
GraphPane.GraphObjList.RemoveAll(o => o is LineObj);
GraphPane.GraphObjList.Add(new LineObj {Location = new Location(scanTime, 0, 0, 1, CoordType.XScaleYChartFraction, AlignH.Center, AlignV.Center), Line = new Line(Color.PaleVioletRed) { Width = 2 } });
SelectedTime = scanTime;
}
public SortedList<double, double> IntensityByScanTime { get; private set; }
public IPointList Points { get; private set; }
public ManagedDataSource Source { get; private set; }
public int MsLevel { get; private set; }
public GraphPane GraphPane { get; private set; }
public double SelectedTime { get; private set; }
}
private List<BoundingBox> heatmapBoundsByMsLevel; // updated when scan time changes
private List<ChromatogramControl> ticChromatogramByMsLevel; // 1 chromatogram per ms level
private List<HeatMapGraphPane> heatmapGraphPaneByMsLevel; // 1 heatmap per ms level
private List<Map<double, List<MobilityBin>>> ionMobilityBinsByMsLevelAndScanTime;
private ManagedDataSource source;
private Manager manager;
public HeatmapForm(Manager manager, ManagedDataSource source)
{
InitializeComponent();
this.manager = manager;
this.source = source;
heatmapGraphPaneByMsLevel = new List<HeatMapGraphPane>();
ticChromatogramByMsLevel = new List<ChromatogramControl>();
heatmapBoundsByMsLevel = new List<BoundingBox>();
ionMobilityBinsByMsLevelAndScanTime = new List<Map<double, List<MobilityBin>>>();
msGraphControl.BorderStyle = BorderStyle.None;
msGraphControl.MasterPane.InnerPaneGap = 1;
msGraphControl.MouseDownEvent += msGraphControl_MouseDownEvent;
msGraphControl.MouseUpEvent += msGraphControl_MouseUpEvent;
msGraphControl.MouseMoveEvent += msGraphControl_MouseMoveEvent;
msGraphControl.ZoomButtons = MouseButtons.Left;
msGraphControl.ZoomModifierKeys = Keys.None;
msGraphControl.ZoomButtons2 = MouseButtons.None;
msGraphControl.UnzoomButtons = new MSGraphControl.MouseButtonClicks( MouseButtons.Middle );
msGraphControl.UnzoomModifierKeys = Keys.None;
msGraphControl.UnzoomButtons2 = new MSGraphControl.MouseButtonClicks( MouseButtons.None );
msGraphControl.UnzoomAllButtons = new MSGraphControl.MouseButtonClicks( MouseButtons.Left, 2 );
msGraphControl.UnzoomAllButtons2 = new MSGraphControl.MouseButtonClicks( MouseButtons.None );
msGraphControl.PanButtons = MouseButtons.Left;
msGraphControl.PanModifierKeys = Keys.Control;
msGraphControl.PanButtons2 = MouseButtons.None;
msGraphControl.ZoomEvent += msGraphControl_ZoomEvent;
msGraphControl.IsEnableVZoom = msGraphControl.IsEnableVPan = true;
Text = TabText = source.Source.Name + " Heatmaps";
ContextMenuStrip dummyMenu = new ContextMenuStrip();
dummyMenu.Opening += foo_Opening;
TabPageContextMenuStrip = dummyMenu;
}
private void setScale(Scale scale, double min, double max, bool isZoom=false)
{
double scaleFactor = Math.Pow(10, Math.Floor(Math.Log10(max - min))) / 10;
if (isZoom)
{
scale.Min = Math.Max(scale.Min, Math.Floor(min / scaleFactor) * scaleFactor);
scale.Max = Math.Min(scale.Max, Math.Ceiling(max / scaleFactor) * scaleFactor);
}
else
{
scale.Min = Math.Floor(min / scaleFactor) * scaleFactor;
scale.Max = Math.Ceiling(max / scaleFactor) * scaleFactor;
}
}
void msGraphControl_ZoomEvent(ZedGraphControl sender, ZoomState oldState, ZoomState newState, PointF mousePosition)
{
for (int i = 0; i < heatmapGraphPaneByMsLevel.Count; ++i)
{
var bounds = heatmapBoundsByMsLevel[i];
setScale(heatmapGraphPaneByMsLevel[i].XAxis.Scale, bounds.MinX, bounds.MaxX, true);
setScale(heatmapGraphPaneByMsLevel[i].YAxis.Scale, bounds.MinY, bounds.MaxY, true);
}
}
private void ShowHeatmap(double scanTime, int msLevel)
{
if (ionMobilityBinsByMsLevelAndScanTime.Count <= msLevel) throw new ArgumentOutOfRangeException("msLevel", "no ion mobility bins for ms level " + msLevel);
var ionMobilityBinsByScanTime = ionMobilityBinsByMsLevelAndScanTime[msLevel];
if (!ionMobilityBinsByScanTime.Contains(scanTime)) throw new ArgumentOutOfRangeException("scanTime", "no ion mobility bins for scan time " + scanTime);
var ionMobilityBins = ionMobilityBinsByScanTime[scanTime];
var heatmapPoints = new List<Point3D>(ionMobilityBins.Count);
var heatmapGraphPane = heatmapGraphPaneByMsLevel[msLevel];
heatmapGraphPane.CurveList.Clear();
heatmapGraphPane.GraphObjList.Add(new TextObj("Loading...", 0.5, 0.5, CoordType.ChartFraction) {FontSpec = new FontSpec {Border = new Border {IsVisible = false}, IsBold = true, Size = 24}});
msGraphControl.Refresh();
var bounds = heatmapBoundsByMsLevel[msLevel];
foreach (var bin in ionMobilityBins)
{
var spectrum = source.GetMassSpectrum(bin.BinIndex);
var points = spectrum.Points;
for (int j = 0; j < points.Count; ++j)
{
double mz = points[j].X;
double intensity = points[j].Y;
bounds.MinX = Math.Min(bounds.MinX, mz);
bounds.MinY = Math.Min(bounds.MinY, bin.IonMobility);
bounds.MaxX = Math.Max(bounds.MaxX, mz);
bounds.MaxY = Math.Max(bounds.MaxY, bin.IonMobility);
heatmapPoints.Add(new Point3D(mz, bin.IonMobility, intensity));
}
}
var g = msGraphControl.CreateGraphics();
var heatmapData = new HeatMapData(heatmapPoints);
heatmapGraphPane.GraphObjList.Clear(); // remove "Loading..."
heatmapGraphPane.SetPoints(heatmapData, bounds.MinY, bounds.MaxY);
heatmapGraphPane.Title.Text = String.Format("Ion Mobility Heatmap (ms{0} @ {1:F4} min.)", msLevel + 1, scanTime);
setScale(heatmapGraphPane.XAxis.Scale, bounds.MinX, bounds.MaxX);
setScale(heatmapGraphPane.YAxis.Scale, bounds.MinY, bounds.MaxY);
heatmapGraphPane.AxisChange(g);
heatmapGraphPane.SetScale(g);
msGraphControl.Refresh();
}
protected override void OnShown(EventArgs e)
{
var dgv = source.SpectrumListForm.GridView;
var ionMobilityColumn = dgv.Columns["IonMobility"];
if (ionMobilityColumn == null || !ionMobilityColumn.Visible)
throw new InvalidOperationException("cannot show heatmap if SpectrumListForm doesn't have an IonMobility column");
var scanTimeColumn = dgv.Columns["ScanTime"];
var ticColumn = dgv.Columns["TotalIonCurrent"];
var msLevelColumn = dgv.Columns["MsLevel"];
var dataPointsColumn = dgv.Columns["DataPoints"];
if (scanTimeColumn == null || ticColumn == null || msLevelColumn == null || dataPointsColumn == null)
throw new InvalidOperationException("scan time, TIC, ms level, and data points columns should never be null");
// build map of ms levels, to scan times, to scan indices
for (int i = 0; i < dgv.RowCount; ++i)
{
int msLevel = (int) dgv[msLevelColumn.Index, i].Value - 1;
while (heatmapGraphPaneByMsLevel.Count <= msLevel)
{
heatmapBoundsByMsLevel.Add(new BoundingBox { MinX = Double.MaxValue, MaxX = Double.MinValue, MinY = Double.MaxValue, MaxY = Double.MinValue });
heatmapGraphPaneByMsLevel.Add(new HeatMapGraphPane()
{
ShowHeatMap = true,
MinDotRadius = 4,
MaxDotRadius = 13,
//XAxis = {Title = {Text = "Scan Time"}},
XAxis = {Title = {Text = "m/z"}},
YAxis = {Title = {Text = "Ion Mobility"}},
Legend = {IsVisible = false},
Title = {Text = String.Format("Ion Mobility Heatmap (ms{0})", msLevel+1), IsVisible = true},
LockYAxisAtZero = false
});
ionMobilityBinsByMsLevelAndScanTime.Add(new Map<double, List<MobilityBin>>());
}
int dataPoints = Convert.ToInt32(dgv[dataPointsColumn.Index, i].Value);
if (dataPoints == 0)
continue;
double scanTime = (double) dgv[scanTimeColumn.Index, i].Value;
double ionMobility = (double) dgv[ionMobilityColumn.Index, i].Value;
//double intensity = (double) dgv[ticColumn.Index, i].Value;
ionMobilityBinsByMsLevelAndScanTime[msLevel][scanTime].Add(new MobilityBin(ionMobility, i));
}
var g = msGraphControl.CreateGraphics();
msGraphControl.MasterPane.PaneList.Clear();
int numColumns = ionMobilityBinsByMsLevelAndScanTime.Count(o => o.IsNullOrEmpty()); // skip empty MS levels (e.g. files with only MS2)
var rowCounts = new int[2] {numColumns, numColumns};
msGraphControl.MasterPane.SetLayout(g, true, rowCounts, new float[2] {0.25f, 0.75f});
// first row is control chromatograms
for (int i = 0; i < heatmapGraphPaneByMsLevel.Count; ++i)
{
if (ionMobilityBinsByMsLevelAndScanTime[i].IsNullOrEmpty())
{
ticChromatogramByMsLevel.Add(null);
continue; // skip empty MS levels (e.g. files with only MS2)
}
var chromatogramPane = new MSGraphPane()
{
Legend = {IsVisible = false},
Title = {Text = String.Format("TIC Chromatogram (ms{0})", i + 1), IsVisible = true},
Tag = i
};
msGraphControl.MasterPane.Add(chromatogramPane);
ticChromatogramByMsLevel.Add(new ChromatogramControl(source, i + 1, chromatogramPane));
msGraphControl.AddGraphItem(chromatogramPane, ticChromatogramByMsLevel[i], true);
}
// second row is heatmaps
for (int i = 0; i < heatmapGraphPaneByMsLevel.Count; ++i)
{
if (ionMobilityBinsByMsLevelAndScanTime[i].IsNullOrEmpty())
continue; // skip empty MS levels (e.g. files with only MS2)
var heatmapGraphPane = heatmapGraphPaneByMsLevel[i];
msGraphControl.MasterPane.Add(heatmapGraphPane);
heatmapGraphPane.GraphObjList.Add(new TextObj("Click on a chromatogram point to generate an IMS heatmap...", 0.5, 0.5, CoordType.ChartFraction) { FontSpec = new FontSpec { Border = new Border { IsVisible = false }, IsBold = true, Size = 16 } });
var bounds = heatmapBoundsByMsLevel[i];
setScale(heatmapGraphPane.XAxis.Scale, 0, 2000);
setScale(heatmapGraphPane.YAxis.Scale, 0, 100);
heatmapGraphPane.AxisChange(g);
heatmapGraphPane.SetScale(g);
}
//msGraphControl.PerformAutoScale();
msGraphControl.MasterPane.DoLayout(g);
msGraphControl.Refresh();
base.OnShown(e);
}
void foo_Opening( object sender, CancelEventArgs e )
{
// close the active form when the tab page strip is right-clicked
Close();
}
bool msGraphControl_MouseMoveEvent( ZedGraphControl sender, MouseEventArgs e )
{
MSGraphPane hoverPane = sender.MasterPane.FindPane( e.Location ) as MSGraphPane;
if( hoverPane == null )
return false;
CurveItem nearestCurve;
int nearestIndex;
//change the cursor if the mouse is sufficiently close to a point
if( hoverPane.FindNearestPoint( e.Location, out nearestCurve, out nearestIndex ) )
{
msGraphControl.Cursor = Cursors.Cross;
} else
{
msGraphControl.Cursor = Cursors.Default;
}
return false;
}
private int distance(Point p1, Point p2)
{
return (int) Math.Round(Math.Sqrt(Math.Pow((p2.X - p1.X), 2) + Math.Pow((p2.Y - p1.Y), 2)));
}
private Point lastMouseDownPos;
bool msGraphControl_MouseDownEvent(ZedGraphControl sender, MouseEventArgs e)
{
// record mouse down point in control chromatogram (to determine whether the user is doing a drag-to-zoom)
var focusedPane = sender.MasterPane.FindPane(e.Location) as MSGraphPane;
if (focusedPane == null || focusedPane.Tag == null)
return false;
lastMouseDownPos = e.Location;
return false;
}
bool msGraphControl_MouseUpEvent( ZedGraphControl sender, MouseEventArgs e )
{
// change heatmap when user clicks in a control chromatogram (unless they're dragging a zoom box)
var focusedPane = sender.MasterPane.FindPane( e.Location ) as MSGraphPane;
if (focusedPane == null || focusedPane.Tag == null)
return false;
CurveItem nearestCurve; int nearestIndex;
focusedPane.FindNearestPoint( e.Location, out nearestCurve, out nearestIndex );
if (nearestCurve == null)
return false;
if (distance(e.Location, lastMouseDownPos) > 2)
return false;
int msLevelIndex = (int) focusedPane.Tag;
double scanTime = nearestCurve[nearestIndex].X;
ticChromatogramByMsLevel[msLevelIndex].SelectTime(scanTime);
ShowHeatmap(scanTime, msLevelIndex);
return false;
}
private void GraphForm_ResizeBegin( object sender, EventArgs e )
{
SuspendLayout();
msGraphControl.Visible = false;
Refresh();
}
private void GraphForm_ResizeEnd( object sender, EventArgs e )
{
ResumeLayout();
msGraphControl.Visible = true;
Refresh();
}
}
}
| |
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien ([email protected])
// 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 Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
#if DOTNET35
using System;
using System.Collections.Generic;
using Rhino.Mocks.Exceptions;
using Rhino.Mocks.Generated;
using Rhino.Mocks.Interfaces;
namespace Rhino.Mocks
{
/// <summary>
/// A set of extension methods that adds Arrange Act Assert mode to Rhino Mocks
/// </summary>
public static class RhinoMocksExtensions
{
/// <summary>
/// Create an expectation on this mock for this action to occur
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<VoidType> Expect<T>(this T mock, Action<T> action)
where T : class
{
return Expect<T, VoidType>(mock, t =>
{
action(t);
return null;
});
}
/// <summary>
/// Reset all expectations on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
public static void BackToRecord<T>(this T mock)
{
BackToRecord(mock, BackToRecordOptions.All);
}
/// <summary>
/// Reset the selected expectation on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="options">The options to reset the expectations on this mock.</param>
public static void BackToRecord<T>(this T mock, BackToRecordOptions options)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
var mocks = mockedObject.Repository;
mocks.BackToRecord(mock, options);
}
/// <summary>
/// Cause the mock state to change to replay, any further call is compared to the
/// ones that were called in the record state.
/// </summary>
/// <param name="mock">the mocked object to move to replay state</param>
public static void Replay<T>(this T mock)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
var mocks = mockedObject.Repository;
if (mocks.IsInReplayMode(mock) != true)
mocks.Replay(mockedObject);
}
/// <summary>
/// Gets the mock repository for this specificied mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <returns></returns>
public static MockRepository GetMockRepository<T>(this T mock)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
return mockedObject.Repository;
}
/// <summary>
/// Create an expectation on this mock for this action to occur
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="R"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<R> Expect<T, R>(this T mock, Function<T, R> action)
where T : class
{
if (mock == null)
throw new ArgumentNullException("mock", "You cannot mock a null instance");
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
MockRepository mocks = mockedObject.Repository;
var isInReplayMode = mocks.IsInReplayMode(mock);
mocks.BackToRecord(mock, BackToRecordOptions.None);
action(mock);
IMethodOptions<R> options = LastCall.GetOptions<R>();
options.TentativeReturn();
if (isInReplayMode)
mocks.ReplayCore(mock, false);
return options;
}
/// <summary>
/// Tell the mock object to perform a certain action when a matching
/// method is called.
/// Does not create an expectation for this method.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<object> Stub<T>(this T mock, Action<T> action)
where T : class
{
return Stub<T, object>(mock, t =>
{
action(t);
return null;
});
}
/// <summary>
/// Tell the mock object to perform a certain action when a matching
/// method is called.
/// Does not create an expectation for this method.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="R"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
public static IMethodOptions<R> Stub<T, R>(this T mock, Function<T, R> action)
where T : class
{
return Expect(mock, action).Repeat.Times(0, int.MaxValue);
}
/// <summary>
/// Gets the arguments for calls made on this mock object and the method that was called
/// in the action.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <returns></returns>
/// <example>
/// Here we will get all the arguments for all the calls made to DoSomething(int)
/// <code>
/// var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0))
/// </code>
/// </example>
public static IList<object[]> GetArgumentsForCallsMadeOn<T>(this T mock, Action<T> action)
{
return GetArgumentsForCallsMadeOn(mock, action, DefaultConstraintSetup);
}
/// <summary>
/// Gets the arguments for calls made on this mock object and the method that was called
/// in the action and matches the given constraints
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
/// <returns></returns>
/// <example>
/// Here we will get all the arguments for all the calls made to DoSomething(int)
/// <code>
/// var argsForCalls = foo54.GetArgumentsForCallsMadeOn(x => x.DoSomething(0))
/// </code>
/// </example>
public static IList<object[]> GetArgumentsForCallsMadeOn<T>(this T mock, Action<T> action, Action<IMethodOptions<object>> setupConstraints)
{
return GetExpectationsToVerify(mock, action, setupConstraints).ArgumentsForAllCalls;
}
/// <summary>
/// Asserts that a particular method was called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasCalled<T>(this T mock, Action<T> action)
{
AssertWasCalled(mock, action, DefaultConstraintSetup);
}
private static void DefaultConstraintSetup(IMethodOptions<object> options)
{
}
/// <summary>
/// Asserts that a particular method was called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasCalled<T>(this T mock, Action<T> action, Action<IMethodOptions<object>> setupConstraints)
{
ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints);
foreach (var args in verificationInformation.ArgumentsForAllCalls)
{
if (verificationInformation.Expected.IsExpected(args))
{
verificationInformation.Expected.AddActualCall();
}
}
if (verificationInformation.Expected.ExpectationSatisfied)
return;
throw new ExpectationViolationException(verificationInformation.Expected.BuildVerificationFailureMessage());
}
/// <summary>
/// Asserts that a particular method was called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasCalled<T>(this T mock, Func<T, object> action)
{
var newAction = new Action<T>(t => action(t));
AssertWasCalled(mock, newAction, DefaultConstraintSetup);
}
/// <summary>
/// Asserts that a particular method was called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasCalled<T>(this T mock, Func<T, object> action, Action<IMethodOptions<object>> setupConstraints)
{
var newAction = new Action<T>(t => action(t));
AssertWasCalled(mock, newAction, setupConstraints);
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasNotCalled<T>(this T mock, Action<T> action)
{
AssertWasNotCalled(mock, action, DefaultConstraintSetup);
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object that match
/// a particular constraint set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasNotCalled<T>(this T mock, Action<T> action, Action<IMethodOptions<object>> setupConstraints)
{
ExpectationVerificationInformation verificationInformation = GetExpectationsToVerify(mock, action, setupConstraints);
foreach (var args in verificationInformation.ArgumentsForAllCalls)
{
if (verificationInformation.Expected.IsExpected(args))
throw new ExpectationViolationException("Expected that " +
verificationInformation.Expected.ErrorMessage +
" would not be called, but it was found on the actual calls made on the mocked object.");
}
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
public static void AssertWasNotCalled<T>(this T mock, Func<T, object> action)
{
var newAction = new Action<T>(t => action(t));
AssertWasNotCalled(mock, newAction, DefaultConstraintSetup);
}
/// <summary>
/// Asserts that a particular method was NOT called on this mock object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mock">The mock.</param>
/// <param name="action">The action.</param>
/// <param name="setupConstraints">The setup constraints.</param>
public static void AssertWasNotCalled<T>(this T mock, Func<T, object> action, Action<IMethodOptions<object>> setupConstraints)
{
var newAction = new Action<T>(t => action(t));
AssertWasNotCalled(mock, newAction, setupConstraints);
}
private static ExpectationVerificationInformation GetExpectationsToVerify<T>(T mock, Action<T> action,
Action<IMethodOptions<object>>
setupConstraints)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mock);
MockRepository mocks = mockedObject.Repository;
if (mocks.IsInReplayMode(mockedObject) == false)
{
throw new InvalidOperationException(
"Cannot assert on an object that is not in replay mode. Did you forget to call ReplayAll() ?");
}
var mockToRecordExpectation =
(T)mocks.DynamicMock(FindAppropriteType(mockedObject), mockedObject.ConstructorArguments);
action(mockToRecordExpectation);
AssertExactlySingleExpectaton(mocks, mockToRecordExpectation);
IMethodOptions<object> lastMethodCall = mocks.LastMethodCall<object>(mockToRecordExpectation);
lastMethodCall.TentativeReturn();
if (setupConstraints != null)
{
setupConstraints(lastMethodCall);
}
ExpectationsList expectationsToVerify = mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation);
if (expectationsToVerify.Count == 0)
throw new InvalidOperationException(
"The expectation was removed from the waiting expectations list, did you call Repeat.Any() ? This is not supported in AssertWasCalled()");
IExpectation expected = expectationsToVerify[0];
ICollection<object[]> argumentsForAllCalls = mockedObject.GetCallArgumentsFor(expected.Method);
return new ExpectationVerificationInformation
{
ArgumentsForAllCalls = new List<object[]>(argumentsForAllCalls),
Expected = expected
};
}
/// <summary>
/// Finds the approprite implementation type of this item.
/// This is the class or an interface outside of the rhino mocks.
/// </summary>
/// <param name="mockedObj">The mocked obj.</param>
/// <returns></returns>
private static Type FindAppropriteType(IMockedObject mockedObj)
{
foreach (var type in mockedObj.ImplementedTypes)
{
if(type.IsClass)
return type;
}
foreach (var type in mockedObj.ImplementedTypes)
{
if(type.Assembly==typeof(IMockedObject).Assembly)
continue;
return type;
}
return mockedObj.ImplementedTypes[0];
}
/// <summary>
/// Verifies all expectations on this mock object
/// </summary>
/// <param name="mockObject">The mock object.</param>
public static void VerifyAllExpectations(this object mockObject)
{
IMockedObject mockedObject = MockRepository.GetMockedObject(mockObject);
mockedObject.Repository.Verify(mockedObject);
}
/// <summary>
/// Gets the event raiser for the event that was called in the action passed
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <param name="mockObject">The mock object.</param>
/// <param name="eventSubscription">The event subscription.</param>
/// <returns></returns>
public static IEventRaiser GetEventRaiser<TEventSource>(this TEventSource mockObject, Action<TEventSource> eventSubscription)
where TEventSource : class
{
return mockObject
.Stub(eventSubscription)
.IgnoreArguments()
.GetEventRaiser();
}
/// <summary>
/// Raise the specified event using the passed arguments.
/// The even is extracted from the passed labmda
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <param name="mockObject">The mock object.</param>
/// <param name="eventSubscription">The event subscription.</param>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param>
public static void Raise<TEventSource>(this TEventSource mockObject, Action<TEventSource> eventSubscription, object sender, EventArgs args)
where TEventSource : class
{
var eventRaiser = GetEventRaiser(mockObject, eventSubscription);
eventRaiser.Raise(sender, args);
}
/// <summary>
/// Raise the specified event using the passed arguments.
/// The even is extracted from the passed labmda
/// </summary>
/// <typeparam name="TEventSource">The type of the event source.</typeparam>
/// <param name="mockObject">The mock object.</param>
/// <param name="eventSubscription">The event subscription.</param>
/// <param name="args">The args.</param>
public static void Raise<TEventSource>(this TEventSource mockObject, Action<TEventSource> eventSubscription, params object[] args)
where TEventSource : class
{
var eventRaiser = GetEventRaiser(mockObject, eventSubscription);
eventRaiser.Raise(args);
}
private static void AssertExactlySingleExpectaton<T>(MockRepository mocks, T mockToRecordExpectation)
{
if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count == 0)
throw new InvalidOperationException(
"No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call");
if (mocks.Replayer.GetAllExpectationsForProxy(mockToRecordExpectation).Count > 1)
throw new InvalidOperationException(
"You can only use a single expectation on AssertWasCalled(), use separate calls to AssertWasCalled() if you want to verify several expectations");
}
#region Nested type: VoidType
/// <summary>
/// Fake type that disallow creating it.
/// Should have been System.Type, but we can't use it.
/// </summary>
public class VoidType
{
private VoidType()
{
}
}
#endregion
}
}
#endif
| |
using System;
using System.Collections;
using Org.BouncyCastle.Asn1.X500;
using Org.BouncyCastle.Asn1.X509;
namespace Org.BouncyCastle.Asn1.IsisMtt.X509
{
/**
* Attribute to indicate that the certificate holder may sign in the name of a
* third person.
* <p>
* ISIS-MTT PROFILE: The corresponding ProcurationSyntax contains either the
* name of the person who is represented (subcomponent thirdPerson) or a
* reference to his/her base certificate (in the component signingFor,
* subcomponent certRef), furthermore the optional components country and
* typeSubstitution to indicate the country whose laws apply, and respectively
* the type of procuration (e.g. manager, procuration, custody).
* </p>
* <p>
* ISIS-MTT PROFILE: The GeneralName MUST be of type directoryName and MAY only
* contain: - RFC3039 attributes, except pseudonym (countryName, commonName,
* surname, givenName, serialNumber, organizationName, organizationalUnitName,
* stateOrProvincename, localityName, postalAddress) and - SubjectDirectoryName
* attributes (title, dateOfBirth, placeOfBirth, gender, countryOfCitizenship,
* countryOfResidence and NameAtBirth).
* </p>
* <pre>
* ProcurationSyntax ::= SEQUENCE {
* country [1] EXPLICIT PrintableString(SIZE(2)) OPTIONAL,
* typeOfSubstitution [2] EXPLICIT DirectoryString (SIZE(1..128)) OPTIONAL,
* signingFor [3] EXPLICIT SigningFor
* }
*
* SigningFor ::= CHOICE
* {
* thirdPerson GeneralName,
* certRef IssuerSerial
* }
* </pre>
*
*/
public class ProcurationSyntax
: Asn1Encodable
{
private readonly string country;
private readonly DirectoryString typeOfSubstitution;
private readonly GeneralName thirdPerson;
private readonly IssuerSerial certRef;
public static ProcurationSyntax GetInstance(
object obj)
{
if (obj == null || obj is ProcurationSyntax)
{
return (ProcurationSyntax) obj;
}
if (obj is Asn1Sequence)
{
return new ProcurationSyntax((Asn1Sequence) obj);
}
throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
}
/**
* Constructor from Asn1Sequence.
* <p/>
* The sequence is of type ProcurationSyntax:
* <p/>
* <pre>
* ProcurationSyntax ::= SEQUENCE {
* country [1] EXPLICIT PrintableString(SIZE(2)) OPTIONAL,
* typeOfSubstitution [2] EXPLICIT DirectoryString (SIZE(1..128)) OPTIONAL,
* signingFor [3] EXPLICIT SigningFor
* }
* <p/>
* SigningFor ::= CHOICE
* {
* thirdPerson GeneralName,
* certRef IssuerSerial
* }
* </pre>
*
* @param seq The ASN.1 sequence.
*/
private ProcurationSyntax(
Asn1Sequence seq)
{
if (seq.Count < 1 || seq.Count > 3)
throw new ArgumentException("Bad sequence size: " + seq.Count);
IEnumerator e = seq.GetEnumerator();
while (e.MoveNext())
{
Asn1TaggedObject o = Asn1TaggedObject.GetInstance(e.Current);
switch (o.TagNo)
{
case 1:
country = DerPrintableString.GetInstance(o, true).GetString();
break;
case 2:
typeOfSubstitution = DirectoryString.GetInstance(o, true);
break;
case 3:
Asn1Object signingFor = o.GetObject();
if (signingFor is Asn1TaggedObject)
{
thirdPerson = GeneralName.GetInstance(signingFor);
}
else
{
certRef = IssuerSerial.GetInstance(signingFor);
}
break;
default:
throw new ArgumentException("Bad tag number: " + o.TagNo);
}
}
}
/**
* Constructor from a given details.
* <p/>
* <p/>
* Either <code>generalName</code> or <code>certRef</code> MUST be
* <code>null</code>.
*
* @param country The country code whose laws apply.
* @param typeOfSubstitution The type of procuration.
* @param certRef Reference to certificate of the person who is represented.
*/
public ProcurationSyntax(
string country,
DirectoryString typeOfSubstitution,
IssuerSerial certRef)
{
this.country = country;
this.typeOfSubstitution = typeOfSubstitution;
this.thirdPerson = null;
this.certRef = certRef;
}
/**
* Constructor from a given details.
* <p/>
* <p/>
* Either <code>generalName</code> or <code>certRef</code> MUST be
* <code>null</code>.
*
* @param country The country code whose laws apply.
* @param typeOfSubstitution The type of procuration.
* @param thirdPerson The GeneralName of the person who is represented.
*/
public ProcurationSyntax(
string country,
DirectoryString typeOfSubstitution,
GeneralName thirdPerson)
{
this.country = country;
this.typeOfSubstitution = typeOfSubstitution;
this.thirdPerson = thirdPerson;
this.certRef = null;
}
public virtual string Country
{
get { return country; }
}
public virtual DirectoryString TypeOfSubstitution
{
get { return typeOfSubstitution; }
}
public virtual GeneralName ThirdPerson
{
get { return thirdPerson; }
}
public virtual IssuerSerial CertRef
{
get { return certRef; }
}
/**
* Produce an object suitable for an Asn1OutputStream.
* <p/>
* Returns:
* <p/>
* <pre>
* ProcurationSyntax ::= SEQUENCE {
* country [1] EXPLICIT PrintableString(SIZE(2)) OPTIONAL,
* typeOfSubstitution [2] EXPLICIT DirectoryString (SIZE(1..128)) OPTIONAL,
* signingFor [3] EXPLICIT SigningFor
* }
* <p/>
* SigningFor ::= CHOICE
* {
* thirdPerson GeneralName,
* certRef IssuerSerial
* }
* </pre>
*
* @return an Asn1Object
*/
public override Asn1Object ToAsn1Object()
{
Asn1EncodableVector vec = new Asn1EncodableVector();
if (country != null)
{
vec.Add(new DerTaggedObject(true, 1, new DerPrintableString(country, true)));
}
if (typeOfSubstitution != null)
{
vec.Add(new DerTaggedObject(true, 2, typeOfSubstitution));
}
if (thirdPerson != null)
{
vec.Add(new DerTaggedObject(true, 3, thirdPerson));
}
else
{
vec.Add(new DerTaggedObject(true, 3, certRef));
}
return new DerSequence(vec);
}
}
}
| |
using SteamKit2;
using System.Collections.Generic;
using SteamTrade;
namespace SteamBot
{
public class SteamTradeDemoHandler : UserHandler
{
// NEW ------------------------------------------------------------------
private GenericInventory mySteamInventory = new GenericInventory();
private GenericInventory OtherSteamInventory = new GenericInventory();
private bool tested;
// ----------------------------------------------------------------------
public SteamTradeDemoHandler (Bot bot, SteamID sid) : base(bot, sid) {}
public override bool OnGroupAdd()
{
return false;
}
public override bool OnFriendAdd ()
{
return true;
}
public override void OnLoginCompleted() {}
public override void OnChatRoomMessage(SteamID chatID, SteamID sender, string message)
{
Log.Info(Bot.SteamFriends.GetFriendPersonaName(sender) + ": " + message);
base.OnChatRoomMessage(chatID, sender, message);
}
public override void OnFriendRemove () {}
public override void OnMessage (string message, EChatEntryType type)
{
Bot.SteamFriends.SendChatMessage(OtherSID, type, Bot.ChatResponse);
}
public override bool OnTradeRequest()
{
return true;
}
public override void OnTradeError (string error)
{
Bot.SteamFriends.SendChatMessage (OtherSID,
EChatEntryType.ChatMsg,
"Oh, there was an error: " + error + "."
);
Bot.log.Warn (error);
}
public override void OnTradeTimeout ()
{
Bot.SteamFriends.SendChatMessage (OtherSID, EChatEntryType.ChatMsg,
"Sorry, but you were AFK and the trade was canceled.");
Bot.log.Info ("User was kicked because he was AFK.");
}
public override void OnTradeInit()
{
// NEW -------------------------------------------------------------------------------
List<long> contextId = new List<long>();
tested = false;
/*************************************************************************************
*
* SteamInventory AppId = 753
*
* Context Id Description
* 1 Gifts (Games), must be public on steam profile in order to work.
* 6 Trading Cards, Emoticons & Backgrounds.
*
************************************************************************************/
contextId.Add(1);
contextId.Add(6);
mySteamInventory.load(753, contextId, Bot.SteamClient.SteamID);
OtherSteamInventory.load(753, contextId, OtherSID);
if (!mySteamInventory.isLoaded | !OtherSteamInventory.isLoaded)
{
Trade.SendMessage("Couldn't open an inventory, type 'errors' for more info.");
}
Trade.SendMessage("Type 'test' to start.");
// -----------------------------------------------------------------------------------
}
public override void OnTradeAddItem (Schema.Item schemaItem, Inventory.Item inventoryItem) {
// USELESS DEBUG MESSAGES -------------------------------------------------------------------------------
Trade.SendMessage("Object AppID: " + inventoryItem.AppId);
Trade.SendMessage("Object ContextId: " + inventoryItem.ContextId);
switch (inventoryItem.AppId)
{
case 440:
Trade.SendMessage("TF2 Item Added.");
Trade.SendMessage("Name: " + schemaItem.Name);
Trade.SendMessage("Quality: " + inventoryItem.Quality);
Trade.SendMessage("Level: " + inventoryItem.Level);
Trade.SendMessage("Craftable: " + (inventoryItem.IsNotCraftable?"No":"Yes"));
break;
case 753:
GenericInventory.ItemDescription tmpDescription = OtherSteamInventory.getDescription(inventoryItem.Id);
Trade.SendMessage("Steam Inventory Item Added.");
Trade.SendMessage("Type: " + tmpDescription.type);
Trade.SendMessage("Marketable: " + (tmpDescription.marketable?"Yes":"No"));
break;
default:
Trade.SendMessage("Unknown item");
break;
}
// ------------------------------------------------------------------------------------------------------
}
public override void OnTradeRemoveItem (Schema.Item schemaItem, Inventory.Item inventoryItem) {}
public override void OnTradeMessage (string message) {
switch (message.ToLower())
{
case "errors":
if (OtherSteamInventory.errors.Count > 0)
{
Trade.SendMessage("User Errors:");
foreach (string error in OtherSteamInventory.errors)
{
Trade.SendMessage(" * " + error);
}
}
if (mySteamInventory.errors.Count > 0)
{
Trade.SendMessage("Bot Errors:");
foreach (string error in mySteamInventory.errors)
{
Trade.SendMessage(" * " + error);
}
}
break;
case "test":
if (tested)
{
foreach (GenericInventory.Item item in mySteamInventory.items.Values)
{
Trade.RemoveItem(item);
}
}
else
{
Trade.SendMessage("Items on my bp: " + mySteamInventory.items.Count);
foreach (GenericInventory.Item item in mySteamInventory.items.Values)
{
Trade.AddItem(item);
}
}
tested = !tested;
break;
case "remove":
foreach (var item in mySteamInventory.items)
{
Trade.RemoveItem(item.Value.assetid, item.Value.appid, item.Value.contextid);
}
break;
}
}
public override void OnTradeReady (bool ready)
{
//Because SetReady must use its own version, it's important
//we poll the trade to make sure everything is up-to-date.
Trade.Poll();
if (!ready)
{
Trade.SetReady (false);
}
else
{
if(Validate () | IsAdmin)
{
Trade.SetReady (true);
}
}
}
public override void OnTradeSuccess()
{
// Trade completed successfully
Log.Success("Trade Complete.");
}
public override void OnTradeAccept()
{
if (Validate() | IsAdmin)
{
//Even if it is successful, AcceptTrade can fail on
//trades with a lot of items so we use a try-catch
try {
Trade.AcceptTrade();
}
catch {
Log.Warn ("The trade might have failed, but we can't be sure.");
}
Log.Success ("Trade Complete!");
}
}
public bool Validate ()
{
List<string> errors = new List<string> ();
errors.Add("This demo is meant to show you how to handle SteamInventory Items. Trade cannot be completed, unless you're an Admin.");
// send the errors
if (errors.Count != 0)
Trade.SendMessage("There were errors in your trade: ");
foreach (string error in errors)
{
Trade.SendMessage(error);
}
return errors.Count == 0;
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using ZXing.Common;
namespace ZXing.QrCode.Internal
{
/// <summary> <p>This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder
/// patterns but are smaller and appear at regular intervals throughout the image.</p>
///
/// <p>At the moment this only looks for the bottom-right alignment pattern.</p>
///
/// <p>This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,
/// pasted and stripped down here for maximum performance but does unfortunately duplicate
/// some code.</p>
///
/// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source
/// </author>
sealed class AlignmentPatternFinder
{
private readonly BitMatrix image;
private readonly IList<AlignmentPattern> possibleCenters;
private readonly int startX;
private readonly int startY;
private readonly int width;
private readonly int height;
private readonly float moduleSize;
private readonly int[] crossCheckStateCount;
private readonly ResultPointCallback resultPointCallback;
/// <summary> <p>Creates a finder that will look in a portion of the whole image.</p>
///
/// </summary>
/// <param name="image">image to search
/// </param>
/// <param name="startX">left column from which to start searching
/// </param>
/// <param name="startY">top row from which to start searching
/// </param>
/// <param name="width">width of region to search
/// </param>
/// <param name="height">height of region to search
/// </param>
/// <param name="moduleSize">estimated module size so far
/// </param>
/// <param name="resultPointCallback">callback function which is called, when a result point is found</param>
internal AlignmentPatternFinder(BitMatrix image, int startX, int startY, int width, int height, float moduleSize, ResultPointCallback resultPointCallback)
{
this.image = image;
this.possibleCenters = new List<AlignmentPattern>(5);
this.startX = startX;
this.startY = startY;
this.width = width;
this.height = height;
this.moduleSize = moduleSize;
this.crossCheckStateCount = new int[3];
this.resultPointCallback = resultPointCallback;
}
/// <summary> <p>This method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since
/// it's pretty performance-critical and so is written to be fast foremost.</p>
///
/// </summary>
/// <returns><see cref="AlignmentPattern"/> if found</returns>
internal AlignmentPattern find()
{
int startX = this.startX;
int height = this.height;
int maxJ = startX + width;
int middleI = startY + (height >> 1);
// We are looking for black/white/black modules in 1:1:1 ratio;
// this tracks the number of black/white/black modules seen so far
int[] stateCount = new int[3];
for (int iGen = 0; iGen < height; iGen++)
{
// Search from middle outwards
int i = middleI + ((iGen & 0x01) == 0 ? ((iGen + 1) >> 1) : -((iGen + 1) >> 1));
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
int j = startX;
// Burn off leading white pixels before anything else; if we start in the middle of
// a white run, it doesn't make sense to count its length, since we don't know if the
// white run continued to the left of the start point
while (j < maxJ && !image[j, i])
{
j++;
}
int currentState = 0;
while (j < maxJ)
{
if (image[j, i])
{
// Black pixel
if (currentState == 1)
{
// Counting black pixels
stateCount[1]++;
}
else
{
// Counting white pixels
if (currentState == 2)
{
// A winner?
if (foundPatternCross(stateCount))
{
// Yes
AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, j);
if (confirmed != null)
{
return confirmed;
}
}
stateCount[0] = stateCount[2];
stateCount[1] = 1;
stateCount[2] = 0;
currentState = 1;
}
else
{
stateCount[++currentState]++;
}
}
}
else
{
// White pixel
if (currentState == 1)
{
// Counting black pixels
currentState++;
}
stateCount[currentState]++;
}
j++;
}
if (foundPatternCross(stateCount))
{
AlignmentPattern confirmed = handlePossibleCenter(stateCount, i, maxJ);
if (confirmed != null)
{
return confirmed;
}
}
}
// Hmm, nothing we saw was observed and confirmed twice. If we had
// any guess at all, return it.
if (possibleCenters.Count != 0)
{
return possibleCenters[0];
}
return null;
}
/// <summary> Given a count of black/white/black pixels just seen and an end position,
/// figures the location of the center of this black/white/black run.
/// </summary>
private static float? centerFromEnd(int[] stateCount, int end)
{
var result = (end - stateCount[2]) - stateCount[1] / 2.0f;
if (Single.IsNaN(result))
return null;
return result;
}
/// <param name="stateCount">count of black/white/black pixels just read
/// </param>
/// <returns> true iff the proportions of the counts is close enough to the 1/1/1 ratios
/// used by alignment patterns to be considered a match
/// </returns>
private bool foundPatternCross(int[] stateCount)
{
float maxVariance = moduleSize / 2.0f;
for (int i = 0; i < 3; i++)
{
if (Math.Abs(moduleSize - stateCount[i]) >= maxVariance)
{
return false;
}
}
return true;
}
/// <summary>
/// <p>After a horizontal scan finds a potential alignment pattern, this method
/// "cross-checks" by scanning down vertically through the center of the possible
/// alignment pattern to see if the same proportion is detected.</p>
/// </summary>
/// <param name="startI">row where an alignment pattern was detected</param>
/// <param name="centerJ">center of the section that appears to cross an alignment pattern</param>
/// <param name="maxCount">maximum reasonable number of modules that should be
/// observed in any reading state, based on the results of the horizontal scan</param>
/// <param name="originalStateCountTotal">The original state count total.</param>
/// <returns>
/// vertical center of alignment pattern, or null if not found
/// </returns>
private float? crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal)
{
int maxI = image.Height;
int[] stateCount = crossCheckStateCount;
stateCount[0] = 0;
stateCount[1] = 0;
stateCount[2] = 0;
// Start counting up from center
int i = startI;
while (i >= 0 && image[centerJ, i] && stateCount[1] <= maxCount)
{
stateCount[1]++;
i--;
}
// If already too many modules in this state or ran off the edge:
if (i < 0 || stateCount[1] > maxCount)
{
return null;
}
while (i >= 0 && !image[centerJ, i] && stateCount[0] <= maxCount)
{
stateCount[0]++;
i--;
}
if (stateCount[0] > maxCount)
{
return null;
}
// Now also count down from center
i = startI + 1;
while (i < maxI && image[centerJ, i] && stateCount[1] <= maxCount)
{
stateCount[1]++;
i++;
}
if (i == maxI || stateCount[1] > maxCount)
{
return null;
}
while (i < maxI && !image[centerJ, i] && stateCount[2] <= maxCount)
{
stateCount[2]++;
i++;
}
if (stateCount[2] > maxCount)
{
return null;
}
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
if (5 * Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal)
{
return null;
}
return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : null;
}
/// <summary> <p>This is called when a horizontal scan finds a possible alignment pattern. It will
/// cross check with a vertical scan, and if successful, will see if this pattern had been
/// found on a previous horizontal scan. If so, we consider it confirmed and conclude we have
/// found the alignment pattern.</p>
///
/// </summary>
/// <param name="stateCount">reading state module counts from horizontal scan
/// </param>
/// <param name="i">row where alignment pattern may be found
/// </param>
/// <param name="j">end of possible alignment pattern in row
/// </param>
/// <returns> {@link AlignmentPattern} if we have found the same pattern twice, or null if not
/// </returns>
private AlignmentPattern handlePossibleCenter(int[] stateCount, int i, int j)
{
int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];
float? centerJ = centerFromEnd(stateCount, j);
if (centerJ == null)
return null;
float? centerI = crossCheckVertical(i, (int)centerJ, 2 * stateCount[1], stateCountTotal);
if (centerI != null)
{
float estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0f;
foreach (var center in possibleCenters)
{
// Look for about the same center and module size:
if (center.aboutEquals(estimatedModuleSize, centerI.Value, centerJ.Value))
{
return center.combineEstimate(centerI.Value, centerJ.Value, estimatedModuleSize);
}
}
// Hadn't found this before; save it
var point = new AlignmentPattern(centerJ.Value, centerI.Value, estimatedModuleSize);
possibleCenters.Add(point);
if (resultPointCallback != null)
{
resultPointCallback(point);
}
}
return null;
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using Mosa.Compiler.MosaTypeSystem;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Mosa.Compiler.Framework
{
/// <summary>
/// Operand class
/// </summary>
public sealed class Operand
{
#region Properties
/// <summary>
/// Holds a list of instructions, which define this operand.
/// </summary>
public List<InstructionNode> Definitions { get; private set; }
/// <summary>
/// Holds a list of instructions, which use this operand.
/// </summary>
public List<InstructionNode> Uses { get; private set; }
/// <summary>
/// Returns the type of the operand.
/// </summary>
public MosaType Type { get; private set; }
/// <summary>
/// Retrieves the register, where the operand is located.
/// </summary>
public Register Register { get; private set; }
/// <summary>
/// Retrieves the offset base.
/// </summary>
public Operand OffsetBase { get; private set; }
/// <summary>
/// Gets the effective base.
/// </summary>
/// <value>
/// The effective base.
/// </value>
public Register EffectiveOffsetBase { get { return OffsetBase != null ? OffsetBase.Register : Register; } }
/// <summary>
/// Gets the base operand.
/// </summary>
public Operand SSAParent { get; private set; }
/// <summary>
/// Holds the address offset if used together with a base register or the absolute address, if register is null.
/// </summary>
/// <value>
/// The offset.
/// </value>
public long Displacement { get; set; }
/// <summary>
/// Retrieves the method.
/// </summary>
public MosaMethod Method { get; private set; }
/// <summary>
/// Retrieves the field.
/// </summary>
public MosaField Field { get; private set; }
/// <summary>
/// Gets the ssa version.
/// </summary>
public int SSAVersion { get; private set; }
/// <summary>
/// Gets or sets the low operand.
/// </summary>
/// <value>
/// The low operand.
/// </value>
public Operand Low { get; private set; }
/// <summary>
/// Gets or sets the high operand.
/// </summary>
/// <value>
/// The high operand.
/// </value>
public Operand High { get; private set; }
/// <summary>
/// Gets the split64 parent.
/// </summary>
/// <value>
/// The split64 parent.
/// </value>
public Operand SplitParent { get; private set; }
/// <summary>
/// Determines if the operand is a constant variable.
/// </summary>
public bool IsConstant { get; private set; }
/// <summary>
/// Determines if the operand is a symbol operand.
/// </summary>
public bool IsSymbol { get; private set; }
/// <summary>
/// Determines if the operand is a label operand.
/// </summary>
public bool IsLabel { get; private set; }
/// <summary>
/// Determines if the operand is a register.
/// </summary>
public bool IsRegister { get { return IsVirtualRegister || IsCPURegister; } }
/// <summary>
/// Determines if the operand is a virtual register operand.
/// </summary>
public bool IsVirtualRegister { get; private set; }
/// <summary>
/// Determines if the operand is a cpu register operand.
/// </summary>
public bool IsCPURegister { get; private set; }
/// <summary>
/// Determines if the operand is a memory operand.
/// </summary>
public bool IsMemoryAddress { get; private set; }
/// <summary>
/// Determines if the operand is a stack local operand.
/// </summary>
public bool IsStackLocal { get; private set; }
/// <summary>
/// Determines if the operand is a runtime member operand.
/// </summary>
public bool IsField { get; private set; }
/// <summary>
/// Determines if the operand is a local variable operand.
/// </summary>
public bool IsParameter { get; private set; }
/// <summary>
/// Determines if the operand is a ssa operand.
/// </summary>
public bool IsSSA { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is split64 child.
/// </summary>
/// <value>
/// <c>true</c> if this instance is split64 child; otherwise, <c>false</c>.
/// </value>
public bool IsSplitChild { get { return SplitParent != null && !IsSSA; } }
/// <summary>
/// Determines if the operand is a shift operand.
/// </summary>
public bool IsShift { get; private set; }
/// <summary>
/// Gets the name.
/// </summary>
/// <value>The name.</value>
public string Name { get; private set; }
/// <summary>
/// Gets the index.
/// </summary>
public int Index { get; private set; }
/// <summary>
/// Gets the constant long integer.
/// </summary>
/// <value>
/// The constant long integer.
/// </value>
public ulong ConstantUnsignedLongInteger { get; private set; }
/// <summary>
/// Gets the constant integer.
/// </summary>
/// <value>
/// The constant integer.
/// </value>
public uint ConstantUnsignedInteger { get { return (uint)ConstantUnsignedLongInteger; } set { ConstantUnsignedLongInteger = value; } }
/// <summary>
/// Gets the constant double float point.
/// </summary>
/// <value>
/// The constant double float point.
/// </value>
public double ConstantDoubleFloatingPoint { get; private set; }
/// <summary>
/// Gets the single double float point.
/// </summary>
/// <value>
/// The single double float point.
/// </value>
public float ConstantSingleFloatingPoint { get; private set; }
/// <summary>
/// Gets or sets the constant signed long integer.
/// </summary>
/// <value>
/// The constant signed long integer.
/// </value>
public long ConstantSignedLongInteger { get { return (long)ConstantUnsignedLongInteger; } set { ConstantUnsignedLongInteger = (ulong)value; } }
/// <summary>
/// Gets or sets the constant signed integer.
/// </summary>
/// <value>
/// The constant signed integer.
/// </value>
public int ConstantSignedInteger { get { return (int)ConstantUnsignedLongInteger; } set { ConstantUnsignedLongInteger = (ulong)value; } }
/// <summary>
/// Gets the string data.
/// </summary>
/// <value>
/// The string data.
/// </value>
public string StringData { get; private set; }
/// <summary>
/// Gets a value indicating whether [is null].
/// </summary>
/// <value>
/// <c>true</c> if [is null]; otherwise, <c>false</c>.
/// </value>
public bool IsNull { get; private set; }
/// <summary>
/// Gets a value indicating whether [is 64 bit integer].
/// </summary>
/// <value>
/// <c>true</c> if [is signed integer]; otherwise, <c>false</c>.
/// </value>
public bool Is64BitInteger { get { return IsLong; } }
/// <summary>
/// Gets the type of the shift.
/// </summary>
/// <value>
/// The type of the shift.
/// </value>
public ShiftType ShiftType { get; private set; }
/// <summary>
/// Gets a value indicating whether [is constant zero].
/// </summary>
/// <value>
/// <c>true</c> if [is constant zero]; otherwise, <c>false</c>.
/// </value>
public bool IsConstantZero
{
get
{
if (!IsConstant)
return false;
else if (IsInteger || IsBoolean || IsChar || IsPointer)
return ConstantUnsignedLongInteger == 0;
else if (IsR8)
return ConstantDoubleFloatingPoint == 0;
else if (IsR4)
return ConstantSingleFloatingPoint == 0;
else if (IsNull)
return true;
throw new InvalidCompilerException();
}
}
/// <summary>
/// Gets a value indicating whether [is constant one].
/// </summary>
/// <value>
/// <c>true</c> if [is constant one]; otherwise, <c>false</c>.
/// </value>
/// <exception cref="InvalidCompilerException"></exception>
public bool IsConstantOne
{
get
{
if (!IsConstant)
return false;
else if (IsInteger || IsBoolean || IsChar || IsPointer)
return ConstantUnsignedLongInteger == 1;
else if (IsR8)
return ConstantDoubleFloatingPoint == 1;
else if (IsR4)
return ConstantSingleFloatingPoint == 1;
else if (IsNull)
return false;
throw new InvalidCompilerException();
}
}
public bool IsR { get { return underlyingType.IsR; } }
public bool IsR8 { get { return underlyingType.IsR8; } }
public bool IsR4 { get { return underlyingType.IsR4; } }
public bool IsInteger { get { return underlyingType.IsInteger; } }
public bool IsSigned { get { return underlyingType.IsSigned; } }
public bool IsUnsigned { get { return underlyingType.IsUnsigned; } }
public bool IsU1 { get { return underlyingType.IsU1; } }
public bool IsI1 { get { return underlyingType.IsI1; } }
public bool IsU2 { get { return underlyingType.IsU2; } }
public bool IsI2 { get { return underlyingType.IsI2; } }
public bool IsU4 { get { return underlyingType.IsU4; } }
public bool IsI4 { get { return underlyingType.IsI4; } }
public bool IsU8 { get { return underlyingType.IsU8; } }
public bool IsI8 { get { return underlyingType.IsI8; } }
public bool IsByte { get { return underlyingType.IsUI1; } }
public bool IsShort { get { return underlyingType.IsUI2; } }
public bool IsChar { get { return underlyingType.IsChar; } }
public bool IsInt { get { return underlyingType.IsUI4; } }
public bool IsLong { get { return underlyingType.IsUI8; } }
public bool IsBoolean { get { return Type.IsBoolean; } }
public bool IsPointer { get { return Type.IsPointer; } }
public bool IsManagedPointer { get { return Type.IsManagedPointer; } }
public bool IsUnmanagedPointer { get { return Type.IsUnmanagedPointer; } }
public bool IsFunctionPointer { get { return Type.IsFunctionPointer; } }
public bool IsValueType { get { return underlyingType.IsValueType; } }
public bool IsArray { get { return Type.IsArray; } }
public bool IsI { get { return underlyingType.IsI; } }
public bool IsU { get { return underlyingType.IsU; } }
public bool IsReferenceType { get { return Type.IsReferenceType; } }
private MosaType underlyingType { get { return Type.GetEnumUnderlyingType(); } }
public bool IsPinned { get; private set; }
#endregion Properties
#region Construction
private Operand()
{
Definitions = new List<InstructionNode>();
Uses = new List<InstructionNode>();
IsParameter = false;
IsStackLocal = false;
IsShift = false;
IsConstant = false;
IsVirtualRegister = false;
IsLabel = false;
IsCPURegister = false;
IsMemoryAddress = false;
IsSSA = false;
IsSymbol = false;
IsField = false;
IsParameter = false;
}
/// <summary>
/// Initializes a new instance of <see cref="Operand"/>.
/// </summary>
/// <param name="type">The type of the operand.</param>
private Operand(MosaType type)
: this()
{
Debug.Assert(type != null);
Type = type;
}
/// <summary>
/// Prevents a default instance of the <see cref="Operand"/> class from being created.
/// </summary>
/// <param name="shiftType">Type of the shift.</param>
private Operand(ShiftType shiftType)
: this()
{
ShiftType = shiftType;
IsShift = true;
}
#endregion Construction
#region Static Factory Constructors
/// <summary>
/// Creates a new constant <see cref="Operand" /> for the given integral value.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="value">The value to create the constant operand for.</param>
/// <returns>
/// A new operand representing the value <paramref name="value" />.
/// </returns>
/// <exception cref="InvalidCompilerException"></exception>
public static Operand CreateConstant(MosaType type, ulong value)
{
var operand = new Operand(type);
operand.IsConstant = true;
operand.ConstantUnsignedLongInteger = value;
operand.IsNull = (type.IsReferenceType && value == 0);
if (type.IsReferenceType && value != 0)
{
throw new InvalidCompilerException();
}
if (!(operand.IsInteger || operand.IsBoolean || operand.IsChar || operand.IsPointer || operand.IsReferenceType))
{
throw new InvalidCompilerException();
}
return operand;
}
/// <summary>
/// Creates a new constant <see cref="Operand" /> for the given integral value.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="value">The value to create the constant operand for.</param>
/// <returns>
/// A new operand representing the value <paramref name="value" />.
/// </returns>
public static Operand CreateConstant(MosaType type, long value)
{
return CreateConstant(type, (ulong)value);
}
/// <summary>
/// Creates a new constant <see cref="Operand" /> for the given integral value.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="value">The value to create the constant operand for.</param>
/// <returns>
/// A new operand representing the value <paramref name="value" />.
/// </returns>
public static Operand CreateConstant(MosaType type, int value)
{
return CreateConstant(type, (long)value);
}
/// <summary>
/// Creates a new constant <see cref="Operand" /> for the given integral value.
/// </summary>
/// <param name="typeSystem">The type system.</param>
/// <param name="value">The value to create the constant operand for.</param>
/// <returns>
/// A new operand representing the value <paramref name="value" />.
/// </returns>
public static Operand CreateConstant(TypeSystem typeSystem, int value)
{
var operand = new Operand(typeSystem.BuiltIn.I4);
operand.IsConstant = true;
operand.ConstantSignedLongInteger = value;
return operand;
}
/// <summary>
/// Creates a new constant <see cref="Operand" /> for the given integral value.
/// </summary>
/// <param name="typeSystem">The type system.</param>
/// <param name="value">The value to create the constant operand for.</param>
/// <returns>
/// A new operand representing the value <paramref name="value" />.
/// </returns>
public static Operand CreateConstant(TypeSystem typeSystem, long value)
{
var operand = new Operand(typeSystem.BuiltIn.I8);
operand.IsConstant = true;
operand.ConstantSignedLongInteger = value;
return operand;
}
/// <summary>
/// Creates a new constant <see cref="Operand"/> for the given integral value.
/// </summary>
/// <param name="typeSystem">The type system.</param>
/// <param name="value">The value to create the constant operand for.</param>
/// <returns>
/// A new operand representing the value <paramref name="value"/>.
/// </returns>
public static Operand CreateConstant(TypeSystem typeSystem, float value)
{
var operand = new Operand(typeSystem.BuiltIn.R4);
operand.IsConstant = true;
operand.ConstantSingleFloatingPoint = value;
return operand;
}
/// <summary>
/// Creates a new constant <see cref="Operand"/> for the given integral value.
/// </summary>
/// <param name="typeSystem">The type system.</param>
/// <param name="value">The value to create the constant operand for.</param>
/// <returns>
/// A new operand representing the value <paramref name="value"/>.
/// </returns>
public static Operand CreateConstant(TypeSystem typeSystem, double value)
{
var operand = new Operand(typeSystem.BuiltIn.R8);
operand.IsConstant = true;
operand.ConstantDoubleFloatingPoint = value;
return operand;
}
/// <summary>
/// Gets the null constant <see cref="Operand"/>.
/// </summary>
/// <returns></returns>
public static Operand GetNull(TypeSystem typeSystem)
{
var operand = new Operand(typeSystem.BuiltIn.Object);
operand.IsNull = true;
operand.IsConstant = true;
return operand;
}
/// <summary>
/// Creates the symbol.
/// </summary>
/// <param name="typeSystem">The type system.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public static Operand CreateUnmanagedSymbolPointer(TypeSystem typeSystem, string name)
{
var operand = new Operand(typeSystem.BuiltIn.Pointer);
operand.IsSymbol = true;
operand.Name = name;
return operand;
}
/// <summary>
/// Creates the symbol.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
private static Operand CreateManagedSymbolPointer(MosaType type, string name)
{
// NOTE: Not being used
var operand = new Operand(type.ToManagedPointer());
operand.IsSymbol = true;
operand.Name = name;
return operand;
}
/// <summary>
/// Creates the symbol.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public static Operand CreateManagedSymbol(MosaType type, string name)
{
var operand = new Operand(type);
operand.IsSymbol = true;
operand.Name = name;
return operand;
}
/// <summary>
/// Creates the string symbol with data.
/// </summary>
/// <param name="typeSystem">The type system.</param>
/// <param name="name">The name.</param>
/// <param name="data">The string data.</param>
/// <returns></returns>
public static Operand CreateStringSymbol(TypeSystem typeSystem, string name, string data)
{
Debug.Assert(data != null);
var operand = new Operand(typeSystem.BuiltIn.String);
operand.IsSymbol = true;
operand.Name = name;
operand.StringData = data;
return operand;
}
/// <summary>
/// Creates a new symbol <see cref="Operand" /> for the given symbol name.
/// </summary>
/// <param name="typeSystem">The type system.</param>
/// <param name="method">The method.</param>
/// <returns></returns>
public static Operand CreateSymbolFromMethod(TypeSystem typeSystem, MosaMethod method)
{
var operand = CreateUnmanagedSymbolPointer(typeSystem, method.FullName);
operand.Method = method;
return operand;
}
/// <summary>
/// Creates a new virtual register <see cref="Operand" />.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="index">The index.</param>
/// <returns></returns>
public static Operand CreateVirtualRegister(MosaType type, int index)
{
var operand = new Operand(type);
operand.IsVirtualRegister = true;
operand.Index = index;
return operand;
}
/// <summary>
/// Creates a new virtual register <see cref="Operand" />.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="index">The index.</param>
/// <param name="name">The name.</param>
/// <returns></returns>
public static Operand CreateVirtualRegister(MosaType type, int index, string name)
{
var operand = new Operand(type);
operand.IsVirtualRegister = true;
operand.Name = name;
operand.Index = index;
return operand;
}
/// <summary>
/// Creates a new physical register <see cref="Operand" />.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="register">The register.</param>
/// <returns></returns>
public static Operand CreateCPURegister(MosaType type, Register register)
{
var operand = new Operand(type);
operand.IsCPURegister = true;
operand.Register = register;
return operand;
}
/// <summary>
/// Creates a new memory address <see cref="Operand" />.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="offsetBase">The base register.</param>
/// <param name="offset">The offset.</param>
/// <returns></returns>
public static Operand CreateMemoryAddress(MosaType type, Operand offsetBase, long offset)
{
var operand = new Operand(type);
operand.IsMemoryAddress = true;
operand.OffsetBase = offsetBase;
operand.Displacement = offset;
return operand;
}
/// <summary>
/// Creates a new symbol <see cref="Operand" /> for the given symbol name.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="label">The label.</param>
/// <returns></returns>
public static Operand CreateLabel(MosaType type, string label)
{
var operand = new Operand(type);
operand.IsMemoryAddress = true;
operand.IsLabel = true;
operand.Name = label;
operand.Displacement = 0;
return operand;
}
/// <summary>
/// Creates a new runtime member <see cref="Operand"/>.
/// </summary>
/// <param name="field">The field.</param>
/// <returns></returns>
public static Operand CreateField(MosaField field)
{
var operand = new Operand(field.FieldType);
operand.IsMemoryAddress = true;
operand.IsField = true;
operand.Displacement = 0;
operand.Field = field;
return operand;
}
/// <summary>
/// Creates a new local variable <see cref="Operand" />.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="register">The register.</param>
/// <param name="displacement">The displacement.</param>
/// <param name="index">The index.</param>
/// <returns></returns>
public static Operand CreateParameter(MosaType type, Register register, int displacement, int index, string name)
{
var operand = new Operand(type);
operand.IsMemoryAddress = true;
operand.IsParameter = true;
operand.Register = register;
operand.Index = index;
operand.Displacement = displacement;
operand.Name = name;
return operand;
}
/// <summary>
/// Creates the stack local.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="register">The register.</param>
/// <param name="index">The index.</param>
/// <param name="pinned">if set to <c>true</c> [pinned].</param>
/// <returns></returns>
public static Operand CreateStackLocal(MosaType type, Register register, int index, bool pinned)
{
var operand = new Operand(type);
operand.IsMemoryAddress = true;
operand.Register = register;
operand.Index = index;
operand.IsStackLocal = true;
operand.IsPinned = pinned;
return operand;
}
/// <summary>
/// Creates the stack local.
/// </summary>
/// <param name="type">The type.</param>
/// <param name="index">The index.</param>
/// <param name="pinned">if set to <c>true</c> [pinned].</param>
/// <returns></returns>
public static Operand CreateStackLocal(MosaType type, int index, bool pinned)
{
var operand = new Operand(type);
operand.Index = index;
operand.IsStackLocal = true;
operand.IsPinned = pinned;
return operand;
}
/// <summary>
/// Creates the SSA <see cref="Operand"/>.
/// </summary>
/// <param name="ssaOperand">The ssa operand.</param>
/// <param name="ssaVersion">The ssa version.</param>
/// <returns></returns>
public static Operand CreateSSA(Operand ssaOperand, int ssaVersion)
{
var operand = new Operand(ssaOperand.Type);
operand.IsParameter = ssaOperand.IsParameter;
operand.IsStackLocal = ssaOperand.IsStackLocal;
operand.IsShift = ssaOperand.IsShift;
operand.IsConstant = ssaOperand.IsConstant;
operand.IsVirtualRegister = ssaOperand.IsVirtualRegister;
operand.IsLabel = ssaOperand.IsLabel;
operand.IsCPURegister = ssaOperand.IsCPURegister;
operand.IsMemoryAddress = ssaOperand.IsMemoryAddress;
operand.IsSymbol = ssaOperand.IsSymbol;
operand.IsField = ssaOperand.IsField;
operand.IsParameter = ssaOperand.IsParameter;
operand.IsSSA = true;
operand.SSAParent = ssaOperand;
operand.SSAVersion = ssaVersion;
return operand;
}
/// <summary>
/// Creates the low 32 bit portion of a 64-bit <see cref="Operand"/>.
/// </summary>
/// <param name="longOperand">The long operand.</param>
/// <param name="offset">The offset.</param>
/// <param name="index">The index.</param>
/// <returns></returns>
public static Operand CreateLowSplitForLong(TypeSystem typeSystem, Operand longOperand, int offset, int index)
{
Debug.Assert(longOperand.IsLong);
Debug.Assert(longOperand.SplitParent == null);
Debug.Assert(longOperand.Low == null);
Operand operand;
if (longOperand.IsConstant)
{
operand = new Operand(typeSystem.BuiltIn.U4);
operand.IsConstant = true;
operand.ConstantUnsignedLongInteger = longOperand.ConstantUnsignedLongInteger & uint.MaxValue;
}
else if (longOperand.IsField)
{
operand = new Operand(typeSystem.BuiltIn.U4);
operand.IsMemoryAddress = true;
operand.IsField = true;
operand.Field = longOperand.Field;
operand.Type = longOperand.Type;
operand.OffsetBase = longOperand.OffsetBase;
operand.Displacement = longOperand.Displacement + offset;
operand.Register = longOperand.Register;
}
else if (longOperand.IsMemoryAddress)
{
operand = new Operand(typeSystem.BuiltIn.U4);
operand.IsMemoryAddress = true;
operand.OffsetBase = longOperand.OffsetBase;
operand.Displacement = longOperand.Displacement + offset;
operand.Register = longOperand.Register;
}
else
{
operand = new Operand(typeSystem.BuiltIn.U4);
operand.IsVirtualRegister = true;
}
operand.SplitParent = longOperand;
Debug.Assert(longOperand.Low == null);
longOperand.Low = operand;
operand.Index = index;
//operand.sequence = index;
return operand;
}
/// <summary>
/// Creates the high 32 bit portion of a 64-bit <see cref="Operand"/>.
/// </summary>
/// <param name="longOperand">The long operand.</param>
/// <param name="offset">The offset.</param>
/// <param name="index">The index.</param>
/// <returns></returns>
public static Operand CreateHighSplitForLong(TypeSystem typeSystem, Operand longOperand, int offset, int index)
{
Debug.Assert(longOperand.IsLong);
Debug.Assert(longOperand.SplitParent == null);
Debug.Assert(longOperand.High == null);
Operand operand;
if (longOperand.IsConstant)
{
operand = new Operand(typeSystem.BuiltIn.U4);
operand.IsConstant = true;
operand.ConstantUnsignedLongInteger = ((uint)(longOperand.ConstantUnsignedLongInteger >> 32)) & uint.MaxValue;
}
else if (longOperand.IsField)
{
operand = new Operand(typeSystem.BuiltIn.U4);
operand.IsMemoryAddress = true;
operand.IsField = true;
operand.Field = longOperand.Field;
operand.Type = longOperand.Type;
operand.OffsetBase = longOperand.OffsetBase;
operand.Displacement = longOperand.Displacement + offset;
operand.Register = longOperand.Register;
}
else if (longOperand.IsMemoryAddress)
{
operand = new Operand(typeSystem.BuiltIn.U4);
operand.IsMemoryAddress = true;
operand.OffsetBase = longOperand.OffsetBase;
operand.Displacement = longOperand.Displacement + offset;
operand.Register = longOperand.Register;
}
else
{
operand = new Operand(typeSystem.BuiltIn.U4);
operand.IsVirtualRegister = true;
}
operand.SplitParent = longOperand;
//operand.SplitParent = longOperand;
Debug.Assert(longOperand.High == null);
longOperand.High = operand;
operand.Index = index;
return operand;
}
/// <summary>
/// Creates the shifter.
/// </summary>
/// <param name="shiftType">Type of the shift.</param>
/// <returns></returns>
public static Operand CreateShifter(ShiftType shiftType)
{
var operand = new Operand(shiftType);
return operand;
}
#endregion Static Factory Constructors
/// <summary>
/// Returns a string representation of <see cref="Operand"/>.
/// </summary>
/// <returns>A string representation of the operand.</returns>
public string ToString(bool full)
{
if (IsSSA)
{
string ssa = SSAParent.ToString(full);
int pos = ssa.IndexOf(' ');
if (pos < 0)
return ssa + "<" + SSAVersion + ">";
else
return ssa.Substring(0, pos) + "<" + SSAVersion + ">" + ssa.Substring(pos);
}
var sb = new StringBuilder();
if (IsVirtualRegister)
{
sb.AppendFormat("V_{0}", Index);
}
else if (IsStackLocal && Name == null)
{
sb.AppendFormat("T_{0}", Index);
}
else if (IsParameter && Name == null)
{
sb.AppendFormat("P_{0}", Index);
}
if (Name != null)
{
sb.Append(Name);
sb.Append(' ');
}
if (IsField)
{
sb.Append(' ');
sb.Append(Field.FullName);
}
if (IsSplitChild)
{
sb.Append(' ');
sb.Append("(" + SplitParent.ToString(full) + ")");
if (SplitParent.High == this)
sb.Append("/high");
else
sb.Append("/low");
}
if (IsConstant)
{
sb.Append(" const {");
if (IsNull)
sb.Append("null");
else if (IsUnsigned || IsBoolean || IsChar || IsPointer)
if (IsU8)
sb.AppendFormat("{0}", ConstantUnsignedLongInteger);
else
sb.AppendFormat("{0}", ConstantUnsignedInteger);
else if (IsSigned)
if (IsI8)
sb.AppendFormat("{0}", ConstantSignedLongInteger);
else
sb.AppendFormat("{0}", ConstantSignedInteger);
if (IsR8)
sb.AppendFormat("{0}", ConstantDoubleFloatingPoint);
else if (IsR4)
sb.AppendFormat("{0}", ConstantSingleFloatingPoint);
sb.Append('}');
}
if (IsCPURegister)
{
sb.AppendFormat(" {0}", Register);
}
else if (IsMemoryAddress)
{
sb.Append(' ');
if (OffsetBase != null)
{
if (Displacement > 0)
sb.AppendFormat("[{0}+{1:X}h]", OffsetBase.ToString(full), Displacement);
else
sb.AppendFormat("[{0}-{1:X}h]", OffsetBase.ToString(full), -Displacement);
}
else if (Register != null)
{
if (Displacement > 0)
sb.AppendFormat("[{0}+{1:X}h]", Register.ToString(), Displacement);
else
sb.AppendFormat("[{0}-{1:X}h]", Register.ToString(), -Displacement);
}
else if (IsField && IsSplitChild)
{
if (Displacement > 0)
sb.AppendFormat("+{0:X}h", Displacement);
else
sb.AppendFormat("-{0:X}h", -Displacement);
}
}
if (full)
{
sb.AppendFormat(" [{0}]", Type.FullName);
}
else
{
if (Type.IsReferenceType)
{
sb.AppendFormat(" [O]");
}
{
sb.AppendFormat(" [{0}]", ShortenTypeName(Type.FullName));
}
}
return sb.ToString().Replace(" ", " ").Trim();
}
private static string ShortenTypeName(string value)
{
if (value.Length < 2)
return value;
string type = value;
string end = string.Empty;
if (value.EndsWith("*"))
{
type = value.Substring(0, value.Length - 1);
end = "*";
}
if (value.EndsWith("&"))
{
type = value.Substring(0, value.Length - 1);
end = "&";
}
if (value.EndsWith("[]"))
{
type = value.Substring(0, value.Length - 2);
end = "[]";
}
return ShortenTypeName2(type) + end;
}
private static string ShortenTypeName2(string value)
{
switch (value)
{
case "System.Object": return "O";
case "System.Char": return "C";
case "System.Void": return "V";
case "System.String": return "String";
case "System.Byte": return "U1";
case "System.SByte": return "I1";
case "System.Boolean": return "B";
case "System.Int8": return "I1";
case "System.UInt8": return "U1";
case "System.Int16": return "I2";
case "System.UInt16": return "U2";
case "System.Int32": return "I4";
case "System.UInt32": return "U4";
case "System.Int64": return "I8";
case "System.UInt64": return "U8";
case "System.Single": return "R4";
case "System.Double": return "R8";
}
return value;
}
internal void RenameIndex(int index)
{
Index = index;
}
#region Object Overrides
public override string ToString()
{
return ToString(false);
}
#endregion Object Overrides
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
#if !XBOX360 && !ZUNE && !WINDOWS_PHONE
using System.Reflection.Emit;
#endif
namespace Gum.Reflection
{
public abstract class LateBinder
{
static Dictionary<Type, LateBinder> mLateBinders = new Dictionary<Type, LateBinder>();
public static LateBinder GetInstance(Type type)
{
if (!mLateBinders.ContainsKey(type))
{
Type t = typeof(LateBinder<>).MakeGenericType(
type);
object obj = Activator.CreateInstance(t);
mLateBinders.Add(type, obj as LateBinder);
}
return mLateBinders[type];
}
public abstract object GetValue(object target, string name);
public abstract void SetValue(object target, string name, object value);
}
/// <summary>
/// Provides a simple interface to late bind a class.
/// </summary>
/// <remarks>The first time you attempt to get or set a property, it will dynamically generate the get and/or set
/// methods and cache them internally. Subsequent gets uses the dynamic methods without having to query the type's
/// meta data.</remarks>
public sealed class LateBinder<T> : LateBinder
{
#region Fields
HashSet<string> mFieldsSet = new HashSet<string>();
HashSet<string> mPropertieSet = new HashSet<string>();
private Type mType;
private Dictionary<string, GetHandler> mPropertyGet;
private Dictionary<string, SetHandler> mPropertySet;
private Dictionary<Type, List<string>> mFields;
private T mTarget = default(T);
private static LateBinder<T> _instance;
#endregion
#region Properties
public static LateBinder<T> Instance
{
get { return _instance; }
}
/// <summary>
/// The instance that this binder operates on by default
/// </summary>
/// <remarks>This can be overridden by the caller explicitly passing a target to the indexer</remarks>
public T Target
{
get { return mTarget; }
set { mTarget = value; }
}
/// <summary>
/// Gets or Sets the supplied property on the contained <seealso cref="Instance"/>
/// </summary>
/// <exception cref="InvalidOperationException">Throws if the contained Instance is null.</exception>
public object this[string propertyName]
{
get
{
ValidateInstance();
return this[mTarget, propertyName];
}
set
{
ValidateInstance();
this[mTarget, propertyName] = value;
}
}
/// <summary>
/// Gets or Sets the supplied property on the supplied target
/// </summary>
public object this[T target, string propertyName]
{
get
{
ValidateGetter(ref propertyName);
return mPropertyGet[propertyName](target);
}
set
{
ValidateSetter(ref propertyName);
mPropertySet[propertyName](target, value);
}
}
#endregion
#region Methods
#region Constructors
static LateBinder()
{
_instance = new LateBinder<T>();
}
public LateBinder(T instance)
: this()
{
mTarget = instance;
}
public LateBinder()
{
mType = typeof(T);
mPropertyGet = new Dictionary<string, GetHandler>();
mPropertySet = new Dictionary<string, SetHandler>();
mFields = new Dictionary<Type, List<string>>();
}
#endregion
#endregion
#region Public Accessors
public override object GetValue(object target, string name)
{
if (mFieldsSet.Contains(name))
{
return GetField(target, name);
}
else if (mPropertieSet.Contains(name))
{
return GetProperty(target, name);
}
else
{
if (mType.GetField(name, mGetFieldBindingFlags) != null)
{
mFieldsSet.Add(name);
return GetField(target, name);
}
else
{
mPropertieSet.Add(name);
return GetProperty(target, name);
}
}
}
public override void SetValue(object target, string name, object value)
{
if (mFieldsSet.Contains(name))
{
// do nothing currently
SetField(target, name, value);
}
else if (mPropertieSet.Contains(name))
{
SetProperty(target, name, value);
}
else
{
if (mType.GetField(name, mGetFieldBindingFlags) != null)
{
mFieldsSet.Add(name);
SetField(target, name, value);
}
else
{
mPropertieSet.Add(name);
SetProperty(target, name, value);
}
}
}
private void SetField(object target, string name, object value)
{
#if XBOX360 || WINDOWS_PHONE || SILVERLIGHT
throw new NotImplementedException();
#else
FieldInfo fieldInfo = target.GetType().GetField(
name);
#if DEBUG
try
{
#endif
fieldInfo.SetValueDirect(
__makeref(target), value);
#if DEBUG
}
catch (Exception)
{
if(fieldInfo == null)
{
throw new Exception("Could nto find field by the name " + name );
}
else
{
throw new Exception("Error trying to set field " + name + " which is of type " + fieldInfo.FieldType + ".\nTrying to set to " + value + " of type " + value.GetType());
}
}
#endif
#endif
}
/// <summary>
/// Sets the supplied property on the supplied target
/// </summary>
/// <typeparam name="K">the type of the value</typeparam>
public void SetProperty<K>(object target, string propertyName, K value)
{
#if XBOX360 || SILVERLIGHT || ZUNE || WINDOWS_PHONE
// find out if this is a property or field
Type type = typeof(T);
PropertyInfo propertyInfo = type.GetProperty(propertyName);
if (propertyInfo != null)
{
propertyInfo.SetValue(target, value, null);
}
else
{
FieldInfo fieldInfo = type.GetField(propertyName);
if (fieldInfo != null)
{
fieldInfo.SetValue(target, value);
}
else
{
throw new ArgumentException("Cannot find property or field with the name " + propertyName);
}
}
#else
ValidateSetter(ref propertyName);
if (mPropertySet.ContainsKey(propertyName))
{
mPropertySet[propertyName](target, value);
}
else
{
// This is probably not a property so see if it is a field.
FieldInfo fieldInfo = mType.GetField(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
if (fieldInfo == null)
{
string errorMessage =
"LateBinder could not find a field or property by the name of " + propertyName +
". Check the name of the property to verify if it is correct.";
throw new System.MemberAccessException(errorMessage);
}
else
{
if (!fieldInfo.IsPublic)
{
fieldInfo.SetValue(target, value);
}
else
{
object[] args = { value };
mType.InvokeMember(propertyName, BindingFlags.SetField, null, target, args);
}
}
}
#endif
}
static BindingFlags mGetFieldBindingFlags = BindingFlags.GetField | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
public object GetField(object target, string fieldName)
{
if (target == null)
{
FieldInfo fieldInfo = mType.GetField(fieldName, mGetFieldBindingFlags);
return fieldInfo.GetValue(null);
}
else
{
Binder binder = null;
object[] args = null;
return mType.InvokeMember(
fieldName,
mGetFieldBindingFlags,
binder,
target,
args
);
}
}
public ReturnType GetField<ReturnType>(T target, string propertyName)
{
return (ReturnType)GetField(target, propertyName);
}
/// <summary>
/// Gets the supplied property on the supplied target
/// </summary>
/// <typeparam name="K">The type of the property being returned</typeparam>
public K GetProperty<K>(T target, string propertyName)
{
return (K)GetProperty(target, propertyName);
}
public object GetProperty(object target, string propertyName)
{
#if XBOX360 || SILVERLIGHT || ZUNE || WINDOWS_PHONE || XNA4
// SLOW, but still works
return GetPropertyThroughReflection(target, propertyName);
#else
// June 11, 2011
// Turns out that
// getters for value
// types don't work properly.
// I found this out by trying to
// get the X value on a System.Drawing.Rectangle
// which was 0, but it kept returning a value of
// 2 billion. Checking for value types and using
// regular reflection fixes this problem.
if (target == null || typeof(T).IsValueType)
{
// SLOW, but still works
return GetPropertyThroughReflection(target, propertyName);
}
else
{
ValidateGetter(ref propertyName);
GetHandler getHandler = mPropertyGet[propertyName];
return getHandler(target);
}
#endif
}
private static object GetPropertyThroughReflection(object target, string propertyName)
{
PropertyInfo pi = typeof(T).GetProperty(propertyName, mGetterBindingFlags);
if (pi == null)
{
string message = "Could not find the property " + propertyName + "\n\nAvailableProperties:\n\n";
PropertyInfo[] properties = typeof(T).GetProperties(mGetterBindingFlags);
foreach (PropertyInfo containedProperty in properties)
{
message += containedProperty.Name + "\n";
}
throw new InvalidOperationException(message);
}
return pi.GetValue(target, null);
}
#endregion
#region Private Helpers
private void ValidateInstance()
{
if (mTarget == null)
{
throw new InvalidOperationException("Instance property must not be null");
}
}
private void ValidateSetter(ref string propertyName)
{
if (!mPropertySet.ContainsKey(propertyName))
{
BindingFlags bindingFlags =
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.Static;
PropertyInfo propertyInfo = mType.GetProperty(propertyName, bindingFlags);
if (propertyInfo != null)
{
mPropertySet.Add(propertyName, DynamicMethodCompiler.CreateSetHandler(mType, propertyInfo));
}
}
}
static BindingFlags mGetterBindingFlags =
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Static;
private void ValidateGetter(ref string propertyName)
{
if (!mPropertyGet.ContainsKey(propertyName))
{
PropertyInfo propertyInfo = mType.GetProperty(propertyName, mGetterBindingFlags);
if (propertyInfo != null)
{
mPropertyGet.Add(propertyName, DynamicMethodCompiler.CreateGetHandler(mType, propertyInfo));
}
}
}
#endregion
#region Contained Classes
internal delegate object GetHandler(object source);
internal delegate void SetHandler(object source, object value);
internal delegate object InstantiateObjectHandler();
/// <summary>
/// provides helper functions for late binding a class
/// </summary>
/// <remarks>
/// Class found here:
/// http://www.codeproject.com/useritems/Dynamic_Code_Generation.asp
/// </remarks>
internal sealed class DynamicMethodCompiler
{
// DynamicMethodCompiler
private DynamicMethodCompiler() { }
// CreateInstantiateObjectDelegate
internal static InstantiateObjectHandler CreateInstantiateObjectHandler(Type type)
{
#if !XBOX360 && !SILVERLIGHT && !ZUNE && !WINDOWS_PHONE
ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
if (constructorInfo == null)
{
throw new ApplicationException(string.Format("The type {0} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).", type));
}
DynamicMethod dynamicMethod = new DynamicMethod("InstantiateObject", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(object), null, type, true);
ILGenerator generator = dynamicMethod.GetILGenerator();
generator.Emit(OpCodes.Newobj, constructorInfo);
generator.Emit(OpCodes.Ret);
return (InstantiateObjectHandler)dynamicMethod.CreateDelegate(typeof(InstantiateObjectHandler));
#else
throw new NotSupportedException();
#endif
}
// CreateGetDelegate
internal static GetHandler CreateGetHandler(Type type, PropertyInfo propertyInfo)
{
#if !XBOX360 && !SILVERLIGHT && !ZUNE && !WINDOWS_PHONE
MethodInfo getMethodInfo = propertyInfo.GetGetMethod(true);
DynamicMethod dynamicGet = CreateGetDynamicMethod(type);
ILGenerator getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Call, getMethodInfo);
BoxIfNeeded(getMethodInfo.ReturnType, getGenerator);
getGenerator.Emit(OpCodes.Ret);
return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
#else
throw new NotSupportedException();
#endif
}
// CreateGetDelegate
internal static GetHandler CreateGetHandler(Type type, FieldInfo fieldInfo)
{
#if !XBOX360 && !SILVERLIGHT && !ZUNE && !WINDOWS_PHONE
DynamicMethod dynamicGet = CreateGetDynamicMethod(type);
ILGenerator getGenerator = dynamicGet.GetILGenerator();
getGenerator.Emit(OpCodes.Ldarg_0);
getGenerator.Emit(OpCodes.Ldfld, fieldInfo);
BoxIfNeeded(fieldInfo.FieldType, getGenerator);
getGenerator.Emit(OpCodes.Ret);
return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler));
#else
throw new NotSupportedException();
#endif
}
// CreateSetDelegate
internal static SetHandler CreateSetHandler(Type type, PropertyInfo propertyInfo)
{
#if !XBOX360 && !SILVERLIGHT && !ZUNE && !WINDOWS_PHONE
MethodInfo setMethodInfo = propertyInfo.GetSetMethod(true);
DynamicMethod dynamicSet = CreateSetDynamicMethod(type);
ILGenerator setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
UnboxIfNeeded(setMethodInfo.GetParameters()[0].ParameterType, setGenerator);
setGenerator.Emit(OpCodes.Call, setMethodInfo);
setGenerator.Emit(OpCodes.Ret);
return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
#else
throw new NotSupportedException();
#endif
}
// CreateSetDelegate
internal static SetHandler CreateSetHandler(Type type, FieldInfo fieldInfo)
{
#if !XBOX360 && !SILVERLIGHT && !ZUNE && !WINDOWS_PHONE
DynamicMethod dynamicSet = CreateSetDynamicMethod(type);
ILGenerator setGenerator = dynamicSet.GetILGenerator();
setGenerator.Emit(OpCodes.Ldarg_0);
setGenerator.Emit(OpCodes.Ldarg_1);
UnboxIfNeeded(fieldInfo.FieldType, setGenerator);
setGenerator.Emit(OpCodes.Stfld, fieldInfo);
setGenerator.Emit(OpCodes.Ret);
return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler));
#else
throw new NotSupportedException();
#endif
}
#if !XBOX360 && !SILVERLIGHT && !ZUNE && !WINDOWS_PHONE
// CreateGetDynamicMethod
private static DynamicMethod CreateGetDynamicMethod(Type type)
{
return new DynamicMethod("DynamicGet", typeof(object), new Type[] { typeof(object) }, type, true);
}
// CreateSetDynamicMethod
private static DynamicMethod CreateSetDynamicMethod(Type type)
{
return new DynamicMethod("DynamicSet", typeof(void), new Type[] { typeof(object), typeof(object) }, type, true);
}
// BoxIfNeeded
private static void BoxIfNeeded(Type type, ILGenerator generator)
{
if (type.IsValueType)
{
generator.Emit(OpCodes.Box, type);
}
}
// UnboxIfNeeded
private static void UnboxIfNeeded(Type type, ILGenerator generator)
{
if (type.IsValueType)
{
generator.Emit(OpCodes.Unbox_Any, type);
}
}
#endif
}
#endregion
}
}
| |
using System;
using Foundation;
using UIKit;
namespace UICatalog
{
[Register ("AlertControllerViewController")]
public class AlertControllerViewController : UITableViewController
{
private UIAlertAction secureTextAlertAction;
// Alert style alerts.
Action[] actionMap;
// Action sheet style alerts.
Action<UIView>[] actionSheetMap;
public AlertControllerViewController (IntPtr handle) : base (handle)
{
actionMap = new Action[] {
ShowSimpleAlert,
ShowOkayCancelAlert,
ShowOtherAlert,
ShowTextEntryAlert,
ShowSecureTextEntryAlert
};
actionSheetMap = new Action<UIView>[] {
ShowOkayCancelActionSheet,
ShowOtherActionSheet
};
}
// Show an alert with an "Okay" button.
private void ShowSimpleAlert()
{
var title = "A Short Title is Best".Localize ();
var message = "A message should be a short, complete sentence.".Localize ();
var cancelButtonTitle = "OK".Localize ();
var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert);
// Create the action.
var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, alertAction => {
Console.WriteLine ("The simple alert's cancel action occured.");
});
// Add the action.
alertController.AddAction (cancelAction);
PresentViewController (alertController, true, null);
}
// Show an alert with an "Okay" and "Cancel" button.
private void ShowOkayCancelAlert()
{
var title = "A Short Title is Best".Localize ();
var message = "A message should be a short, complete sentence.".Localize ();
var cancelButtonTitle = "Cancel".Localize ();
var otherButtonTitle = "OK".Localize ();
var alertCotroller = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert);
// Create the actions.
var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, alertAction => {
Console.WriteLine ("The 'Okay/Cancel' alert's cancel action occured.");
});
var otherAction = UIAlertAction.Create (otherButtonTitle, UIAlertActionStyle.Default, alertAction => {
Console.WriteLine ("The 'Okay/Cancel' alert's other action occured.");
});
// Add the actions.
alertCotroller.AddAction (cancelAction);
alertCotroller.AddAction (otherAction);
PresentViewController (alertCotroller, true, null);
}
// Show an alert with two custom buttons.
private void ShowOtherAlert()
{
var title = "A Short Title is Best".Localize ();
var message = "A message should be a short, complete sentence.".Localize ();
var cancelButtonTitle = "Cancel".Localize ();
var otherButtonTitleOne = "Choice One".Localize ();
var otherButtonTitleTwo = "Choice Two".Localize ();
var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert);
// Create the actions.
var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, alertAction => {
Console.WriteLine ("The 'Other' alert's cancel action occured.");
});
var otherButtonOneAction = UIAlertAction.Create (otherButtonTitleOne, UIAlertActionStyle.Default, alertAction => {
Console.WriteLine ("The 'Other' alert's other button one action occured.");
});
var otherButtonTwoAction = UIAlertAction.Create (otherButtonTitleTwo, UIAlertActionStyle.Default, alertAction => {
Console.WriteLine ("The 'Other' alert's other button two action occured.");
});
// Add the actions.
alertController.AddAction (cancelAction);
alertController.AddAction (otherButtonOneAction);
alertController.AddAction (otherButtonTwoAction);
PresentViewController (alertController, true, null);
}
// Show a text entry alert with two custom buttons.
private void ShowTextEntryAlert()
{
var title = "A Short Title is Best".Localize ();
var message = "A message should be a short, complete sentence.".Localize ();
var cancelButtonTitle = "Cancel".Localize ();
var otherButtonTitle = "OK".Localize ();
var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert);
// Add the text field for text entry.
alertController.AddTextField (textField => {
// If you need to customize the text field, you can do so here.
});
// Create the actions.
var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, alertAction => {
Console.WriteLine ("The 'Text Entry' alert's cancel action occured.");
});
var otherAction = UIAlertAction.Create (otherButtonTitle, UIAlertActionStyle.Default, alertAction => {
Console.WriteLine ("The 'Text Entry' alert's other action occured.");
});
// Add the actions.
alertController.AddAction (cancelAction);
alertController.AddAction (otherAction);
PresentViewController (alertController, true, null);
}
// Show a secure text entry alert with two custom buttons.
private void ShowSecureTextEntryAlert()
{
var title = "A Short Title is Best".Localize ();
var message = "A message should be a short, complete sentence.".Localize ();
var cancelButtonTitle = "Cancel".Localize ();
var otherButtonTitle = "OK".Localize ();
var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert);
NSObject observer = null;
// Add the text field for the secure text entry.
alertController.AddTextField(textField => {
// Listen for changes to the text field's text so that we can toggle the current
// action's enabled property based on whether the user has entered a sufficiently
// secure entry.
observer = NSNotificationCenter.DefaultCenter.AddObserver(UITextField.TextFieldTextDidChangeNotification, HandleTextFieldTextDidChangeNotification);
textField.SecureTextEntry = true;
});
// Stop listening for text change notifications on the text field. This func will be called in the two action handlers.
Action removeTextFieldObserver = () => {
NSNotificationCenter.DefaultCenter.RemoveObserver(observer);
};
// Create the actions.
var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, alertAction => {
Console.WriteLine ("The 'Secure Text Entry' alert's cancel action occured.");
removeTextFieldObserver();
});
var otherAction = UIAlertAction.Create (otherButtonTitle, UIAlertActionStyle.Default, alertAction => {
Console.WriteLine ("The 'Secure Text Entry' alert's other action occured.");
removeTextFieldObserver ();
});
// The text field initially has no text in the text field, so we'll disable it.
otherAction.Enabled = false;
// Hold onto the secure text alert action to toggle the enabled/disabled state when the text changed.
secureTextAlertAction = otherAction;
// Add the actions.
alertController.AddAction (cancelAction);
alertController.AddAction (otherAction);
PresentViewController (alertController, true, null);
}
// Show a dialog with an "Okay" and "Cancel" button.
private void ShowOkayCancelActionSheet(UIView sourceView)
{
var cancelButtonTitle = "Cancel".Localize ();
var destructiveButtonTitle = "OK".Localize ();
var alertController = UIAlertController.Create (null, null, UIAlertControllerStyle.ActionSheet);
// Create the actions.
var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Default, _ => {
Console.WriteLine ("The 'Okay-Cancel' alert action sheet's cancel action occured.");
});
var destructiveAction = UIAlertAction.Create (destructiveButtonTitle, UIAlertActionStyle.Destructive, _ => {
Console.WriteLine ("The 'Okay-Cancel' alert action sheet's destructive action occured.");
});
// Add the actions.
alertController.AddAction (cancelAction);
alertController.AddAction (destructiveAction);
SetupPopover (alertController, sourceView);
PresentViewController (alertController, true, null);
}
// Show a dialog with two custom buttons.
private void ShowOtherActionSheet(UIView sourceView)
{
var destructiveButtonTitle = "Destructive Choice".Localize ();
var otherButtonTitle = "Safe Choice".Localize ();
var alertController = UIAlertController.Create (null, null, UIAlertControllerStyle.ActionSheet);
// Create the actions.
var destructiveAction = UIAlertAction.Create (destructiveButtonTitle, UIAlertActionStyle.Destructive, _ => {
Console.WriteLine ("The 'Other' alert action sheet's destructive action occured.");
});
var otherAction = UIAlertAction.Create (otherButtonTitle, UIAlertActionStyle.Default, _ => {
Console.WriteLine ("The 'Other' alert action sheet's other action occured.");
});
// Add the actions.
alertController.AddAction (destructiveAction);
alertController.AddAction (otherAction);
SetupPopover (alertController, sourceView);
PresentViewController (alertController, true, null);
}
static void SetupPopover (UIAlertController alertController, UIView sourceView)
{
var popover = alertController.PopoverPresentationController;
if (popover != null) {
popover.SourceView = sourceView;
popover.SourceRect = sourceView.Bounds;
}
}
private void HandleTextFieldTextDidChangeNotification(NSNotification notification)
{
var textField = notification.Object as UITextField;
// Enforce a minimum length of >= 5 for secure text alerts.
if (secureTextAlertAction == null)
throw new InvalidOperationException ();
secureTextAlertAction.Enabled = textField.Text.Length >= 5;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
// A matrix of closures that should be invoked based on which table view cell is
// tapped (index by section, row).
bool simpleAlert = indexPath.Section == 0;
if (simpleAlert) {
var action = actionMap [indexPath.Row];
action ();
} else {
var action = actionSheetMap [indexPath.Row];
action (tableView.CellAt(indexPath));
}
tableView.DeselectRow (indexPath, animated: true);
}
}
}
| |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot ([email protected])
//
// Copyright 2013 ServiceStack.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.Common.Utils;
using ServiceStack.DesignPatterns.Model;
using ServiceStack.Redis.Support;
using ServiceStack.Text;
using ServiceStack.Common.Extensions;
namespace ServiceStack.Redis.Generic
{
public partial class RedisTypedClient<T>
{
public IHasNamed<IRedisSortedSet<T>> SortedSets { get; set; }
internal class RedisClientSortedSets
: IHasNamed<IRedisSortedSet<T>>
{
private readonly RedisTypedClient<T> client;
public RedisClientSortedSets(RedisTypedClient<T> client)
{
this.client = client;
}
public IRedisSortedSet<T> this[string setId]
{
get
{
return new RedisClientSortedSet<T>(client, setId);
}
set
{
var col = this[setId];
col.Clear();
col.CopyTo(value.ToArray(), 0);
}
}
}
public static T DeserializeFromString(string serializedObj)
{
return JsonSerializer.DeserializeFromString<T>(serializedObj);
}
private static IDictionary<T, double> CreateGenericMap(IDictionary<string, double> map)
{
var genericMap = new OrderedDictionary<T, double>();
foreach (var entry in map)
{
genericMap[DeserializeFromString(entry.Key)] = entry.Value;
}
return genericMap;
}
public void AddItemToSortedSet(IRedisSortedSet<T> toSet, T value)
{
client.AddItemToSortedSet(toSet.Id, value.SerializeToString());
}
public void AddItemToSortedSet(IRedisSortedSet<T> toSet, T value, double score)
{
client.AddItemToSortedSet(toSet.Id, value.SerializeToString(), score);
}
public bool RemoveItemFromSortedSet(IRedisSortedSet<T> fromSet, T value)
{
return client.RemoveItemFromSortedSet(fromSet.Id, value.SerializeToString());
}
public T PopItemWithLowestScoreFromSortedSet(IRedisSortedSet<T> fromSet)
{
return DeserializeFromString(
client.PopItemWithLowestScoreFromSortedSet(fromSet.Id));
}
public T PopItemWithHighestScoreFromSortedSet(IRedisSortedSet<T> fromSet)
{
return DeserializeFromString(
client.PopItemWithHighestScoreFromSortedSet(fromSet.Id));
}
public bool SortedSetContainsItem(IRedisSortedSet<T> set, T value)
{
return client.SortedSetContainsItem(set.Id, value.SerializeToString());
}
public double IncrementItemInSortedSet(IRedisSortedSet<T> set, T value, double incrementBy)
{
return client.IncrementItemInSortedSet(set.Id, value.SerializeToString(), incrementBy);
}
public long GetItemIndexInSortedSet(IRedisSortedSet<T> set, T value)
{
return client.GetItemIndexInSortedSet(set.Id, value.SerializeToString());
}
public long GetItemIndexInSortedSetDesc(IRedisSortedSet<T> set, T value)
{
return client.GetItemIndexInSortedSetDesc(set.Id, value.SerializeToString());
}
public List<T> GetAllItemsFromSortedSet(IRedisSortedSet<T> set)
{
var list = client.GetAllItemsFromSortedSet(set.Id);
return list.ConvertEachTo<T>();
}
public List<T> GetAllItemsFromSortedSetDesc(IRedisSortedSet<T> set)
{
var list = client.GetAllItemsFromSortedSetDesc(set.Id);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSet(IRedisSortedSet<T> set, int fromRank, int toRank)
{
var list = client.GetRangeFromSortedSet(set.Id, fromRank, toRank);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetDesc(IRedisSortedSet<T> set, int fromRank, int toRank)
{
var list = client.GetRangeFromSortedSetDesc(set.Id, fromRank, toRank);
return list.ConvertEachTo<T>();
}
public IDictionary<T, double> GetAllWithScoresFromSortedSet(IRedisSortedSet<T> set)
{
var map = client.GetRangeWithScoresFromSortedSet(set.Id, FirstElement, LastElement);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSet(IRedisSortedSet<T> set, int fromRank, int toRank)
{
var map = client.GetRangeWithScoresFromSortedSet(set.Id, fromRank, toRank);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetDesc(IRedisSortedSet<T> set, int fromRank, int toRank)
{
var map = client.GetRangeWithScoresFromSortedSetDesc(set.Id, fromRank, toRank);
return CreateGenericMap(map);
}
public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore)
{
var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take)
{
var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore, skip, take);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromScore, toScore);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take)
{
var list = client.GetRangeFromSortedSetByLowestScore(set.Id, fromScore, toScore, skip, take);
return list.ConvertEachTo<T>();
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore)
{
var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take)
{
var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromStringScore, toStringScore, skip, take);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromScore, toScore);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByLowestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take)
{
var map = client.GetRangeWithScoresFromSortedSetByLowestScore(set.Id, fromScore, toScore, skip, take);
return CreateGenericMap(map);
}
public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore)
{
var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take)
{
var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore, skip, take);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromScore, toScore);
return list.ConvertEachTo<T>();
}
public List<T> GetRangeFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take)
{
var list = client.GetRangeFromSortedSetByHighestScore(set.Id, fromScore, toScore, skip, take);
return list.ConvertEachTo<T>();
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore)
{
var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, string fromStringScore, string toStringScore, int? skip, int? take)
{
var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromStringScore, toStringScore, skip, take);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromScore, toScore);
return CreateGenericMap(map);
}
public IDictionary<T, double> GetRangeWithScoresFromSortedSetByHighestScore(IRedisSortedSet<T> set, double fromScore, double toScore, int? skip, int? take)
{
var map = client.GetRangeWithScoresFromSortedSetByHighestScore(set.Id, fromScore, toScore, skip, take);
return CreateGenericMap(map);
}
public long RemoveRangeFromSortedSet(IRedisSortedSet<T> set, int minRank, int maxRank)
{
return client.RemoveRangeFromSortedSet(set.Id, minRank, maxRank);
}
public long RemoveRangeFromSortedSetByScore(IRedisSortedSet<T> set, double fromScore, double toScore)
{
return client.RemoveRangeFromSortedSetByScore(set.Id, fromScore, toScore);
}
public long GetSortedSetCount(IRedisSortedSet<T> set)
{
return client.GetSortedSetCount(set.Id);
}
public double GetItemScoreInSortedSet(IRedisSortedSet<T> set, T value)
{
return client.GetItemScoreInSortedSet(set.Id, value.SerializeToString());
}
public long StoreIntersectFromSortedSets(IRedisSortedSet<T> intoSetId, params IRedisSortedSet<T>[] setIds)
{
return client.StoreIntersectFromSortedSets(intoSetId.Id, setIds.ConvertAll(x => x.Id).ToArray());
}
public long StoreUnionFromSortedSets(IRedisSortedSet<T> intoSetId, params IRedisSortedSet<T>[] setIds)
{
return client.StoreUnionFromSortedSets(intoSetId.Id, setIds.ConvertAll(x => x.Id).ToArray());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DDay.iCal
{
#region Alarms
public enum AlarmAction
{
Audio,
Display,
Email,
Procedure
};
public enum TriggerRelation
{
Start,
End
}
#endregion
#region Components
public class Components
{
#region Constants
public const string ALARM = "VALARM";
public const string CALENDAR = "VCALENDAR";
public const string EVENT = "VEVENT";
public const string FREEBUSY = "VFREEBUSY";
public const string TODO = "VTODO";
public const string JOURNAL = "VJOURNAL";
public const string TIMEZONE = "VTIMEZONE";
public const string DAYLIGHT = "DAYLIGHT";
public const string STANDARD = "STANDARD";
#endregion
}
#endregion
#region Status Constants
public class ParticipationStatus
{
#region Constants
public const string NeedsAction = "NEEDS-ACTION";
public const string Accepted = "ACCEPTED";
public const string Declined = "DECLINED";
public const string Tentative = "TENTATIVE";
public const string Delegated = "DELEGATED";
#endregion
}
/// <summary>
/// Status codes available to an <see cref="Event"/> item
/// </summary>
public enum EventStatus
{
Tentative,
Confirmed,
Cancelled
};
/// <summary>
/// Status codes available to a <see cref="Todo"/> item.
/// </summary>
public enum TodoStatus
{
NeedsAction,
Completed,
InProcess,
Cancelled
};
/// <summary>
/// Status codes available to a <see cref="Journal"/> entry.
/// </summary>
public enum JournalStatus
{
Draft, // Indicates journal is draft.
Final, // Indicates journal is final.
Cancelled // Indicates journal is removed.
};
public enum FreeBusyStatus
{
Free = 0,
BusyTentative = 1,
BusyUnavailable = 2,
Busy = 3
}
#endregion
#region Occurrence Evaluation
public enum FrequencyType
{
None,
Secondly,
Minutely,
Hourly,
Daily,
Weekly,
Monthly,
Yearly
};
/// <summary>
/// Indicates the occurrence of the specific day within a
/// MONTHLY or YEARLY recurrence frequency. For example, within
/// a MONTHLY frequency, consider the following:
///
/// RecurrencePattern r = new RecurrencePattern();
/// r.Frequency = FrequencyType.Monthly;
/// r.ByDay.Add(new WeekDay(DayOfWeek.Monday, FrequencyOccurrence.First));
///
/// The above example represents the first Monday within the month,
/// whereas if FrequencyOccurrence.Last were specified, it would
/// represent the last Monday of the month.
///
/// For a YEARLY frequency, consider the following:
///
/// Recur r = new Recur();
/// r.Frequency = FrequencyType.Yearly;
/// r.ByDay.Add(new WeekDay(DayOfWeek.Monday, FrequencyOccurrence.Second));
///
/// The above example represents the second Monday of the year. This can
/// also be represented with the following code:
///
/// r.ByDay.Add(new WeekDay(DayOfWeek.Monday, 2));
/// </summary>
public enum FrequencyOccurrence
{
None = int.MinValue,
Last = -1,
SecondToLast = -2,
ThirdToLast = -3,
FourthToLast = -4,
FifthToLast = -5,
First = 1,
Second = 2,
Third = 3,
Fourth = 4,
Fifth = 5
}
public enum RecurrenceRestrictionType
{
/// <summary>
/// Same as RestrictSecondly.
/// </summary>
Default,
/// <summary>
/// Does not restrict recurrence evaluation - WARNING: this may cause very slow performance!
/// </summary>
NoRestriction,
/// <summary>
/// Disallows use of the SECONDLY frequency for recurrence evaluation
/// </summary>
RestrictSecondly,
/// <summary>
/// Disallows use of the MINUTELY and SECONDLY frequencies for recurrence evaluation
/// </summary>
RestrictMinutely,
/// <summary>
/// Disallows use of the HOURLY, MINUTELY, and SECONDLY frequencies for recurrence evaluation
/// </summary>
RestrictHourly
}
public enum RecurrenceEvaluationModeType
{
/// <summary>
/// Same as ThrowException.
/// </summary>
Default,
/// <summary>
/// Automatically adjusts the evaluation to the next-best frequency based on the restriction type.
/// For example, if the restriction were IgnoreSeconds, and the frequency were SECONDLY, then
/// this would cause the frequency to be adjusted to MINUTELY, the next closest thing.
/// </summary>
AdjustAutomatically,
/// <summary>
/// This will throw an exception if a recurrence rule is evaluated that does not meet the minimum
/// restrictions. For example, if the restriction were IgnoreSeconds, and a SECONDLY frequency
/// were evaluated, an exception would be thrown.
/// </summary>
ThrowException
}
#endregion
#region Transparency
public enum TransparencyType
{
Opaque,
Transparent
}
#endregion
#region Calendar Properties
public class CalendarProductIDs
{
public const string Default = "-//ddaysoftware.com//NONSGML DDay.iCal 1.0//EN";
}
public class CalendarVersions
{
public const string v2_0 = "2.0";
}
public class CalendarScales
{
public const string Gregorian = "GREGORIAN";
}
public class CalendarMethods
{
/// <summary>
/// Used to publish an iCalendar object to one or
/// more "Calendar Users". There is no interactivity
/// between the publisher and any other "Calendar User".
/// An example might include a baseball team publishing
/// its schedule to the public.
/// </summary>
public const string Publish = "PUBLISH";
/// <summary>
/// Used to schedule an iCalendar object with other
/// "Calendar Users". Requests are interactive in
/// that they require the receiver to respond using
/// the reply methods. Meeting requests, busy-time
/// requests, and the assignment of tasks to other
/// "Calendar Users" are all examples. Requests are
/// also used by the Organizer to update the status
/// of an iCalendar object.
/// </summary>
public const string Request = "REQUEST";
/// <summary>
/// A reply is used in response to a request to
/// convey Attendee status to the Organizer.
/// Replies are commonly used to respond to meeting
/// and task requests.
/// </summary>
public const string Reply = "REPLY";
/// <summary>
/// Add one or more new instances to an existing
/// recurring iCalendar object.
/// </summary>
public const string Add = "ADD";
/// <summary>
/// Cancel one or more instances of an existing
/// iCalendar object.
/// </summary>
public const string Cancel = "CANCEL";
/// <summary>
/// Used by an Attendee to request the latest
/// version of an iCalendar object.
/// </summary>
public const string Refresh = "REFRESH";
/// <summary>
/// Used by an Attendee to negotiate a change in an
/// iCalendar object. Examples include the request
/// to change a proposed event time or change the
/// due date for a task.
/// </summary>
public const string Counter = "COUNTER";
/// <summary>
/// Used by the Organizer to decline the proposed
/// counter-proposal.
/// </summary>
public const string DeclineCounter = "DECLINECOUNTER";
}
#endregion
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine.AssetBundles.GraphTool;
using Model=UnityEngine.AssetBundles.GraphTool.DataModel.Version2;
namespace UnityEngine.AssetBundles.GraphTool {
[CustomNode("Assert/Assert Unwanted Assets In Bundle", 80)]
public class AssertUnwantedAssetsInBundle : Node {
public enum AssertionStyle : int {
AllowOnlyAssetsUnderAssertionPath, // Only allows asssets under assertion path to be included
ProhibitAssetsUnderAssertionPath // Prohibit assets under assertion path to be included
}
[SerializeField] private SerializableMultiTargetString m_path;
[SerializeField] private AssertionStyle m_style;
public override string ActiveStyle {
get {
return "node 7 on";
}
}
public override string InactiveStyle {
get {
return "node 7";
}
}
public override string Category {
get {
return "Assert";
}
}
public override Model.NodeOutputSemantics NodeInputType {
get {
return Model.NodeOutputSemantics.AssetBundleConfigurations;
}
}
public override Model.NodeOutputSemantics NodeOutputType {
get {
return Model.NodeOutputSemantics.AssetBundleConfigurations;
}
}
public override void Initialize(Model.NodeData data) {
m_path = new SerializableMultiTargetString();
m_style = AssertionStyle.AllowOnlyAssetsUnderAssertionPath;
data.AddDefaultInputPoint();
data.AddDefaultOutputPoint();
}
public override Node Clone(Model.NodeData newData) {
var newNode = new AssertUnwantedAssetsInBundle();
newNode.m_path = new SerializableMultiTargetString(m_path);
newNode.m_style = m_style;
newData.AddDefaultInputPoint();
newData.AddDefaultOutputPoint();
return newNode;
}
public override bool OnAssetsReimported(
Model.NodeData nodeData,
AssetReferenceStreamManager streamManager,
BuildTarget target,
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
return true;
}
public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged) {
EditorGUILayout.HelpBox("Assert Unwanted Assets In Bundle: Checks if unwanted assets are included in bundle configurations.", MessageType.Info);
editor.UpdateNodeName(node);
GUILayout.Space(10f);
var newValue = (AssertionStyle)EditorGUILayout.EnumPopup("Assertion Style", m_style);
if(newValue != m_style) {
using(new RecordUndoScope("Change Assertion Style", node, true)) {
m_style = newValue;
onValueChanged();
}
}
GUILayout.Space(4f);
//Show target configuration tab
editor.DrawPlatformSelector(node);
using (new EditorGUILayout.VerticalScope(GUI.skin.box)) {
var disabledScope = editor.DrawOverrideTargetToggle(node, m_path.ContainsValueOf(editor.CurrentEditingGroup), (bool b) => {
using(new RecordUndoScope("Remove Target Load Path Settings", node, true)) {
if(b) {
m_path[editor.CurrentEditingGroup] = m_path.DefaultValue;
} else {
m_path.Remove(editor.CurrentEditingGroup);
}
onValueChanged();
}
});
using (disabledScope) {
var path = m_path[editor.CurrentEditingGroup];
EditorGUILayout.LabelField("Assertion Path:");
string newLoadPath = null;
newLoadPath = editor.DrawFolderSelector (Model.Settings.Path.ASSETS_PATH, "Select Asset Folder",
path,
FileUtility.PathCombine(Model.Settings.Path.ASSETS_PATH, path),
(string folderSelected) => {
var dataPath = Application.dataPath;
if(dataPath == folderSelected) {
folderSelected = string.Empty;
} else {
var index = folderSelected.IndexOf(dataPath);
if(index >= 0 ) {
folderSelected = folderSelected.Substring(dataPath.Length + index);
if(folderSelected.IndexOf('/') == 0) {
folderSelected = folderSelected.Substring(1);
}
}
}
return folderSelected;
}
);
if (newLoadPath != path) {
using(new RecordUndoScope("Path Change", node, true)){
m_path[editor.CurrentEditingGroup] = newLoadPath;
onValueChanged();
}
}
var dirPath = Path.Combine(Model.Settings.Path.ASSETS_PATH,newLoadPath);
bool dirExists = Directory.Exists(dirPath);
GUILayout.Space(10f);
using (new EditorGUILayout.HorizontalScope()) {
using(new EditorGUI.DisabledScope(string.IsNullOrEmpty(newLoadPath)||!dirExists))
{
GUILayout.FlexibleSpace();
if(GUILayout.Button("Highlight in Project Window", GUILayout.Width(180f))) {
// trailing is "/" not good for LoadMainAssetAtPath
if(dirPath[dirPath.Length-1] == '/') {
dirPath = dirPath.Substring(0, dirPath.Length-1);
}
var obj = AssetDatabase.LoadMainAssetAtPath(dirPath);
EditorGUIUtility.PingObject(obj);
}
}
}
}
}
}
/**
* Prepare is called whenever graph needs update.
*/
public override void Prepare (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output)
{
if(string.IsNullOrEmpty(m_path[target])) {
throw new NodeException(node.Name + ":Assertion Path is empty.", node.Id);
}
// Pass incoming assets straight to Output
if(Output != null) {
var destination = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
if(incoming != null) {
var checkPath = m_path[target];
var allow = m_style == AssertionStyle.AllowOnlyAssetsUnderAssertionPath;
foreach(var ag in incoming) {
foreach (var assets in ag.assetGroups.Values) {
foreach(var a in assets) {
if(allow != a.importFrom.Contains(checkPath)) {
throw new NodeException(node.Name + ":Unwanted asset '" + a.importFrom + "' found.", node.Id);
}
var dependencies = AssetDatabase.GetDependencies(new string[] { a.importFrom } );
foreach(var d in dependencies) {
if(allow != d.Contains(checkPath)) {
throw new NodeException(node.Name + ":Unwanted asset found in dependency:'" + d
+ "' from following asset:" + a.importFrom, node.Id);
}
}
}
}
Output(destination, ag.assetGroups);
}
} else {
// Overwrite output with empty Dictionary when no there is incoming asset
Output(destination, new Dictionary<string, List<AssetReference>>());
}
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2006 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NUnit.TestUtilities.Collections;
using NUnit.TestUtilities.Comparers;
namespace NUnit.Framework.Assertions
{
/// <summary>
/// Test Library for the NUnit CollectionAssert class.
/// </summary>
[TestFixture()]
public class CollectionAssertTest
{
#region AllItemsAreInstancesOfType
[Test()]
public void ItemsOfType()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string));
}
[Test]
public void ItemsOfTypeFailure()
{
var collection = new SimpleObjectCollection("x", "y", new object());
var expectedMessage =
" Expected: all items instance of <System.String>" + Environment.NewLine +
" But was: < \"x\", \"y\", <System.Object> >" + Environment.NewLine +
" First non-matching item at index [2]: <System.Object>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreInstancesOfType(collection, typeof(string)));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region AllItemsAreNotNull
[Test()]
public void ItemsNotNull()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AllItemsAreNotNull(collection);
}
[Test]
public void ItemsNotNullFailure()
{
var collection = new SimpleObjectCollection("x", null, "z");
var expectedMessage =
" Expected: all items not null" + Environment.NewLine +
" But was: < \"x\", null, \"z\" >" + Environment.NewLine +
" First non-matching item at index [1]: null" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreNotNull(collection));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region AllItemsAreUnique
[Test]
public void Unique_WithObjects()
{
CollectionAssert.AllItemsAreUnique(
new SimpleObjectCollection(new object(), new object(), new object()));
}
[Test]
public void Unique_WithStrings()
{
CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "z"));
}
[Test]
public void Unique_WithNull()
{
CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", null, "z"));
}
[Test]
public void UniqueFailure()
{
var expectedMessage =
" Expected: all items unique" + Environment.NewLine +
" But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "x")));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void UniqueFailure_WithTwoNulls()
{
Assert.Throws<AssertionException>(
() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", null, "y", null, "z")));
}
[Test]
public void UniqueFailure_ElementTypeIsObject_NUnitEqualityIsUsed()
{
var collection = new List<object> { 42, null, 42f };
Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection));
}
[Test]
public void UniqueFailure_ElementTypeIsInterface_NUnitEqualityIsUsed()
{
var collection = new List<IConvertible> { 42, null, 42f };
Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection));
}
[Test]
public void UniqueFailure_ElementTypeIsStruct_ImplicitCastAndNewAlgorithmIsUsed()
{
var collection = new List<float> { 42, 42f };
Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection));
}
[Test]
public void UniqueFailure_ElementTypeIsNotSealed_NUnitEqualityIsUsed()
{
var collection = new List<ValueType> { 42, 42f };
Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(collection));
}
static readonly IEnumerable<int> RANGE = Enumerable.Range(0, 10000);
static readonly IEnumerable[] PerformanceData =
{
RANGE,
new List<int>(RANGE),
new List<double>(RANGE.Select(v => (double)v)),
new List<string>(RANGE.Select(v => v.ToString()))
};
[TestCaseSource(nameof(PerformanceData))]
public void PerformanceTests(IEnumerable values)
{
Warn.Unless(() => CollectionAssert.AllItemsAreUnique(values), HelperConstraints.HasMaxTime(100));
}
#endregion
#region AreEqual
[Test]
public void AreEqual()
{
var set1 = new SimpleEnumerable("x", "y", "z");
var set2 = new SimpleEnumerable("x", "y", "z");
CollectionAssert.AreEqual(set1,set2);
CollectionAssert.AreEqual(set1,set2,new TestComparer());
Assert.AreEqual(set1,set2);
}
[Test]
public void AreEqualFailCount()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("x", "y", "z", "a");
var expectedMessage =
" Expected is <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements, actual is <NUnit.TestUtilities.Collections.SimpleObjectList> with 4 elements" + Environment.NewLine +
" Values differ at index [3]" + Environment.NewLine +
" Extra: < \"a\" >";
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEqualFail()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("x", "y", "a");
var expectedMessage =
" Expected and actual are both <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements" + Environment.NewLine +
" Values differ at index [2]" + Environment.NewLine +
" String lengths are both 1. Strings differ at index 0." + Environment.NewLine +
" Expected: \"z\"" + Environment.NewLine +
" But was: \"a\"" + Environment.NewLine +
" -----------^" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1,set2,new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEqual_HandlesNull()
{
object[] set1 = new object[3];
object[] set2 = new object[3];
CollectionAssert.AreEqual(set1,set2);
CollectionAssert.AreEqual(set1,set2,new TestComparer());
}
[Test]
public void EnsureComparerIsUsed()
{
// Create two collections
int[] array1 = new int[2];
int[] array2 = new int[2];
array1[0] = 4;
array1[1] = 5;
array2[0] = 99;
array2[1] = -99;
CollectionAssert.AreEqual(array1, array2, new AlwaysEqualComparer());
}
[Test]
public void AreEqual_UsingIterator()
{
int[] array = new int[] { 1, 2, 3 };
CollectionAssert.AreEqual(array, CountToThree());
}
[Test]
public void AreEqualFails_ObjsUsingIEquatable()
{
IEnumerable set1 = new SimpleEnumerableWithIEquatable("x", "y", "z");
IEnumerable set2 = new SimpleEnumerableWithIEquatable("x", "z", "z");
CollectionAssert.AreNotEqual(set1, set2);
Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2));
}
[Test]
public void IEnumerablesAreEqualWithCollectionsObjectsImplemetingIEquatable()
{
IEnumerable set1 = new SimpleEnumerable(new SimpleIEquatableObj());
IEnumerable set2 = new SimpleEnumerable(new SimpleIEquatableObj());
CollectionAssert.AreEqual(set1, set2);
}
[Test]
public void ArraysAreEqualWithCollectionsObjectsImplementingIEquatable()
{
SimpleIEquatableObj[] set1 = new SimpleIEquatableObj[] { new SimpleIEquatableObj() };
SimpleIEquatableObj[] set2 = new SimpleIEquatableObj[] { new SimpleIEquatableObj() };
CollectionAssert.AreEqual(set1, set2);
}
IEnumerable CountToThree()
{
yield return 1;
yield return 2;
yield return 3;
}
[Test]
public void AreEqual_UsingIterator_Fails()
{
int[] array = new int[] { 1, 3, 5 };
AssertionException ex = Assert.Throws<AssertionException>(
delegate { CollectionAssert.AreEqual(array, CountToThree()); } );
Assert.That(ex.Message, Does.Contain("Values differ at index [1]").And.
Contains("Expected: 3").And.
Contains("But was: 2"));
}
#if !NET20
[Test]
public void AreEqual_UsingLinqQuery()
{
int[] array = new int[] { 1, 2, 3 };
CollectionAssert.AreEqual(array, array.Select((item) => item));
}
[Test]
public void AreEqual_UsingLinqQuery_Fails()
{
int[] array = new int[] { 1, 2, 3 };
AssertionException ex = Assert.Throws<AssertionException>(
delegate { CollectionAssert.AreEqual(array, array.Select((item) => item * 2)); } );
Assert.That(ex.Message, Does.Contain("Values differ at index [0]").And.
Contains("Expected: 1").And.
Contains("But was: 2"));
}
#endif
[Test]
public void AreEqual_IEquatableImplementationIsIgnored()
{
var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42);
var y = new Constraints.EnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 15);
// They are not equal using Assert
Assert.AreNotEqual(x, y, "Assert 1");
Assert.AreNotEqual(y, x, "Assert 2");
// Using CollectionAssert they are equal
CollectionAssert.AreEqual(x, y, "CollectionAssert 1");
CollectionAssert.AreEqual(y, x, "CollectionAssert 2");
}
#endregion
#region AreEquivalent
[Test]
public void Equivalent()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "z");
ICollection set2 = new SimpleObjectCollection("z", "y", "x");
CollectionAssert.AreEquivalent(set1,set2);
}
[Test]
public void EquivalentFailOne()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "z");
ICollection set2 = new SimpleObjectCollection("x", "y", "x");
var expectedMessage =
" Expected: equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine +
" Missing (1): < \"z\" >" + Environment.NewLine +
" Extra (1): < \"x\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void EquivalentFailTwo()
{
ICollection set1 = new SimpleObjectCollection("x", "y", "x");
ICollection set2 = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: equivalent to < \"x\", \"y\", \"x\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" Missing (1): < \"x\" >" + Environment.NewLine +
" Extra (1): < \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreEquivalentHandlesNull()
{
ICollection set1 = new SimpleObjectCollection(null, "x", null, "z");
ICollection set2 = new SimpleObjectCollection("z", null, "x", null);
CollectionAssert.AreEquivalent(set1,set2);
}
#endregion
#region AreNotEqual
[Test]
public void AreNotEqual()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "x");
CollectionAssert.AreNotEqual(set1,set2);
CollectionAssert.AreNotEqual(set1,set2,new TestComparer());
CollectionAssert.AreNotEqual(set1,set2,"test");
CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test");
CollectionAssert.AreNotEqual(set1,set2,"test {0}","1");
CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test {0}","1");
}
[Test]
public void AreNotEqual_Fails()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: not equal to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEqual(set1, set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void AreNotEqual_HandlesNull()
{
object[] set1 = new object[3];
var set2 = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.AreNotEqual(set1,set2);
CollectionAssert.AreNotEqual(set1,set2,new TestComparer());
}
[Test]
public void AreNotEqual_IEquatableImplementationIsIgnored()
{
var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42);
var y = new Constraints.EnumerableObject<int>(new[] { 5, 4, 3, 2, 1 }, 42);
// Equal using Assert
Assert.AreEqual(x, y, "Assert 1");
Assert.AreEqual(y, x, "Assert 2");
// Not equal using CollectionAssert
CollectionAssert.AreNotEqual(x, y, "CollectionAssert 1");
CollectionAssert.AreNotEqual(y, x, "CollectionAssert 2");
}
#endregion
#region AreNotEquivalent
[Test]
public void NotEquivalent()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "y", "x");
CollectionAssert.AreNotEquivalent(set1,set2);
}
[Test]
public void NotEquivalent_Fails()
{
var set1 = new SimpleObjectCollection("x", "y", "z");
var set2 = new SimpleObjectCollection("x", "z", "y");
var expectedMessage =
" Expected: not equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEquivalent(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void NotEquivalentHandlesNull()
{
var set1 = new SimpleObjectCollection("x", null, "z");
var set2 = new SimpleObjectCollection("x", null, "x");
CollectionAssert.AreNotEquivalent(set1,set2);
}
#endregion
#region Contains
[Test]
public void Contains_IList()
{
var list = new SimpleObjectList("x", "y", "z");
CollectionAssert.Contains(list, "x");
}
[Test]
public void Contains_ICollection()
{
var collection = new SimpleObjectCollection("x", "y", "z");
CollectionAssert.Contains(collection,"x");
}
[Test]
public void ContainsFails_ILIst()
{
var list = new SimpleObjectList("x", "y", "z");
var expectedMessage =
" Expected: some item equal to \"a\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"a"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_ICollection()
{
var collection = new SimpleObjectCollection("x", "y", "z");
var expectedMessage =
" Expected: some item equal to \"a\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(collection,"a"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_EmptyIList()
{
var list = new SimpleObjectList();
var expectedMessage =
" Expected: some item equal to \"x\"" + Environment.NewLine +
" But was: <empty>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"x"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsFails_EmptyICollection()
{
var ca = new SimpleObjectCollection(new object[0]);
var expectedMessage =
" Expected: some item equal to \"x\"" + Environment.NewLine +
" But was: <empty>" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(ca,"x"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void ContainsNull_IList()
{
Object[] oa = new object[] { 1, 2, 3, null, 4, 5 };
CollectionAssert.Contains( oa, null );
}
[Test]
public void ContainsNull_ICollection()
{
var ca = new SimpleObjectCollection(new object[] { 1, 2, 3, null, 4, 5 });
CollectionAssert.Contains( ca, null );
}
#endregion
#region DoesNotContain
[Test]
public void DoesNotContain()
{
var list = new SimpleObjectList();
CollectionAssert.DoesNotContain(list,"a");
}
[Test]
public void DoesNotContain_Empty()
{
var list = new SimpleObjectList();
CollectionAssert.DoesNotContain(list,"x");
}
[Test]
public void DoesNotContain_Fails()
{
var list = new SimpleObjectList("x", "y", "z");
var expectedMessage =
" Expected: not some item equal to \"y\"" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.DoesNotContain(list,"y"));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#region IsSubsetOf
[Test]
public void IsSubsetOf()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z");
CollectionAssert.IsSubsetOf(set2,set1);
Assert.That(set2, Is.SubsetOf(set1));
}
[Test]
public void IsSubsetOf_Fails()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z", "a");
var expectedMessage =
" Expected: subset of < \"y\", \"z\", \"a\" >" + Environment.NewLine +
" But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsSubsetOf(set1,set2));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsSubsetOfHandlesNull()
{
var set1 = new SimpleObjectList("x", null, "z");
var set2 = new SimpleObjectList(null, "z");
CollectionAssert.IsSubsetOf(set2,set1);
Assert.That(set2, Is.SubsetOf(set1));
}
#endregion
#region IsNotSubsetOf
[Test]
public void IsNotSubsetOf()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z", "a");
CollectionAssert.IsNotSubsetOf(set1,set2);
Assert.That(set1, Is.Not.SubsetOf(set2));
}
[Test]
public void IsNotSubsetOf_Fails()
{
var set1 = new SimpleObjectList("x", "y", "z");
var set2 = new SimpleObjectList("y", "z");
var expectedMessage =
" Expected: not subset of < \"x\", \"y\", \"z\" >" + Environment.NewLine +
" But was: < \"y\", \"z\" >" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsNotSubsetOf(set2,set1));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsNotSubsetOfHandlesNull()
{
var set1 = new SimpleObjectList("x", null, "z");
var set2 = new SimpleObjectList(null, "z", "a");
CollectionAssert.IsNotSubsetOf(set1,set2);
}
#endregion
#region IsOrdered
[Test]
public void IsOrdered()
{
var list = new SimpleObjectList("x", "y", "z");
CollectionAssert.IsOrdered(list);
}
[Test]
public void IsOrdered_Fails()
{
var list = new SimpleObjectList("x", "z", "y");
var expectedMessage =
" Expected: collection ordered" + Environment.NewLine +
" But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine +
" Ordering breaks at index [2]: \"y\"" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsOrdered(list));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
[Test]
public void IsOrdered_Allows_adjacent_equal_values()
{
var list = new SimpleObjectList("x", "x", "z");
CollectionAssert.IsOrdered(list);
}
[Test]
public void IsOrdered_Handles_null()
{
var list = new SimpleObjectList(null, "x", "z");
Assert.That(list, Is.Ordered);
}
[Test]
public void IsOrdered_ContainedTypesMustBeCompatible()
{
var list = new SimpleObjectList(1, "x");
Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list));
}
[Test]
public void IsOrdered_TypesMustImplementIComparable()
{
var list = new SimpleObjectList(new object(), new object());
Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list));
}
[Test]
public void IsOrdered_Handles_custom_comparison()
{
var list = new SimpleObjectList(new object(), new object());
CollectionAssert.IsOrdered(list, new AlwaysEqualComparer());
}
[Test]
public void IsOrdered_Handles_custom_comparison2()
{
var list = new SimpleObjectList(2, 1);
CollectionAssert.IsOrdered(list, new TestComparer());
}
#endregion
#region Equals
[Test]
public void EqualsFailsWhenUsed()
{
var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.Equals(string.Empty, string.Empty));
Assert.That(ex.Message, Does.StartWith("CollectionAssert.Equals should not be used for Assertions"));
}
[Test]
public void ReferenceEqualsFailsWhenUsed()
{
var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.ReferenceEquals(string.Empty, string.Empty));
Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used for Assertions"));
}
#endregion
#if NET45
#region ValueTuple
[Test]
public void ValueTupleAreEqual()
{
var set1 = new SimpleEnumerable(ValueTuple.Create(1,2,3), ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3));
var set2 = new SimpleEnumerable(ValueTuple.Create(1,2,3), ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3));
CollectionAssert.AreEqual(set1, set2);
CollectionAssert.AreEqual(set1, set2, new TestComparer());
Assert.AreEqual(set1, set2);
}
[Test]
public void ValueTupleAreEqualFail()
{
var set1 = new SimpleEnumerable(ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3));
var set2 = new SimpleEnumerable(ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 3), ValueTuple.Create(1, 2, 4));
var expectedMessage =
" Expected and actual are both <NUnit.TestUtilities.Collections.SimpleEnumerable>" + Environment.NewLine +
" Values differ at index [2]" + Environment.NewLine +
" Expected: (1, 2, 3)" + Environment.NewLine +
" But was: (1, 2, 4)" + Environment.NewLine;
var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer()));
Assert.That(ex.Message, Is.EqualTo(expectedMessage));
}
#endregion
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Runtime.Remoting
{
public static class __RemotingConfiguration
{
public static IObservable<System.Reactive.Unit> RegisterWellKnownServiceType(IObservable<System.Type> type,
IObservable<System.String> objectUri, IObservable<System.Runtime.Remoting.WellKnownObjectMode> mode)
{
return ObservableExt.ZipExecute(type, objectUri, mode,
(typeLambda, objectUriLambda, modeLambda) =>
System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownServiceType(typeLambda,
objectUriLambda, modeLambda));
}
public static IObservable<System.Reactive.Unit> RegisterWellKnownServiceType(
IObservable<System.Runtime.Remoting.WellKnownServiceTypeEntry> entry)
{
return
Observable.Do(entry,
(entryLambda) =>
System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownServiceType(entryLambda))
.ToUnit();
}
public static IObservable<System.Reactive.Unit> Configure(IObservable<System.String> filename)
{
return
Observable.Do(filename,
(filenameLambda) => System.Runtime.Remoting.RemotingConfiguration.Configure(filenameLambda))
.ToUnit();
}
public static IObservable<System.Reactive.Unit> Configure(IObservable<System.String> filename,
IObservable<System.Boolean> ensureSecurity)
{
return ObservableExt.ZipExecute(filename, ensureSecurity,
(filenameLambda, ensureSecurityLambda) =>
System.Runtime.Remoting.RemotingConfiguration.Configure(filenameLambda, ensureSecurityLambda));
}
public static IObservable<System.Boolean> CustomErrorsEnabled(IObservable<System.Boolean> isLocalRequest)
{
return Observable.Select(isLocalRequest,
(isLocalRequestLambda) =>
System.Runtime.Remoting.RemotingConfiguration.CustomErrorsEnabled(isLocalRequestLambda));
}
public static IObservable<System.Reactive.Unit> RegisterActivatedServiceType(IObservable<System.Type> type)
{
return
Observable.Do(type,
(typeLambda) =>
System.Runtime.Remoting.RemotingConfiguration.RegisterActivatedServiceType(typeLambda)).ToUnit();
}
public static IObservable<System.Reactive.Unit> RegisterActivatedServiceType(
IObservable<System.Runtime.Remoting.ActivatedServiceTypeEntry> entry)
{
return
Observable.Do(entry,
(entryLambda) =>
System.Runtime.Remoting.RemotingConfiguration.RegisterActivatedServiceType(entryLambda))
.ToUnit();
}
public static IObservable<System.Reactive.Unit> RegisterActivatedClientType(IObservable<System.Type> type,
IObservable<System.String> appUrl)
{
return ObservableExt.ZipExecute(type, appUrl,
(typeLambda, appUrlLambda) =>
System.Runtime.Remoting.RemotingConfiguration.RegisterActivatedClientType(typeLambda, appUrlLambda));
}
public static IObservable<System.Reactive.Unit> RegisterActivatedClientType(
IObservable<System.Runtime.Remoting.ActivatedClientTypeEntry> entry)
{
return
Observable.Do(entry,
(entryLambda) =>
System.Runtime.Remoting.RemotingConfiguration.RegisterActivatedClientType(entryLambda)).ToUnit();
}
public static IObservable<System.Reactive.Unit> RegisterWellKnownClientType(IObservable<System.Type> type,
IObservable<System.String> objectUrl)
{
return ObservableExt.ZipExecute(type, objectUrl,
(typeLambda, objectUrlLambda) =>
System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownClientType(typeLambda,
objectUrlLambda));
}
public static IObservable<System.Reactive.Unit> RegisterWellKnownClientType(
IObservable<System.Runtime.Remoting.WellKnownClientTypeEntry> entry)
{
return
Observable.Do(entry,
(entryLambda) =>
System.Runtime.Remoting.RemotingConfiguration.RegisterWellKnownClientType(entryLambda)).ToUnit();
}
public static IObservable<System.Runtime.Remoting.ActivatedServiceTypeEntry[]>
GetRegisteredActivatedServiceTypes()
{
return
ObservableExt.Factory(
() => System.Runtime.Remoting.RemotingConfiguration.GetRegisteredActivatedServiceTypes());
}
public static IObservable<System.Runtime.Remoting.WellKnownServiceTypeEntry[]>
GetRegisteredWellKnownServiceTypes()
{
return
ObservableExt.Factory(
() => System.Runtime.Remoting.RemotingConfiguration.GetRegisteredWellKnownServiceTypes());
}
public static IObservable<System.Runtime.Remoting.ActivatedClientTypeEntry[]> GetRegisteredActivatedClientTypes()
{
return
ObservableExt.Factory(
() => System.Runtime.Remoting.RemotingConfiguration.GetRegisteredActivatedClientTypes());
}
public static IObservable<System.Runtime.Remoting.WellKnownClientTypeEntry[]> GetRegisteredWellKnownClientTypes()
{
return
ObservableExt.Factory(
() => System.Runtime.Remoting.RemotingConfiguration.GetRegisteredWellKnownClientTypes());
}
public static IObservable<System.Runtime.Remoting.ActivatedClientTypeEntry> IsRemotelyActivatedClientType(
IObservable<System.Type> svrType)
{
return Observable.Select(svrType,
(svrTypeLambda) =>
System.Runtime.Remoting.RemotingConfiguration.IsRemotelyActivatedClientType(svrTypeLambda));
}
public static IObservable<System.Runtime.Remoting.ActivatedClientTypeEntry> IsRemotelyActivatedClientType(
IObservable<System.String> typeName, IObservable<System.String> assemblyName)
{
return Observable.Zip(typeName, assemblyName,
(typeNameLambda, assemblyNameLambda) =>
System.Runtime.Remoting.RemotingConfiguration.IsRemotelyActivatedClientType(typeNameLambda,
assemblyNameLambda));
}
public static IObservable<System.Runtime.Remoting.WellKnownClientTypeEntry> IsWellKnownClientType(
IObservable<System.Type> svrType)
{
return Observable.Select(svrType,
(svrTypeLambda) => System.Runtime.Remoting.RemotingConfiguration.IsWellKnownClientType(svrTypeLambda));
}
public static IObservable<System.Runtime.Remoting.WellKnownClientTypeEntry> IsWellKnownClientType(
IObservable<System.String> typeName, IObservable<System.String> assemblyName)
{
return Observable.Zip(typeName, assemblyName,
(typeNameLambda, assemblyNameLambda) =>
System.Runtime.Remoting.RemotingConfiguration.IsWellKnownClientType(typeNameLambda,
assemblyNameLambda));
}
public static IObservable<System.Boolean> IsActivationAllowed(IObservable<System.Type> svrType)
{
return Observable.Select(svrType,
(svrTypeLambda) => System.Runtime.Remoting.RemotingConfiguration.IsActivationAllowed(svrTypeLambda));
}
public static IObservable<System.String> get_ApplicationName()
{
return ObservableExt.Factory(() => System.Runtime.Remoting.RemotingConfiguration.ApplicationName);
}
public static IObservable<System.String> get_ApplicationId()
{
return ObservableExt.Factory(() => System.Runtime.Remoting.RemotingConfiguration.ApplicationId);
}
public static IObservable<System.String> get_ProcessId()
{
return ObservableExt.Factory(() => System.Runtime.Remoting.RemotingConfiguration.ProcessId);
}
public static IObservable<System.Runtime.Remoting.CustomErrorsModes> get_CustomErrorsMode()
{
return ObservableExt.Factory(() => System.Runtime.Remoting.RemotingConfiguration.CustomErrorsMode);
}
public static IObservable<System.Reactive.Unit> set_ApplicationName(IObservable<System.String> value)
{
return
Observable.Do(value,
(valueLambda) => System.Runtime.Remoting.RemotingConfiguration.ApplicationName = valueLambda)
.ToUnit();
}
public static IObservable<System.Reactive.Unit> set_CustomErrorsMode(
IObservable<System.Runtime.Remoting.CustomErrorsModes> value)
{
return
Observable.Do(value,
(valueLambda) => System.Runtime.Remoting.RemotingConfiguration.CustomErrorsMode = valueLambda)
.ToUnit();
}
}
}
| |
// Copyright (c) "Neo4j"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Reactive.Testing;
using Neo4j.Driver.Reactive;
using Xunit;
using Xunit.Abstractions;
using static Neo4j.Driver.IntegrationTests.VersionComparison;
using static Neo4j.Driver.Reactive.Utils;
using static Neo4j.Driver.Tests.Assertions;
namespace Neo4j.Driver.IntegrationTests.Reactive
{
public class TransactionIT : AbstractRxIT
{
private const string BehaviourDifferenceWJavaDriver = "TODO: Behaviour Difference w/Java Driver";
private readonly IRxSession session;
public TransactionIT(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture)
: base(output, fixture)
{
// clean database after each test run
using (var tmpSession = Server.Driver.Session())
{
tmpSession.Run("MATCH (n) DETACH DELETE n").Consume();
}
session = NewSession();
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldCommitEmptyTx()
{
var bookmarkBefore = session.LastBookmark;
session.BeginTransaction()
.SelectMany(tx => tx.Commit<int>())
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
var bookmarkAfter = session.LastBookmark;
bookmarkBefore.Should().BeNull();
bookmarkAfter.Should().NotBe(bookmarkBefore);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldRollbackEmptyTx()
{
var bookmarkBefore = session.LastBookmark;
session.BeginTransaction()
.SelectMany(tx => tx.Rollback<int>())
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
var bookmarkAfter = session.LastBookmark;
bookmarkBefore.Should().BeNull();
bookmarkAfter.Should().Be(bookmarkBefore);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldRunQueryAndCommit()
{
session.BeginTransaction()
.SelectMany(txc =>
txc.Run("CREATE (n:Node {id: 42}) RETURN n")
.Records()
.Select(r => r["n"].As<INode>()["id"].As<int>())
.Concat(txc.Commit<int>())
.Catch(txc.Rollback<int>()))
.WaitForCompletion()
.AssertEqual(
OnNext(0, 42),
OnCompleted<int>(0));
CountNodes(42).Should().Be(1);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldRunQueryAndRollback()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 4242);
VerifyCanRollback(txc);
CountNodes(4242).Should().Be(0);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleQuerysAndCommit()
{
return VerifyRunMultipleQuerys(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleQuerysAndRollback()
{
return VerifyRunMultipleQuerys(false);
}
private async Task VerifyRunMultipleQuerys(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("CREATE (n:Node {id : 1})");
await result1.Records().SingleOrDefaultAsync();
var result2 = txc.Run("CREATE (n:Node {id : 2})");
await result2.Records().SingleOrDefaultAsync();
var result3 = txc.Run("CREATE (n:Node {id : 1})");
await result3.Records().SingleOrDefaultAsync();
VerifyCanCommitOrRollback(txc, commit);
VerifyCommittedOrRollbacked(commit);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleQuerysWithoutWaitingAndCommit()
{
return VerifyRunMultipleQuerysWithoutWaiting(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleQuerysWithoutWaitingAndRollback()
{
return VerifyRunMultipleQuerysWithoutWaiting(false);
}
private async Task VerifyRunMultipleQuerysWithoutWaiting(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("CREATE (n:Node {id : 1})");
var result2 = txc.Run("CREATE (n:Node {id : 2})");
var result3 = txc.Run("CREATE (n:Node {id : 1})");
await result1.Records().Concat(result2.Records()).Concat(result3.Records()).SingleOrDefaultAsync();
VerifyCanCommitOrRollback(txc, commit);
VerifyCommittedOrRollbacked(commit);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleQuerysWithoutStreamingAndCommit()
{
return VerifyRunMultipleQuerysWithoutStreaming(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldRunMultipleQuerysWithoutStreamingAndRollback()
{
return VerifyRunMultipleQuerysWithoutStreaming(false);
}
private async Task VerifyRunMultipleQuerysWithoutStreaming(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("CREATE (n:Node {id : 1})");
var result2 = txc.Run("CREATE (n:Node {id : 2})");
var result3 = txc.Run("CREATE (n:Node {id : 1})");
await result1.Keys().Concat(result2.Keys()).Concat(result3.Keys());
VerifyCanCommitOrRollback(txc, commit);
VerifyCommittedOrRollbacked(commit);
}
[RequireServerFact]
public async Task ShouldFailToCommitAfterAFailedQuery()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyFailsWithWrongQuery(txc);
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0, MatchesException<ClientException>()));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldSucceedToRollbackAfterAFailedQuery()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyFailsWithWrongQuery(txc);
txc.Rollback<int>()
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
}
[RequireServerFact]
public async Task ShouldFailToCommitAfterSuccessfulAndFailedQuerys()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 5);
VerifyCanReturnOne(txc);
VerifyFailsWithWrongQuery(txc);
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0, MatchesException<ClientException>()));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldSucceedToRollbackAfterSuccessfulAndFailedQuerys()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 5);
VerifyCanReturnOne(txc);
VerifyFailsWithWrongQuery(txc);
txc.Rollback<int>()
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldFailToRunAnotherQueryAfterAFailedOne()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyFailsWithWrongQuery(txc);
txc.Run("CREATE ()")
.Records()
.WaitForCompletion()
.AssertEqual(
OnError<IRecord>(0,
Matches<Exception>(exc =>
exc.Message.Should().Contain("Cannot run query in this transaction"))));
VerifyCanRollback(txc);
}
[RequireServerFact]
public void ShouldFailToBeginTxcWithInvalidBookmark()
{
Server.Driver
.RxSession(
o => o.WithDefaultAccessMode(AccessMode.Read).WithBookmarks(Bookmark.From("InvalidBookmark")))
.BeginTransaction()
.WaitForCompletion()
.AssertEqual(
OnError<IRxTransaction>(0,
Matches<Exception>(exc => exc.Message.Should().Contain("InvalidBookmark"))));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldNotAllowCommitAfterCommit()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 6);
VerifyCanCommit(txc);
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0,
Matches<Exception>(exc =>
exc.Message.Should()
.Be("Cannot commit this transaction, because it has already been committed."))));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldNotAllowRollbackAfterRollback()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 6);
VerifyCanRollback(txc);
txc.Rollback<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0,
Matches<Exception>(exc =>
exc.Message.Should()
.Be("Cannot rollback this transaction, because it has already been rolled back."))));
}
[RequireServerFact]
public async Task ShouldFailToCommitAfterRollback()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 6);
VerifyCanRollback(txc);
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnError<int>(0,
Matches<Exception>(exc =>
exc.Message.Should()
.Be("Cannot commit this transaction, because it has already been rolled back."))));
}
[RequireServerFact]
public async Task ShouldFailToRollbackAfterCommit()
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 6);
VerifyCanCommit(txc);
txc.Rollback<string>()
.WaitForCompletion()
.AssertEqual(
OnError<string>(0,
Matches<Exception>(exc =>
exc.Message.Should()
.Be("Cannot rollback this transaction, because it has already been committed."))));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldFailToRunQueryAfterCompletedTxcAndCommit()
{
return VerifyFailToRunQueryAfterCompletedTxc(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldFailToRunQueryAfterCompletedTxcAndRollback()
{
return VerifyFailToRunQueryAfterCompletedTxc(false);
}
private async Task VerifyFailToRunQueryAfterCompletedTxc(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc, 15);
VerifyCanCommitOrRollback(txc, commit);
CountNodes(15).Should().Be(commit ? 1 : 0);
txc.Run("CREATE ()")
.Records()
.WaitForCompletion()
.AssertEqual(
OnError<IRecord>(0,
Matches<Exception>(exc => exc.Message.Should().Contain("Cannot run query in this"))));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldUpdateBookmark()
{
var bookmark1 = session.LastBookmark;
var txc1 = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc1, 20);
VerifyCanCommit(txc1);
var bookmark2 = session.LastBookmark;
var txc2 = await session.BeginTransaction().SingleAsync();
VerifyCanCreateNode(txc2, 20);
VerifyCanCommit(txc2);
var bookmark3 = session.LastBookmark;
bookmark1.Should().BeNull();
bookmark2.Should().NotBe(bookmark1);
bookmark3.Should().NotBe(bookmark1).And.NotBe(bookmark2);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldPropagateFailuresFromQuerys()
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("CREATE (:TestNode) RETURN 1 as n");
var result2 = txc.Run("CREATE (:TestNode) RETURN 2 as n");
var result3 = txc.Run("RETURN 10 / 0 as n");
var result4 = txc.Run("CREATE (:TestNode) RETURN 3 as n");
Observable.Concat(
result1.Records(),
result2.Records(),
result3.Records(),
result4.Records())
.WaitForCompletion()
.AssertEqual(
OnNext(0, MatchesRecord(new[] {"n"}, 1)),
OnNext(0, MatchesRecord(new[] {"n"}, 2)),
OnError<IRecord>(0, Matches<Exception>(exc => exc.Message.Should().Contain("/ by zero"))));
VerifyCanRollback(txc);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldNotRunUntilSubscribed()
{
var txc = await session.BeginTransaction().SingleAsync();
var result1 = txc.Run("RETURN 1");
var result2 = txc.Run("RETURN 2");
var result3 = txc.Run("RETURN 3");
var result4 = txc.Run("RETURN 4");
Observable.Concat(
result4.Records(),
result3.Records(),
result2.Records(),
result1.Records())
.Select(r => r[0].As<int>())
.WaitForCompletion()
.AssertEqual(
OnNext(0, 4),
OnNext(0, 3),
OnNext(0, 2),
OnNext(0, 1),
OnCompleted<int>(0));
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldNotPropagateFailureIfNotExecutedAndCommitted()
{
return VerifyNotPropagateFailureIfNotExecuted(true);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public Task ShouldNotPropagateFailureIfNotExecutedAndRollBacked()
{
return VerifyNotPropagateFailureIfNotExecuted(false);
}
private async Task VerifyNotPropagateFailureIfNotExecuted(bool commit)
{
var txc = await session.BeginTransaction().SingleAsync();
txc.Run("RETURN ILLEGAL");
VerifyCanCommitOrRollback(txc, commit);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public async Task ShouldNotPropagateRunFailureFromSummary()
{
var txc = await session.BeginTransaction().SingleAsync();
var result = txc.Run("RETURN Wrong");
result.Records()
.WaitForCompletion()
.AssertEqual(
OnError<IRecord>(0, MatchesException<ClientException>()));
result.Consume()
.WaitForCompletion()
.AssertEqual(
OnNext(0, Matches<IResultSummary>(x => x.Should().NotBeNull())),
OnCompleted<IResultSummary>(0));
VerifyCanRollback(txc);
}
[RequireServerFact("4.0.0", GreaterThanOrEqualTo)]
public void ShouldHandleNestedQueries()
{
const int size = 1024;
var messages = session.BeginTransaction()
.SelectMany(txc =>
txc.Run("UNWIND range(1, $size) AS x RETURN x", new {size})
.Records()
.Select(r => r[0].As<int>())
.Buffer(50)
.SelectMany(x =>
txc.Run("UNWIND $x AS id CREATE (n:Node {id: id}) RETURN n.id", new {x}).Records())
.Select(r => r[0].As<int>())
.Concat(txc.Commit<int>())
.Catch((Exception exc) => txc.Rollback<int>().Concat(Observable.Throw<int>(exc))))
.WaitForCompletion()
.ToList();
messages.Should()
.HaveCount(size + 1).And
.NotContain(n => n.Value.Kind == NotificationKind.OnError);
}
private static void VerifyCanCommit(IRxTransaction txc)
{
txc.Commit<int>()
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
}
private static void VerifyCanRollback(IRxTransaction txc)
{
txc.Rollback<int>()
.WaitForCompletion()
.AssertEqual(
OnCompleted<int>(0));
}
private static void VerifyCanCommitOrRollback(IRxTransaction txc, bool commit)
{
if (commit)
{
VerifyCanCommit(txc);
}
else
{
VerifyCanRollback(txc);
}
}
private static void VerifyCanCreateNode(IRxTransaction txc, int id)
{
txc.Run("CREATE (n:Node {id: $id}) RETURN n", new {id})
.Records()
.Select(r => r["n"].As<INode>())
.SingleAsync()
.WaitForCompletion()
.AssertEqual(
OnNext(0, Matches<INode>(node => node.Should().BeEquivalentTo(new
{
Labels = new[] {"Node"},
Properties = new Dictionary<string, object>
{
{"id", (long) id}
}
}))),
OnCompleted<INode>(0));
}
private static void VerifyCanReturnOne(IRxTransaction txc)
{
txc.Run("RETURN 1")
.Records()
.Select(r => r[0].As<int>())
.WaitForCompletion()
.AssertEqual(
OnNext(0, 1),
OnCompleted<int>(0));
}
private static void VerifyFailsWithWrongQuery(IRxTransaction txc)
{
txc.Run("RETURN")
.Records()
.WaitForCompletion()
.AssertEqual(
OnError<IRecord>(0, MatchesException<ClientException>(e => e.Code.Contains("SyntaxError"))));
}
private void VerifyCommittedOrRollbacked(bool commit)
{
if (commit)
{
CountNodes(1).Should().Be(2);
CountNodes(2).Should().Be(1);
}
else
{
CountNodes(1).Should().Be(0);
CountNodes(2).Should().Be(0);
}
}
private int CountNodes(int id)
{
return NewSession()
.Run("MATCH (n:Node {id: $id}) RETURN count(n)", new {id})
.Records()
.Select(r => r[0].As<int>())
.SingleAsync()
.Wait();
}
}
}
| |
// 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.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLMcode = Interop.Http.CURLMcode;
using CURLoption = Interop.Http.CURLoption;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
#region Constants
private const char SpaceChar = ' ';
private const int StatusCodeLength = 3;
private const string UriSchemeHttp = "http";
private const string UriSchemeHttps = "https";
private const string EncodingNameGzip = "gzip";
private const string EncodingNameDeflate = "deflate";
private const int RequestBufferSize = 16384; // Default used by libcurl
private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":";
private const string NoContentType = HttpKnownHeaderNames.ContentType + ":";
private const int CurlAge = 5;
private const int MinCurlAge = 3;
#endregion
#region Fields
// To enable developers to opt-in to support certain auth types that we don't want
// to enable by default (e.g. NTLM), we allow for such types to be specified explicitly
// when credentials are added to a credential cache, but we don't enable them
// when no auth type is specified, e.g. when a NetworkCredential is provided directly
// to the handler. As such, we have two different sets of auth types that we use
// for when the supplied creds are a cache vs not.
private readonly static KeyValuePair<string,CURLAUTH>[] s_orderedAuthTypesCredentialCache = new KeyValuePair<string, CURLAUTH>[] {
new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate),
new KeyValuePair<string,CURLAUTH>("NTLM", CURLAUTH.NTLM), // only available when credentials supplied via a credential cache
new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest),
new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic),
};
private readonly static KeyValuePair<string, CURLAUTH>[] s_orderedAuthTypesICredential = new KeyValuePair<string, CURLAUTH>[] {
new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate),
new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest),
new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic),
};
private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF };
private readonly static bool s_supportsAutomaticDecompression;
private readonly static bool s_supportsSSL;
private readonly static bool s_supportsHttp2Multiplexing;
private readonly static DiagnosticListener s_diagnosticListener = new DiagnosticListener(HttpHandlerLoggingStrings.DiagnosticListenerName);
private readonly MultiAgent _agent = new MultiAgent();
private volatile bool _anyOperationStarted;
private volatile bool _disposed;
private IWebProxy _proxy = null;
private ICredentials _serverCredentials = null;
private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate;
private CredentialCache _credentialCache = null; // protected by LockObject
private CookieContainer _cookieContainer = new CookieContainer();
private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption;
private object LockObject { get { return _agent; } }
#endregion
static CurlHandler()
{
// curl_global_init call handled by Interop.LibCurl's cctor
int age;
if (!Interop.Http.GetCurlVersionInfo(
out age,
out s_supportsSSL,
out s_supportsAutomaticDecompression,
out s_supportsHttp2Multiplexing))
{
throw new InvalidOperationException(SR.net_http_unix_https_libcurl_no_versioninfo);
}
// Verify the version of curl we're using is new enough
if (age < MinCurlAge)
{
throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old);
}
}
#region Properties
internal bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
internal bool SupportsProxy
{
get
{
return true;
}
}
internal bool SupportsRedirectConfiguration
{
get
{
return true;
}
}
internal bool UseProxy
{
get
{
return _useProxy;
}
set
{
CheckDisposedOrStarted();
_useProxy = value;
}
}
internal IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
internal ICredentials Credentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
internal ClientCertificateOption ClientCertificateOptions
{
get
{
return _clientCertificateOption;
}
set
{
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
internal bool SupportsAutomaticDecompression
{
get
{
return s_supportsAutomaticDecompression;
}
}
internal DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
internal bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
CheckDisposedOrStarted();
_preAuthenticate = value;
if (value && _credentialCache == null)
{
_credentialCache = new CredentialCache();
}
}
}
internal bool UseCookie
{
get
{
return _useCookie;
}
set
{
CheckDisposedOrStarted();
_useCookie = value;
}
}
internal CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
internal int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
/// <summary>
/// <b> UseDefaultCredentials is a no op on Unix </b>
/// </summary>
internal bool UseDefaultCredentials
{
get
{
return false;
}
set
{
}
}
#endregion
protected override void Dispose(bool disposing)
{
_disposed = true;
base.Dispose(disposing);
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
if (request.RequestUri.Scheme == UriSchemeHttps)
{
if (!s_supportsSSL)
{
throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl);
}
}
else
{
Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https.");
}
if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
if (_useCookie && _cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request);
CheckDisposed();
SetOperationStarted();
// Do an initial cancellation check to avoid initiating the async operation if
// cancellation has already been requested. After this, we'll rely on CancellationToken.Register
// to notify us of cancellation requests and shut down the operation if possible.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
}
EventSourceTrace("{0}", request);
// Create the easy request. This associates the easy request with this handler and configures
// it based on the settings configured for the handler.
var easy = new EasyRequest(this, request, cancellationToken);
try
{
easy.InitializeCurl();
if (easy._requestContentStream != null)
{
easy._requestContentStream.Run();
}
_agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
}
catch (Exception exc)
{
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
s_diagnosticListener.LogHttpResponse(easy.Task, loggingRequestId);
return easy.Task;
}
#region Private methods
private void SetOperationStarted()
{
if (!_anyOperationStarted)
{
_anyOperationStarted = true;
}
}
private KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri)
{
// Get the auth types (Negotiate, Digest, etc.) that are allowed to be selected automatically
// based on the type of the ICredentials provided.
KeyValuePair<string, CURLAUTH>[] validAuthTypes = AuthTypesPermittedByCredentialKind(_serverCredentials);
// If preauthentication is enabled, we may have populated our internal credential cache,
// so first check there to see if we have any credentials for this uri.
if (_preAuthenticate)
{
KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme;
lock (LockObject)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
ncAndScheme = GetCredentials(requestUri, _credentialCache, validAuthTypes);
}
if (ncAndScheme.Key != null)
{
return ncAndScheme;
}
}
// We either weren't preauthenticating or we didn't have any cached credentials
// available, so check the credentials on the handler.
return GetCredentials(requestUri, _serverCredentials, validAuthTypes);
}
private void TransferCredentialsToCache(Uri serverUri, CURLAUTH serverAuthAvail)
{
if (_serverCredentials == null)
{
// No credentials, nothing to put into the cache.
return;
}
// Get the auth types valid based on the type of the ICredentials used. We're effectively
// going to intersect this (the types we allow to be used) with those the server supports
// and with the credentials we have available. The best of that resulting intersection
// will be added to the cache.
KeyValuePair<string, CURLAUTH>[] validAuthTypes = AuthTypesPermittedByCredentialKind(_serverCredentials);
lock (LockObject)
{
// For each auth type we allow, check whether it's one supported by the server.
for (int i = 0; i < validAuthTypes.Length; i++)
{
// Is it supported by the server?
if ((serverAuthAvail & validAuthTypes[i].Value) != 0)
{
// And do we have a credential for it?
NetworkCredential nc = _serverCredentials.GetCredential(serverUri, validAuthTypes[i].Key);
if (nc != null)
{
// We have a credential for it, so add it, and we're done.
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
try
{
_credentialCache.Add(serverUri, validAuthTypes[i].Key, nc);
}
catch (ArgumentException)
{
// Ignore the case of key already present
}
break;
}
}
}
}
}
private static KeyValuePair<string, CURLAUTH>[] AuthTypesPermittedByCredentialKind(ICredentials c)
{
// Special-case CredentialCache for auth types, as credentials put into the cache are put
// in explicitly tagged with an auth type, and thus credentials are opted-in to potentially
// less secure auth types we might otherwise want disabled by default.
return c is CredentialCache ?
s_orderedAuthTypesCredentialCache :
s_orderedAuthTypesICredential;
}
private void AddResponseCookies(EasyRequest state, string cookieHeader)
{
if (!_useCookie)
{
return;
}
try
{
_cookieContainer.SetCookies(state._targetUri, cookieHeader);
state.SetCookieOption(state._requestMessage.RequestUri);
}
catch (CookieException e)
{
EventSourceTrace(
"Malformed cookie parsing failed: {0}, server: {1}, cookie: {2}",
e.Message, state._requestMessage.RequestUri, cookieHeader);
}
}
private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair<string, CURLAUTH>[] validAuthTypes)
{
NetworkCredential nc = null;
CURLAUTH curlAuthScheme = CURLAUTH.None;
if (credentials != null)
{
// For each auth type we consider valid, try to get a credential for it.
// Union together the auth types for which we could get credentials, but validate
// that the found credentials are all the same, as libcurl doesn't support differentiating
// by auth type.
for (int i = 0; i < validAuthTypes.Length; i++)
{
NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key);
if (networkCredential != null)
{
curlAuthScheme |= validAuthTypes[i].Value;
if (nc == null)
{
nc = networkCredential;
}
else if(!AreEqualNetworkCredentials(nc, networkCredential))
{
throw new PlatformNotSupportedException(SR.net_http_unix_invalid_credential);
}
}
}
}
EventSourceTrace("Authentication scheme: {0}", curlAuthScheme);
return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ;
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_anyOperationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private static void ThrowIfCURLEError(CURLcode error)
{
if (error != CURLcode.CURLE_OK)
{
var inner = new CurlException((int)error, isMulti: false);
EventSourceTrace(inner.Message);
throw inner;
}
}
private static void ThrowIfCURLMError(CURLMcode error)
{
if (error != CURLMcode.CURLM_OK && // success
error != CURLMcode.CURLM_CALL_MULTI_PERFORM) // success + a hint to try curl_multi_perform again
{
string msg = CurlException.GetCurlErrorString((int)error, true);
EventSourceTrace(msg);
switch (error)
{
case CURLMcode.CURLM_ADDED_ALREADY:
case CURLMcode.CURLM_BAD_EASY_HANDLE:
case CURLMcode.CURLM_BAD_HANDLE:
case CURLMcode.CURLM_BAD_SOCKET:
throw new ArgumentException(msg);
case CURLMcode.CURLM_UNKNOWN_OPTION:
throw new ArgumentOutOfRangeException(msg);
case CURLMcode.CURLM_OUT_OF_MEMORY:
throw new OutOfMemoryException(msg);
case CURLMcode.CURLM_INTERNAL_ERROR:
default:
throw new CurlException((int)error, msg);
}
}
}
private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2)
{
Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check");
return credential1.UserName == credential2.UserName &&
credential1.Domain == credential2.Domain &&
string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal);
}
private static bool EventSourceTracingEnabled { get { return HttpEventSource.Log.IsEnabled(); } }
// PERF NOTE:
// These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler
// nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking
// EventSourceTracingEnabled. Do not remove these without fixing the call sites accordingly.
private static void EventSourceTrace<TArg0>(
string formatMessage, TArg0 arg0,
MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
if (EventSourceTracingEnabled)
{
EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName);
}
}
private static void EventSourceTrace<TArg0, TArg1, TArg2>
(string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2,
MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
if (EventSourceTracingEnabled)
{
EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName);
}
}
private static void EventSourceTrace(
string message,
MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
if (EventSourceTracingEnabled)
{
EventSourceTraceCore(message, agent, easy, memberName);
}
}
private static void EventSourceTraceCore(string message, MultiAgent agent, EasyRequest easy, string memberName)
{
// If we weren't handed a multi agent, see if we can get one from the EasyRequest
if (agent == null && easy != null)
{
agent = easy._associatedMultiAgent;
}
HttpEventSource.Log.HandlerMessage(
agent != null && agent.RunningWorkerId.HasValue ? agent.RunningWorkerId.GetValueOrDefault() : 0,
easy != null ? easy.Task.Id : 0,
memberName,
message);
}
private static HttpRequestException CreateHttpRequestException(Exception inner)
{
return new HttpRequestException(SR.net_http_client_execution_error, inner);
}
private static IOException MapToReadWriteIOException(Exception error, bool isRead)
{
return new IOException(
isRead ? SR.net_http_io_read : SR.net_http_io_write,
error is HttpRequestException && error.InnerException != null ? error.InnerException : error);
}
private static void HandleRedirectLocationHeader(EasyRequest state, string locationValue)
{
Debug.Assert(state._isRedirect);
Debug.Assert(state._handler.AutomaticRedirection);
string location = locationValue.Trim();
//only for absolute redirects
Uri forwardUri;
if (Uri.TryCreate(location, UriKind.RelativeOrAbsolute, out forwardUri) && forwardUri.IsAbsoluteUri)
{
// Just as with WinHttpHandler, for security reasons, we drop the server credential if it is
// anything other than a CredentialCache. We allow credentials in a CredentialCache since they
// are specifically tied to URIs.
var creds = state._handler.Credentials as CredentialCache;
KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme = GetCredentials(forwardUri, creds, AuthTypesPermittedByCredentialKind(creds));
if (ncAndScheme.Key != null)
{
state.SetCredentialsOptions(ncAndScheme);
}
else
{
state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
}
// reset proxy - it is possible that the proxy has different credentials for the new URI
state.SetProxyOptions(forwardUri);
if (state._handler._useCookie)
{
// reset cookies.
state.SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero);
// set cookies again
state.SetCookieOption(forwardUri);
}
state.SetRedirectUri(forwardUri);
}
// set the headers again. This is a workaround for libcurl's limitation in handling headers with empty values
state.SetRequestHeaders();
}
private static void SetChunkedModeForSend(HttpRequestMessage request)
{
bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault();
HttpContent requestContent = request.Content;
Debug.Assert(requestContent != null, "request is null");
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// libcurl adds a Tranfer-Encoding header by default and the request fails if both are set.
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Same behaviour as WinHttpHandler
requestContent.Headers.ContentLength = null;
}
else
{
// Prevent libcurl from adding Transfer-Encoding header
request.Headers.TransferEncodingChunked = false;
}
}
else if (!chunkedMode)
{
// Make sure Transfer-Encoding: chunked header is set,
// as we have content to send but no known length for it.
request.Headers.TransferEncodingChunked = true;
}
}
#endregion
}
}
| |
namespace WixSharp
{
//Standard Actions Reference: https://msdn.microsoft.com/en-us/library/aa372023(v=vs.85).aspx
/// <summary>
/// Specifies predefined values for <see cref="Action.Step"/>,
/// which controls order of <c>Custom Action</c> to be executed.
/// <para><c>Before</c> or <c>After</c> switch for <c>Custom Action</c> is controlled by <see cref="When"/>.</para>
/// </summary>
public class Step
{
/// <summary>
/// A top-level action used for an administrative installation.
/// </summary>
public static Step ADMIN = new Step("ADMIN");
/// <summary>
/// A top-level action called to install or remove advertised components.
/// </summary>
public static Step ADVERTISE = new Step("ADVERTISE");
/// <summary>
/// Validates that the free space specified by AVAILABLEFREEREG exists in the registry.
/// </summary>
public static Step AllocateRegistrySpace = new Step("AllocateRegistrySpace");
/// <summary>
/// Searches for previous versions of products and determines that upgrades are installed.
/// </summary>
public static Step AppSearch = new Step("AppSearch");
/// <summary>
/// Binds executables to imported DLLs.
/// </summary>
public static Step BindImage = new Step("BindImage");
/// <summary>
/// Uses file signatures to validate that qualifying products are installed on a system before an upgrade installation is performed.
/// </summary>
public static Step CCPSearch = new Step("CCPSearch");
/// <summary>
/// Ends the internal installation costing process begun by the CostInitialize action.
/// </summary>
public static Step CostFinalize = new Step("CostFinalize");
/// <summary>
/// Starts the installation costing process.
/// </summary>
public static Step CostInitialize = new Step("CostInitialize");
/// <summary>
/// Creates empty folders for components.
/// </summary>
public static Step CreateFolders = new Step("CreateFolders");
/// <summary>
/// Creates shortcuts.
/// </summary>
public static Step CreateShortcuts = new Step("CreateShortcuts");
/// <summary>
/// Removes system services.
/// </summary>
public static Step DeleteServices = new Step("DeleteServices");
/// <summary>
/// Disables rollback for the remainder of the installation.
/// </summary>
public static Step DisableRollback = new Step("DisableRollback");
/// <summary>
/// Duplicates files installed by the InstallFiles action.
/// </summary>
public static Step DuplicateFiles = new Step("DuplicateFiles");
/// <summary>
/// Checks the EXECUTEACTION property to determine which top-level action begins the execution sequence, then runs that action.
/// </summary>
public static Step ExecuteAction = new Step("ExecuteAction");
/// <summary>
/// Initializes disk cost calculation with the installer. Disk costing is not finalized until the CostFinalize action is executed.
/// </summary>
public static Step FileCost = new Step("FileCost");
/// <summary>
/// Detects correspondence between the Upgrade table and installed products.
/// </summary>
public static Step FindRelatedProducts = new Step("FindRelatedProducts");
/// <summary>
/// Used in the action sequence to prompt the user for a restart of the system during the installation.
/// </summary>
public static Step ForceReboot = new Step("ForceReboot");
/// <summary>
/// A top-level action called to install or remove components.
/// </summary>
public static Step INSTALL = new Step("INSTALL");
/// <summary>
/// Copies the installer database to the administrative installation point.
/// </summary>
public static Step InstallAdminPackage = new Step("InstallAdminPackage");
/// <summary>
/// Runs a script containing all operations in the action sequence since either the start of the installation or the last InstallFinalize action. Does not end the transaction.
/// </summary>
public static Step InstallExecute = new Step("InstallExecute");
/// <summary>
/// Copies files from the source to the destination directory.
/// </summary>
public static Step InstallFiles = new Step("InstallFiles");
/// <summary>
/// Runs a script containing all operations in the action sequence since either the start of the installation or the last InstallFinalize action. Marks the end of a transaction.
/// </summary>
public static Step InstallFinalize = new Step("InstallFinalize");
/// <summary>
/// Marks the beginning of a transaction.
/// </summary>
public static Step InstallInitialize = new Step("InstallInitialize");
/// <summary>
/// The InstallSFPCatalogFile action installs the catalogs used by Windows Me for Windows File Protection.
/// </summary>
public static Step InstallSFPCatalogFile = new Step("InstallSFPCatalogFile");
/// <summary>
/// Verifies that all volumes with attributed costs have sufficient space for the installation.
/// </summary>
public static Step InstallValidate = new Step("InstallValidate");
/// <summary>
/// Processes the IsolatedComponent table
/// </summary>
public static Step IsolateComponents = new Step("IsolateComponents");
/// <summary>
/// Evaluates a set of conditional statements contained in the LaunchCondition table that must all evaluate to True before the installation can proceed.
/// </summary>
public static Step LaunchConditions = new Step("LaunchConditions");
/// <summary>
/// Migrates current feature states to the pending installation.
/// </summary>
public static Step MigrateFeatureStates = new Step("MigrateFeatureStates");
/// <summary>
/// Locates existing files and moves or copies those files to a new location.
/// </summary>
public static Step MoveFiles = new Step("MoveFiles");
/// <summary>
/// Configures a service for the system.
/// Windows Installer 4.5 and earlier: Not supported.
/// </summary>
public static Step MsiConfigureServices = new Step("MsiConfigureServices");
/// <summary>
/// Manages the advertisement of common language runtime assemblies and Win32 assemblies that are being installed.
/// </summary>
public static Step MsiPublishAssemblies = new Step("MsiPublishAssemblies");
/// <summary>
/// Manages the advertisement of common language runtime assemblies and Win32 assemblies that are being removed.
/// </summary>
public static Step MsiUnpublishAssemblies = new Step("MsiUnpublishAssemblies");
/// <summary>
/// Installs the ODBC drivers, translators, and data sources.
/// </summary>
public static Step InstallODBC = new Step("InstallODBC");
/// <summary>
/// Registers a service with the system.
/// </summary>
public static Step InstallServices = new Step("InstallServices");
/// <summary>
/// Queries the Patch table to determine which patches are applied to specific files and then performs the byte-wise patching of the files.
/// </summary>
public static Step PatchFiles = new Step("PatchFiles");
/// <summary>
/// Registers components, their key paths, and component clients.
/// </summary>
public static Step ProcessComponents = new Step("ProcessComponents");
/// <summary>
/// Advertises the components specified in the PublishComponent table.
/// </summary>
public static Step PublishComponents = new Step("PublishComponents");
/// <summary>
/// Writes the feature state of each feature into the system registry
/// </summary>
public static Step PublishFeatures = new Step("PublishFeatures");
/// <summary>
/// Publishes product information with the system.
/// </summary>
public static Step PublishProduct = new Step("PublishProduct");
/// <summary>
/// Manages the registration of COM class information with the system.
/// </summary>
public static Step RegisterClassInfo = new Step("RegisterClassInfo");
/// <summary>
/// The RegisterComPlus action registers COM+ applications.
/// </summary>
public static Step RegisterComPlus = new Step("RegisterComPlus");
/// <summary>
/// Registers extension related information with the system.
/// </summary>
public static Step RegisterExtensionInfo = new Step("RegisterExtensionInfo");
/// <summary>
/// Registers installed fonts with the system.
/// </summary>
public static Step RegisterFonts = new Step("RegisterFonts");
/// <summary>
/// Registers MIME information with the system.
/// </summary>
public static Step RegisterMIMEInfo = new Step("RegisterMIMEInfo");
/// <summary>
/// Registers product information with the installer and stores the installer database on the local computer.
/// </summary>
public static Step RegisterProduct = new Step("RegisterProduct");
/// <summary>
/// Registers OLE ProgId information with the system.
/// </summary>
public static Step RegisterProgIdInfo = new Step("RegisterProgIdInfo");
/// <summary>
/// Registers type libraries with the system.
/// </summary>
public static Step RegisterTypeLibraries = new Step("RegisterTypeLibraries");
/// <summary>
/// Registers user information to identify the user of a product.
/// </summary>
public static Step RegisterUser = new Step("RegisterUser");
/// <summary>
/// Deletes files installed by the DuplicateFiles action.
/// </summary>
public static Step RemoveDuplicateFiles = new Step("RemoveDuplicateFiles");
/// <summary>
/// Modifies the values of environment variables.
/// </summary>
public static Step RemoveEnvironmentStrings = new Step("RemoveEnvironmentStrings");
/// <summary>
/// Removes installed versions of a product.
/// </summary>
public static Step RemoveExistingProducts = new Step("RemoveExistingProducts");
/// <summary>
/// Removes files previously installed by the InstallFiles action.
/// </summary>
public static Step RemoveFiles = new Step("RemoveFiles");
/// <summary>
/// Removes empty folders linked to components set to be removed.
/// </summary>
public static Step RemoveFolders = new Step("RemoveFolders");
/// <summary>
/// Deletes .ini file information associated with a component specified in the IniFile table.
/// </summary>
public static Step RemoveIniValues = new Step("RemoveIniValues");
/// <summary>
/// Removes ODBC data sources, translators, and drivers.
/// </summary>
public static Step RemoveODBC = new Step("RemoveODBC");
/// <summary>
/// Removes an application's registry keys that were created from the Registry table..
/// </summary>
public static Step RemoveRegistryValues = new Step("RemoveRegistryValues");
/// <summary>
/// Manages the removal of an advertised shortcut whose feature is selected for uninstallation.
/// </summary>
public static Step RemoveShortcuts = new Step("RemoveShortcuts");
/// <summary>
/// Determines the source location and sets the SourceDir property.
/// </summary>
public static Step ResolveSource = new Step("ResolveSource");
/// <summary>
/// Uses file signatures to validate that qualifying products are installed on a system before an upgrade installation is performed.
/// </summary>
public static Step RMCCPSearch = new Step("RMCCPSearch");
/// <summary>
/// Prompts the user for a system restart at the end of the installation.
/// </summary>
public static Step ScheduleReboot = new Step("ScheduleReboot");
/// <summary>
/// Processes modules in the SelfReg table and registers them if they are installed.
/// </summary>
public static Step SelfRegModules = new Step("SelfRegModules");
/// <summary>
/// Unregisters the modules in the SelfReg table that are set to be uninstalled.
/// </summary>
public static Step SelfUnregModules = new Step("SelfUnregModules");
/// <summary>
/// Runs the actions in a table specified by the SEQUENCE property.
/// </summary>
public static Step SEQUENCE = new Step("SEQUENCE");
/// <summary>
/// Checks the system for existing ODBC drivers and sets target directory for new ODBC drivers.
/// </summary>
public static Step SetODBCFolders = new Step("SetODBCFolders");
/// <summary>
/// Starts system services.
/// </summary>
public static Step StartServices = new Step("StartServices");
/// <summary>
/// Stops system services.
/// </summary>
public static Step StopServices = new Step("StopServices");
/// <summary>
/// Manages the unadvertisement of components from the PublishComponent table and removes information about published components.
/// </summary>
public static Step UnpublishComponents = new Step("UnpublishComponents");
/// <summary>
/// Removes the selection-state and feature-component mapping information from the system registry.
/// </summary>
public static Step UnpublishFeatures = new Step("UnpublishFeatures");
/// <summary>
/// Manages the removal of COM classes from the system registry.
/// </summary>
public static Step UnregisterClassInfo = new Step("UnregisterClassInfo");
/// <summary>
/// The UnregisterComPlus action removes COM+ applications from the registry.
/// </summary>
public static Step UnregisterComPlus = new Step("UnregisterComPlus");
/// <summary>
/// Manages the removal of extension-related information from the system.
/// </summary>
public static Step UnregisterExtensionInfo = new Step("UnregisterExtensionInfo");
/// <summary>
/// Removes registration information about installed fonts from the system.
/// </summary>
public static Step UnregisterFonts = new Step("UnregisterFonts");
/// <summary>
/// Unregisters MIME-related information from the system registry.
/// </summary>
public static Step UnregisterMIMEInfo = new Step("UnregisterMIMEInfo");
/// <summary>
/// Manages the unregistration of OLE ProgId information with the system.
/// </summary>
public static Step UnregisterProgIdInfo = new Step("UnregisterProgIdInfo");
/// <summary>
/// Unregisters type libraries with the system.
/// </summary>
public static Step UnregisterTypeLibraries = new Step("UnregisterTypeLibraries");
/// <summary>
/// Sets ProductID property to the full product identifier.
/// </summary>
public static Step ValidateProductID = new Step("ValidateProductID");
/// <summary>
/// Modifies the values of environment variables.
/// </summary>
public static Step WriteEnvironmentStrings = new Step("WriteEnvironmentStrings");
/// <summary>
/// Writes .ini file information.
/// </summary>
public static Step WriteIniValues = new Step("WriteIniValues");
/// <summary>
/// Sets up registry information.
/// </summary>
public static Step WriteRegistryValues = new Step("WriteRegistryValues");
/// <summary>
/// The InstallExecuteAgain action runs a script containing all operations in the action sequence since either the start of the installation or the last InstallExecuteAgain action or the last InstallExecute action. The InstallExecute action updates the system without ending the transaction. InstallExecuteAgain performs the same operation as the InstallExecute action but should only be used after InstallExecute.
/// </summary>
public static Step InstallExecuteAgain = new Step("InstallExecuteAgain");
/// <summary>
/// <c>Custom Action</c> is to be executed before/after the previous action declared in <see cref="Project.Actions"/>.
/// </summary>
public static Step PreviousAction = new Step("PreviousAction");
/// <summary>
/// <c>Custom Action</c> is to be executed before/after the previous action item in <see cref="Project.Actions"/>.
/// If <c>Custom Action</c> is the first item in item in <see cref="Project.Actions"/> it will be executed before/after
/// MSI built-in <c>InstallFinalize</c> action.
/// </summary>
public static Step PreviousActionOrInstallFinalize = new Step("PreviousActionOrInstallFinalize"); //if first usage of a CA, same as "InstallFinalize"; otherwise same as "PreviousAction"
/// <summary>
/// <c>Custom Action</c> is to be executed before/after the previous action item in <see cref="Project.Actions"/>.
/// If <c>Custom Action</c> is the first item in item in <see cref="Project.Actions"/> it will be executed before/after
/// MSI built-in <c>InstallInitialize</c> action.
/// </summary>
public static Step PreviousActionOrInstallInitialize = new Step("PreviousActionOrInstallInitialize"); //if first usage of a CA, same as "InstallInitialize"; otherwise same as "PreviousAction"
/// <summary>
/// Initializes a new instance of the <see cref="Step"/> class.
/// </summary>
/// <param name="value">The value.</param>
public Step(string value)
{
Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="Step"/> class.
/// </summary>
/// <param name="value">The value.</param>
public Step(Step value)
{
Value = value.ToString();
}
/// <summary>
/// The string value of the Step object
/// </summary>
protected string Value;
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return Value;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg001.neg001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg001.neg001;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// Negtive: The operator is *=, /=, %=, &=, |=, ^=, <<=, >>=
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public event Dele E = x => x;
public static int Foo(int i)
{
return i;
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
int result = 0;
try
{
c.E *= new Dele(C.Foo);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "*=", "Dele", "Dele"))
result += 1;
}
try
{
c.E /= new Dele(C.Foo);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "/=", "Dele", "Dele"))
result += 2;
}
try
{
c.E %= new Dele(C.Foo);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "%=", "Dele", "Dele"))
result += 4;
}
try
{
c.E &= new Dele(C.Foo);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "&=", "Dele", "Dele"))
result += 8;
}
try
{
c.E |= new Dele(C.Foo);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "|=", "Dele", "Dele"))
result += 16;
}
try
{
c.E ^= new Dele(C.Foo);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "^=", "Dele", "Dele"))
result += 32;
}
try
{
c.E <<= new Dele(C.Foo);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, "<<=", "Dele", "Dele"))
result += 64;
}
try
{
c.E >>= new Dele(C.Foo);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadBinaryOps, e.Message, ">>=", "Dele", "Dele"))
result += 128;
}
if (result != 255)
{
System.Console.WriteLine("result = {0}", result);
return 1;
}
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg002.neg002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg002.neg002;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// Negtive: rhs is dynamic expression with runtime non-delegate type
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public event Dele E;
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
try
{
c.E += c;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
// incorrect error message
// resolusion is 'By design' so this error message should be use again
// new error message
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "C", "Dele"))
return 0;
}
return 1;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg003.neg003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg003.neg003;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// Negtive: rhs is non-matched delegate
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public event Dele E;
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
int result = 0;
try
{
c.E += (Func<int, int>)(x => x);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "System.Func<int,int>", "Dele"))
result += 1;
}
try
{
c.E -= (Func<int, int>)(x => x);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "System.Func<int,int>", "Dele"))
result += 2;
}
if (result != 3)
{
System.Console.WriteLine("Result = {0}", result);
return 1;
}
return 0;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg004.neg004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg004.neg004;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// Negtive: rhs is compile time known type and it's non valid type
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
using System;
public delegate int Dele(int i);
public class C
{
public event Dele E;
public static int Foo(int i)
{
return i;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
int result = 0;
try
{
c.E += new C();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "C", "Dele"))
result++;
}
try
{
c.E += 1;
} // : not type info for c.E at runtime as it's null
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "int", "Dele"))
result++;
;
}
try
{
c.E -= new C();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "C", "Dele"))
result++;
;
}
try
{
c.E -= 1; // : not type info for c.E at runtime as it's null
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (!ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "int", "Dele"))
result++;
;
}
return result;
}
public int DoEvent(int arg)
{
return this.E(arg);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg005.neg005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.negative.neg005.neg005;
// <Area> Dynamic -- compound operator</Area>
// <Title> compund operator +=/-= on event </Title>
// <Description>
// Negtive: rhs is non-matched delegate and lhs is null
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(17,23\).*CS0067</Expects>
using System;
public delegate int Dele(int i);
public class C
{
public event Dele E;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic c = new C();
int result = 0;
try
{
c.E += (Func<int, int>)(x => x);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "System.Func<int,int>", "Dele"))
result += 1;
}
try
{
c.E += (Func<int, int, int>)((x, y) => x);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "System.Func<int,int,int>", "Dele"))
result += 2;
}
try
{
// - no error for -= (by design :()
// it seems that it is fixed now.
c.E -= (Func<int, int>)(x => x);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "System.Func<int,int>", "Dele"))
result += 4;
}
try
{
// - no error for -= (by design :()
c.E -= (Func<int, int, int>)((x, y) => x);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConv, e.Message, "System.Func<int,int,int>", "Dele"))
result += 8;
}
return (result == 15) ? 0 : 1;
}
}
// </Code>
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreGraphics;
using FlyoutNavigation;
using Foundation;
using MediaPlayer;
using MonoTouch.Dialog;
using MusicPlayer.Data;
using MusicPlayer.Cells;
using MusicPlayer.Managers;
using UIKit;
using SimpleTables;
using Section = MonoTouch.Dialog.Section;
using Localizations;
namespace MusicPlayer.iOS.ViewControllers
{
internal class RootViewController : UIViewController
{
FlyoutNavigationController Menu;
NowPlayingViewController NowPlaying;
public RootViewController()
{
}
RootView view;
Tuple<Element, UIViewController>[] menuItems;
public override void LoadView()
{
View = view = new RootView();
menuItems = new Tuple<Element, UIViewController>[]
{
new Tuple<Element, UIViewController>(new MenuElement(Strings.Search,"SVG/search.svg",20) {SaveIndex = false }, new SearchViewController()),
new Tuple<Element, UIViewController>(new MenuHeaderElement(Strings.MusicLibraryHeading), null),
new Tuple<Element, UIViewController>(new MenuElement(Strings.Artists, "SVG/artist.svg"), new ArtistViewController()),
new Tuple<Element, UIViewController>(new MenuElement(Strings.Albums, "SVG/album.svg"), new AlbumViewController()),
new Tuple<Element, UIViewController>(new MenuElement(Strings.Genres, "SVG/genres.svg"), new GenreViewController()),
new Tuple<Element, UIViewController>(new MenuElement(Strings.Songs, "SVG/songs.svg"), new SongViewController()),
new Tuple<Element, UIViewController>(new MenuElement(Strings.Playlists, "SVG/playlists.svg"), new PlaylistViewController()),
new Tuple<Element, UIViewController>(new MenuHeaderElement(Strings.Online), null),
//new Tuple<Element, UIViewController>(new MenuElement("trending", "SVG/trending.svg"),
// new BaseViewController {Title = "Trending", View = {BackgroundColor = UIColor.White}}),
new Tuple<Element, UIViewController>(new MenuElement(Strings.Radio, "SVG/radio.svg"), new RadioStationViewController()),
new Tuple<Element, UIViewController>(new MenuHeaderElement(Strings.Settings), null),
new Tuple<Element, UIViewController>(new MenuSwitch(Strings.OfflineOnly, "SVG/offline.svg", Settings.ShowOfflineOnly) {ValueUpdated = (b)=> Settings.ShowOfflineOnly = b}, null),
new Tuple<Element, UIViewController>(new MenuSubtextSwitch(Strings.Equalizer
, MusicPlayer.Playback.Equalizer.Shared.CurrentPreset?.Name , "SVG/equalizer.svg", Settings.EqualizerEnabled){ValueUpdated = (b) => MusicPlayer.Playback.Equalizer.Shared.Active = b},
new EqualizerViewController()),
new Tuple<Element, UIViewController>(new MenuElement(Strings.Settings, "SVG/settings.svg"){SaveIndex = false }, new SettingViewController()),
#if DEBUG || ADHOC
new Tuple<Element, UIViewController>(new MenuElement("Console", "SVG/settings.svg"){SaveIndex = false }, new ConsoleViewController()),
#endif
};
Menu = new FlyoutNavigationController {};
Menu.NavigationRoot = new RootElement("gMusic")
{
new Section
{
menuItems.Select(x => x.Item1)
}
};
Menu.NavigationRoot.TableView.TableFooterView =
new UIView(new CGRect(0, 0, 320, NowPlayingViewController.MinVideoHeight));
Menu.NavigationRoot.TableView.BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle("launchBg"));
Menu.NavigationRoot.TableView.BackgroundView = new BluredView(Style.DefaultStyle.NavigationBlurStyle);
Menu.NavigationRoot.TableView.SeparatorColor = UIColor.Clear;
Menu.NavigationRoot.TableView.EstimatedSectionHeaderHeight = 0;
Menu.NavigationRoot.TableView.EstimatedSectionFooterHeight = 0;
Menu.ViewControllers = menuItems.Select(x => x.Item2 == null ? null : new UINavigationController(x.Item2)).ToArray();
Menu.HideShadow = false;
Menu.ShadowViewColor = UIColor.Gray.ColorWithAlpha(.25f);
view.Menu = Menu;
Menu.SelectedIndex = Settings.CurrentMenuIndex;
AddChildViewController(Menu);
NowPlaying = new NowPlayingViewController
{
Close = () => view.HideNowPlaying(true, true),
};
view.NowPlaying = NowPlaying;
AddChildViewController(NowPlaying);
SetupEvents();
}
void SetupEvents()
{
NotificationManager.Shared.ToggleMenu += SharedOnToggleMenu;
NotificationManager.Shared.ToggleNowPlaying += ToggleNowPlaying;
NotificationManager.Shared.GoToAlbum += GoToAlbum;
NotificationManager.Shared.GoToArtist += GoToArtist;
NotificationManager.Shared.VideoPlaybackChanged += VideoPlaybackChanged;
}
void VideoPlaybackChanged(object sender, EventArgs<bool> eventArgs)
{
UIView.AnimateAsync(.2, () => view.LayoutSubviews());
}
void GoToArtist(object sender, EventArgs<string> eventArgs)
{
var artistControllerItem = menuItems.FirstOrDefault(x => x.Item2 is ArtistViewController);
var artistViewController = artistControllerItem.Item2 as ArtistViewController;
var artistIndex = menuItems.IndexOf(artistControllerItem);
artistViewController.NavigationController.PopToRootViewController(false);
artistViewController.GoToArtist(eventArgs.Data);
view?.HideNowPlaying(true);
Menu.SelectedIndex = artistIndex;
}
public void GoToPlaylists()
{
var playlistItem = menuItems.FirstOrDefault(x => x.Item2 is PlaylistViewController);
var playlistIndex = menuItems.IndexOf(playlistItem);
view?.HideNowPlaying(true);
Menu.SelectedIndex = playlistIndex;
}
void GoToAlbum(object sender, EventArgs<string> eventArgs)
{
var albumControllerItem = menuItems.FirstOrDefault(x => x.Item2 is AlbumViewController);
var albumController = albumControllerItem.Item2 as AlbumViewController;
var albumIndex = menuItems.IndexOf(albumControllerItem);
albumController.NavigationController.PopToRootViewController(false);
albumController.GoToAlbum(eventArgs.Data);
view?.HideNowPlaying(true);
Menu.SelectedIndex = albumIndex;
}
void ToggleNowPlaying(object sender, EventArgs eventArgs)
{
view?.ShowNowPlaying(true);
}
void SharedOnToggleMenu(object sender, EventArgs eventArgs)
{
Menu.ToggleMenu();
}
void TearDownEvents()
{
NotificationManager.Shared.ToggleMenu -= SharedOnToggleMenu;
NotificationManager.Shared.ToggleNowPlaying -= ToggleNowPlaying;
NotificationManager.Shared.GoToAlbum -= GoToAlbum;
NotificationManager.Shared.GoToArtist -= GoToArtist;
NotificationManager.Shared.VideoPlaybackChanged -= VideoPlaybackChanged;
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
view.WillAppear();
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
Menu.ViewDidAppear(animated);
ApiManager.Shared.StartSync();
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
view.WillDisapear();
}
public class RootView : UIView
{
const float FlickVelocity = 1000f;
static float NowPlayingGestureTollerance = 50 + 100;
nfloat startY;
UIViewController menu;
NowPlayingViewController nowPlaying;
public UIViewController Menu
{
get { return menu; }
set
{
menu?.RemoveFromParentViewController();
menu?.View.RemoveFromSuperview();
menu = value;
Add(menu.View);
}
}
public override void SafeAreaInsetsDidChange()
{
base.SafeAreaInsetsDidChange();
if (Device.IsIos11)
{
NowPlaying.BottomInset = this.SafeAreaInsets.Bottom;
Console.WriteLine(NowPlaying.BottomInset);
}
}
public NowPlayingViewController NowPlaying
{
get { return nowPlaying; }
set
{
nowPlaying?.RemoveFromParentViewController();
nowPlaying?.View.RemoveFromSuperview();
nowPlaying = value;
Add(nowPlaying.View);
}
}
UIPanGestureRecognizer panGesture;
public void WillAppear()
{
NowPlaying.View.AddGestureRecognizer(panGesture = new UIPanGestureRecognizer(Panned)
{
ShouldReceiveTouch = (sender, touch) =>
{
bool isMovingCell =
touch.View.ToString().IndexOf("UITableViewCellReorderControl", StringComparison.InvariantCultureIgnoreCase) >
-1;
if (isMovingCell || touch.View is UISlider || touch.View is MPVolumeView || isMovingCell ||
touch.View is ProgressView ||
touch.View is OBSlider)
return false;
return true;
},
//ShouldRecognizeSimultaneously = (recognizer, gestureRecognizer) =>
//{
// return true;
//},
});
}
public void WillDisapear()
{
if (panGesture != null)
{
NowPlaying.View.RemoveGestureRecognizer(panGesture);
panGesture = null;
}
}
public override void LayoutSubviews()
{
base.LayoutSubviews();
CGRect bounds = Bounds;
Menu.View.Frame = bounds;
if (isPanning)
return;
if (isHidden)
{
HideNowPlaying(false);
return;
}
else
{
ShowNowPlaying(false);
}
CGRect frame = NowPlaying.View.Frame;
frame.Size = Bounds.Size;
frame.Height += NowPlaying.GetHeaderOverhangHeight();
NowPlaying.View.Frame = frame;
}
bool isHidden = true;
public virtual void HideNowPlaying(bool animated = true, bool completeClose = true)
{
isHidden = true;
if (animated)
BeginAnimations("hideNowPlaying");
CGRect frame = Bounds;
if (frame == CGRect.Empty)
return;
frame.Y = frame.Height - (completeClose ? NowPlaying.GetHeight() : NowPlaying.GetVisibleHeight());
frame.Height += NowPlaying.GetHeaderOverhangHeight();
NowPlaying.View.Frame = frame;
if (animated)
CommitAnimations();
}
public virtual void ShowNowPlaying(bool animated = true)
{
isHidden = false;
if (animated)
BeginAnimations("showNowPlaying");
CGRect frame = Bounds;
var overhang = NowPlaying.GetHeaderOverhangHeight();
frame.Y -= overhang;
frame.Height += overhang;
NowPlaying.View.Frame = frame;
if (animated)
CommitAnimations();
//Logger.LogPageView(NowPlaying);
}
bool isPanning;
void Panned(UIPanGestureRecognizer panGesture)
{
CGRect frame = NowPlaying.View.Frame;
nfloat translation = panGesture.TranslationInView(this).Y;
//Console.WriteLine("Translation: {0}, {1}", translation, NowPlaying.GetOffset());
if (panGesture.State == UIGestureRecognizerState.Began)
{
isPanning = true;
startY = frame.Y;
//NowPlaying.BackgroundView = Menu.View;
//NowPlaying.UpdateBackgound();
}
else if (panGesture.State == UIGestureRecognizerState.Changed)
{
frame.Y = translation + startY;
frame.Y = NMath.Min(frame.Height, NMath.Max(frame.Y, NowPlaying.GetHeaderOverhangHeight()*-1));
NowPlaying.View.Frame = frame;
}
else if (panGesture.State == UIGestureRecognizerState.Ended)
{
isPanning = false;
var velocity = panGesture.VelocityInView(this).Y;
// Console.WriteLine (velocity);
var show = (Math.Abs(velocity) > FlickVelocity)
? (velocity < 0)
: (translation*-1 > NowPlayingGestureTollerance);
const float playbackBarHideTollerance = NowPlayingViewController.PlaybackBarHeight*2/3;
if (show)
ShowNowPlaying(true);
else
HideNowPlaying(true,
Math.Abs(velocity) > FlickVelocity ||
(translation > 5 && NowPlaying.GetOffset() - NowPlaying.GetHeaderOverhangHeight() < playbackBarHideTollerance));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using Docu.Parsing.Model;
namespace Docu.Documentation
{
public class DeclaredType : BaseDocumentationElement, IReferencable
{
readonly List<Event> events = new List<Event>();
readonly List<Field> fields = new List<Field>();
readonly List<Method> methods = new List<Method>();
readonly List<Property> properties = new List<Property>();
Type declaration;
/// <summary>
/// Initializes a new instance of the <see cref="DeclaredType" /> class.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <param name="ns">
/// The ns.
/// </param>
public DeclaredType(TypeIdentifier name, Namespace ns)
: base(name)
{
Namespace = ns;
Interfaces = new List<IReferencable>();
}
public IList<Event> Events
{
get { return events; }
}
public IList<Field> Fields
{
get { return fields; }
}
public string FullName
{
get { return (Namespace == null ? string.Empty : Namespace.FullName + ".") + PrettyName; }
}
public IList<IReferencable> Interfaces { get; set; }
public bool IsInterface
{
get { return declaration != null && declaration.IsInterface; }
}
public bool IsStatic
{
get { return declaration != null && declaration.IsSealed && declaration.IsAbstract; }
}
public IList<Method> Methods
{
get { return methods; }
}
public Namespace Namespace { get; private set; }
public IReferencable ParentType { get; set; }
public string PrettyName
{
get { return declaration == null ? Name : declaration.GetPrettyName(); }
}
public IList<Property> Properties
{
get { return properties; }
}
public static DeclaredType Unresolved(TypeIdentifier typeIdentifier, Type declaration, Namespace ns)
{
var declaredType = new DeclaredType(typeIdentifier, ns) {IsResolved = false, declaration = declaration};
if (declaration.BaseType != null)
{
declaredType.ParentType = Unresolved(
IdentifierFor.Type(declaration.BaseType),
declaration.BaseType,
Namespace.Unresolved(IdentifierFor.Namespace(declaration.BaseType.Namespace)));
}
IEnumerable<Type> interfaces = GetInterfaces(declaration);
foreach (Type face in interfaces)
{
declaredType.Interfaces.Add(
Unresolved(IdentifierFor.Type(face), face, Namespace.Unresolved(IdentifierFor.Namespace(face.Namespace))));
}
return declaredType;
}
public static DeclaredType Unresolved(TypeIdentifier typeIdentifier, Namespace ns)
{
return new DeclaredType(typeIdentifier, ns) {IsResolved = false};
}
public void AddEvent(Event ev)
{
events.Add(ev);
}
public void AddField(Field field)
{
fields.Add(field);
}
public void Resolve(IDictionary<Identifier, IReferencable> referencables)
{
if (referencables.ContainsKey(identifier))
{
IsResolved = true;
IReferencable referencable = referencables[identifier];
var type = referencable as DeclaredType;
if (type == null)
{
throw new InvalidOperationException("Cannot resolve to '" + referencable.GetType().FullName + "'");
}
Namespace = type.Namespace;
declaration = type.declaration;
ParentType = type.ParentType;
Interfaces = type.Interfaces;
if (!Namespace.IsResolved)
{
Namespace.Resolve(referencables);
}
if (ParentType != null && !ParentType.IsResolved)
{
ParentType.Resolve(referencables);
}
foreach (IReferencable face in Interfaces)
{
if (!face.IsResolved)
{
face.Resolve(referencables);
}
}
if (declaration != null && declaration.IsDefined(typeof(ObsoleteAttribute)))
{
ObsoleteReason = declaration.GetCustomAttribute<ObsoleteAttribute>().Message;
}
if (!Summary.IsResolved)
{
Summary.Resolve(referencables);
}
foreach (Method method in Methods)
{
if (!method.IsResolved)
{
method.Resolve(referencables);
}
}
foreach (Property property in Properties)
{
if (!property.IsResolved)
{
property.Resolve(referencables);
}
}
foreach (Event ev in Events)
{
if (!ev.IsResolved)
{
ev.Resolve(referencables);
}
}
foreach (Field field in Fields)
{
if (!field.IsResolved)
{
field.Resolve(referencables);
}
}
}
else
{
ConvertToExternalReference();
}
}
public void Sort()
{
methods.Sort((x, y) => x.Name.CompareTo(y.Name));
properties.Sort((x, y) => x.Name.CompareTo(y.Name));
}
public override string ToString()
{
return base.ToString() + " { Name = '" + Name + "'}";
}
internal void AddMethod(Method method)
{
methods.Add(method);
}
internal void AddProperty(Property property)
{
properties.Add(property);
}
static void FilterInterfaces(IList<Type> topLevelInterfaces, Type type)
{
foreach (Type face in type.GetInterfaces())
{
if (topLevelInterfaces.Contains(face))
{
topLevelInterfaces.Remove(face);
continue;
}
FilterInterfaces(topLevelInterfaces, face);
}
if (type.BaseType != null)
{
FilterInterfaces(topLevelInterfaces, type.BaseType);
}
}
static IEnumerable<Type> GetInterfaces(Type type)
{
var interfaces = new List<Type>(type.GetInterfaces());
foreach (Type face in type.GetInterfaces())
{
FilterInterfaces(interfaces, face);
}
if (type.BaseType != null)
{
FilterInterfaces(interfaces, type.BaseType);
}
return interfaces;
}
}
}
| |
/*
* 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.Binary
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
#if !NETCOREAPP
using System.Linq;
#endif
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using NUnit.Framework;
/// <summary>
/// <see cref="TypeResolver"/> tests.
/// </summary>
public class TypeResolverTest
{
/// <summary>
/// Tests basic types.
/// </summary>
[Test]
public void TestBasicTypes()
{
var resolver = new TypeResolver();
Assert.AreEqual(typeof(int), resolver.ResolveType("System.Int32"));
Assert.AreEqual(GetType(), resolver.ResolveType(GetType().FullName));
Assert.IsNull(resolver.ResolveType("invalidType"));
}
/// <summary>
/// Tests basic types.
/// </summary>
[Test]
public void TestBasicTypesSimpleMapper()
{
var resolver = new TypeResolver();
var mapper = BinaryBasicNameMapper.SimpleNameInstance;
Assert.AreEqual(typeof(int), resolver.ResolveType("Int32", nameMapper: mapper));
Assert.AreEqual(GetType(), resolver.ResolveType("TypeResolverTest", nameMapper: mapper));
Assert.IsNull(resolver.ResolveType("invalidType", nameMapper: mapper));
}
/// <summary>
/// Tests generic type resolve.
/// </summary>
[Test]
public void TestGenerics()
{
var testTypes = new[]
{
typeof (TestGenericBinarizable<int>),
typeof (TestGenericBinarizable<string>),
typeof (TestGenericBinarizable<TestGenericBinarizable<int>>),
typeof (TestGenericBinarizable<List<Tuple<int, string>>>),
typeof (TestGenericBinarizable<List<TestGenericBinarizable<List<Tuple<int, string>>>>>),
typeof (List<TestGenericBinarizable<List<TestGenericBinarizable<List<Tuple<int, string>>>>>>),
typeof (TestGenericBinarizable<int, string>),
typeof (TestGenericBinarizable<int, TestGenericBinarizable<string>>),
typeof (TestGenericBinarizable<int, string, Type>),
typeof (TestGenericBinarizable<int, string, TestGenericBinarizable<int, string, Type>>)
};
foreach (var type in testTypes)
{
// Without assembly
var resolvedType = new TypeResolver().ResolveType(type.FullName);
Assert.AreEqual(type.FullName, resolvedType.FullName);
// With assembly
resolvedType = new TypeResolver().ResolveType(type.FullName, type.Assembly.FullName);
Assert.AreEqual(type.FullName, resolvedType.FullName);
// Assembly-qualified
resolvedType = new TypeResolver().ResolveType(type.AssemblyQualifiedName);
Assert.AreEqual(type.FullName, resolvedType.FullName);
}
}
/// <summary>
/// Tests generic type resolve.
/// </summary>
[Test]
public void TestGenericsSimpleName()
{
var resolver = new TypeResolver();
var mapper = BinaryBasicNameMapper.SimpleNameInstance;
Assert.AreEqual(typeof(TestGenericBinarizable<int>),
resolver.ResolveType("TestGenericBinarizable`1[[Int32]]", nameMapper: mapper));
Assert.IsNull(resolver.ResolveType("TestGenericBinarizable`1[[Invalid-Type]]", nameMapper: mapper));
var testTypes = new[]
{
typeof (TestGenericBinarizable<int>),
typeof (TestGenericBinarizable<string>),
typeof (TestGenericBinarizable<TestGenericBinarizable<int>>),
typeof (TestGenericBinarizable<List<Tuple<int, string>>>),
typeof (TestGenericBinarizable<List<TestGenericBinarizable<List<Tuple<int, string>>>>>),
typeof (List<TestGenericBinarizable<List<TestGenericBinarizable<List<Tuple<int, string>>>>>>),
typeof (TestGenericBinarizable<int, string>),
typeof (TestGenericBinarizable<int, TestGenericBinarizable<string>>),
typeof (TestGenericBinarizable<int, string, Type>),
typeof (TestGenericBinarizable<int, string, TestGenericBinarizable<int, string, Type>>)
};
foreach (var type in testTypes)
{
var typeName = mapper.GetTypeName(type.AssemblyQualifiedName);
var resolvedType = resolver.ResolveType(typeName, nameMapper: mapper);
Assert.AreEqual(type, resolvedType);
}
}
/// <summary>
/// Tests array type resolve.
/// </summary>
[Test]
public void TestArrays()
{
var resolver = new TypeResolver();
Assert.AreEqual(typeof(int[]), resolver.ResolveType("System.Int32[]"));
Assert.AreEqual(typeof(int[][]), resolver.ResolveType("System.Int32[][]"));
Assert.AreEqual(typeof(int[,,][,]), resolver.ResolveType("System.Int32[,][,,]"));
Assert.AreEqual(typeof(int).MakeArrayType(1), resolver.ResolveType("System.Int32[*]"));
Assert.AreEqual(typeof(TestGenericBinarizable<TypeResolverTest>[]),
resolver.ResolveType("Apache.Ignite.Core.Tests.TestGenericBinarizable`1" +
"[[Apache.Ignite.Core.Tests.Binary.TypeResolverTest]][]"));
}
/// <summary>
/// Tests array type resolve.
/// </summary>
[Test]
public void TestArraysSimpleName()
{
var resolver = new TypeResolver();
var mapper = BinaryBasicNameMapper.SimpleNameInstance;
Assert.AreEqual(typeof(int[]), resolver.ResolveType("Int32[]", nameMapper: mapper));
Assert.AreEqual(typeof(int[][]), resolver.ResolveType("Int32[][]", nameMapper: mapper));
Assert.AreEqual(typeof(int[,,][,]), resolver.ResolveType("Int32[,][,,]", nameMapper: mapper));
Assert.AreEqual(typeof(int).MakeArrayType(1), resolver.ResolveType("Int32[*]", nameMapper: mapper));
Assert.AreEqual(typeof(TestGenericBinarizable<TypeResolverTest>[]),
resolver.ResolveType("TestGenericBinarizable`1[[TypeResolverTest]][]", nameMapper: mapper));
}
/// <summary>
/// Tests that types from dynamic assemblies can be resolved.
/// </summary>
[Test]
public void TestDynamicallyGeneratedType()
{
var typeName = nameof(TestDynamicallyGeneratedType) + new Random().Next();
var assemblyName = new AssemblyName("DynamicAssembly1");
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule1");
var typeAttributes = TypeAttributes.Public | TypeAttributes.Class;
var typeBuilder = moduleBuilder.DefineType(typeName, typeAttributes);
var generatedType = typeBuilder.CreateType();
var resolver = new TypeResolver();
var resolvedType = resolver.ResolveType(typeName);
Assert.AreEqual(generatedType, resolvedType);
}
#if !NETCOREAPP
/// <summary>
/// Tests loading a type from referenced assembly that is not yet loaded.
/// </summary>
[Test]
public void TestReferencedAssemblyLoading()
{
const string dllName = "Apache.Ignite.Core.Tests.TestDll,";
const string typeName = "Apache.Ignite.Core.Tests.TestDll.TestClass";
// Check that the dll is not yet loaded
Assert.IsFalse(AppDomain.CurrentDomain.GetAssemblies().Any(x => x.FullName.StartsWith(dllName)));
// Check that the dll is referenced by current assembly
Assert.IsTrue(Assembly.GetExecutingAssembly().GetReferencedAssemblies()
.Any(x => x.FullName.StartsWith(dllName)));
// Check resolver
var type = new TypeResolver().ResolveType(typeName);
Assert.IsNotNull(type);
Assert.AreEqual(typeName, type.FullName);
Assert.IsNotNull(Activator.CreateInstance(type));
// At this moment the dll should be loaded
Assert.IsTrue(AppDomain.CurrentDomain.GetAssemblies().Any(x => x.FullName.StartsWith(dllName)));
}
/// <summary>
/// Unused method that forces C# compiler to include TestDll assembly reference.
/// Without this, compiler will remove the reference as unused.
/// However, since it is never called, TestDll does not get loaded.
/// </summary>
public void UnusedMethod()
{
Assert.IsNotNull(typeof(TestDll.TestClass));
}
#endif
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Marten.Events;
using Marten.Events.Aggregation;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;
using Xunit.Abstractions;
namespace Marten.Testing.Events.Aggregation
{
public class when_doing_live_aggregations : AggregationContext
{
private readonly ITestOutputHelper _output;
public when_doing_live_aggregations(DefaultStoreFixture fixture, ITestOutputHelper output) : base(fixture)
{
_output = output;
}
[Fact]
public async Task sync_apply_and_default_create()
{
UsingDefinition<AllSync>();
var aggregate = await LiveAggregation(x =>
{
x.B();
x.C();
x.B();
x.C();
x.C();
x.A();
x.D();
});
_output.WriteLine(_projection.SourceCode());
aggregate.ACount.ShouldBe(1);
aggregate.BCount.ShouldBe(2);
aggregate.CCount.ShouldBe(3);
aggregate.DCount.ShouldBe(1);
}
[Fact]
public async Task sync_apply_and_specific_create()
{
UsingDefinition<AllSync>();
var aggregate = await LiveAggregation(x =>
{
x.Add(new CreateEvent(2, 3, 4, 5));
x.B();
x.C();
x.B();
x.C();
x.C();
x.A();
x.D();
});
_output.WriteLine(_projection.SourceCode());
aggregate.ACount.ShouldBe(3);
aggregate.BCount.ShouldBe(5);
aggregate.CCount.ShouldBe(7);
aggregate.DCount.ShouldBe(6);
}
[Fact]
public async Task async_create_and_apply_with_session()
{
var user1 = new User {UserName = "Creator"};
var user2 = new User {UserName = "Updater"};
theSession.Store(user1, user2);
await theSession.SaveChangesAsync();
UsingDefinition<AsyncEverything>();
_output.WriteLine(_projection.SourceCode());
var aggregate = await LiveAggregation(x =>
{
x.Add(new UserStarted {UserId = user1.Id});
x.Add(new UserUpdated {UserId = user2.Id});
});
aggregate.Created.ShouldBe(user1.UserName);
aggregate.UpdatedBy.ShouldBe(user2.UserName);
}
[Fact]
public async Task using_sync_value_task_with_otherwise_async_create()
{
var user1 = new User {UserName = "Creator"};
var user2 = new User {UserName = "Updater"};
theSession.Store(user1, user2);
await theSession.SaveChangesAsync();
UsingDefinition<AsyncEverything>();
var aggregate = await LiveAggregation(x =>
{
x.A();
x.A();
x.A();
});
aggregate.ACount.ShouldBe(3);
}
[Fact]
public async Task async_create_and_sync_apply()
{
var user1 = new User {UserName = "Creator"};
theSession.Store(user1);
await theSession.SaveChangesAsync();
UsingDefinition<AsyncCreateSyncApply>();
var aggregate = await LiveAggregation(x =>
{
x.Add(new UserStarted {UserId = user1.Id});
x.B();
x.C();
x.B();
x.C();
x.C();
x.A();
x.D();
});
aggregate.Created.ShouldBe(user1.UserName);
aggregate.ACount.ShouldBe(1);
aggregate.BCount.ShouldBe(2);
aggregate.CCount.ShouldBe(3);
aggregate.DCount.ShouldBe(1);
}
[Fact]
public async Task sync_create_and_async_apply()
{
var user1 = new User {UserName = "Updater"};
theSession.Store(user1);
await theSession.SaveChangesAsync();
UsingDefinition<SyncCreateAsyncApply>();
var aggregate = await LiveAggregation(x =>
{
x.Add(new CreateEvent(2, 3, 4, 5));
x.Add(new UserUpdated {UserId = user1.Id});
x.B();
x.C();
x.B();
x.C();
x.C();
x.A();
x.D();
});
_output.WriteLine(_projection.SourceCode());
aggregate.UpdatedBy.ShouldBe(user1.UserName);
aggregate.ACount.ShouldBe(3);
aggregate.BCount.ShouldBe(5);
aggregate.CCount.ShouldBe(7);
aggregate.DCount.ShouldBe(6);
}
[Fact]
public async Task using_event_metadata()
{
UsingDefinition<UsingMetadata>();
var streamId = Guid.NewGuid();
var aId = Guid.NewGuid();
var aggregate = await LiveAggregation(x =>
{
x.Add(new CreateEvent(2, 3, 4, 5)).StreamId = streamId;
x.A().Id = aId;
});
aggregate.Id.ShouldBe(streamId);
aggregate.EventId.ShouldBe(aId);
}
}
public class UserStarted
{
public Guid UserId { get; set; }
}
public class UserUpdated
{
public Guid UserId { get; set; }
}
public class UsingMetadata : AggregateProjection<MyAggregate>
{
public MyAggregate Create(CreateEvent create, IEvent e)
{
return new MyAggregate
{
ACount = create.A,
BCount = create.B,
CCount = create.C,
DCount = create.D,
Id = e.StreamId
};
}
public void Apply(IEvent<AEvent> @event, MyAggregate aggregate)
{
aggregate.EventId = @event.Id;
aggregate.ACount++;
}
}
public class AsyncEverything: AggregateProjection<MyAggregate>
{
public async Task<MyAggregate> Create(UserStarted @event, IQuerySession session, CancellationToken cancellation)
{
var user = await session.LoadAsync<User>(@event.UserId, cancellation);
return new MyAggregate
{
Created = user.UserName
};
}
public async Task Apply(UserUpdated @event, MyAggregate aggregate, IQuerySession session)
{
var user = await session.LoadAsync<User>(@event.UserId);
aggregate.UpdatedBy = user.UserName;
}
public void Apply(AEvent @event, MyAggregate aggregate)
{
aggregate.ACount++;
}
}
public class AsyncCreateSyncApply: AggregateProjection<MyAggregate>
{
public async Task<MyAggregate> Create(UserStarted @event, IQuerySession session, CancellationToken cancellation)
{
var user = await session.LoadAsync<User>(@event.UserId, cancellation);
return new MyAggregate
{
Created = user.UserName
};
}
public void Apply(AEvent @event, MyAggregate aggregate)
{
aggregate.ACount++;
}
public void Apply(BEvent @event, MyAggregate aggregate)
{
aggregate.BCount++;
}
public void Apply(MyAggregate aggregate, CEvent @event)
{
aggregate.CCount++;
}
public void Apply(MyAggregate aggregate, DEvent @event)
{
aggregate.DCount++;
}
}
public class SyncCreateAsyncApply: AggregateProjection<MyAggregate>
{
public MyAggregate Create(CreateEvent @event)
{
return new MyAggregate
{
ACount = @event.A,
BCount = @event.B,
CCount = @event.C,
DCount = @event.D
};
}
public async Task Apply(UserUpdated @event, MyAggregate aggregate, IQuerySession session)
{
var user = await session.LoadAsync<User>(@event.UserId);
aggregate.UpdatedBy = user.UserName;
}
public void Apply(AEvent @event, MyAggregate aggregate)
{
aggregate.ACount++;
}
public void Apply(BEvent @event, MyAggregate aggregate)
{
aggregate.BCount++;
}
public void Apply(MyAggregate aggregate, CEvent @event)
{
aggregate.CCount++;
}
public void Apply(MyAggregate aggregate, DEvent @event)
{
aggregate.DCount++;
}
}
public class AllSync: AggregateProjection<MyAggregate>
{
public MyAggregate Create(CreateEvent @event)
{
return new MyAggregate
{
ACount = @event.A,
BCount = @event.B,
CCount = @event.C,
DCount = @event.D
};
}
public void Apply(AEvent @event, MyAggregate aggregate)
{
aggregate.ACount++;
}
public MyAggregate Apply(BEvent @event, MyAggregate aggregate)
{
return new MyAggregate
{
ACount = aggregate.ACount,
BCount = aggregate.BCount + 1,
CCount = aggregate.CCount,
DCount = aggregate.DCount,
Id = aggregate.Id
};
}
public void Apply(MyAggregate aggregate, CEvent @event)
{
aggregate.CCount++;
}
public MyAggregate Apply(MyAggregate aggregate, DEvent @event)
{
return new MyAggregate
{
ACount = aggregate.ACount,
BCount = aggregate.BCount,
CCount = aggregate.CCount,
DCount = aggregate.DCount + 1,
Id = aggregate.Id
};
}
}
}
| |
//
// ChangeTrackerTest.cs
//
// Author:
// Zachary Gramana <[email protected]>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Net;
using Apache.Http;
using Apache.Http.Client;
using Apache.Http.Impl.Client;
using Couchbase.Lite;
using Couchbase.Lite.Replicator;
using Couchbase.Lite.Threading;
using Couchbase.Lite.Util;
using NUnit.Framework;
using Sharpen;
namespace Couchbase.Lite.Replicator
{
public class ChangeTrackerTest : LiteTestCase
{
public const string Tag = "ChangeTracker";
/// <exception cref="System.Exception"></exception>
public virtual void TestChangeTracker()
{
CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1);
Uri testURL = GetReplicationURL();
ChangeTrackerClient client = new _ChangeTrackerClient_31(changeTrackerFinishedSignal
);
ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode
.OneShot, 0, client);
changeTracker.Start();
try
{
bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
private sealed class _ChangeTrackerClient_31 : ChangeTrackerClient
{
public _ChangeTrackerClient_31(CountDownLatch changeTrackerFinishedSignal)
{
this.changeTrackerFinishedSignal = changeTrackerFinishedSignal;
}
public void ChangeTrackerStopped(ChangeTracker tracker)
{
changeTrackerFinishedSignal.CountDown();
}
public void ChangeTrackerReceivedChange(IDictionary<string, object> change)
{
object seq = change.Get("seq");
}
public HttpClient GetHttpClient()
{
return new DefaultHttpClient();
}
private readonly CountDownLatch changeTrackerFinishedSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestChangeTrackerLongPoll()
{
ChangeTrackerTestWithMode(ChangeTracker.ChangeTrackerMode.LongPoll);
}
/// <exception cref="System.Exception"></exception>
public virtual void FailingTestChangeTrackerContinuous()
{
CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1);
CountDownLatch changeReceivedSignal = new CountDownLatch(1);
Uri testURL = GetReplicationURL();
ChangeTrackerClient client = new _ChangeTrackerClient_72(changeTrackerFinishedSignal
, changeReceivedSignal);
ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode
.Continuous, 0, client);
changeTracker.Start();
try
{
bool success = changeReceivedSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
changeTracker.Stop();
try
{
bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
private sealed class _ChangeTrackerClient_72 : ChangeTrackerClient
{
public _ChangeTrackerClient_72(CountDownLatch changeTrackerFinishedSignal, CountDownLatch
changeReceivedSignal)
{
this.changeTrackerFinishedSignal = changeTrackerFinishedSignal;
this.changeReceivedSignal = changeReceivedSignal;
}
public void ChangeTrackerStopped(ChangeTracker tracker)
{
changeTrackerFinishedSignal.CountDown();
}
public void ChangeTrackerReceivedChange(IDictionary<string, object> change)
{
object seq = change.Get("seq");
changeReceivedSignal.CountDown();
}
public HttpClient GetHttpClient()
{
return new DefaultHttpClient();
}
private readonly CountDownLatch changeTrackerFinishedSignal;
private readonly CountDownLatch changeReceivedSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void ChangeTrackerTestWithMode(ChangeTracker.ChangeTrackerMode mode
)
{
CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1);
CountDownLatch changeReceivedSignal = new CountDownLatch(1);
Uri testURL = GetReplicationURL();
ChangeTrackerClient client = new _ChangeTrackerClient_119(changeTrackerFinishedSignal
, changeReceivedSignal);
ChangeTracker changeTracker = new ChangeTracker(testURL, mode, 0, client);
changeTracker.Start();
try
{
bool success = changeReceivedSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
changeTracker.Stop();
try
{
bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
private sealed class _ChangeTrackerClient_119 : ChangeTrackerClient
{
public _ChangeTrackerClient_119(CountDownLatch changeTrackerFinishedSignal, CountDownLatch
changeReceivedSignal)
{
this.changeTrackerFinishedSignal = changeTrackerFinishedSignal;
this.changeReceivedSignal = changeReceivedSignal;
}
public void ChangeTrackerStopped(ChangeTracker tracker)
{
changeTrackerFinishedSignal.CountDown();
}
public void ChangeTrackerReceivedChange(IDictionary<string, object> change)
{
object seq = change.Get("seq");
NUnit.Framework.Assert.AreEqual("*:1", seq.ToString());
changeReceivedSignal.CountDown();
}
public HttpClient GetHttpClient()
{
CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient();
mockHttpClient.SetResponder("_changes", new _Responder_136());
return mockHttpClient;
}
private sealed class _Responder_136 : CustomizableMockHttpClient.Responder
{
public _Responder_136()
{
}
/// <exception cref="System.IO.IOException"></exception>
public HttpResponse Execute(HttpRequestMessage httpUriRequest)
{
string json = "{\"results\":[\n" + "{\"seq\":\"*:1\",\"id\":\"doc1-138\",\"changes\":[{\"rev\":\"1-82d\"}]}],\n"
+ "\"last_seq\":\"*:50\"}";
return CustomizableMockHttpClient.GenerateHttpResponseObject(json);
}
}
private readonly CountDownLatch changeTrackerFinishedSignal;
private readonly CountDownLatch changeReceivedSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestChangeTrackerWithFilterURL()
{
Uri testURL = GetReplicationURL();
ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode
.LongPoll, 0, null);
// set filter
changeTracker.SetFilterName("filter");
// build filter map
IDictionary<string, object> filterMap = new Dictionary<string, object>();
filterMap.Put("param", "value");
// set filter map
changeTracker.SetFilterParams(filterMap);
NUnit.Framework.Assert.AreEqual("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=filter¶m=value"
, changeTracker.GetChangesFeedPath());
}
public virtual void TestChangeTrackerWithDocsIds()
{
Uri testURL = GetReplicationURL();
ChangeTracker changeTrackerDocIds = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode
.LongPoll, 0, null);
IList<string> docIds = new AList<string>();
docIds.AddItem("doc1");
docIds.AddItem("doc2");
changeTrackerDocIds.SetDocIDs(docIds);
string docIdsEncoded = URLEncoder.Encode("[\"doc1\",\"doc2\"]");
string expectedFeedPath = string.Format("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=_doc_ids&doc_ids=%s"
, docIdsEncoded);
string changesFeedPath = changeTrackerDocIds.GetChangesFeedPath();
NUnit.Framework.Assert.AreEqual(expectedFeedPath, changesFeedPath);
}
/// <exception cref="System.Exception"></exception>
public virtual void TestChangeTrackerBackoff()
{
Uri testURL = GetReplicationURL();
CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient();
mockHttpClient.AddResponderThrowExceptionAllRequests();
ChangeTrackerClient client = new _ChangeTrackerClient_214(mockHttpClient);
ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode
.LongPoll, 0, client);
BackgroundTask task = new _BackgroundTask_235(changeTracker);
task.Execute();
try
{
// expected behavior:
// when:
// mockHttpClient throws IOExceptions -> it should start high and then back off and numTimesExecute should be low
for (int i = 0; i < 30; i++)
{
int numTimesExectutedAfter10seconds = 0;
try
{
Sharpen.Thread.Sleep(1000);
// take a snapshot of num times the http client was called after 10 seconds
if (i == 10)
{
numTimesExectutedAfter10seconds = mockHttpClient.GetCapturedRequests().Count;
}
// take another snapshot after 20 seconds have passed
if (i == 20)
{
// by now it should have backed off, so the delta between 10s and 20s should be small
int delta = mockHttpClient.GetCapturedRequests().Count - numTimesExectutedAfter10seconds;
NUnit.Framework.Assert.IsTrue(delta < 25);
}
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
}
finally
{
changeTracker.Stop();
}
}
private sealed class _ChangeTrackerClient_214 : ChangeTrackerClient
{
public _ChangeTrackerClient_214(CustomizableMockHttpClient mockHttpClient)
{
this.mockHttpClient = mockHttpClient;
}
public void ChangeTrackerStopped(ChangeTracker tracker)
{
Log.V(ChangeTrackerTest.Tag, "changeTrackerStopped");
}
public void ChangeTrackerReceivedChange(IDictionary<string, object> change)
{
object seq = change.Get("seq");
Log.V(ChangeTrackerTest.Tag, "changeTrackerReceivedChange: " + seq.ToString());
}
public HttpClient GetHttpClient()
{
return mockHttpClient;
}
private readonly CustomizableMockHttpClient mockHttpClient;
}
private sealed class _BackgroundTask_235 : BackgroundTask
{
public _BackgroundTask_235(ChangeTracker changeTracker)
{
this.changeTracker = changeTracker;
}
public override void Run()
{
changeTracker.Start();
}
private readonly ChangeTracker changeTracker;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestChangeTrackerInvalidJson()
{
Uri testURL = GetReplicationURL();
CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient();
mockHttpClient.AddResponderThrowExceptionAllRequests();
ChangeTrackerClient client = new _ChangeTrackerClient_290(mockHttpClient);
ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode
.LongPoll, 0, client);
BackgroundTask task = new _BackgroundTask_311(changeTracker);
task.Execute();
try
{
// expected behavior:
// when:
// mockHttpClient throws IOExceptions -> it should start high and then back off and numTimesExecute should be low
for (int i = 0; i < 30; i++)
{
int numTimesExectutedAfter10seconds = 0;
try
{
Sharpen.Thread.Sleep(1000);
// take a snapshot of num times the http client was called after 10 seconds
if (i == 10)
{
numTimesExectutedAfter10seconds = mockHttpClient.GetCapturedRequests().Count;
}
// take another snapshot after 20 seconds have passed
if (i == 20)
{
// by now it should have backed off, so the delta between 10s and 20s should be small
int delta = mockHttpClient.GetCapturedRequests().Count - numTimesExectutedAfter10seconds;
NUnit.Framework.Assert.IsTrue(delta < 25);
}
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
}
finally
{
changeTracker.Stop();
}
}
private sealed class _ChangeTrackerClient_290 : ChangeTrackerClient
{
public _ChangeTrackerClient_290(CustomizableMockHttpClient mockHttpClient)
{
this.mockHttpClient = mockHttpClient;
}
public void ChangeTrackerStopped(ChangeTracker tracker)
{
Log.V(ChangeTrackerTest.Tag, "changeTrackerStopped");
}
public void ChangeTrackerReceivedChange(IDictionary<string, object> change)
{
object seq = change.Get("seq");
Log.V(ChangeTrackerTest.Tag, "changeTrackerReceivedChange: " + seq.ToString());
}
public HttpClient GetHttpClient()
{
return mockHttpClient;
}
private readonly CustomizableMockHttpClient mockHttpClient;
}
private sealed class _BackgroundTask_311 : BackgroundTask
{
public _BackgroundTask_311(ChangeTracker changeTracker)
{
this.changeTracker = changeTracker;
}
public override void Run()
{
changeTracker.Start();
}
private readonly ChangeTracker changeTracker;
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class StopPositionRequestDecoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 15;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private StopPositionRequestDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public StopPositionRequestDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public StopPositionRequestDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int RecordingIdId()
{
return 3;
}
public static int RecordingIdSinceVersion()
{
return 0;
}
public static int RecordingIdEncodingOffset()
{
return 16;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long RecordingId()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[StopPositionRequest](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("RecordingId=");
builder.Append(RecordingId());
Limit(originalLimit);
return builder;
}
}
}
| |
//
// CGImageProperties.cs: Accessors to various kCGImageProperty values
//
// Authors: Marek Safar ([email protected])
//
// Copyright 2012, Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
using MonoMac.CoreImage;
#if !COREBUILD
using Keys = MonoMac.ImageIO.CGImageProperties;
#endif
namespace MonoMac.CoreGraphics {
public enum CGImageColorModel
{
RGB,
Gray,
CMYK,
Lab
}
public class CGImageProperties : DictionaryContainer
{
#if !COREBUILD
public CGImageProperties ()
: base (new NSMutableDictionary ())
{
}
public CGImageProperties (NSDictionary dictionary)
: base (dictionary)
{
}
public bool? Alpha {
get {
return GetBoolValue (Keys.HasAlpha);
}
set {
SetBooleanValue (Keys.HasAlpha, value);
}
}
public CGImageColorModel? ColorModel {
get {
var v = GetNSStringValue (Keys.ColorModel);
if (v == Keys.ColorModelRGB)
return CGImageColorModel.RGB;
if (v == Keys.ColorModelGray)
return CGImageColorModel.Gray;
if (v == Keys.ColorModelCMYK)
return CGImageColorModel.CMYK;
if (v == Keys.ColorModelLab)
return CGImageColorModel.Lab;
return null;
}
set {
NSString key;
switch (value) {
case CGImageColorModel.RGB:
key = Keys.ColorModelRGB;
break;
case CGImageColorModel.Gray:
key = Keys.ColorModelGray;
break;
case CGImageColorModel.CMYK:
key = Keys.ColorModelCMYK;
break;
case CGImageColorModel.Lab:
key = Keys.ColorModelLab;
break;
default:
throw new ArgumentOutOfRangeException ("value");
}
SetNativeValue (Keys.ColorModel, key);
}
}
public int? Depth {
get {
return GetInt32Value (Keys.Depth);
}
set {
SetNumberValue (Keys.Depth, value);
}
}
public int? DPIHeight {
get {
return GetInt32Value (Keys.DPIHeight);
}
set {
SetNumberValue (Keys.DPIHeight, value);
}
}
public int? DPIWidth {
get {
return GetInt32Value (Keys.DPIWidth);
}
set {
SetNumberValue (Keys.DPIWidth, value);
}
}
public int? FileSize {
get {
return GetInt32Value (Keys.FileSize);
}
set {
SetNumberValue (Keys.FileSize, value);
}
}
public bool? IsFloat {
get {
return GetBoolValue (Keys.IsFloat);
}
set {
SetBooleanValue (Keys.IsFloat, value);
}
}
public bool? IsIndexed {
get {
return GetBoolValue (Keys.IsIndexed);
}
set {
SetBooleanValue (Keys.IsIndexed, value);
}
}
public CIImageOrientation? Orientation {
get {
return (CIImageOrientation?)GetInt32Value (Keys.Orientation);
}
set {
SetNumberValue (Keys.Orientation, (int?) value);
}
}
public int? PixelHeight {
get {
return GetInt32Value (Keys.PixelHeight);
}
set {
SetNumberValue (Keys.PixelHeight, value);
}
}
public int? PixelWidth {
get {
return GetInt32Value (Keys.PixelWidth);
}
set {
SetNumberValue (Keys.PixelWidth, value);
}
}
public string ProfileName {
get {
return GetStringValue (Keys.ProfileName);
}
set {
SetStringValue (Keys.ProfileName, value);
}
}
public CGImagePropertiesExif Exif {
get {
var dict = GetNSDictionary (Keys.ExifDictionary);
return dict == null ? null : new CGImagePropertiesExif (dict);
}
}
public CGImagePropertiesGps Gps {
get {
var dict = GetNSDictionary (Keys.GPSDictionary);
return dict == null ? null : new CGImagePropertiesGps (dict);
}
}
public CGImagePropertiesIptc Iptc {
get {
var dict = GetNSDictionary (Keys.IPTCDictionary);
return dict == null ? null : new CGImagePropertiesIptc (dict);
}
}
public CGImagePropertiesPng Png {
get {
var dict = GetNSDictionary (Keys.PNGDictionary);
return dict == null ? null : new CGImagePropertiesPng (dict);
}
}
public CGImagePropertiesJfif Jfif {
get {
var dict = GetNSDictionary (Keys.JFIFDictionary);
return dict == null ? null : new CGImagePropertiesJfif (dict);
}
}
public CGImagePropertiesTiff Tiff {
get {
var dict = GetNSDictionary (Keys.TIFFDictionary);
return dict == null ? null : new CGImagePropertiesTiff (dict);
}
}
#endif
}
#if !COREBUILD
public class CGImagePropertiesExif : DictionaryContainer
{
public CGImagePropertiesExif ()
: base (new NSMutableDictionary ())
{
}
public CGImagePropertiesExif (NSDictionary dictionary)
: base (dictionary)
{
}
public float? Aperture {
get {
return GetFloatValue (Keys.ExifApertureValue);
}
set {
SetNumberValue (Keys.ExifApertureValue, value);
}
}
public float? Brightness {
get {
return GetFloatValue (Keys.ExifBrightnessValue);
}
set {
SetNumberValue (Keys.ExifBrightnessValue, value);
}
}
public float? CompressedBitsPerPixel {
get {
return GetFloatValue (Keys.ExifCompressedBitsPerPixel);
}
set {
SetNumberValue (Keys.ExifCompressedBitsPerPixel, value);
}
}
public float? DigitalZoomRatio {
get {
return GetFloatValue (Keys.ExifDigitalZoomRatio);
}
set {
SetNumberValue (Keys.ExifDigitalZoomRatio, value);
}
}
public float? ExposureBias {
get {
return GetFloatValue (Keys.ExifExposureBiasValue);
}
set {
SetNumberValue (Keys.ExifExposureBiasValue, value);
}
}
public float? ExposureIndex {
get {
return GetFloatValue (Keys.ExifExposureIndex);
}
set {
SetNumberValue (Keys.ExifExposureIndex, value);
}
}
public float? ExposureTime {
get {
return GetFloatValue (Keys.ExifExposureTime);
}
set {
SetNumberValue (Keys.ExifExposureTime, value);
}
}
public int? ExposureProgram {
get {
return GetInt32Value (Keys.ExifExposureProgram);
}
set {
SetNumberValue (Keys.ExifExposureProgram, value);
}
}
public bool? Flash {
get {
return GetBoolValue (Keys.ExifFlash);
}
set {
SetBooleanValue (Keys.ExifFlash, value);
}
}
public float? FlashEnergy {
get {
return GetFloatValue (Keys.ExifFlashEnergy);
}
set {
SetNumberValue (Keys.ExifFlashEnergy, value);
}
}
public float? FocalPlaneXResolution {
get {
return GetFloatValue (Keys.ExifFocalPlaneXResolution);
}
set {
SetNumberValue (Keys.ExifFocalPlaneXResolution, value);
}
}
public float? FocalPlaneYResolution {
get {
return GetFloatValue (Keys.ExifFocalPlaneYResolution);
}
set {
SetNumberValue (Keys.ExifFocalPlaneYResolution, value);
}
}
public float? GainControl {
get {
return GetFloatValue (Keys.ExifGainControl);
}
set {
SetNumberValue (Keys.ExifGainControl, value);
}
}
public int[] ISOSpeedRatings {
get {
return GetArray (Keys.ExifISOSpeedRatings, l => new NSNumber (l).Int32Value);
}
}
public float? MaximumLensAperture {
get {
return GetFloatValue (Keys.ExifMaxApertureValue);
}
set {
SetNumberValue (Keys.ExifMaxApertureValue, value);
}
}
public int? PixelXDimension {
get {
return GetInt32Value (Keys.ExifPixelXDimension);
}
set {
SetNumberValue (Keys.ExifPixelXDimension, value);
}
}
public int? PixelYDimension {
get {
return GetInt32Value (Keys.ExifPixelYDimension);
}
set {
SetNumberValue (Keys.ExifPixelYDimension, value);
}
}
public float? SubjectDistance {
get {
return GetFloatValue (Keys.ExifSubjectDistance);
}
set {
SetNumberValue (Keys.ExifSubjectDistance, value);
}
}
public float? ShutterSpeed {
get {
return GetFloatValue (Keys.ExifShutterSpeedValue);
}
set {
SetNumberValue (Keys.ExifShutterSpeedValue, value);
}
}
// TODO: Many more available but underlying types need to be investigated
}
public class CGImagePropertiesTiff : DictionaryContainer
{
public CGImagePropertiesTiff ()
: base (new NSMutableDictionary ())
{
}
public CGImagePropertiesTiff (NSDictionary dictionary)
: base (dictionary)
{
}
public CIImageOrientation? Orientation {
get {
return (CIImageOrientation?)GetInt32Value (Keys.TIFFOrientation);
}
set {
SetNumberValue (Keys.TIFFOrientation, (int?) value);
}
}
public int? XResolution {
get {
return GetInt32Value (Keys.TIFFXResolution);
}
set {
SetNumberValue (Keys.TIFFXResolution, value);
}
}
public int? YResolution {
get {
return GetInt32Value (Keys.TIFFYResolution);
}
set {
SetNumberValue (Keys.TIFFYResolution, value);
}
}
public string Software {
get {
return GetStringValue (Keys.TIFFSoftware);
}
set {
SetStringValue (Keys.TIFFSoftware, value);
}
}
// TODO: Many more available but underlying types need to be investigated
}
public class CGImagePropertiesJfif : DictionaryContainer
{
public CGImagePropertiesJfif ()
: base (new NSMutableDictionary ())
{
}
public CGImagePropertiesJfif (NSDictionary dictionary)
: base (dictionary)
{
}
public int? XDensity {
get {
return GetInt32Value (Keys.JFIFXDensity);
}
set {
SetNumberValue (Keys.JFIFXDensity, value);
}
}
public int? YDensity {
get {
return GetInt32Value (Keys.JFIFYDensity);
}
set {
SetNumberValue (Keys.JFIFYDensity, value);
}
}
// TODO: Many more available but underlying types need to be investigated
}
public class CGImagePropertiesPng : DictionaryContainer
{
public CGImagePropertiesPng ()
: base (new NSMutableDictionary ())
{
}
public CGImagePropertiesPng (NSDictionary dictionary)
: base (dictionary)
{
}
[Since (5,0)]
public string Author {
get {
return GetStringValue (Keys.PNGAuthor);
}
set {
SetStringValue (Keys.PNGAuthor, value);
}
}
[Since (5,0)]
public string Description {
get {
return GetStringValue (Keys.PNGDescription);
}
set {
SetStringValue (Keys.PNGDescription, value);
}
}
public float? Gamma {
get {
return GetFloatValue (Keys.PNGGamma);
}
set {
SetNumberValue (Keys.PNGGamma, value);
}
}
[Since (5,0)]
public string Software {
get {
return GetStringValue (Keys.PNGSoftware);
}
set {
SetStringValue (Keys.PNGSoftware, value);
}
}
public int? XPixelsPerMeter {
get {
return GetInt32Value (Keys.PNGXPixelsPerMeter);
}
set {
SetNumberValue (Keys.PNGXPixelsPerMeter, value);
}
}
public int? YPixelsPerMeter {
get {
return GetInt32Value (Keys.PNGYPixelsPerMeter);
}
set {
SetNumberValue (Keys.PNGYPixelsPerMeter, value);
}
}
[Since (5,0)]
public string Title {
get {
return GetStringValue (Keys.PNGTitle);
}
set {
SetStringValue (Keys.PNGTitle, value);
}
}
// TODO: Many more available but underlying types need to be investigated
}
public class CGImagePropertiesGps : DictionaryContainer
{
public CGImagePropertiesGps ()
: base (new NSMutableDictionary ())
{
}
public CGImagePropertiesGps (NSDictionary dictionary)
: base (dictionary)
{
}
public int? Altitude {
get {
return GetInt32Value (Keys.GPSAltitude);
}
set {
SetNumberValue (Keys.GPSAltitude, value);
}
}
public float? Latitude {
get {
return GetFloatValue (Keys.GPSLatitude);
}
set {
SetNumberValue (Keys.GPSLatitude, value);
}
}
public float? Longitude {
get {
return GetFloatValue (Keys.GPSLongitude);
}
set {
SetNumberValue (Keys.GPSLongitude, value);
}
}
// TODO: Many more available but underlying types need to be investigated
}
public class CGImagePropertiesIptc : DictionaryContainer
{
public CGImagePropertiesIptc ()
: base (new NSMutableDictionary ())
{
}
public CGImagePropertiesIptc (NSDictionary dictionary)
: base (dictionary)
{
}
public string Byline {
get {
return GetStringValue (Keys.IPTCByline);
}
set {
SetStringValue (Keys.IPTCByline, value);
}
}
public string BylineTitle {
get {
return GetStringValue (Keys.IPTCBylineTitle);
}
set {
SetStringValue (Keys.IPTCBylineTitle, value);
}
}
public string CaptionAbstract {
get {
return GetStringValue (Keys.IPTCCaptionAbstract);
}
set {
SetStringValue (Keys.IPTCCaptionAbstract, value);
}
}
public string City {
get {
return GetStringValue (Keys.IPTCCity);
}
set {
SetStringValue (Keys.IPTCCity, value);
}
}
public string ContentLocationName {
get {
return GetStringValue (Keys.IPTCContentLocationName);
}
set {
SetStringValue (Keys.IPTCContentLocationName, value);
}
}
public string CountryPrimaryLocationName {
get {
return GetStringValue (Keys.IPTCCountryPrimaryLocationName);
}
set {
SetStringValue (Keys.IPTCCountryPrimaryLocationName, value);
}
}
public string CopyrightNotice {
get {
return GetStringValue (Keys.IPTCCopyrightNotice);
}
set {
SetStringValue (Keys.IPTCCopyrightNotice, value);
}
}
public string Credit {
get {
return GetStringValue (Keys.IPTCCredit);
}
set {
SetStringValue (Keys.IPTCCredit, value);
}
}
public string Source {
get {
return GetStringValue (Keys.IPTCSource);
}
set {
SetStringValue (Keys.IPTCSource, value);
}
}
public string WriterEditor {
get {
return GetStringValue (Keys.IPTCWriterEditor);
}
set {
SetStringValue (Keys.IPTCWriterEditor, value);
}
}
// TODO: Many more available but underlying types need to be investigated
}
#endif
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Carousel;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Tests.Visual.SongSelect
{
[TestFixture]
public class TestCaseBeatmapCarousel : OsuTestCase
{
private TestBeatmapCarousel carousel;
private RulesetStore rulesets;
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(CarouselItem),
typeof(CarouselGroup),
typeof(CarouselGroupEagerSelect),
typeof(CarouselBeatmap),
typeof(CarouselBeatmapSet),
typeof(DrawableCarouselItem),
typeof(CarouselItemState),
typeof(DrawableCarouselBeatmap),
typeof(DrawableCarouselBeatmapSet),
};
private readonly Stack<BeatmapSetInfo> selectedSets = new Stack<BeatmapSetInfo>();
private readonly HashSet<int> eagerSelectedIDs = new HashSet<int>();
private BeatmapInfo currentSelection;
private const int set_count = 5;
[BackgroundDependencyLoader]
private void load(RulesetStore rulesets)
{
this.rulesets = rulesets;
Add(carousel = new TestBeatmapCarousel
{
RelativeSizeAxes = Axes.Both,
});
List<BeatmapSetInfo> beatmapSets = new List<BeatmapSetInfo>();
for (int i = 1; i <= set_count; i++)
beatmapSets.Add(createTestBeatmapSet(i));
carousel.SelectionChanged = s => currentSelection = s;
loadBeatmaps(beatmapSets);
testTraversal();
testFiltering();
testRandom();
testAddRemove();
testSorting();
testRemoveAll();
testEmptyTraversal();
testHiding();
testSelectingFilteredRuleset();
testCarouselRootIsRandom();
}
private void loadBeatmaps(List<BeatmapSetInfo> beatmapSets)
{
bool changed = false;
AddStep($"Load {beatmapSets.Count} Beatmaps", () =>
{
carousel.BeatmapSetsChanged = () => changed = true;
carousel.BeatmapSets = beatmapSets;
});
AddUntilStep("Wait for load", () => changed);
}
private void ensureRandomFetchSuccess() =>
AddAssert("ensure prev random fetch worked", () => selectedSets.Peek() == carousel.SelectedBeatmapSet);
private void checkSelected(int set, int? diff = null) =>
AddAssert($"selected is set{set}{(diff.HasValue ? $" diff{diff.Value}" : "")}", () =>
{
if (diff != null)
return carousel.SelectedBeatmap == carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff.Value - 1).First();
return carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Contains(carousel.SelectedBeatmap);
});
private void setSelected(int set, int diff) =>
AddStep($"select set{set} diff{diff}", () =>
carousel.SelectBeatmap(carousel.BeatmapSets.Skip(set - 1).First().Beatmaps.Skip(diff - 1).First()));
private void advanceSelection(bool diff, int direction = 1, int count = 1)
{
if (count == 1)
AddStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () =>
carousel.SelectNext(direction, !diff));
else
{
AddRepeatStep($"select {(direction > 0 ? "next" : "prev")} {(diff ? "diff" : "set")}", () =>
carousel.SelectNext(direction, !diff), count);
}
}
private void checkVisibleItemCount(bool diff, int count) =>
AddAssert($"{count} {(diff ? "diffs" : "sets")} visible", () =>
carousel.Items.Count(s => (diff ? s.Item is CarouselBeatmap : s.Item is CarouselBeatmapSet) && s.Item.Visible) == count);
private void checkNoSelection() => AddAssert("Selection is null", () => currentSelection == null);
private void nextRandom() =>
AddStep("select random next", () =>
{
carousel.RandomAlgorithm.Value = RandomSelectAlgorithm.RandomPermutation;
if (!selectedSets.Any() && carousel.SelectedBeatmap != null)
selectedSets.Push(carousel.SelectedBeatmapSet);
carousel.SelectNextRandom();
selectedSets.Push(carousel.SelectedBeatmapSet);
});
private void ensureRandomDidntRepeat() =>
AddAssert("ensure no repeats", () => selectedSets.Distinct().Count() == selectedSets.Count);
private void prevRandom() => AddStep("select random last", () =>
{
carousel.SelectPreviousRandom();
selectedSets.Pop();
});
private bool selectedBeatmapVisible()
{
var currentlySelected = carousel.Items.Find(s => s.Item is CarouselBeatmap && s.Item.State.Value == CarouselItemState.Selected);
if (currentlySelected == null)
return true;
return currentlySelected.Item.Visible;
}
private void checkInvisibleDifficultiesUnselectable()
{
nextRandom();
AddAssert("Selection is visible", selectedBeatmapVisible);
}
private void checkNonmatchingFilter()
{
AddStep("Toggle non-matching filter", () =>
{
carousel.Filter(new FilterCriteria { SearchText = "Dingo" }, false);
carousel.Filter(new FilterCriteria(), false);
eagerSelectedIDs.Add(carousel.SelectedBeatmapSet.ID);
});
}
/// <summary>
/// Test keyboard traversal
/// </summary>
private void testTraversal()
{
advanceSelection(direction: 1, diff: false);
checkSelected(1, 1);
advanceSelection(direction: 1, diff: true);
checkSelected(1, 2);
advanceSelection(direction: -1, diff: false);
checkSelected(set_count, 1);
advanceSelection(direction: -1, diff: true);
checkSelected(set_count - 1, 3);
advanceSelection(diff: false);
advanceSelection(diff: false);
checkSelected(1, 2);
advanceSelection(direction: -1, diff: true);
advanceSelection(direction: -1, diff: true);
checkSelected(set_count, 3);
}
/// <summary>
/// Test filtering
/// </summary>
private void testFiltering()
{
// basic filtering
setSelected(1, 1);
AddStep("Filter", () => carousel.Filter(new FilterCriteria { SearchText = "set #3!" }, false));
checkVisibleItemCount(diff: false, count: 1);
checkVisibleItemCount(diff: true, count: 3);
checkSelected(3, 1);
advanceSelection(diff: true, count: 4);
checkSelected(3, 2);
AddStep("Un-filter (debounce)", () => carousel.Filter(new FilterCriteria()));
AddUntilStep("Wait for debounce", () => !carousel.PendingFilterTask);
checkVisibleItemCount(diff: false, count: set_count);
checkVisibleItemCount(diff: true, count: 3);
// test filtering some difficulties (and keeping current beatmap set selected).
setSelected(1, 2);
AddStep("Filter some difficulties", () => carousel.Filter(new FilterCriteria { SearchText = "Normal" }, false));
checkSelected(1, 1);
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
checkSelected(1, 1);
AddStep("Filter all", () => carousel.Filter(new FilterCriteria { SearchText = "Dingo" }, false));
checkVisibleItemCount(false, 0);
checkVisibleItemCount(true, 0);
AddAssert("Selection is null", () => currentSelection == null);
advanceSelection(true);
AddAssert("Selection is null", () => currentSelection == null);
advanceSelection(false);
AddAssert("Selection is null", () => currentSelection == null);
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
AddAssert("Selection is non-null", () => currentSelection != null);
}
/// <summary>
/// Test random non-repeating algorithm
/// </summary>
private void testRandom()
{
setSelected(1, 1);
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
prevRandom();
ensureRandomFetchSuccess();
prevRandom();
ensureRandomFetchSuccess();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
ensureRandomDidntRepeat();
nextRandom();
AddAssert("ensure repeat", () => selectedSets.Contains(carousel.SelectedBeatmapSet));
AddStep("Add set with 100 difficulties", () => carousel.UpdateBeatmapSet(createTestBeatmapSetWithManyDifficulties(set_count + 1)));
AddStep("Filter Extra", () => carousel.Filter(new FilterCriteria { SearchText = "Extra 10" }, false));
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
checkInvisibleDifficultiesUnselectable();
AddStep("Un-filter", () => carousel.Filter(new FilterCriteria(), false));
}
/// <summary>
/// Test adding and removing beatmap sets
/// </summary>
private void testAddRemove()
{
AddStep("Add new set", () => carousel.UpdateBeatmapSet(createTestBeatmapSet(set_count + 1)));
AddStep("Add new set", () => carousel.UpdateBeatmapSet(createTestBeatmapSet(set_count + 2)));
checkVisibleItemCount(false, set_count + 2);
AddStep("Remove set", () => carousel.RemoveBeatmapSet(createTestBeatmapSet(set_count + 2)));
checkVisibleItemCount(false, set_count + 1);
setSelected(set_count + 1, 1);
AddStep("Remove set", () => carousel.RemoveBeatmapSet(createTestBeatmapSet(set_count + 1)));
checkVisibleItemCount(false, set_count);
checkSelected(set_count);
}
/// <summary>
/// Test sorting
/// </summary>
private void testSorting()
{
AddStep("Sort by author", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Author }, false));
AddAssert("Check zzzzz is at bottom", () => carousel.BeatmapSets.Last().Metadata.AuthorString == "zzzzz");
AddStep("Sort by artist", () => carousel.Filter(new FilterCriteria { Sort = SortMode.Artist }, false));
AddAssert($"Check #{set_count} is at bottom", () => carousel.BeatmapSets.Last().Metadata.Title.EndsWith($"#{set_count}!"));
}
private void testRemoveAll()
{
setSelected(2, 1);
AddAssert("Selection is non-null", () => currentSelection != null);
AddStep("Remove selected", () => carousel.RemoveBeatmapSet(carousel.SelectedBeatmapSet));
checkSelected(2);
AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First()));
AddStep("Remove first", () => carousel.RemoveBeatmapSet(carousel.BeatmapSets.First()));
checkSelected(1);
AddUntilStep("Remove all", () =>
{
if (!carousel.BeatmapSets.Any()) return true;
carousel.RemoveBeatmapSet(carousel.BeatmapSets.Last());
return false;
});
checkNoSelection();
}
private void testEmptyTraversal()
{
advanceSelection(direction: 1, diff: false);
checkNoSelection();
advanceSelection(direction: 1, diff: true);
checkNoSelection();
advanceSelection(direction: -1, diff: false);
checkNoSelection();
advanceSelection(direction: -1, diff: true);
checkNoSelection();
}
private void testHiding()
{
var hidingSet = createTestBeatmapSet(1);
hidingSet.Beatmaps[1].Hidden = true;
AddStep("Add set with diff 2 hidden", () => carousel.UpdateBeatmapSet(hidingSet));
setSelected(1, 1);
checkVisibleItemCount(true, 2);
advanceSelection(true);
checkSelected(1, 3);
setHidden(3);
checkSelected(1, 1);
setHidden(2, false);
advanceSelection(true);
checkSelected(1, 2);
setHidden(1);
checkSelected(1, 2);
setHidden(2);
checkNoSelection();
void setHidden(int diff, bool hidden = true)
{
AddStep((hidden ? "" : "un") + $"hide diff {diff}", () =>
{
hidingSet.Beatmaps[diff - 1].Hidden = hidden;
carousel.UpdateBeatmapSet(hidingSet);
});
}
}
private void testSelectingFilteredRuleset()
{
var testMixed = createTestBeatmapSet(set_count + 1);
AddStep("add mixed ruleset beatmapset", () =>
{
for (int i = 0; i <= 2; i++)
{
testMixed.Beatmaps[i].Ruleset = rulesets.AvailableRulesets.ElementAt(i);
testMixed.Beatmaps[i].RulesetID = i;
}
carousel.UpdateBeatmapSet(testMixed);
});
AddStep("filter to ruleset 0", () =>
carousel.Filter(new FilterCriteria { Ruleset = rulesets.AvailableRulesets.ElementAt(0) }, false));
AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testMixed.Beatmaps[1], false));
AddAssert("unfiltered beatmap selected", () => carousel.SelectedBeatmap.Equals(testMixed.Beatmaps[0]));
AddStep("remove mixed set", () =>
{
carousel.RemoveBeatmapSet(testMixed);
testMixed = null;
});
var testSingle = createTestBeatmapSet(set_count + 2);
testSingle.Beatmaps.ForEach(b =>
{
b.Ruleset = rulesets.AvailableRulesets.ElementAt(1);
b.RulesetID = b.Ruleset.ID ?? 1;
});
AddStep("add single ruleset beatmapset", () => carousel.UpdateBeatmapSet(testSingle));
AddStep("select filtered map skipping filtered", () => carousel.SelectBeatmap(testSingle.Beatmaps[0], false));
checkNoSelection();
AddStep("remove single ruleset set", () => carousel.RemoveBeatmapSet(testSingle));
}
private void testCarouselRootIsRandom()
{
List<BeatmapSetInfo> beatmapSets = new List<BeatmapSetInfo>();
for (int i = 1; i <= 50; i++)
beatmapSets.Add(createTestBeatmapSet(i));
loadBeatmaps(beatmapSets);
advanceSelection(direction: 1, diff: false);
checkNonmatchingFilter();
checkNonmatchingFilter();
checkNonmatchingFilter();
checkNonmatchingFilter();
checkNonmatchingFilter();
AddAssert("Selection was random", () => eagerSelectedIDs.Count > 1);
}
private BeatmapSetInfo createTestBeatmapSet(int id)
{
return new BeatmapSetInfo
{
ID = id,
OnlineBeatmapSetID = id,
Hash = new MemoryStream(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())).ComputeMD5Hash(),
Metadata = new BeatmapMetadata
{
// Create random metadata, then we can check if sorting works based on these
Artist = $"peppy{id.ToString().PadLeft(6, '0')}",
Title = $"test set #{id}!",
AuthorString = string.Concat(Enumerable.Repeat((char)('z' - Math.Min(25, id - 1)), 5))
},
Beatmaps = new List<BeatmapInfo>(new[]
{
new BeatmapInfo
{
OnlineBeatmapID = id * 10,
Path = "normal.osu",
Version = "Normal",
StarDifficulty = 2,
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = 3.5f,
}
},
new BeatmapInfo
{
OnlineBeatmapID = id * 10 + 1,
Path = "hard.osu",
Version = "Hard",
StarDifficulty = 5,
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = 5,
}
},
new BeatmapInfo
{
OnlineBeatmapID = id * 10 + 2,
Path = "insane.osu",
Version = "Insane",
StarDifficulty = 6,
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = 7,
}
},
}),
};
}
private BeatmapSetInfo createTestBeatmapSetWithManyDifficulties(int id)
{
var toReturn = new BeatmapSetInfo
{
ID = id,
OnlineBeatmapSetID = id,
Hash = new MemoryStream(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString())).ComputeMD5Hash(),
Metadata = new BeatmapMetadata
{
// Create random metadata, then we can check if sorting works based on these
Artist = $"peppy{id.ToString().PadLeft(6, '0')}",
Title = $"test set #{id}!",
AuthorString = string.Concat(Enumerable.Repeat((char)('z' - Math.Min(25, id - 1)), 5))
},
Beatmaps = new List<BeatmapInfo>(),
};
for (int b = 1; b < 101; b++)
{
toReturn.Beatmaps.Add(new BeatmapInfo
{
OnlineBeatmapID = b * 10,
Path = $"extra{b}.osu",
Version = $"Extra {b}",
StarDifficulty = 2,
BaseDifficulty = new BeatmapDifficulty
{
OverallDifficulty = 3.5f,
}
});
}
return toReturn;
}
private class TestBeatmapCarousel : BeatmapCarousel
{
public new List<DrawableCarouselItem> Items => base.Items;
public bool PendingFilterTask => PendingFilter != null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
namespace Microsoft.AspNetCore.Authentication.OAuth
{
public class OAuthTests : RemoteAuthenticationTests<OAuthOptions>
{
protected override string DefaultScheme => OAuthDefaults.DisplayName;
protected override Type HandlerType => typeof(OAuthHandler<OAuthOptions>);
protected override bool SupportsSignIn { get => false; }
protected override bool SupportsSignOut { get => false; }
protected override void RegisterAuth(AuthenticationBuilder services, Action<OAuthOptions> configure)
{
services.AddOAuth(DefaultScheme, o =>
{
ConfigureDefaults(o);
configure.Invoke(o);
});
}
[Fact]
public async Task ThrowsIfClientIdMissing()
{
using var host = await CreateHost(
services => services.AddAuthentication().AddOAuth("weeblie", o =>
{
o.SignInScheme = "whatever";
o.CallbackPath = "/";
o.ClientSecret = "whatever";
o.TokenEndpoint = "/";
o.AuthorizationEndpoint = "/";
}));
using var server = host.GetTestServer();
await Assert.ThrowsAsync<ArgumentException>("ClientId", () => server.SendAsync("http://example.com/"));
}
[Fact]
public async Task ThrowsIfClientSecretMissing()
{
using var host = await CreateHost(
services => services.AddAuthentication().AddOAuth("weeblie", o =>
{
o.SignInScheme = "whatever";
o.ClientId = "Whatever;";
o.CallbackPath = "/";
o.TokenEndpoint = "/";
o.AuthorizationEndpoint = "/";
}));
using var server = host.GetTestServer();
await Assert.ThrowsAsync<ArgumentException>("ClientSecret", () => server.SendAsync("http://example.com/"));
}
[Fact]
public async Task ThrowsIfCallbackPathMissing()
{
using var host = await CreateHost(
services => services.AddAuthentication().AddOAuth("weeblie", o =>
{
o.ClientId = "Whatever;";
o.ClientSecret = "Whatever;";
o.TokenEndpoint = "/";
o.AuthorizationEndpoint = "/";
o.SignInScheme = "eh";
}));
using var server = host.GetTestServer();
await Assert.ThrowsAsync<ArgumentException>("CallbackPath", () => server.SendAsync("http://example.com/"));
}
[Fact]
public async Task ThrowsIfTokenEndpointMissing()
{
using var host = await CreateHost(
services => services.AddAuthentication().AddOAuth("weeblie", o =>
{
o.ClientId = "Whatever;";
o.ClientSecret = "Whatever;";
o.CallbackPath = "/";
o.AuthorizationEndpoint = "/";
o.SignInScheme = "eh";
}));
using var server = host.GetTestServer();
await Assert.ThrowsAsync<ArgumentException>("TokenEndpoint", () => server.SendAsync("http://example.com/"));
}
[Fact]
public async Task ThrowsIfAuthorizationEndpointMissing()
{
using var host = await CreateHost(
services => services.AddAuthentication().AddOAuth("weeblie", o =>
{
o.ClientId = "Whatever;";
o.ClientSecret = "Whatever;";
o.CallbackPath = "/";
o.TokenEndpoint = "/";
o.SignInScheme = "eh";
}));
using var server = host.GetTestServer();
await Assert.ThrowsAsync<ArgumentException>("AuthorizationEndpoint", () => server.SendAsync("http://example.com/"));
}
[Fact]
public async Task RedirectToIdentityProvider_SetsCorrelationIdCookiePath_ToCallBackPath()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
ConfigureDefaults(opt);
}),
async ctx =>
{
await ctx.ChallengeAsync("Weblie");
return true;
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://www.example.com/challenge");
var res = transaction.Response;
Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.NotNull(res.Headers.Location);
var setCookie = Assert.Single(res.Headers, h => h.Key == "Set-Cookie");
var correlation = Assert.Single(setCookie.Value, v => v.StartsWith(".AspNetCore.Correlation.", StringComparison.Ordinal));
Assert.Contains("path=/oauth-callback", correlation);
}
[Fact]
public async Task RedirectToAuthorizeEndpoint_CorrelationIdCookieOptions_CanBeOverriden()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
ConfigureDefaults(opt);
opt.CorrelationCookie.Path = "/";
}),
async ctx =>
{
await ctx.ChallengeAsync("Weblie");
return true;
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://www.example.com/challenge");
var res = transaction.Response;
Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.NotNull(res.Headers.Location);
var setCookie = Assert.Single(res.Headers, h => h.Key == "Set-Cookie");
var correlation = Assert.Single(setCookie.Value, v => v.StartsWith(".AspNetCore.Correlation.", StringComparison.Ordinal));
Assert.Contains("path=/", correlation);
}
[Fact]
public async Task RedirectToAuthorizeEndpoint_HasScopeAsConfigured()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
ConfigureDefaults(opt);
opt.Scope.Clear();
opt.Scope.Add("foo");
opt.Scope.Add("bar");
}),
async ctx =>
{
await ctx.ChallengeAsync("Weblie");
return true;
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://www.example.com/challenge");
var res = transaction.Response;
Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.Contains("scope=foo%20bar", res.Headers.Location.Query);
}
[Fact]
public async Task RedirectToAuthorizeEndpoint_HasScopeAsOverwritten()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
ConfigureDefaults(opt);
opt.Scope.Clear();
opt.Scope.Add("foo");
opt.Scope.Add("bar");
}),
async ctx =>
{
var properties = new OAuthChallengeProperties();
properties.SetScope("baz", "qux");
await ctx.ChallengeAsync("Weblie", properties);
return true;
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://www.example.com/challenge");
var res = transaction.Response;
Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.Contains("scope=baz%20qux", res.Headers.Location.Query);
}
[Fact]
public async Task RedirectToAuthorizeEndpoint_HasScopeAsOverwrittenWithBaseAuthenticationProperties()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
ConfigureDefaults(opt);
opt.Scope.Clear();
opt.Scope.Add("foo");
opt.Scope.Add("bar");
}),
async ctx =>
{
var properties = new AuthenticationProperties();
properties.SetParameter(OAuthChallengeProperties.ScopeKey, new string[] { "baz", "qux" });
await ctx.ChallengeAsync("Weblie", properties);
return true;
});
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://www.example.com/challenge");
var res = transaction.Response;
Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
Assert.Contains("scope=baz%20qux", res.Headers.Location.Query);
}
protected override void ConfigureDefaults(OAuthOptions o)
{
o.ClientId = "Test Id";
o.ClientSecret = "secret";
o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.AuthorizationEndpoint = "https://example.com/provider/login";
o.TokenEndpoint = "https://example.com/provider/token";
o.CallbackPath = "/oauth-callback";
}
[Fact]
public async Task HandleRequestAsync_RedirectsToAccessDeniedPathWhenExplicitlySet()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
opt.ClientId = "Test Id";
opt.ClientSecret = "secret";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.AuthorizationEndpoint = "https://example.com/provider/login";
opt.TokenEndpoint = "https://example.com/provider/token";
opt.CallbackPath = "/oauth-callback";
opt.AccessDeniedPath = "/access-denied";
opt.StateDataFormat = new TestStateDataFormat();
opt.Events.OnRemoteFailure = context => throw new InvalidOperationException("This event should not be called.");
}));
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://www.example.com/oauth-callback?error=access_denied&state=protected_state",
".AspNetCore.Correlation.correlationId=N");
Assert.Equal(HttpStatusCode.Redirect, transaction.Response.StatusCode);
Assert.Equal("https://www.example.com/access-denied?ReturnUrl=http%3A%2F%2Ftesthost%2Fredirect", transaction.Response.Headers.Location.ToString());
}
[Fact]
public async Task HandleRequestAsync_InvokesAccessDeniedEvent()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
opt.ClientId = "Test Id";
opt.ClientSecret = "secret";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.AuthorizationEndpoint = "https://example.com/provider/login";
opt.TokenEndpoint = "https://example.com/provider/token";
opt.CallbackPath = "/oauth-callback";
opt.StateDataFormat = new TestStateDataFormat();
opt.Events = new OAuthEvents()
{
OnAccessDenied = context =>
{
Assert.Equal("testvalue", context.Properties.Items["testkey"]);
context.Response.StatusCode = StatusCodes.Status406NotAcceptable;
context.HandleResponse();
return Task.CompletedTask;
}
};
}));
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://www.example.com/oauth-callback?error=access_denied&state=protected_state",
".AspNetCore.Correlation.correlationId=N");
Assert.Equal(HttpStatusCode.NotAcceptable, transaction.Response.StatusCode);
Assert.Null(transaction.Response.Headers.Location);
}
[Fact]
public async Task HandleRequestAsync_InvokesRemoteFailureEventWhenAccessDeniedPathIsNotExplicitlySet()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
opt.ClientId = "Test Id";
opt.ClientSecret = "secret";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.AuthorizationEndpoint = "https://example.com/provider/login";
opt.TokenEndpoint = "https://example.com/provider/token";
opt.CallbackPath = "/oauth-callback";
opt.StateDataFormat = new TestStateDataFormat();
opt.Events = new OAuthEvents()
{
OnRemoteFailure = context =>
{
Assert.Equal("Access was denied by the resource owner or by the remote server.", context.Failure.Message);
Assert.Equal("testvalue", context.Properties.Items["testkey"]);
context.Response.StatusCode = StatusCodes.Status406NotAcceptable;
context.HandleResponse();
return Task.CompletedTask;
}
};
}));
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://www.example.com/oauth-callback?error=access_denied&state=protected_state",
".AspNetCore.Correlation.correlationId=N");
Assert.Equal(HttpStatusCode.NotAcceptable, transaction.Response.StatusCode);
Assert.Null(transaction.Response.Headers.Location);
}
[Fact]
public async Task RemoteAuthenticationFailed_OAuthError_IncludesProperties()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
opt.ClientId = "Test Id";
opt.ClientSecret = "secret";
opt.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.AuthorizationEndpoint = "https://example.com/provider/login";
opt.TokenEndpoint = "https://example.com/provider/token";
opt.CallbackPath = "/oauth-callback";
opt.StateDataFormat = new TestStateDataFormat();
opt.Events = new OAuthEvents()
{
OnRemoteFailure = context =>
{
Assert.Contains("custom_error", context.Failure.Message);
Assert.Equal("testvalue", context.Properties.Items["testkey"]);
context.Response.StatusCode = StatusCodes.Status406NotAcceptable;
context.HandleResponse();
return Task.CompletedTask;
}
};
}));
using var server = host.GetTestServer();
var transaction = await server.SendAsync("https://www.example.com/oauth-callback?error=custom_error&state=protected_state",
".AspNetCore.Correlation.correlationId=N");
Assert.Equal(HttpStatusCode.NotAcceptable, transaction.Response.StatusCode);
Assert.Null(transaction.Response.Headers.Location);
}
[Theory]
[InlineData(HttpStatusCode.OK)]
[InlineData(HttpStatusCode.BadRequest)]
public async Task ExchangeCodeAsync_ChecksForErrorInformation(HttpStatusCode httpStatusCode)
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
ConfigureDefaults(opt);
opt.StateDataFormat = new TestStateDataFormat();
opt.BackchannelHttpHandler = new TestHttpMessageHandler
{
Sender = req =>
{
if (req.RequestUri.AbsoluteUri == "https://example.com/provider/token")
{
return ReturnJsonResponse(new
{
error = "incorrect_client_credentials",
error_description = "The client_id and/or client_secret passed are incorrect.",
error_uri = "https://example.com/troubleshooting-oauth-app-access-token-request-errors/#incorrect-client-credentials",
}, httpStatusCode);
}
return null;
}
};
opt.Events = new OAuthEvents()
{
OnRemoteFailure = context =>
{
Assert.Equal("incorrect_client_credentials", context.Failure.Data["error"]);
Assert.Equal("The client_id and/or client_secret passed are incorrect.", context.Failure.Data["error_description"]);
Assert.Equal("https://example.com/troubleshooting-oauth-app-access-token-request-errors/#incorrect-client-credentials", context.Failure.Data["error_uri"]);
return Task.CompletedTask;
}
};
}));
using var server = host.GetTestServer();
var exception = await Assert.ThrowsAsync<Exception>(
() => server.SendAsync("https://www.example.com/oauth-callback?code=random_code&state=protected_state", ".AspNetCore.Correlation.correlationId=N"));
}
[Fact]
public async Task ExchangeCodeAsync_FallbackToBasicErrorReporting_WhenErrorInformationIsNotPresent()
{
using var host = await CreateHost(
s => s.AddAuthentication().AddOAuth(
"Weblie",
opt =>
{
ConfigureDefaults(opt);
opt.StateDataFormat = new TestStateDataFormat();
opt.BackchannelHttpHandler = new TestHttpMessageHandler
{
Sender = req =>
{
if (req.RequestUri.AbsoluteUri == "https://example.com/provider/token")
{
return ReturnJsonResponse(new
{
ErrorCode = "ThisIsCustomErrorCode",
ErrorDescription = "ThisIsCustomErrorDescription"
}, HttpStatusCode.BadRequest);
}
return null;
}
};
opt.Events = new OAuthEvents()
{
OnRemoteFailure = context =>
{
Assert.StartsWith("OAuth token endpoint failure:", context.Failure.Message);
return Task.CompletedTask;
}
};
}));
using var server = host.GetTestServer();
var exception = await Assert.ThrowsAsync<Exception>(
() => server.SendAsync("https://www.example.com/oauth-callback?code=random_code&state=protected_state", ".AspNetCore.Correlation.correlationId=N"));
}
private static async Task<IHost> CreateHost(Action<IServiceCollection> configureServices, Func<HttpContext, Task<bool>> handler = null)
{
var host = new HostBuilder()
.ConfigureWebHost(builder =>
builder.UseTestServer()
.Configure(app =>
{
app.UseAuthentication();
app.Use(async (context, next) =>
{
if (handler == null || !await handler(context))
{
await next(context);
}
});
})
.ConfigureServices(configureServices))
.Build();
await host.StartAsync();
return host;
}
private static HttpResponseMessage ReturnJsonResponse(object content, HttpStatusCode code = HttpStatusCode.OK)
{
var res = new HttpResponseMessage(code);
var text = JsonSerializer.Serialize(content);
res.Content = new StringContent(text, Encoding.UTF8, "application/json");
return res;
}
private class TestStateDataFormat : ISecureDataFormat<AuthenticationProperties>
{
private AuthenticationProperties Data { get; set; }
public string Protect(AuthenticationProperties data)
{
return "protected_state";
}
public string Protect(AuthenticationProperties data, string purpose)
{
throw new NotImplementedException();
}
public AuthenticationProperties Unprotect(string protectedText)
{
Assert.Equal("protected_state", protectedText);
var properties = new AuthenticationProperties(new Dictionary<string, string>()
{
{ ".xsrf", "correlationId" },
{ "testkey", "testvalue" }
});
properties.RedirectUri = "http://testhost/redirect";
return properties;
}
public AuthenticationProperties Unprotect(string protectedText, string purpose)
{
throw new NotImplementedException();
}
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComMaterials.ActualCost.DS
{
public class cst_FreightMasterDS
{
public cst_FreightMasterDS()
{
}
private const string THIS = "PCSComMaterials.ActualCost.DS.cst_FreightMasterDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to cst_FreightMaster
/// </Description>
/// <Inputs>
/// cst_FreightMasterVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, February 23, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
cst_FreightMasterVO objObject = (cst_FreightMasterVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO cst_FreightMaster("
+ cst_FreightMasterTable.TRANNO_FLD + ","
+ cst_FreightMasterTable.NOTE_FLD + ","
+ cst_FreightMasterTable.EXCHANGERATE_FLD + ","
+ cst_FreightMasterTable.TOTALAMOUNT_FLD + ","
+ cst_FreightMasterTable.CCNID_FLD + ","
+ cst_FreightMasterTable.CURRENCYID_FLD + ","
+ cst_FreightMasterTable.TRANSPORTERID_FLD + ","
+ cst_FreightMasterTable.VENDORID_FLD + ","
// + cst_FreightMasterTable.COSTELEMENTID_FLD + ","
+ cst_FreightMasterTable.RECEIPTMASTERID_FLD + ","
+ cst_FreightMasterTable.GRANDTOTAL_FLD + ","
+ cst_FreightMasterTable.SUBTOTAL_FLD + ","
+ cst_FreightMasterTable.TOTALVAT_FLD + ","
+ cst_FreightMasterTable.VATPERCENT_FLD + ","
+ cst_FreightMasterTable.POSTDATE_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TRANNO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[cst_FreightMasterTable.TRANNO_FLD].Value = objObject.TranNo;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.NOTE_FLD, OleDbType.WChar));
ocmdPCS.Parameters[cst_FreightMasterTable.NOTE_FLD].Value = objObject.Note;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.EXCHANGERATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TOTALAMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.TOTALAMOUNT_FLD].Value = objObject.TotalAmount;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.CURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.CURRENCYID_FLD].Value = objObject.CurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TRANSPORTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.TRANSPORTERID_FLD].Value = objObject.TransporterID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.VENDORID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.VENDORID_FLD].Value = objObject.VendorID;
// ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.COSTELEMENTID_FLD, OleDbType.Integer));
// ocmdPCS.Parameters[cst_FreightMasterTable.COSTELEMENTID_FLD].Value = objObject.CostElementID;
//
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.RECEIPTMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.RECEIPTMASTERID_FLD].Value = objObject.ReceiveMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.GRANDTOTAL_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.GRANDTOTAL_FLD].Value = objObject.GrandTotal;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.SUBTOTAL_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.SUBTOTAL_FLD].Value = objObject.SubTotal;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TOTALVAT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.TOTALVAT_FLD].Value = objObject.TotalVAT;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.VATPERCENT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.VATPERCENT_FLD].Value = objObject.VATPercent;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.POSTDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[cst_FreightMasterTable.POSTDATE_FLD].Value = objObject.PostDate;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// AddAndReturnID
/// </summary>
/// <param name="pobjObjectVO"></param>
///<author>Trada</author>
///<date>Monday, Feb 27 2006</date>
public int AddAndReturnID(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".AddAndReturnID()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
cst_FreightMasterVO objObject = (cst_FreightMasterVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO cst_FreightMaster("
+ cst_FreightMasterTable.TRANNO_FLD + ","
+ cst_FreightMasterTable.NOTE_FLD + ","
+ cst_FreightMasterTable.EXCHANGERATE_FLD + ","
+ cst_FreightMasterTable.TOTALAMOUNT_FLD + ","
+ cst_FreightMasterTable.CCNID_FLD + ","
+ cst_FreightMasterTable.CURRENCYID_FLD + ","
+ cst_FreightMasterTable.TRANSPORTERID_FLD + ","
+ cst_FreightMasterTable.VENDORID_FLD + ","
+ cst_FreightMasterTable.ACOBJECTID_FLD + ","
+ cst_FreightMasterTable.ACPURPOSEID_FLD + ","
+ cst_FreightMasterTable.MAKERID_FLD + ","
// + cst_FreightMasterTable.COSTELEMENTID_FLD + ","
+ cst_FreightMasterTable.RECEIPTMASTERID_FLD + ","
+ cst_FreightMasterTable.RETURNTOVENDORMASTERID_FLD + ","
+ cst_FreightMasterTable.GRANDTOTAL_FLD + ","
+ cst_FreightMasterTable.SUBTOTAL_FLD + ","
+ cst_FreightMasterTable.TOTALVAT_FLD + ","
+ cst_FreightMasterTable.VATPERCENT_FLD + ","
+ cst_FreightMasterTable.POSTDATE_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
+ "; SELECT @@IDENTITY as LatestID";
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TRANNO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[cst_FreightMasterTable.TRANNO_FLD].Value = objObject.TranNo;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.NOTE_FLD, OleDbType.WChar));
if (objObject.Note != string.Empty)
{
ocmdPCS.Parameters[cst_FreightMasterTable.NOTE_FLD].Value = objObject.Note;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.NOTE_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.EXCHANGERATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TOTALAMOUNT_FLD, OleDbType.Decimal));
if (objObject.TotalAmount != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.TOTALAMOUNT_FLD].Value = objObject.TotalAmount;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.TOTALAMOUNT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.CURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.CURRENCYID_FLD].Value = objObject.CurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TRANSPORTERID_FLD, OleDbType.Integer));
if (objObject.TransporterID != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.TRANSPORTERID_FLD].Value = objObject.TransporterID;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.TRANSPORTERID_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.VENDORID_FLD, OleDbType.Integer));
if (objObject.VendorID != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.VENDORID_FLD].Value = objObject.VendorID;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.VENDORID_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.ACOBJECTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.ACOBJECTID_FLD].Value = objObject.ACObjectID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.ACPURPOSEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.ACPURPOSEID_FLD].Value = objObject.ACPurposeID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.MAKERID_FLD, OleDbType.Integer));
if (objObject.MakerID != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.MAKERID_FLD].Value = objObject.MakerID;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.MAKERID_FLD].Value = DBNull.Value;
// ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.COSTELEMENTID_FLD, OleDbType.Integer));
// ocmdPCS.Parameters[cst_FreightMasterTable.COSTELEMENTID_FLD].Value = objObject.CostElementID;
//
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.RECEIPTMASTERID_FLD, OleDbType.Integer));
if (objObject.ReceiveMasterID != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.RECEIPTMASTERID_FLD].Value = objObject.ReceiveMasterID;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.RECEIPTMASTERID_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.RETURNTOVENDORMASTERID_FLD, OleDbType.Integer));
if (objObject.ReturnToVendorMasterID != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.RETURNTOVENDORMASTERID_FLD].Value = objObject.ReturnToVendorMasterID;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.RETURNTOVENDORMASTERID_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.GRANDTOTAL_FLD, OleDbType.Decimal));
if (objObject.GrandTotal != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.GRANDTOTAL_FLD].Value = objObject.GrandTotal;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.GRANDTOTAL_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.SUBTOTAL_FLD, OleDbType.Decimal));
if (objObject.SubTotal != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.SUBTOTAL_FLD].Value = objObject.SubTotal;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.SUBTOTAL_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TOTALVAT_FLD, OleDbType.Decimal));
if (objObject.TotalVAT != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.TOTALVAT_FLD].Value = objObject.TotalVAT;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.TOTALVAT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.VATPERCENT_FLD, OleDbType.Decimal));
if (objObject.VATPercent != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.VATPERCENT_FLD].Value = objObject.VATPercent;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.VATPERCENT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.POSTDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[cst_FreightMasterTable.POSTDATE_FLD].Value = objObject.PostDate;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
object objReturnValue = ocmdPCS.ExecuteScalar();
if(objReturnValue != null)
{
return int.Parse(objReturnValue.ToString());
}
else
{
return -1;
}
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from cst_FreightMaster
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + cst_FreightMasterTable.TABLE_NAME + " WHERE " + "FreightMasterID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Get PO detail to freight
/// </summary>
/// <param name="pintPOReceiveMasterID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Friday, Feb 24 2006</date>
public DataSet GetPOReceive(int pintPOReceiveMasterID)
{
const string METHOD_NAME = THIS + ".GetPOReceive()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = " SELECT 0 Line, P.Code, P.ProductID, P.Description, P.Revision, "
+ " UM.Code MST_UnitOfMeasureCode, RD.BuyingUMID, RD.ReceiveQuantity Quantity, "
+ " case RM.ReceiptType when 3 then Invoice.UnitPrice "
+ " when 4 Then PO.UnitPrice when 2 Then PO.UnitPrice End UnitPriceCIF,"
+ " case RM.ReceiptType when 3 then Invoice.ImportTax "
+ " when 4 Then PO.ImportTax when 2 Then PO.ImportTax End ImportTax,"
+ " case RM.ReceiptType when 3 then Invoice.VAT "
+ " when 4 Then PO.VAT when 2 Then PO.VAT End VAT,"
+ " 0.0 Amount, 0.0 VATAmount, 0.0 TotalAmount, "
+ " 0 FreightMasterID, 0 FreightDetailID, RM.PurchaseOrderReceiptID, 0 AdjustmentID, '' TransNo, '' InvoiceNo, 0 InvoiceMasterID,"
+ " RD.PurchaseOrderReceiptDetailID,RM.PurchaseOrderMasterID "
+ " FROM PO_PurchaseOrderReceiptDetail RD INNER JOIN PO_PurchaseOrderReceiptMaster RM "
+ " ON RM.PurchaseOrderReceiptID = RD.PurchaseOrderReceiptID "
+ " INNER JOIN ITM_Product P ON P.ProductID = RD.ProductID "
+ " INNER JOIN MST_UnitOfMeasure UM ON UM.UnitOfMeasureID = RD.BuyingUMID "
+ " Left Join (Select IVD.InvoiceMasterID, DeliveryScheduleID, IVD.UnitPrice,"
+ " IVD.ImportTax, IVD.VAT "
+ " from PO_InvoiceDetail IVD INNER JOIN PO_InvoiceMaster IVM "
+ " ON IVM.InvoiceMasterID = IVD.InvoiceMasterID ) Invoice ON RM.InvoiceMasterID=Invoice.InvoiceMasterID and RD.DeliveryScheduleID=invoice.DeliveryScheduleID "
+ " Left Join (Select UnitPrice,DeliveryScheduleID,PD.PurchaseOrderMasterID, "
+ " PD.ImportTax,PD.VAT from PO_PurchaseOrderDetail PD INNER JOIN PO_PurchaseOrderMaster PM "
+ " ON PD.PurchaseOrderMasterID = PM.PurchaseOrderMasterID "
+ " INNER JOIN PO_DeliverySchedule DS ON PD.PurchaseOrderDetailID = DS.PurchaseOrderDetailID"
+ ") PO ON RM.PurchaseOrderMasterID=PO.PurchaseOrderMasterID and RD.DeliveryScheduleID=PO.DeliveryScheduleID"
+ " WHERE RM.PurchaseOrderReceiptID = " + pintPOReceiveMasterID.ToString();
strSql += " select PM.Code, IM.InvoiceNo from PO_PurchaseOrderReceiptMaster PR "
+ " Left join dbo.PO_PurchaseOrderMaster PM ON PM.PurchaseOrderMasterID = PR.PurchaseOrderMasterID "
+ " Left join dbo.PO_InvoiceMaster IM ON IM.InvoiceMasterID = PR.InvoiceMasterID "
+ " where " + PO_PurchaseOrderReceiptMasterTable.PURCHASEORDERRECEIPTID_FLD + " = " + pintPOReceiveMasterID.ToString();
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, cst_FreightDetailTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from cst_FreightMaster
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// cst_FreightMasterVO
/// </Outputs>
/// <Returns>
/// cst_FreightMasterVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, February 23, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ cst_FreightMasterTable.FREIGHTMASTERID_FLD + ","
+ cst_FreightMasterTable.TRANNO_FLD + ","
+ cst_FreightMasterTable.NOTE_FLD + ","
+ cst_FreightMasterTable.EXCHANGERATE_FLD + ","
+ cst_FreightMasterTable.TOTALAMOUNT_FLD + ","
+ cst_FreightMasterTable.CCNID_FLD + ","
+ cst_FreightMasterTable.CURRENCYID_FLD + ","
+ cst_FreightMasterTable.TRANSPORTERID_FLD + ","
+ cst_FreightMasterTable.VENDORID_FLD + ","
// + cst_FreightMasterTable.COSTELEMENTID_FLD + ","
+ cst_FreightMasterTable.RECEIPTMASTERID_FLD + ","
+ cst_FreightMasterTable.GRANDTOTAL_FLD + ","
+ cst_FreightMasterTable.SUBTOTAL_FLD + ","
+ cst_FreightMasterTable.TOTALVAT_FLD + ","
+ cst_FreightMasterTable.VATPERCENT_FLD + ","
+ cst_FreightMasterTable.POSTDATE_FLD
+ " FROM " + cst_FreightMasterTable.TABLE_NAME
+" WHERE " + cst_FreightMasterTable.FREIGHTMASTERID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
cst_FreightMasterVO objObject = new cst_FreightMasterVO();
while (odrPCS.Read())
{
objObject.FreightMasterID = int.Parse(odrPCS[cst_FreightMasterTable.FREIGHTMASTERID_FLD].ToString().Trim());
objObject.TranNo = odrPCS[cst_FreightMasterTable.TRANNO_FLD].ToString().Trim();
if (odrPCS[cst_FreightMasterTable.NOTE_FLD] != DBNull.Value)
{
objObject.Note = odrPCS[cst_FreightMasterTable.NOTE_FLD].ToString().Trim();
}
else objObject.Note = string.Empty;
objObject.ExchangeRate = Decimal.Parse(odrPCS[cst_FreightMasterTable.EXCHANGERATE_FLD].ToString().Trim());
objObject.TotalAmount = Decimal.Parse(odrPCS[cst_FreightMasterTable.TOTALAMOUNT_FLD].ToString().Trim());
objObject.CCNID = int.Parse(odrPCS[cst_FreightMasterTable.CCNID_FLD].ToString().Trim());
objObject.CurrencyID = int.Parse(odrPCS[cst_FreightMasterTable.CURRENCYID_FLD].ToString().Trim());
objObject.TransporterID = int.Parse(odrPCS[cst_FreightMasterTable.TRANSPORTERID_FLD].ToString().Trim());
objObject.VendorID = int.Parse(odrPCS[cst_FreightMasterTable.VENDORID_FLD].ToString().Trim());
// objObject.CostElementID = int.Parse(odrPCS[cst_FreightMasterTable.COSTELEMENTID_FLD].ToString().Trim());
objObject.ReceiveMasterID = int.Parse(odrPCS[cst_FreightMasterTable.RECEIPTMASTERID_FLD].ToString().Trim());
objObject.GrandTotal = Decimal.Parse(odrPCS[cst_FreightMasterTable.GRANDTOTAL_FLD].ToString().Trim());
objObject.SubTotal = Decimal.Parse(odrPCS[cst_FreightMasterTable.SUBTOTAL_FLD].ToString().Trim());
if (odrPCS[cst_FreightMasterTable.TOTALVAT_FLD] != DBNull.Value)
{
objObject.TotalVAT = Decimal.Parse(odrPCS[cst_FreightMasterTable.TOTALVAT_FLD].ToString().Trim());
}
else objObject.TotalVAT = 0;
if (odrPCS[cst_FreightMasterTable.VATPERCENT_FLD] != DBNull.Value)
{
objObject.VATPercent = Decimal.Parse(odrPCS[cst_FreightMasterTable.VATPERCENT_FLD].ToString().Trim());
}
else objObject.VATPercent = 0;
objObject.PostDate = DateTime.Parse(odrPCS[cst_FreightMasterTable.POSTDATE_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to cst_FreightMaster
/// </Description>
/// <Inputs>
/// cst_FreightMasterVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
cst_FreightMasterVO objObject = (cst_FreightMasterVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE cst_FreightMaster SET "
+ cst_FreightMasterTable.TRANNO_FLD + "= ?" + ","
+ cst_FreightMasterTable.NOTE_FLD + "= ?" + ","
+ cst_FreightMasterTable.EXCHANGERATE_FLD + "= ?" + ","
+ cst_FreightMasterTable.TOTALAMOUNT_FLD + "= ?" + ","
+ cst_FreightMasterTable.CCNID_FLD + "= ?" + ","
+ cst_FreightMasterTable.CURRENCYID_FLD + "= ?" + ","
+ cst_FreightMasterTable.TRANSPORTERID_FLD + "= ?" + ","
+ cst_FreightMasterTable.VENDORID_FLD + "= ?" + ","
+ cst_FreightMasterTable.MAKERID_FLD + " = ?,"
+ cst_FreightMasterTable.ACOBJECTID_FLD + "= ?" + ","
+ cst_FreightMasterTable.ACPURPOSEID_FLD + "= ?" + ","
// + cst_FreightMasterTable.COSTELEMENTID_FLD + "= ?" + ","
+ cst_FreightMasterTable.RECEIPTMASTERID_FLD + "= ?" + ","
+ cst_FreightMasterTable.GRANDTOTAL_FLD + "= ?" + ","
+ cst_FreightMasterTable.SUBTOTAL_FLD + "= ?" + ","
+ cst_FreightMasterTable.TOTALVAT_FLD + "= ?" + ","
+ cst_FreightMasterTable.VATPERCENT_FLD + "= ?" + ","
+ cst_FreightMasterTable.POSTDATE_FLD + "= ?"
+" WHERE " + cst_FreightMasterTable.FREIGHTMASTERID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TRANNO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[cst_FreightMasterTable.TRANNO_FLD].Value = objObject.TranNo;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.NOTE_FLD, OleDbType.WChar));
if (objObject.Note != null)
{
ocmdPCS.Parameters[cst_FreightMasterTable.NOTE_FLD].Value = objObject.Note;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.NOTE_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.EXCHANGERATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TOTALAMOUNT_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.TOTALAMOUNT_FLD].Value = objObject.TotalAmount;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.CURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.CURRENCYID_FLD].Value = objObject.CurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TRANSPORTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.TRANSPORTERID_FLD].Value = objObject.TransporterID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.VENDORID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.VENDORID_FLD].Value = objObject.VendorID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.MAKERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.MAKERID_FLD].Value = objObject.MakerID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.ACOBJECTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.ACOBJECTID_FLD].Value = objObject.ACObjectID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.ACPURPOSEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.ACPURPOSEID_FLD].Value = objObject.ACPurposeID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.RECEIPTMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.RECEIPTMASTERID_FLD].Value = objObject.ReceiveMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.GRANDTOTAL_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.GRANDTOTAL_FLD].Value = objObject.GrandTotal;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.SUBTOTAL_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[cst_FreightMasterTable.SUBTOTAL_FLD].Value = objObject.SubTotal;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.TOTALVAT_FLD, OleDbType.Decimal));
if (objObject.TotalVAT != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.TOTALVAT_FLD].Value = objObject.TotalVAT;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.TOTALVAT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.VATPERCENT_FLD, OleDbType.Decimal));
if (objObject.VATPercent != 0)
{
ocmdPCS.Parameters[cst_FreightMasterTable.VATPERCENT_FLD].Value = objObject.VATPercent;
}
else
ocmdPCS.Parameters[cst_FreightMasterTable.VATPERCENT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.POSTDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[cst_FreightMasterTable.POSTDATE_FLD].Value = objObject.PostDate;
ocmdPCS.Parameters.Add(new OleDbParameter(cst_FreightMasterTable.FREIGHTMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[cst_FreightMasterTable.FREIGHTMASTERID_FLD].Value = objObject.FreightMasterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from cst_FreightMaster
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, February 23, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ cst_FreightMasterTable.FREIGHTMASTERID_FLD + ","
+ cst_FreightMasterTable.TRANNO_FLD + ","
+ cst_FreightMasterTable.NOTE_FLD + ","
+ cst_FreightMasterTable.EXCHANGERATE_FLD + ","
+ cst_FreightMasterTable.TOTALAMOUNT_FLD + ","
+ cst_FreightMasterTable.CCNID_FLD + ","
+ cst_FreightMasterTable.CURRENCYID_FLD + ","
+ cst_FreightMasterTable.TRANSPORTERID_FLD + ","
+ cst_FreightMasterTable.VENDORID_FLD + ","
// + cst_FreightMasterTable.COSTELEMENTID_FLD + ","
+ cst_FreightMasterTable.RECEIPTMASTERID_FLD + ","
+ cst_FreightMasterTable.GRANDTOTAL_FLD + ","
+ cst_FreightMasterTable.SUBTOTAL_FLD + ","
+ cst_FreightMasterTable.TOTALVAT_FLD + ","
+ cst_FreightMasterTable.VATPERCENT_FLD + ","
+ cst_FreightMasterTable.POSTDATE_FLD
+ " FROM " + cst_FreightMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,cst_FreightMasterTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// GetInvoice_PONumber
/// </summary>
/// <param name="pintReturnToVendorMasterID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Thursday, July 6 2006</date>
public DataSet GetInvoice_PONumber(int pintReturnToVendorMasterID)
{
const string METHOD_NAME = THIS + ".GetInvoice_PONumber()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ " IM.InvoiceNo, PM.Code "
+ " from PO_ReturnToVendorMaster RM "
+ " left join PO_PurchaseOrderMaster PM "
+ " ON PM.PurchaseOrderMasterID = RM.PurchaseOrderMasterID "
+ " left join PO_InvoiceMaster IM "
+ " ON IM.InvoiceMasterID = RM.InvoiceMasterID "
+ " Where RM." + PO_ReturnToVendorMasterTable.RETURNTOVENDORMASTERID_FLD + " = " + pintReturnToVendorMasterID.ToString();
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,cst_FreightMasterTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// List Freight Master by ID
/// </summary>
/// <param name="pintFreightMasterID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Tuesday, Feb 28 2006</date>
public DataTable ListMasterByID(int pintFreightMasterID)
{
const string METHOD_NAME = THIS + ".ListMasterByID()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ " FM." + cst_FreightMasterTable.FREIGHTMASTERID_FLD + ","
+ " FM." + cst_FreightMasterTable.TRANNO_FLD + ","
+ " FM." + cst_FreightMasterTable.NOTE_FLD + ","
+ " FM." + cst_FreightMasterTable.EXCHANGERATE_FLD + ","
+ " FM." + cst_FreightMasterTable.TOTALAMOUNT_FLD + ","
+ " FM." + cst_FreightMasterTable.CCNID_FLD + ","
+ " FM." + cst_FreightMasterTable.CURRENCYID_FLD + ","
+ " FM." + cst_FreightMasterTable.TRANSPORTERID_FLD + ","
+ " FM." + cst_FreightMasterTable.VENDORID_FLD + ","
+ "FM.MakerID,"
+ " PM.Code PONo,"
+ " IM." + PO_InvoiceMasterTable.INVOICENO_FLD + ","
+ " FM." + cst_FreightMasterTable.ACOBJECTID_FLD + ","
+ " FM." + cst_FreightMasterTable.ACPURPOSEID_FLD + ","
// + " FM." + cst_FreightMasterTable.COSTELEMENTID_FLD + ","
+ " FM." + cst_FreightMasterTable.RECEIPTMASTERID_FLD + ","
+ " FM." + cst_FreightMasterTable.RETURNTOVENDORMASTERID_FLD + ","
+ " FM." + cst_FreightMasterTable.GRANDTOTAL_FLD + ","
+ " FM." + cst_FreightMasterTable.SUBTOTAL_FLD + ","
+ " FM." + cst_FreightMasterTable.TOTALVAT_FLD + ","
+ " FM." + cst_FreightMasterTable.VATPERCENT_FLD + ","
+ " CR." + MST_CurrencyTable.CODE_FLD + Constants.WHITE_SPACE + MST_CurrencyTable.TABLE_NAME + MST_CurrencyTable.CODE_FLD + " ,"
+ " V." + MST_PartyTable.CODE_FLD + Constants.WHITE_SPACE + " VendorCode,"
//+ " CE." + STD_CostElementTable.CODE_FLD + Constants.WHITE_SPACE + STD_CostElementTable.TABLE_NAME + STD_CostElementTable.CODE_FLD + ","
+ " V." + MST_PartyTable.NAME_FLD + Constants.WHITE_SPACE + " VendorName,"
+ " T." + MST_PartyTable.CODE_FLD + Constants.WHITE_SPACE + " TransporterCode,"
+ " T." + MST_PartyTable.NAME_FLD + Constants.WHITE_SPACE + " TransporterName,"
+ " MK.Name MakerName, MK.Code MakerCode, FM.ACObjectID, OB.Description OBDes, "
+ " FM.ACPurposeID, PU.Description PUDes, "
+ " PRM." + PO_PurchaseOrderReceiptMasterTable.RECEIVENO_FLD + ","
+ " RVM." + PO_ReturnToVendorMasterTable.RTVNO_FLD + ","
+ " FM." + cst_FreightMasterTable.POSTDATE_FLD
+ " FROM " + cst_FreightMasterTable.TABLE_NAME + " FM"
+ " INNER JOIN " + MST_CurrencyTable.TABLE_NAME + " CR ON FM."
+ cst_FreightMasterTable.CURRENCYID_FLD + " = " + " CR." + MST_CurrencyTable.CURRENCYID_FLD
+ " LEFT JOIN " + MST_PartyTable.TABLE_NAME + " V ON FM."
+ cst_FreightMasterTable.VENDORID_FLD + " = " + " V." + MST_PartyTable.PARTYID_FLD
+ " LEFT JOIN " + MST_PartyTable.TABLE_NAME + " T ON FM."
+ cst_FreightMasterTable.TRANSPORTERID_FLD + " = " + " T." + MST_PartyTable.PARTYID_FLD
+ " LEFT JOIN " + MST_PartyTable.TABLE_NAME + " MK ON FM."
+ "MakerID" + " = " + " MK." + MST_PartyTable.PARTYID_FLD
+ " INNER JOIN " + "enm_ACObject" + " OB ON FM."
+ "ACObjectID" + " = " + " OB.ACObjectID "
+ " INNER JOIN " + "enm_ACPurpose" + " PU ON FM."
+ "ACPurposeID" + " = " + " PU.ACPurposeID"
+ " LEFT JOIN " + PO_PurchaseOrderReceiptMasterTable.TABLE_NAME + " PRM ON FM."
+ cst_FreightMasterTable.RECEIPTMASTERID_FLD + " = " + " PRM." + PO_PurchaseOrderReceiptMasterTable.PURCHASEORDERRECEIPTID_FLD
+ " LEFT JOIN " + PO_ReturnToVendorMasterTable.TABLE_NAME + " RVM ON FM."
+ cst_FreightMasterTable.RETURNTOVENDORMASTERID_FLD + " = " + " RVM." + PO_ReturnToVendorMasterTable.RETURNTOVENDORMASTERID_FLD
+ " LEFT JOIN PO_PurchaseOrderMaster PM ON PRM.PurchaseOrderMasterID = PM.PurchaseOrderMasterID "
+ " LEFT JOIN dbo.PO_InvoiceMaster IM ON IM.InvoiceMasterID = PRM.InvoiceMasterID "
+ " WHERE " + cst_FreightMasterTable.FREIGHTMASTERID_FLD + " = " + pintFreightMasterID.ToString();
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,cst_FreightMasterTable.TABLE_NAME);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, February 23, 2006
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ cst_FreightMasterTable.FREIGHTMASTERID_FLD + ","
+ cst_FreightMasterTable.TRANNO_FLD + ","
+ cst_FreightMasterTable.NOTE_FLD + ","
+ cst_FreightMasterTable.EXCHANGERATE_FLD + ","
+ cst_FreightMasterTable.TOTALAMOUNT_FLD + ","
+ cst_FreightMasterTable.CCNID_FLD + ","
+ cst_FreightMasterTable.CURRENCYID_FLD + ","
+ cst_FreightMasterTable.TRANSPORTERID_FLD + ","
+ cst_FreightMasterTable.VENDORID_FLD + ","
// + cst_FreightMasterTable.COSTELEMENTID_FLD + ","
+ cst_FreightMasterTable.RECEIPTMASTERID_FLD + ","
+ cst_FreightMasterTable.GRANDTOTAL_FLD + ","
+ cst_FreightMasterTable.SUBTOTAL_FLD + ","
+ cst_FreightMasterTable.TOTALVAT_FLD + ","
+ cst_FreightMasterTable.VATPERCENT_FLD + ","
+ cst_FreightMasterTable.POSTDATE_FLD
+ " FROM " + cst_FreightMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,cst_FreightMasterTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if(ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
// using System.Threading.Tasks;
using NUnit.Framework;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentDictionaryTests : AssertionHelper
{
/*
[Test]
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);
}
*/
/*
[Test]
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.AreEqual(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.AreEqual(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.AreEqual(expectedCount, dict.Count);
Assert.AreEqual(expectedCount, dictConcurrent.ToArray().Length);
}
*/
/*
[Test]
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.AreEqual(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.AreEqual(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)
);
}
}
*/
/*
[Test]
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))
{
if (j % 2 == 1 || j != val)
{
Console.WriteLine("* TestRead1(cLevel={0}, threads={1}, readsPerThread={2})", cLevel, threads, readsPerThread);
Assert.False(true, " > FAILED. Invalid element in the dictionary.");
}
}
else
{
if (j % 2 == 0)
{
Console.WriteLine("* TestRead1(cLevel={0}, threads={1}, readsPerThread={2})", cLevel, threads, readsPerThread);
Assert.False(true, " > FAILED. Element missing from the dictionary");
}
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
}
*/
/*
[Test]
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.AreEqual(-key, value);
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.AreEqual(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.AreEqual(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.AreEqual(expectKeys.Count, dict.Count);
Assert.AreEqual(expectKeys.Count, dict.ToArray().Length);
}
*/
/*
[Test]
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.AreEqual(-key, value);
}
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
Assert.AreEqual(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)
);
}
}
*/
[Test]
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.AreEqual(0, dict.Count);
Assert.AreEqual(0, dict.ToArray().Length);
}
/*
[Test]
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);
}
[Test]
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.AreEqual(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.AreEqual(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.AreEqual(addsPerThread, dict.Count);
Assert.AreEqual(addsPerThread, dict.ToArray().Length);
}
*/
[Test]
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;
}
}
[Test]
public static void TestConstructor()
{
var dictionary = new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) });
Assert.False(dictionary.IsEmpty);
Assert.AreEqual(1, dictionary.Keys.Count);
Assert.AreEqual(1, dictionary.Values.Count);
}
/*
[Test]
public static void TestDebuggerAttributes()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentDictionary<string, int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ConcurrentDictionary<string, int>());
}
*/
[Test]
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");
}
[Test]
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");
}
[Test]
public static void TestIDictionary()
{
IDictionary dictionary = new ConcurrentDictionary<string, int>();
Assert.False(dictionary.IsReadOnly);
foreach (var entry in dictionary)
{
Assert.False(true, "TestIDictionary: FAILED. GetEnumerator retuned items when the dictionary is empty");
}
const int SIZE = 10;
for (int i = 0; i < SIZE; i++)
dictionary.Add(i.ToString(), i);
Assert.AreEqual(SIZE, dictionary.Count);
//test contains
Assert.False(dictionary.Contains(1), "TestIDictionary: FAILED. Contain retuned true for incorrect key type");
Assert.False(dictionary.Contains("100"), "TestIDictionary: FAILED. Contain retuned true for incorrect key");
Assert.True(dictionary.Contains("1"), "TestIDictionary: FAILED. Contain retuned 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.AreEqual(SIZE, count);
Assert.AreEqual(SIZE, dictionary.Keys.Count);
Assert.AreEqual(SIZE, dictionary.Values.Count);
//Test Remove
dictionary.Remove("9");
Assert.AreEqual(SIZE - 1, dictionary.Count);
//Test this[]
for (int i = 0; i < dictionary.Count; i++)
Assert.AreEqual(i, (int)dictionary[i.ToString()]);
dictionary["1"] = 100; // try a valid setter
Assert.AreEqual(100, (int)dictionary["1"]);
//nonsexist key
Assert.Null(dictionary["NotAKey"]);
}
[Test]
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");
}
[Test]
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.AreEqual(key, ((KeyValuePair<int, int>)objectArray[0]).Key);
Assert.AreEqual(value, ((KeyValuePair<int, int>)objectArray[0]).Value);
var keyValueArray = new KeyValuePair<int, int>[1];
dictionary.CopyTo(keyValueArray, 0);
Assert.AreEqual(key, keyValueArray[0].Key);
Assert.AreEqual(value, keyValueArray[0].Value);
var entryArray = new DictionaryEntry[1];
dictionary.CopyTo(entryArray, 0);
Assert.AreEqual(key, (int)entryArray[0].Key);
Assert.AreEqual(value, (int)entryArray[0].Value);
}
[Test]
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");
}
[Test]
public static void TestClear()
{
var dictionary = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
dictionary.TryAdd(i, i);
Assert.AreEqual(10, dictionary.Count);
dictionary.Clear();
Assert.AreEqual(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.AreEqual(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
}
}
| |
#region Apache Notice
/*****************************************************************************
*
* Castle.MVC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
#region Autors
/************************************************
* Gilles Bayon
*************************************************/
#endregion
#region Using
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Xml;
#endregion
namespace Castle.MVC.Configuration
{
/// <summary>
/// MVCConfigSettings.
/// </summary>
public class MVCConfigSettings
{
#region Const
/// <summary>
/// Token to retrieve configuration node
/// </summary>
private const string NODE_WEB_VIEW_XPATH = "webViews/view";
private const string NODE_WIN_VIEW_XPATH = "winViews/view";
private const string ATTRIBUTE_ID = "id";
private const string ATTRIBUTE_VIEW = "view";
private const string ATTRIBUTE_PATH = "path";
private const string ATTRIBUTE_TYPE = "type";
private const string NODE_COMMANDS_XPATH = "command-mappings/commands";
private const string NODE_GLOBAL_COMMANDS_XPATH = "global-commands/command";
#endregion
#region Fields
private StringDictionary _urls = new StringDictionary();
private StringDictionary _webViews= new StringDictionary();
private HybridDictionary _types = new HybridDictionary();
private HybridDictionary _winViews= new HybridDictionary();
private HybridDictionary _mappings = new HybridDictionary();
private StringDictionary _globalCommands = new StringDictionary();
#endregion
#region Constructor
/// <summary>
/// Creates MVCConfigSettings from an XmlNode read of the web.config and an IFormatProvider.
/// </summary>
/// <param name="configNode">The XmlNode from the configuration file.</param>
/// <param name="formatProvider">The provider.</param>
public MVCConfigSettings(XmlNode configNode, IFormatProvider formatProvider)
{
LoadWebViews(configNode, formatProvider);
LoadWinViews(configNode, formatProvider);
LoadGlobalCommand(configNode);
LoadCommandMapping(configNode);
}
#endregion
#region Methods
/// <summary>
/// Load the global commands
/// </summary>
/// <param name="configNode">The XmlNode from the configuration file.</param>
private void LoadGlobalCommand(XmlNode configNode)
{
foreach(XmlNode commandNode in configNode.SelectNodes( NODE_GLOBAL_COMMANDS_XPATH ) )
{
string id = commandNode.Attributes[ATTRIBUTE_ID].Value;
string view = commandNode.Attributes[ATTRIBUTE_VIEW].Value;
_globalCommands.Add( id, view );
}
}
/// <summary>
/// Load the command mapping
/// </summary>
/// <param name="configNode">The XmlNode from the configuration file.</param>
private void LoadCommandMapping(XmlNode configNode)
{
foreach( XmlNode currentNode in configNode.SelectNodes( NODE_COMMANDS_XPATH ) )
{
CommandsSetting setting = new CommandsSetting( currentNode );
_mappings.Add( setting.View, setting );
}
}
/// <summary>
/// Load the views
/// </summary>
/// <param name="configNode">The XmlNode from the configuration file.</param>
/// <param name="formatProvider">The provider.</param>
private void LoadWebViews(XmlNode configNode, IFormatProvider formatProvider)
{
//Get the views
foreach( XmlNode viewNode in configNode.SelectNodes( NODE_WEB_VIEW_XPATH ) )
{
string viewName = viewNode.Attributes[ATTRIBUTE_ID].Value;
string viewUrl = viewNode.Attributes[ATTRIBUTE_PATH].Value;
if( !_webViews.ContainsKey( viewName ) )
{
_urls.Add( viewName, viewUrl );
_webViews.Add( viewUrl, viewName );
}
else
{
throw new ConfigurationException( Resource.ResourceManager.FormatMessage( Resource.MessageKeys.ViewAlreadyConfigured, viewName ) );
}
}
}
/// <summary>
/// Load the windows views
/// </summary>
/// <param name="configNode">The XmlNode from the configuration file.</param>
/// <param name="formatProvider">The provider.</param>
private void LoadWinViews(XmlNode configNode, IFormatProvider formatProvider)
{
//Get the views
foreach( XmlNode viewNode in configNode.SelectNodes( NODE_WIN_VIEW_XPATH ) )
{
string viewId = viewNode.Attributes[ATTRIBUTE_ID].Value;
string viewType = viewNode.Attributes[ATTRIBUTE_TYPE].Value;
// infer type from viewType
Type type = null;
if( !_winViews.Contains( type ) )
{
_types.Add( viewId, type );
//_winViews.Add( type, viewId );
}
else
{
throw new ConfigurationException( Resource.ResourceManager.FormatMessage( Resource.MessageKeys.ViewAlreadyConfigured, viewId ) );
}
}
}
///<summary>
///Looks up a url view based on view name.
///</summary>
///<param name="viewName">The name of the view to retrieve the settings for.</param>
public virtual string GetUrl( string viewName )
{
return _urls[viewName] as string;
}
///<summary>
/// Looks up a web view based on his url.
///</summary>
///<param name="url">The URL.</param>
public virtual string GetView(string url)
{
return _webViews[url] as string;
}
///<summary>
/// Looks up a windows view based on his type.
///</summary>
///<param name="type">The view type.</param>
public virtual string GetView(Type type)
{
return _winViews[type] as string;
}
///<summary>
///Looks up a next view based on current command id and and current view id.
///</summary>
///<param name="commandID">The id of the current command.</param>
///<param name="viewID">The id of the current view.</param>
///<returns>The next web view to go.</returns>
public virtual string GetNextView(string viewID, string commandID)
{
string nextView = string.Empty;
if (_globalCommands.ContainsKey(commandID))
{
nextView = _globalCommands[commandID];
}
else
{
CommandsSetting setting= null;
if( _mappings.Contains( viewID ) )
{
setting = _mappings[viewID] as CommandsSetting;
}
else
{
throw new ConfigurationException( Resource.ResourceManager.FormatMessage( Resource.MessageKeys.CantFindCommandMapping, viewID ) );
}
nextView = setting[commandID];
if( nextView==null )
{
throw new ConfigurationException( Resource.ResourceManager.FormatMessage( Resource.MessageKeys.CantGetNextView, viewID, commandID ) );
}
}
return nextView;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Dns.Fluent
{
using ResourceManager.Fluent.Core;
using Models;
/// <summary>
/// Represents an record set collection associated with a DNS zone.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmRucy5pbXBsZW1lbnRhdGlvbi5EbnNSZWNvcmRTZXRzSW1wbA==
internal partial class DnsRecordSetsImpl :
ExternalChildResourcesNonCached<DnsRecordSetImpl, IDnsRecordSet, RecordSetInner, IDnsZone, DnsZoneImpl>
{
private const long defaultTtlInSeconds = 3600;
/// <summary>
/// Creates new DnsRecordSetsImpl.
/// </summary>
/// <param name="parent">The parent DNS zone of the record set.</param>
///GENMHASH:679769A0C3AB0DC0D68CC67BCE854713:D191C7503BF1FFF7DC0169944F6D7D1D
internal DnsRecordSetsImpl(DnsZoneImpl parent)
: base(parent, "RecordSet")
{
}
///GENMHASH:76F011335BBB78AE07E7C19B287C17C2:EC4740AE1730815931674A743CFA405F
internal DnsRecordSetImpl DefineAaaaRecordSet(string name)
{
return this.SetDefaults(base.PrepareDefine(AaaaRecordSetImpl.NewRecordSet(name, Parent)));
}
///GENMHASH:11F6C7A282BFB4C2631CAE48D9B23761:26D2A37A37D05787C741D51B51540036
internal DnsRecordSetImpl DefineARecordSet(string name)
{
return this.SetDefaults(base.PrepareDefine(ARecordSetImpl.NewRecordSet(name, Parent)));
}
///GENMHASH:0E653C21FA610AD7BE55F29A75505790:FE5E8EB27FB4ABCF6536E14AAC77C56A
internal DnsRecordSetImpl DefineCaaRecordSet(string name)
{
return this.SetDefaults(base.PrepareDefine(CaaRecordSetImpl.NewRecordSet(name, Parent)));
}
///GENMHASH:D5078976D64C68B60845416B4A519771:63D1257FE4C4E0A90A6B61D62E75B243
internal DnsRecordSetImpl DefineCNameRecordSet(string name)
{
return this.SetDefaults(base.PrepareDefine(CNameRecordSetImpl.NewRecordSet(name, this.Parent)));
}
///GENMHASH:7FD0DE0CD548F2703A15E4BAA97D6873:F89F3B1F2BD56AF43A4D34802A0631E2
internal DnsRecordSetImpl DefineMXRecordSet(string name)
{
return this.SetDefaults(base.PrepareDefine(MXRecordSetImpl.NewRecordSet(name, Parent)));
}
///GENMHASH:46C9C87DA2C900034A20B7DB46BD77F5:8BB7B2E82DEC8CA3D4E4D604C40FDD15
internal DnsRecordSetImpl DefineNSRecordSet(string name)
{
return this.SetDefaults(base.PrepareDefine(NSRecordSetImpl.NewRecordSet(name, Parent)));
}
///GENMHASH:33CE6A50234E86DD2006E428BDBB63DF:2DFEFB602FB64D29979A84CF65A69C61
internal DnsRecordSetImpl DefinePtrRecordSet(string name)
{
return this.SetDefaults(base.PrepareDefine(PtrRecordSetImpl.NewRecordSet(name, Parent)));
}
///GENMHASH:9AB7664BD0C8EE192BC61FD76EFCAF87:EEDBF02FD0C3468E6C240E4B90603434
internal DnsRecordSetImpl DefineSrvRecordSet(string name)
{
return this.SetDefaults(base.PrepareDefine(SrvRecordSetImpl.NewRecordSet(name, Parent)));
}
///GENMHASH:6CCAD6D4D3A8F0925655956402A80C0F:97C26A4AE31E04D6392CA1F0ED41B303
internal DnsRecordSetImpl DefineTxtRecordSet(string name)
{
return this.SetDefaults(base.PrepareDefine(TxtRecordSetImpl.NewRecordSet(name, Parent)));
}
///GENMHASH:19FB56D67F1C3171819C68171374B827:FD0DE8482528744FFBB05D150412A8E3
internal DnsRecordSetImpl UpdateAaaaRecordSet(string name)
{
return base.PrepareUpdate(AaaaRecordSetImpl.NewRecordSet(name, Parent));
}
///GENMHASH:DEFDD202FC66399CE6F4DC2385FFBE4E:2EF7C751D386980613D0960A28E45B96
internal DnsRecordSetImpl UpdateARecordSet(string name)
{
return base.PrepareUpdate(ARecordSetImpl.NewRecordSet(name, Parent));
}
///GENMHASH:4DD4D85C5B408CD0398C0BFCDACCFC59:E939DA7F66049CE24B893A2AF4A5AE45
internal DnsRecordSetImpl UpdateCaaRecordSet(string name)
{
return base.PrepareUpdate(CaaRecordSetImpl.NewRecordSet(name, this.Parent));
}
///GENMHASH:4F52CFFC8EB4D698DB3A4C3B1E187BD0:E3BD08E5FE933A570B0B4BECAAB8332D
internal DnsRecordSetImpl UpdateCNameRecordSet(string name)
{
return this.PrepareUpdate(CNameRecordSetImpl.NewRecordSet(name, this.Parent));
}
///GENMHASH:5CC95DD8B9468242DBEEF10F96E9EECF:1DBE6FD5118017062E44D7FD1F4DC7CC
internal DnsRecordSetImpl UpdateMXRecordSet(string name)
{
return base.PrepareUpdate(MXRecordSetImpl.NewRecordSet(name, Parent));
}
///GENMHASH:CC4422F1AB1A272DA6DBEBD9DD8767DF:C631BFEF9752170EDB60599311ACE154
internal DnsRecordSetImpl UpdateNSRecordSet(string name)
{
return base.PrepareUpdate(NSRecordSetImpl.NewRecordSet(name, Parent));
}
///GENMHASH:52729C9C39AC4D628145F797BF5100E5:1B2A4B5E7066BFD0B85818CC859F0757
internal DnsRecordSetImpl UpdatePtrRecordSet(string name)
{
return base.PrepareUpdate(PtrRecordSetImpl.NewRecordSet(name, Parent));
}
///GENMHASH:307087E2D68C3C7331CD91AE28C42489:C114B58978EA69D660C2EF5281A61567
internal DnsRecordSetImpl UpdateSoaRecordSet()
{
return base.PrepareUpdate(SoaRecordSetImpl.NewRecordSet(Parent));
}
///GENMHASH:22B43E023856C663DE5242D855A7FD7E:19CC40D60B6231A8B9D359AFC62E9389
internal DnsRecordSetImpl UpdateSrvRecordSet(string name)
{
return base.PrepareUpdate(SrvRecordSetImpl.NewRecordSet(name, Parent));
}
///GENMHASH:62675C05A328D2B3015CB3D2B125891F:1D57A12FB408D4A35683D2515C9C02C6
internal DnsRecordSetImpl UpdateTxtRecordSet(string name)
{
return base.PrepareUpdate(TxtRecordSetImpl.NewRecordSet(name, Parent));
}
///GENMHASH:1F806E4CBC9AF647A64C1631E4524D83:4EE852CE78913BB7BC91F609C38B4650
internal void WithCNameRecordSet(string name, string alias)
{
CNameRecordSetImpl recordSet = CNameRecordSetImpl.NewRecordSet(name, Parent);
recordSet.Inner.CnameRecord.Cname = alias;
this.SetDefaults(base.PrepareDefine(recordSet.WithTimeToLive(defaultTtlInSeconds)));
}
///GENMHASH:762F03CE80F4A9BF3ADBEEC0D41DB5AF:3D390F3CC05AF82A3E866C7ED3823AC5
internal void WithoutAaaaRecordSet(string name, string eTagValue)
{
base.PrepareRemove(AaaaRecordSetImpl.NewRecordSet(name, Parent).WithETagOnDelete(eTagValue));
}
///GENMHASH:B52E7C54A2094CF7BC537D1CC67AD933:780F5F6769B115A637D6C4C0A4B5A95A
internal void WithoutARecordSet(string name, string eTagValue)
{
base.PrepareRemove(ARecordSetImpl.NewRecordSet(name, Parent).WithETagOnDelete(eTagValue));
}
///GENMHASH:E515F51C44205F030312A4B9FE9FFF71:F7C62765B0EF2651B439940EDD72D30A
internal void WithoutCaaRecordSet(string name, string eTagValue)
{
base.PrepareRemove(CaaRecordSetImpl.NewRecordSet(name, this.Parent).WithETagOnDelete(eTagValue));
}
///GENMHASH:69DD1218436902CDC3B7BC8695982064:0C6A030D75273122C7F8AE8A8B9F2610
internal void WithoutCNameRecordSet(string name, string eTagValue)
{
this.PrepareRemove(CNameRecordSetImpl.NewRecordSet(name, Parent).WithETagOnDelete(eTagValue));
}
///GENMHASH:CAE11DD729AC8148C1BB19AC98C19A66:D19AA3E93E28C2680A74EF50A8D6D4BB
internal void WithoutMXRecordSet(string name, string eTagValue)
{
base.PrepareRemove(MXRecordSetImpl.NewRecordSet(name, Parent).WithETagOnDelete(eTagValue));
}
///GENMHASH:0A638BEAEF3AE7294B3373C1072B1E0A:E4015679DD5DAB294A7133C7CED1679D
internal void WithoutNSRecordSet(string name, string eTagValue)
{
this.PrepareRemove(NSRecordSetImpl.NewRecordSet(name, Parent).WithETagOnDelete(eTagValue));
}
///GENMHASH:C9A7146C9B1311BD2295FF461FD54E80:0BFB0327C156B42E021F2B7B7D954718
internal void WithoutPtrRecordSet(string name, string eTagValue)
{
base.PrepareRemove(PtrRecordSetImpl.NewRecordSet(name, Parent).WithETagOnDelete(eTagValue));
}
///GENMHASH:EC620CE3EF72DD020734D0F57C7057F2:FE30C4C19C12B6680207B4A1C6F7E5E3
internal void WithoutSrvRecordSet(string name, string eTagValue)
{
base.PrepareRemove(SrvRecordSetImpl.NewRecordSet(name, Parent).WithETagOnDelete(eTagValue));
}
///GENMHASH:2AAD8D85A395EE1384B1E0A6010A750B:9F2576B17FCE81461B0CABD653D22294
internal void WithoutTxtRecordSet(string name, string eTagValue)
{
base.PrepareRemove(TxtRecordSetImpl.NewRecordSet(name, this.Parent).WithETagOnDelete(eTagValue));
}
///GENMHASH:EDB813BC169498B6DE770C4D9858547C:D7878BB646FC3265F12A85E42D5F6FB5
private DnsRecordSetImpl SetDefaults(DnsRecordSetImpl recordSet)
{
return recordSet.WithTimeToLive(defaultTtlInSeconds);
}
internal void ClearPendingOperations()
{
this.collection.Clear();
}
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* Feb., 2016, @imzhenyu (Zhenyu Guo), done in Tron project and copied here
* xxxx-xx-xx, author, fix bug about xxx
*/
using System;
using System.Collections.Generic;
using System.IO;
namespace rDSN.Tron.Contract
{
public enum ConsistencyLevel
{
Any,
Eventual,
Causal,
Strong // Primary-backup or Quorum
}
public enum PartitionType
{
None,
Fixed,
Dynamic
}
public class ServiceProperty
{
/// <summary>
/// whether the service needs to be deployed by our infrastructure, or it is an existing service that we can invoke directly
/// </summary>
public bool? IsDeployedAlready { get; set; }
/// <summary>
/// whether the service is a primtive service or a service composed in TRON
/// </summary>
public bool? IsPrimitive { get; set; }
/// <summary>
/// whether the service is partitioned and will be deployed on multiple machines
/// </summary>
public bool? IsPartitioned { get; set; }
/// <summary>
/// whether the service is stateful or stateless. A stateless service can lose its state safely.
/// </summary>
public bool? IsStateful { get; set; }
/// <summary>
/// whether the service is replicated (multiple copies)
/// </summary>
public bool? IsReplicated { get; set; }
}
/// <summary>
/// service description
/// </summary>
public class Service
{
public Service(string package, string url, string name = "")
{
PackageName = package;
Url = url;
Name = !string.IsNullOrEmpty(name) ? name : url;
Properties = new ServiceProperty();
Spec = new ServiceSpec();
}
/// <summary>
/// package name for this service (the package is published and stored in a service store)
/// with the package, the service can be deployed with a deployment service
/// </summary>
public string PackageName { get; private set; }
/// <summary>
/// universal remote link for the service, which is used for service address resolve
/// example: http://service-manager-url/service-name
/// </summary>
public string Url { get; private set; }
/// <summary>
/// service name for print and RPC resolution (e.g., service-name.method-name for invoking a RPC)
/// </summary>
public string Name { get; private set; }
/// <summary>
/// service properties
/// </summary>
public ServiceProperty Properties { get; set; }
/// <summary>
/// spec info
/// </summary>
public ServiceSpec Spec { get; private set; }
public string TypeName ()
{
return (GetType().Namespace + "." + GetType().Name.Substring("Service_".Length));
}
public string PlainTypeName ()
{
return TypeName().Replace('.', '_');
}
public ServiceSpec ExtractSpec()
{
if (Spec.Directory != "") return Spec;
Spec.Directory = ".";
var files = new List<string> {Spec.MainSpecFile};
files.AddRange(Spec.ReferencedSpecFiles);
foreach (var f in files)
{
if (File.Exists(Path.Combine(Spec.Directory, f))) continue;
var stream = GetType().Assembly.GetManifestResourceStream(f);
using (Stream file = File.Create(Path.Combine(Spec.Directory, f)))
{
int len;
var buffer = new byte[8 * 1024];
while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
{
file.Write(buffer, 0, len);
}
}
}
return Spec;
}
}
public class PrimitiveService
{
public PrimitiveService(string name, string classFullName, string classShortName)
{
Name = name;
ServiceClassFullName = classFullName;
ServiceClassShortName = classShortName;
ReadConsistency = ConsistencyLevel.Any;
WriteConsistency = ConsistencyLevel.Any;
PartitionKey = null;
PartitionType = PartitionType.None;
PartitionCount = 1;
}
protected PrimitiveService Replicate(
int minDegree,
int maxDegree,
ConsistencyLevel readConsistency = ConsistencyLevel.Any,
ConsistencyLevel writeConsistency = ConsistencyLevel.Any
)
{
ReplicateMinDegree = minDegree;
ReplicateMaxDegree = maxDegree;
ReadConsistency = readConsistency;
WriteConsistency = writeConsistency;
return this;
}
protected PrimitiveService Partition(Type key, PartitionType type, int partitionCount = 1)
{
PartitionKey = key;
PartitionType = type;
PartitionCount = partitionCount;
return this;
}
protected PrimitiveService SetDataSource(string dataSource) // e.g., cosmos structured stream
{
DataSource = dataSource;
return this;
}
protected PrimitiveService SetConfiguration(string uri)
{
Configuration = uri;
return this;
}
public Type PartitionKey { get; private set; }
public PartitionType PartitionType { get; private set; }
public int PartitionCount { get; private set; }
public int ReplicateMinDegree { get; private set; }
public int ReplicateMaxDegree { get; private set; }
public ConsistencyLevel ReadConsistency { get; private set; }
public ConsistencyLevel WriteConsistency { get; private set; }
public string DataSource { get; private set; }
public string Configuration { get; private set; }
public string Name { get; private set; }
public string ServiceClassFullName { get; private set; }
public string ServiceClassShortName { get; private set; }
}
public class PrimitiveService<TSelf> : PrimitiveService
where TSelf : PrimitiveService<TSelf>
{
public PrimitiveService(string name, string classFullName)
: base(name, classFullName, classFullName.Substring(classFullName.LastIndexOfAny(new[]{':', '.'}) + 1))
{
}
public new TSelf Replicate(
int minDegree,
int maxDegree,
ConsistencyLevel readConsistency = ConsistencyLevel.Any,
ConsistencyLevel writeConsistency = ConsistencyLevel.Any
)
{
return base.Replicate(minDegree, maxDegree, readConsistency, writeConsistency) as TSelf;
}
public new TSelf Partition(Type key, PartitionType type = PartitionType.Dynamic, int partitionCount = 1)
{
return base.Partition(key, type, partitionCount) as TSelf;
}
public TSelf DataSource(string dataSource) // e.g., cosmos structured stream
{
return SetDataSource(dataSource) as TSelf;
}
public TSelf Configuration(string uri)
{
return SetConfiguration(uri) as TSelf;
}
}
public class Sla
{
public enum Metric
{
Latency99Percentile,
Latency95Percentile,
Latency90Percentile,
Latency50Percentile,
WorkflowConsistency
}
public enum WorkflowConsistencyLevel
{
Any,
Atomic,
Acid
}
public Sla Add<TValue>(Metric prop, TValue value)
{
return Add(prop, value.ToString());
}
public Sla Add(Metric prop, string value)
{
_mProperties.Add(prop, value);
return this;
}
public string Get(Metric prop)
{
string v;
_mProperties.TryGetValue(prop, out v);
return v;
}
private Dictionary<Metric, string> _mProperties = new Dictionary<Metric, string>();
}
}
| |
using Patterns.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace SocketHttpListener.Net
{
sealed class EndPointListener
{
HttpListener listener;
IPEndPoint endpoint;
Socket sock;
Dictionary<ListenerPrefix,HttpListener> prefixes; // Dictionary <ListenerPrefix, HttpListener>
List<ListenerPrefix> unhandled; // List<ListenerPrefix> unhandled; host = '*'
List<ListenerPrefix> all; // List<ListenerPrefix> all; host = '+'
X509Certificate cert;
bool secure;
Dictionary<HttpConnection, HttpConnection> unregistered;
private readonly ILogger _logger;
private bool _closed;
private readonly bool _enableDualMode;
public EndPointListener(HttpListener listener, IPAddress addr, int port, bool secure, X509Certificate cert, ILogger logger)
{
this.listener = listener;
_logger = logger;
this.secure = secure;
this.cert = cert;
_enableDualMode = Equals(addr, IPAddress.IPv6Any);
endpoint = new IPEndPoint(addr, port);
prefixes = new Dictionary<ListenerPrefix, HttpListener>();
unregistered = new Dictionary<HttpConnection, HttpConnection>();
CreateSocket();
}
internal HttpListener Listener
{
get
{
return listener;
}
}
private void CreateSocket()
{
if (_enableDualMode)
{
_logger.Info("Enabling DualMode socket");
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
sock = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
EnableDualMode(sock);
}
else
{
sock = new Socket(SocketType.Stream, ProtocolType.Tcp);
}
}
else
{
_logger.Info("Enabling non-DualMode socket");
sock = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
sock.Bind(endpoint);
// This is the number TcpListener uses.
sock.Listen(2147483647);
Socket dummy = null;
StartAccept(null, ref dummy);
_closed = false;
}
private void EnableDualMode(Socket socket)
{
try
{
//sock.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, false);
socket.DualMode = true;
}
catch (MissingMemberException)
{
}
}
public void StartAccept(SocketAsyncEventArgs acceptEventArg, ref Socket accepted)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
}
else
{
// socket must be cleared since the context object is being reused
acceptEventArg.AcceptSocket = null;
}
try
{
bool willRaiseEvent = sock.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
}
}
catch
{
if (accepted != null)
{
try
{
accepted.Close();
}
catch
{
}
accepted = null;
}
}
}
// This method is the callback method associated with Socket.AcceptAsync
// operations and is invoked when an accept operation is complete
//
void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
ProcessAccept(e);
}
private void ProcessAccept(SocketAsyncEventArgs e)
{
if (_closed)
{
return;
}
// http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync%28v=vs.110%29.aspx
// Under certain conditions ConnectionReset can occur
// Need to attept to re-accept
if (e.SocketError == SocketError.ConnectionReset)
{
_logger.Error("SocketError.ConnectionReset reported. Attempting to re-accept.");
Socket dummy = null;
StartAccept(e, ref dummy);
return;
}
var acceptSocket = e.AcceptSocket;
if (acceptSocket != null)
{
ProcessAccept(acceptSocket);
}
if (sock != null)
{
// Accept the next connection request
StartAccept(e, ref acceptSocket);
}
}
private void ProcessAccept(Socket accepted)
{
try
{
var listener = this;
if (listener.secure && listener.cert == null)
{
accepted.Close();
return;
}
HttpConnection conn = new HttpConnection(_logger, accepted, listener, listener.secure, listener.cert);
//_logger.Debug("Adding unregistered connection to {0}. Id: {1}", accepted.RemoteEndPoint, connectionId);
lock (listener.unregistered)
{
listener.unregistered[conn] = conn;
}
conn.BeginReadRequest();
}
catch (Exception ex)
{
_logger.ErrorException("Error in ProcessAccept", ex);
}
}
internal void RemoveConnection(HttpConnection conn)
{
lock (unregistered)
{
unregistered.Remove(conn);
}
}
public bool BindContext(HttpListenerContext context)
{
HttpListenerRequest req = context.Request;
ListenerPrefix prefix;
HttpListener listener = SearchListener(req.Url, out prefix);
if (listener == null)
return false;
context.Listener = listener;
context.Connection.Prefix = prefix;
return true;
}
public void UnbindContext(HttpListenerContext context)
{
if (context == null || context.Request == null)
return;
context.Listener.UnregisterContext(context);
}
HttpListener SearchListener(Uri uri, out ListenerPrefix prefix)
{
prefix = null;
if (uri == null)
return null;
string host = uri.Host;
int port = uri.Port;
string path = WebUtility.UrlDecode(uri.AbsolutePath);
string path_slash = path[path.Length - 1] == '/' ? path : path + "/";
HttpListener best_match = null;
int best_length = -1;
if (host != null && host != "")
{
var p_ro = prefixes;
foreach (ListenerPrefix p in p_ro.Keys)
{
string ppath = p.Path;
if (ppath.Length < best_length)
continue;
if (p.Host != host || p.Port != port)
continue;
if (path.StartsWith(ppath) || path_slash.StartsWith(ppath))
{
best_length = ppath.Length;
best_match = (HttpListener)p_ro[p];
prefix = p;
}
}
if (best_length != -1)
return best_match;
}
List<ListenerPrefix> list = unhandled;
best_match = MatchFromList(host, path, list, out prefix);
if (path != path_slash && best_match == null)
best_match = MatchFromList(host, path_slash, list, out prefix);
if (best_match != null)
return best_match;
list = all;
best_match = MatchFromList(host, path, list, out prefix);
if (path != path_slash && best_match == null)
best_match = MatchFromList(host, path_slash, list, out prefix);
if (best_match != null)
return best_match;
return null;
}
HttpListener MatchFromList(string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
{
prefix = null;
if (list == null)
return null;
HttpListener best_match = null;
int best_length = -1;
foreach (ListenerPrefix p in list)
{
string ppath = p.Path;
if (ppath.Length < best_length)
continue;
if (path.StartsWith(ppath))
{
best_length = ppath.Length;
best_match = p.Listener;
prefix = p;
}
}
return best_match;
}
void AddSpecial(List<ListenerPrefix> coll, ListenerPrefix prefix)
{
if (coll == null)
return;
foreach (ListenerPrefix p in coll)
{
if (p.Path == prefix.Path) //TODO: code
throw new System.Net.HttpListenerException(400, "Prefix already in use.");
}
coll.Add(prefix);
}
bool RemoveSpecial(List<ListenerPrefix> coll, ListenerPrefix prefix)
{
if (coll == null)
return false;
int c = coll.Count;
for (int i = 0; i < c; i++)
{
ListenerPrefix p = (ListenerPrefix)coll[i];
if (p.Path == prefix.Path)
{
coll.RemoveAt(i);
return true;
}
}
return false;
}
void CheckIfRemove()
{
if (prefixes.Count > 0)
return;
List<ListenerPrefix> list = unhandled;
if (list != null && list.Count > 0)
return;
list = all;
if (list != null && list.Count > 0)
return;
EndPointManager.RemoveEndPoint(this, endpoint);
}
public void Close()
{
_closed = true;
sock.Close();
lock (unregistered)
{
//
// Clone the list because RemoveConnection can be called from Close
//
var connections = new List<HttpConnection>(unregistered.Keys);
foreach (HttpConnection c in connections)
c.Close(true);
unregistered.Clear();
}
}
public void AddPrefix(ListenerPrefix prefix, HttpListener listener)
{
List<ListenerPrefix> current;
List<ListenerPrefix> future;
if (prefix.Host == "*")
{
do
{
current = unhandled;
future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
prefix.Listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref unhandled, future, current) != current);
return;
}
if (prefix.Host == "+")
{
do
{
current = all;
future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
prefix.Listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref all, future, current) != current);
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs;
Dictionary<ListenerPrefix, HttpListener> p2;
do
{
prefs = prefixes;
if (prefs.ContainsKey(prefix))
{
HttpListener other = (HttpListener)prefs[prefix];
if (other != listener) // TODO: code.
throw new System.Net.HttpListenerException(400, "There's another listener for " + prefix);
return;
}
p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
p2[prefix] = listener;
} while (Interlocked.CompareExchange(ref prefixes, p2, prefs) != prefs);
}
public void RemovePrefix(ListenerPrefix prefix, HttpListener listener)
{
List<ListenerPrefix> current;
List<ListenerPrefix> future;
if (prefix.Host == "*")
{
do
{
current = unhandled;
future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref unhandled, future, current) != current);
CheckIfRemove();
return;
}
if (prefix.Host == "+")
{
do
{
current = all;
future = (current != null) ? current.ToList() : new List<ListenerPrefix>();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref all, future, current) != current);
CheckIfRemove();
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs;
Dictionary<ListenerPrefix, HttpListener> p2;
do
{
prefs = prefixes;
if (!prefs.ContainsKey(prefix))
break;
p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
p2.Remove(prefix);
} while (Interlocked.CompareExchange(ref prefixes, p2, prefs) != prefs);
CheckIfRemove();
}
}
}
| |
namespace java.lang
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Class : java.lang.Object, java.io.Serializable, java.lang.reflect.GenericDeclaration, java.lang.reflect.Type, java.lang.reflect.AnnotatedElement
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Class(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::java.lang.Class forName(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Class._m0.native == global::System.IntPtr.Zero)
global::java.lang.Class._m0 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Class.staticClass, "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Class>(@__env.CallStaticObjectMethod(java.lang.Class.staticClass, global::java.lang.Class._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Class;
}
private static global::MonoJavaBridge.MethodId _m1;
public static global::java.lang.Class forName(java.lang.String arg0, bool arg1, java.lang.ClassLoader arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::java.lang.Class._m1.native == global::System.IntPtr.Zero)
global::java.lang.Class._m1 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Class.staticClass, "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.Class>(@__env.CallStaticObjectMethod(java.lang.Class.staticClass, global::java.lang.Class._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.Class;
}
private static global::MonoJavaBridge.MethodId _m2;
public sealed override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.Class.staticClass, "toString", "()Ljava/lang/String;", ref global::java.lang.Class._m2) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m3;
public bool isAssignableFrom(java.lang.Class arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isAssignableFrom", "(Ljava/lang/Class;)Z", ref global::java.lang.Class._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public bool isInstance(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isInstance", "(Ljava/lang/Object;)Z", ref global::java.lang.Class._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int Modifiers
{
get
{
return getModifiers();
}
}
private static global::MonoJavaBridge.MethodId _m5;
public int getModifiers()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.lang.Class.staticClass, "getModifiers", "()I", ref global::java.lang.Class._m5);
}
private static global::MonoJavaBridge.MethodId _m6;
public bool isInterface()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isInterface", "()Z", ref global::java.lang.Class._m6);
}
private static global::MonoJavaBridge.MethodId _m7;
public bool isArray()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isArray", "()Z", ref global::java.lang.Class._m7);
}
private static global::MonoJavaBridge.MethodId _m8;
public bool isPrimitive()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isPrimitive", "()Z", ref global::java.lang.Class._m8);
}
public new global::java.lang.Class Superclass
{
get
{
return getSuperclass();
}
}
private static global::MonoJavaBridge.MethodId _m9;
public global::java.lang.Class getSuperclass()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Class>(this, global::java.lang.Class.staticClass, "getSuperclass", "()Ljava/lang/Class;", ref global::java.lang.Class._m9) as java.lang.Class;
}
public new global::java.lang.Class ComponentType
{
get
{
return getComponentType();
}
}
private static global::MonoJavaBridge.MethodId _m10;
public global::java.lang.Class getComponentType()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Class>(this, global::java.lang.Class.staticClass, "getComponentType", "()Ljava/lang/Class;", ref global::java.lang.Class._m10) as java.lang.Class;
}
public new global::java.lang.String Name
{
get
{
return getName();
}
}
private static global::MonoJavaBridge.MethodId _m11;
public global::java.lang.String getName()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.Class.staticClass, "getName", "()Ljava/lang/String;", ref global::java.lang.Class._m11) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m12;
public global::java.lang.Object newInstance()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.Class.staticClass, "newInstance", "()Ljava/lang/Object;", ref global::java.lang.Class._m12) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m13;
public bool isAnnotation()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isAnnotation", "()Z", ref global::java.lang.Class._m13);
}
private static global::MonoJavaBridge.MethodId _m14;
public bool isSynthetic()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isSynthetic", "()Z", ref global::java.lang.Class._m14);
}
public new global::java.lang.ClassLoader ClassLoader
{
get
{
return getClassLoader();
}
}
private static global::MonoJavaBridge.MethodId _m15;
public global::java.lang.ClassLoader getClassLoader()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.Class.staticClass, "getClassLoader", "()Ljava/lang/ClassLoader;", ref global::java.lang.Class._m15) as java.lang.ClassLoader;
}
public new global::java.lang.reflect.TypeVariable[] TypeParameters
{
get
{
return getTypeParameters();
}
}
private static global::MonoJavaBridge.MethodId _m16;
public global::java.lang.reflect.TypeVariable[] getTypeParameters()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.reflect.TypeVariable>(this, global::java.lang.Class.staticClass, "getTypeParameters", "()[Ljava/lang/reflect/TypeVariable;", ref global::java.lang.Class._m16) as java.lang.reflect.TypeVariable[];
}
public new global::java.lang.reflect.Type GenericSuperclass
{
get
{
return getGenericSuperclass();
}
}
private static global::MonoJavaBridge.MethodId _m17;
public global::java.lang.reflect.Type getGenericSuperclass()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.reflect.Type>(this, global::java.lang.Class.staticClass, "getGenericSuperclass", "()Ljava/lang/reflect/Type;", ref global::java.lang.Class._m17) as java.lang.reflect.Type;
}
public new global::java.lang.Package Package
{
get
{
return getPackage();
}
}
private static global::MonoJavaBridge.MethodId _m18;
public global::java.lang.Package getPackage()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.Class.staticClass, "getPackage", "()Ljava/lang/Package;", ref global::java.lang.Class._m18) as java.lang.Package;
}
public new global::java.lang.Class[] Interfaces
{
get
{
return getInterfaces();
}
}
private static global::MonoJavaBridge.MethodId _m19;
public global::java.lang.Class[] getInterfaces()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.Class>(this, global::java.lang.Class.staticClass, "getInterfaces", "()[Ljava/lang/Class;", ref global::java.lang.Class._m19) as java.lang.Class[];
}
public new global::java.lang.reflect.Type[] GenericInterfaces
{
get
{
return getGenericInterfaces();
}
}
private static global::MonoJavaBridge.MethodId _m20;
public global::java.lang.reflect.Type[] getGenericInterfaces()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.reflect.Type>(this, global::java.lang.Class.staticClass, "getGenericInterfaces", "()[Ljava/lang/reflect/Type;", ref global::java.lang.Class._m20) as java.lang.reflect.Type[];
}
public new global::java.lang.Object[] Signers
{
get
{
return getSigners();
}
}
private static global::MonoJavaBridge.MethodId _m21;
public global::java.lang.Object[] getSigners()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.Object>(this, global::java.lang.Class.staticClass, "getSigners", "()[Ljava/lang/Object;", ref global::java.lang.Class._m21) as java.lang.Object[];
}
public new global::java.lang.reflect.Method EnclosingMethod
{
get
{
return getEnclosingMethod();
}
}
private static global::MonoJavaBridge.MethodId _m22;
public global::java.lang.reflect.Method getEnclosingMethod()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.reflect.Method>(this, global::java.lang.Class.staticClass, "getEnclosingMethod", "()Ljava/lang/reflect/Method;", ref global::java.lang.Class._m22) as java.lang.reflect.Method;
}
public new global::java.lang.reflect.Constructor EnclosingConstructor
{
get
{
return getEnclosingConstructor();
}
}
private static global::MonoJavaBridge.MethodId _m23;
public global::java.lang.reflect.Constructor getEnclosingConstructor()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.reflect.Constructor>(this, global::java.lang.Class.staticClass, "getEnclosingConstructor", "()Ljava/lang/reflect/Constructor;", ref global::java.lang.Class._m23) as java.lang.reflect.Constructor;
}
public new global::java.lang.Class DeclaringClass
{
get
{
return getDeclaringClass();
}
}
private static global::MonoJavaBridge.MethodId _m24;
public global::java.lang.Class getDeclaringClass()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Class>(this, global::java.lang.Class.staticClass, "getDeclaringClass", "()Ljava/lang/Class;", ref global::java.lang.Class._m24) as java.lang.Class;
}
public new global::java.lang.Class EnclosingClass
{
get
{
return getEnclosingClass();
}
}
private static global::MonoJavaBridge.MethodId _m25;
public global::java.lang.Class getEnclosingClass()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Class>(this, global::java.lang.Class.staticClass, "getEnclosingClass", "()Ljava/lang/Class;", ref global::java.lang.Class._m25) as java.lang.Class;
}
public new global::java.lang.String SimpleName
{
get
{
return getSimpleName();
}
}
private static global::MonoJavaBridge.MethodId _m26;
public global::java.lang.String getSimpleName()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.Class.staticClass, "getSimpleName", "()Ljava/lang/String;", ref global::java.lang.Class._m26) as java.lang.String;
}
public new global::java.lang.String CanonicalName
{
get
{
return getCanonicalName();
}
}
private static global::MonoJavaBridge.MethodId _m27;
public global::java.lang.String getCanonicalName()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.lang.Class.staticClass, "getCanonicalName", "()Ljava/lang/String;", ref global::java.lang.Class._m27) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m28;
public bool isAnonymousClass()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isAnonymousClass", "()Z", ref global::java.lang.Class._m28);
}
private static global::MonoJavaBridge.MethodId _m29;
public bool isLocalClass()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isLocalClass", "()Z", ref global::java.lang.Class._m29);
}
private static global::MonoJavaBridge.MethodId _m30;
public bool isMemberClass()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isMemberClass", "()Z", ref global::java.lang.Class._m30);
}
public new global::java.lang.Class[] Classes
{
get
{
return getClasses();
}
}
private static global::MonoJavaBridge.MethodId _m31;
public global::java.lang.Class[] getClasses()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.Class>(this, global::java.lang.Class.staticClass, "getClasses", "()[Ljava/lang/Class;", ref global::java.lang.Class._m31) as java.lang.Class[];
}
public new global::java.lang.reflect.Field[] Fields
{
get
{
return getFields();
}
}
private static global::MonoJavaBridge.MethodId _m32;
public global::java.lang.reflect.Field[] getFields()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.reflect.Field>(this, global::java.lang.Class.staticClass, "getFields", "()[Ljava/lang/reflect/Field;", ref global::java.lang.Class._m32) as java.lang.reflect.Field[];
}
public new global::java.lang.reflect.Method[] Methods
{
get
{
return getMethods();
}
}
private static global::MonoJavaBridge.MethodId _m33;
public global::java.lang.reflect.Method[] getMethods()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.reflect.Method>(this, global::java.lang.Class.staticClass, "getMethods", "()[Ljava/lang/reflect/Method;", ref global::java.lang.Class._m33) as java.lang.reflect.Method[];
}
public new global::java.lang.reflect.Constructor[] Constructors
{
get
{
return getConstructors();
}
}
private static global::MonoJavaBridge.MethodId _m34;
public global::java.lang.reflect.Constructor[] getConstructors()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.reflect.Constructor>(this, global::java.lang.Class.staticClass, "getConstructors", "()[Ljava/lang/reflect/Constructor;", ref global::java.lang.Class._m34) as java.lang.reflect.Constructor[];
}
private static global::MonoJavaBridge.MethodId _m35;
public global::java.lang.reflect.Field getField(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.reflect.Field>(this, global::java.lang.Class.staticClass, "getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ref global::java.lang.Class._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.reflect.Field;
}
private static global::MonoJavaBridge.MethodId _m36;
public global::java.lang.reflect.Method getMethod(java.lang.String arg0, java.lang.Class[] arg1)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.reflect.Method>(this, global::java.lang.Class.staticClass, "getMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", ref global::java.lang.Class._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.reflect.Method;
}
private static global::MonoJavaBridge.MethodId _m37;
public global::java.lang.reflect.Constructor getConstructor(java.lang.Class[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.reflect.Constructor>(this, global::java.lang.Class.staticClass, "getConstructor", "([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;", ref global::java.lang.Class._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.reflect.Constructor;
}
public new global::java.lang.Class[] DeclaredClasses
{
get
{
return getDeclaredClasses();
}
}
private static global::MonoJavaBridge.MethodId _m38;
public global::java.lang.Class[] getDeclaredClasses()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.Class>(this, global::java.lang.Class.staticClass, "getDeclaredClasses", "()[Ljava/lang/Class;", ref global::java.lang.Class._m38) as java.lang.Class[];
}
public new global::java.lang.reflect.Field[] DeclaredFields
{
get
{
return getDeclaredFields();
}
}
private static global::MonoJavaBridge.MethodId _m39;
public global::java.lang.reflect.Field[] getDeclaredFields()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.reflect.Field>(this, global::java.lang.Class.staticClass, "getDeclaredFields", "()[Ljava/lang/reflect/Field;", ref global::java.lang.Class._m39) as java.lang.reflect.Field[];
}
public new global::java.lang.reflect.Method[] DeclaredMethods
{
get
{
return getDeclaredMethods();
}
}
private static global::MonoJavaBridge.MethodId _m40;
public global::java.lang.reflect.Method[] getDeclaredMethods()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.reflect.Method>(this, global::java.lang.Class.staticClass, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;", ref global::java.lang.Class._m40) as java.lang.reflect.Method[];
}
public new global::java.lang.reflect.Constructor[] DeclaredConstructors
{
get
{
return getDeclaredConstructors();
}
}
private static global::MonoJavaBridge.MethodId _m41;
public global::java.lang.reflect.Constructor[] getDeclaredConstructors()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.reflect.Constructor>(this, global::java.lang.Class.staticClass, "getDeclaredConstructors", "()[Ljava/lang/reflect/Constructor;", ref global::java.lang.Class._m41) as java.lang.reflect.Constructor[];
}
private static global::MonoJavaBridge.MethodId _m42;
public global::java.lang.reflect.Field getDeclaredField(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.reflect.Field>(this, global::java.lang.Class.staticClass, "getDeclaredField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", ref global::java.lang.Class._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.reflect.Field;
}
private static global::MonoJavaBridge.MethodId _m43;
public global::java.lang.reflect.Method getDeclaredMethod(java.lang.String arg0, java.lang.Class[] arg1)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.reflect.Method>(this, global::java.lang.Class.staticClass, "getDeclaredMethod", "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;", ref global::java.lang.Class._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.reflect.Method;
}
private static global::MonoJavaBridge.MethodId _m44;
public global::java.lang.reflect.Constructor getDeclaredConstructor(java.lang.Class[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.reflect.Constructor>(this, global::java.lang.Class.staticClass, "getDeclaredConstructor", "([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;", ref global::java.lang.Class._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.reflect.Constructor;
}
private static global::MonoJavaBridge.MethodId _m45;
public global::java.io.InputStream getResourceAsStream(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.Class.staticClass, "getResourceAsStream", "(Ljava/lang/String;)Ljava/io/InputStream;", ref global::java.lang.Class._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.io.InputStream;
}
private static global::MonoJavaBridge.MethodId _m46;
public global::java.net.URL getResource(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.net.URL>(this, global::java.lang.Class.staticClass, "getResource", "(Ljava/lang/String;)Ljava/net/URL;", ref global::java.lang.Class._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.net.URL;
}
public new global::java.security.ProtectionDomain ProtectionDomain
{
get
{
return getProtectionDomain();
}
}
private static global::MonoJavaBridge.MethodId _m47;
public global::java.security.ProtectionDomain getProtectionDomain()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.Class.staticClass, "getProtectionDomain", "()Ljava/security/ProtectionDomain;", ref global::java.lang.Class._m47) as java.security.ProtectionDomain;
}
private static global::MonoJavaBridge.MethodId _m48;
public bool desiredAssertionStatus()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "desiredAssertionStatus", "()Z", ref global::java.lang.Class._m48);
}
private static global::MonoJavaBridge.MethodId _m49;
public bool isEnum()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isEnum", "()Z", ref global::java.lang.Class._m49);
}
public new global::java.lang.Object[] EnumConstants
{
get
{
return getEnumConstants();
}
}
private static global::MonoJavaBridge.MethodId _m50;
public global::java.lang.Object[] getEnumConstants()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.Object>(this, global::java.lang.Class.staticClass, "getEnumConstants", "()[Ljava/lang/Object;", ref global::java.lang.Class._m50) as java.lang.Object[];
}
private static global::MonoJavaBridge.MethodId _m51;
public global::java.lang.Object cast(java.lang.Object arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.lang.Class.staticClass, "cast", "(Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.lang.Class._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m52;
public global::java.lang.Class asSubclass(java.lang.Class arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Class>(this, global::java.lang.Class.staticClass, "asSubclass", "(Ljava/lang/Class;)Ljava/lang/Class;", ref global::java.lang.Class._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Class;
}
private static global::MonoJavaBridge.MethodId _m53;
public global::java.lang.annotation.Annotation getAnnotation(java.lang.Class arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.annotation.Annotation>(this, global::java.lang.Class.staticClass, "getAnnotation", "(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;", ref global::java.lang.Class._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.annotation.Annotation;
}
private static global::MonoJavaBridge.MethodId _m54;
public bool isAnnotationPresent(java.lang.Class arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.lang.Class.staticClass, "isAnnotationPresent", "(Ljava/lang/Class;)Z", ref global::java.lang.Class._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::java.lang.annotation.Annotation[] Annotations
{
get
{
return getAnnotations();
}
}
private static global::MonoJavaBridge.MethodId _m55;
public global::java.lang.annotation.Annotation[] getAnnotations()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.annotation.Annotation>(this, global::java.lang.Class.staticClass, "getAnnotations", "()[Ljava/lang/annotation/Annotation;", ref global::java.lang.Class._m55) as java.lang.annotation.Annotation[];
}
public new global::java.lang.annotation.Annotation[] DeclaredAnnotations
{
get
{
return getDeclaredAnnotations();
}
}
private static global::MonoJavaBridge.MethodId _m56;
public global::java.lang.annotation.Annotation[] getDeclaredAnnotations()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.annotation.Annotation>(this, global::java.lang.Class.staticClass, "getDeclaredAnnotations", "()[Ljava/lang/annotation/Annotation;", ref global::java.lang.Class._m56) as java.lang.annotation.Annotation[];
}
static Class()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::java.lang.Class.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Class"));
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Globalization;
using Common.Logging;
using Spring.Collections;
using Spring.Core;
using Spring.Util;
namespace Spring.Objects.Factory.Config
{
/// <summary>
/// Resolves placeholder values in one or more object definitions
/// </summary>
/// <remarks>
/// The placeholder syntax follows the NAnt style: <c>${...}</c>.
/// Placeholders values are resolved against a list of
/// <see cref="IVariableSource"/>s. In case of multiple definitions
/// for the same property placeholder name, the first one in the
/// list is used.
/// <para>Variable substitution is performed on simple property values,
/// lists, dictionaries, sets, constructor
/// values, object type name, and object names in
/// runtime object references (
/// <see cref="Spring.Objects.Factory.Config.RuntimeObjectReference"/>).</para>
/// <para>Furthermore, placeholder values can also cross-reference other
/// placeholders, in the manner of the following example where the
/// <c>rootPath</c> property is cross-referenced by the <c>subPath</c>
/// property.
/// </para>
/// <example>
/// <code escaped="true">
/// <name-values>
/// <add key="rootPath" value="myrootdir"/>
/// <add key="subPath" value="${rootPath}/subdir"/>
/// </name-values>
/// </code>
/// </example>
/// <para>If a configurer cannot resolve a placeholder, and the value of the
/// <see cref="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer.IgnoreUnresolvablePlaceholders"/>
/// property is currently set to <see langword="false"/>, an
/// <see cref="Spring.Objects.Factory.ObjectDefinitionStoreException"/>
/// will be thrown. </para>
/// </remarks>
/// <author>Mark Pollack</author>
public class VariablePlaceholderConfigurer : IObjectFactoryPostProcessor, IPriorityOrdered
{
/// <summary>
/// The default placeholder prefix.
/// </summary>
public static readonly string DefaultPlaceholderPrefix = "${";
/// <summary>
/// The default placeholder suffix.
/// </summary>
public static readonly string DefaultPlaceholderSuffix = "}";
#region Fields
private int order = Int32.MaxValue; // default: same as non-Ordered
private bool ignoreUnresolvablePlaceholders;
private string placeholderPrefix = DefaultPlaceholderPrefix;
private string placeholderSuffix = DefaultPlaceholderSuffix;
private IList variableSourceList = new ArrayList();
#endregion
/// <summary>
/// Create a new instance without any variable sources
/// </summary>
public VariablePlaceholderConfigurer()
{}
/// <summary>
/// Create a new instance and initialize with the given variable source
/// </summary>
/// <param name="variableSource"></param>
public VariablePlaceholderConfigurer(IVariableSource variableSource)
{
this.VariableSource = variableSource;
}
/// <summary>
/// Create a new instance and initialize with the given list of variable sources
/// </summary>
public VariablePlaceholderConfigurer(IList variableSources)
{
this.VariableSources = variableSources;
}
#region Properties
/// <summary>
/// Sets the list of <see cref="IVariableSource"/>s that will be used to resolve placeholder names.
/// </summary>
/// <value>A list of <see cref="IVariableSource"/>s.</value>
public IList VariableSources
{
set { variableSourceList = value; }
}
/// <summary>
/// Sets <see cref="IVariableSource"/> that will be used to resolve placeholder names.
/// </summary>
/// <value>A <see cref="IVariableSource"/> instance.</value>
public IVariableSource VariableSource
{
set
{
variableSourceList = new ArrayList();
variableSourceList.Add( value );
}
}
/// <summary>
/// The placeholder prefix (the default is <c>${</c>).
/// </summary>
/// <seealso cref="DefaultPlaceholderPrefix"/>
public string PlaceholderPrefix
{
set { placeholderPrefix = value; }
}
/// <summary>
/// The placeholder suffix (the default is <c>}</c>)
/// </summary>
/// <seealso cref="DefaultPlaceholderSuffix"/>
public string PlaceholderSuffix
{
set { placeholderSuffix = value; }
}
/// <summary>
/// Indicates whether unresolved placeholders should be ignored.
/// </summary>
public bool IgnoreUnresolvablePlaceholders
{
set { ignoreUnresolvablePlaceholders = value; }
}
#endregion
#region IObjectFactoryPostProcessor Members
/// <summary>
/// Modify the application context's internal object factory after its
/// standard initialization.
/// </summary>
/// <param name="factory">The object factory used by the application context.</param>
/// <remarks>
/// <p>
/// All object definitions will have been loaded, but no objects will have
/// been instantiated yet. This allows for overriding or adding properties
/// even to eager-initializing objects.
/// </p>
/// </remarks>
/// <exception cref="Spring.Objects.ObjectsException">
/// In case of errors.
/// </exception>
public void PostProcessObjectFactory( IConfigurableListableObjectFactory factory )
{
if (CollectionUtils.IsEmpty(variableSourceList))
{
throw new ArgumentException("No VariableSources configured");
}
ICollection filtered = CollectionUtils.FindValuesOfType(this.variableSourceList, typeof (IVariableSource));
if (filtered.Count != this.variableSourceList.Count)
{
throw new ArgumentException("'VariableSources' must contain IVariableSource elements only", "VariableSources");
}
try
{
ProcessProperties( factory );
}
catch (Exception ex)
{
if (typeof( ObjectsException ).IsInstanceOfType( ex ))
{
throw;
}
else
{
throw new ObjectsException(
"Errored while postprocessing an object factory.", ex );
}
}
}
#endregion
#region IOrdered Members
/// <summary>
/// Return the order value of this object, where a higher value means greater in
/// terms of sorting.
/// </summary>
/// <returns>The order value.</returns>
/// <seealso cref="Spring.Core.IOrdered.Order"/>
public int Order
{
get { return order; }
set { order = value; }
}
#endregion
/// <summary>
/// Apply the property replacement using the specified <see cref="IVariableSource"/>s for all
/// object in the supplied
/// <see cref="Spring.Objects.Factory.Config.IConfigurableListableObjectFactory"/>.
/// </summary>
/// <param name="factory">
/// The <see cref="Spring.Objects.Factory.Config.IConfigurableListableObjectFactory"/>
/// used by the application context.
/// </param>
/// <exception cref="Spring.Objects.ObjectsException">
/// If an error occured.
/// </exception>
protected virtual void ProcessProperties( IConfigurableListableObjectFactory factory )
{
CompositeVariableSource compositeVariableSource = new CompositeVariableSource(variableSourceList);
TextProcessor tp = new TextProcessor(this, compositeVariableSource);
ObjectDefinitionVisitor visitor = new ObjectDefinitionVisitor(new ObjectDefinitionVisitor.ResolveHandler(tp.ParseAndResolveVariables));
string[] objectDefinitionNames = factory.GetObjectDefinitionNames();
for (int i = 0; i < objectDefinitionNames.Length; ++i)
{
string name = objectDefinitionNames[i];
IObjectDefinition definition = factory.GetObjectDefinition( name );
try
{
visitor.VisitObjectDefinition( definition );
}
catch (ObjectDefinitionStoreException ex)
{
throw new ObjectDefinitionStoreException(
definition.ResourceDescription, name, ex.Message );
}
}
}
#region Helper class
private class TextProcessor
{
private readonly ILog logger = LogManager.GetLogger(typeof(TextProcessor));
private readonly VariablePlaceholderConfigurer owner;
private readonly IVariableSource variableSource;
public TextProcessor(VariablePlaceholderConfigurer owner, IVariableSource variableSource)
{
this.owner = owner;
this.variableSource = variableSource;
}
public string ParseAndResolveVariables(string rawStringValue)
{
return ParseAndResolveVariables(rawStringValue, new HashedSet());
}
private string ParseAndResolveVariables(string strVal, ISet visitedPlaceholders)
{
if (strVal == null)
{
return null;
}
int startIndex = strVal.IndexOf(owner.placeholderPrefix);
while (startIndex != -1)
{
int endIndex = strVal.IndexOf(
owner.placeholderSuffix, startIndex + owner.placeholderPrefix.Length);
if (endIndex != -1)
{
int pos = startIndex + owner.placeholderPrefix.Length;
string placeholder = strVal.Substring(pos, endIndex - pos);
if (visitedPlaceholders.Contains(placeholder))
{
throw new ObjectDefinitionStoreException(
string.Format(
CultureInfo.InvariantCulture,
"Circular placeholder reference '{0}' detected. ",
placeholder));
}
visitedPlaceholders.Add(placeholder);
if (variableSource.CanResolveVariable(placeholder))
{
string resolvedValue = variableSource.ResolveVariable(placeholder);
resolvedValue = ParseAndResolveVariables(resolvedValue, visitedPlaceholders);
#region Instrumentation
if (logger.IsDebugEnabled)
{
logger.Debug(string.Format(
CultureInfo.InvariantCulture,
"Resolving placeholder '{0}' to '{1}'.", placeholder, resolvedValue));
}
#endregion
if (resolvedValue == null
&& startIndex == 0
&& strVal.Length <= endIndex + owner.placeholderSuffix.Length)
{
return null;
}
strVal = strVal.Substring(0, startIndex) + resolvedValue + strVal.Substring(endIndex + owner.placeholderSuffix.Length);
startIndex = strVal.IndexOf(owner.placeholderPrefix, startIndex + (resolvedValue == null ? 0 : resolvedValue.Length));
}
else if (owner.ignoreUnresolvablePlaceholders)
{
// simply return the unprocessed value...
return strVal;
}
else
{
throw new ObjectDefinitionStoreException(string.Format(
CultureInfo.InvariantCulture,
"Could not resolve placeholder '{0}'.", placeholder));
}
visitedPlaceholders.Remove(placeholder);
}
else
{
startIndex = -1;
}
}
return strVal;
}
}
private class CompositeVariableSource : IVariableSource
{
private readonly IList variableSourceList;
public CompositeVariableSource( IList variableSourceList )
{
this.variableSourceList = variableSourceList;
}
public string ResolveVariable( string variableName )
{
foreach (IVariableSource variableSource in variableSourceList)
{
if (!variableSource.CanResolveVariable(variableName)) continue;
return variableSource.ResolveVariable( variableName );
}
throw new ArgumentException(string.Format("cannot resolve variable '{0}'", variableName));
}
public bool CanResolveVariable(string variableName)
{
foreach (IVariableSource variableSource in variableSourceList)
{
if (variableSource.CanResolveVariable(variableName))
return true;
}
return 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.
/******************************************************************************
* 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 ResetLowestSetBitUInt32()
{
var test = new ScalarUnaryOpTest__ResetLowestSetBitUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.ReadUnaligned
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.ReadUnaligned
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.ReadUnaligned
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ScalarUnaryOpTest__ResetLowestSetBitUInt32
{
private struct TestStruct
{
public UInt32 _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld = TestLibrary.Generator.GetUInt32();
return testStruct;
}
public void RunStructFldScenario(ScalarUnaryOpTest__ResetLowestSetBitUInt32 testClass)
{
var result = Bmi1.ResetLowestSetBit(_fld);
testClass.ValidateResult(_fld, result);
}
}
private static UInt32 _data;
private static UInt32 _clsVar;
private UInt32 _fld;
static ScalarUnaryOpTest__ResetLowestSetBitUInt32()
{
_clsVar = TestLibrary.Generator.GetUInt32();
}
public ScalarUnaryOpTest__ResetLowestSetBitUInt32()
{
Succeeded = true;
_fld = TestLibrary.Generator.GetUInt32();
_data = TestLibrary.Generator.GetUInt32();
}
public bool IsSupported => Bmi1.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Bmi1.ResetLowestSetBit(
Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data))
);
ValidateResult(_data, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Bmi1).GetMethod(nameof(Bmi1.ResetLowestSetBit), new Type[] { typeof(UInt32) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data))
});
ValidateResult(_data, (UInt32)result);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Bmi1.ResetLowestSetBit(
_clsVar
);
ValidateResult(_clsVar, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data = Unsafe.ReadUnaligned<UInt32>(ref Unsafe.As<UInt32, byte>(ref _data));
var result = Bmi1.ResetLowestSetBit(data);
ValidateResult(data, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarUnaryOpTest__ResetLowestSetBitUInt32();
var result = Bmi1.ResetLowestSetBit(test._fld);
ValidateResult(test._fld, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Bmi1.ResetLowestSetBit(_fld);
ValidateResult(_fld, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Bmi1.ResetLowestSetBit(test._fld);
ValidateResult(test._fld, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(UInt32 data, UInt32 result, [CallerMemberName] string method = "")
{
var isUnexpectedResult = false;
isUnexpectedResult = (((data - 1) & data) != result);
if (isUnexpectedResult)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1)}.{nameof(Bmi1.ResetLowestSetBit)}<UInt32>(UInt32): ResetLowestSetBit failed:");
TestLibrary.TestFramework.LogInformation($" data: {data}");
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.
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Runtime.Versioning;
namespace System.Collections.Generic
{
// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length
// of the internal array. As elements are added to a List, the capacity
// of the List is automatically increased as required by reallocating the
// internal array.
//
[DebuggerTypeProxy(typeof(ICollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
{
private const int _defaultCapacity = 4;
private T[] _items; // Do not rename (binary serialization)
[ContractPublicPropertyName("Count")]
private int _size; // Do not rename (binary serialization)
private int _version; // Do not rename (binary serialization)
[NonSerialized]
private object _syncRoot;
private static readonly T[] s_emptyArray = new T[0];
// Constructs a List. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
// increased to _defaultCapacity, and then increased in multiples of two
// as required.
public List()
{
_items = s_emptyArray;
}
// Constructs a List with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
public List(int capacity)
{
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (capacity == 0)
_items = s_emptyArray;
else
_items = new T[capacity];
}
// Constructs a List, copying the contents of the given collection. The
// size and capacity of the new list will both be equal to the size of the
// given collection.
//
public List(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
int count = c.Count;
if (count == 0)
{
_items = s_emptyArray;
}
else
{
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
else
{
_size = 0;
_items = s_emptyArray;
// This enumerable could be empty. Let Add allocate a new array, if needed.
// Note it will also go to _defaultCapacity first, not 1, then 2, etc.
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Add(en.Current);
}
}
}
}
// Gets and sets the capacity of this list. The capacity is the size of
// the internal array used to hold items. When set, the internal
// array of the list is reallocated to the given capacity.
//
public int Capacity
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _items.Length;
}
set
{
if (value < _size)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity);
}
Contract.EndContractBlock();
if (value != _items.Length)
{
if (value > 0)
{
var items = new T[value];
Array.Copy(_items, 0, items, 0, _size);
_items = items;
}
else
{
_items = s_emptyArray;
}
}
}
}
// Read-only property describing how many elements are in the List.
public int Count
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
bool System.Collections.IList.IsFixedSize
{
get { return false; }
}
// Is this List read-only?
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
bool System.Collections.IList.IsReadOnly
{
get { return false; }
}
// Is this List synchronized (thread-safe)?
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
// Synchronization root for this object.
object System.Collections.ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
// Sets or Gets the element at the given index.
public T this[int index]
{
get
{
// Following trick can reduce the range check by one
if ((uint)index >= (uint)_size)
{
throw new ArgumentOutOfRangeException();
}
Contract.EndContractBlock();
return _items[index];
}
set
{
if ((uint)index >= (uint)_size)
{
throw new ArgumentOutOfRangeException();
}
Contract.EndContractBlock();
_items[index] = value;
_version++;
}
}
private static bool IsCompatibleObject(object value)
{
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
object System.Collections.IList.this[int index]
{
get
{
return this[index];
}
set
{
if (value == null && !(default(T) == null))
throw new ArgumentNullException(nameof(value));
try
{
this[index] = (T)value;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(T)), nameof(value));
}
}
}
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
public void Add(T item)
{
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
_version++;
}
int System.Collections.IList.Add(object item)
{
if (item == null && !(default(T) == null))
throw new ArgumentNullException(nameof(item));
try
{
Add((T)item);
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, item, typeof(T)), nameof(item));
}
return Count - 1;
}
// Adds the elements of the given collection to the end of this list. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger.
public void AddRange(IEnumerable<T> collection)
{
Contract.Ensures(Count >= Contract.OldValue(Count));
InsertRange(_size, collection);
}
public ReadOnlyCollection<T> AsReadOnly()
{
return new ReadOnlyCollection<T>(this);
}
// Searches a section of the list for a given element using a binary search
// algorithm. Elements of the list are compared to the search value using
// the given IComparer interface. If comparer is null, elements of
// the list are compared to the search value using the IComparable
// interface, which in that case must be implemented by all elements of the
// list and the given search value. This method assumes that the given
// section of the list is already sorted; if this is not the case, the
// result will be incorrect.
//
// The method returns the index of the given value in the list. If the
// list does not contain the given value, the method returns a negative
// integer. The bitwise complement operator (~) can be applied to a
// negative result to produce the index of the first element (if any) that
// is larger than the given search value. This is also the index at which
// the search value should be inserted into the list in order for the list
// to remain sorted.
//
// The method uses the Array.BinarySearch method to perform the
// search.
public int BinarySearch(int index, int count, T item, IComparer<T> comparer)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
if (_size - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.Ensures(Contract.Result<int>() <= index + count);
Contract.EndContractBlock();
return Array.BinarySearch<T>(_items, index, count, item, comparer);
}
public int BinarySearch(T item)
{
Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, null);
}
public int BinarySearch(T item, IComparer<T> comparer)
{
Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, comparer);
}
// Clears the contents of List.
public void Clear()
{
if (_size > 0)
{
Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
}
_version++;
}
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// EqualityComparer<T>.Default.Equals().
public bool Contains(T item)
{
// PERF: IndexOf calls Array.IndexOf, which internally
// calls EqualityComparer<T>.Default.IndexOf, which
// is specialized for different types. This
// boosts performance since instead of making a
// virtual method call each iteration of the loop,
// via EqualityComparer<T>.Default.Equals, we
// only make one virtual call to EqualityComparer.IndexOf.
return _size != 0 && IndexOf(item) != -1;
}
bool System.Collections.IList.Contains(object item)
{
if (IsCompatibleObject(item))
{
return Contains((T)item);
}
return false;
}
public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)
{
if (converter == null)
{
throw new ArgumentNullException(nameof(converter));
}
Contract.EndContractBlock();
List<TOutput> list = new List<TOutput>(_size);
for (int i = 0; i < _size; i++)
{
list._items[i] = converter(_items[i]);
}
list._size = _size;
return list;
}
// Copies this List into array, which must be of a
// compatible array type.
public void CopyTo(T[] array)
{
CopyTo(array, 0);
}
// Copies this List into array, which must be of a
// compatible array type.
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
{
if ((array != null) && (array.Rank != 1))
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
Contract.EndContractBlock();
try
{
// Array.Copy will check for NULL.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Copies a section of this list to the given array at the given index.
//
// The method uses the Array.Copy method to copy the elements.
public void CopyTo(int index, T[] array, int arrayIndex, int count)
{
if (_size - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Contract.EndContractBlock();
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, index, array, arrayIndex, count);
}
public void CopyTo(T[] array, int arrayIndex)
{
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
// Ensures that the capacity of this list is at least the given minimum
// value. If the current capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min)
{
if (_items.Length < min)
{
int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
//if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
public bool Exists(Predicate<T> match)
{
return FindIndex(match) != -1;
}
public T Find(Predicate<T> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
for (int i = 0; i < _size; i++)
{
if (match(_items[i]))
{
return _items[i];
}
}
return default(T);
}
public List<T> FindAll(Predicate<T> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
List<T> list = new List<T>();
for (int i = 0; i < _size; i++)
{
if (match(_items[i]))
{
list.Add(_items[i]);
}
}
return list;
}
public int FindIndex(Predicate<T> match)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindIndex(0, _size, match);
}
public int FindIndex(int startIndex, Predicate<T> match)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < startIndex + Count);
return FindIndex(startIndex, _size - startIndex, match);
}
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
if ((uint)startIndex > (uint)_size)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > _size - count)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count);
}
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < startIndex + count);
Contract.EndContractBlock();
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++)
{
if (match(_items[i])) return i;
}
return -1;
}
public T FindLast(Predicate<T> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
for (int i = _size - 1; i >= 0; i--)
{
if (match(_items[i]))
{
return _items[i];
}
}
return default(T);
}
public int FindLastIndex(Predicate<T> match)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindLastIndex(_size - 1, _size, match);
}
public int FindLastIndex(int startIndex, Predicate<T> match)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
return FindLastIndex(startIndex, startIndex + 1, match);
}
public int FindLastIndex(int startIndex, int count, Predicate<T> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
Contract.EndContractBlock();
if (_size == 0)
{
// Special case for 0 length List
if (startIndex != -1)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index);
}
}
else if ((uint)startIndex >= (uint)_size) // Make sure we're not out of range
{
throw new ArgumentOutOfRangeException(nameof(startIndex), startIndex, SR.ArgumentOutOfRange_Index);
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count);
}
int endIndex = startIndex - count;
for (int i = startIndex; i > endIndex; i--)
{
if (match(_items[i]))
{
return i;
}
}
return -1;
}
public void ForEach(Action<T> action)
{
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
int version = _version;
for (int i = 0; i < _size; i++)
{
if (version != _version)
{
break;
}
action(_items[i]);
}
if (version != _version)
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
// Returns an enumerator for this list with the given
// permission for removal of elements. If modifications made to the list
// while an enumeration is in progress, the MoveNext and
// GetObject methods of the enumerator will throw an exception.
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
public List<T> GetRange(int index, int count)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Contract.Ensures(Contract.Result<List<T>>() != null);
Contract.EndContractBlock();
List<T> list = new List<T>(count);
Array.Copy(_items, index, list._items, 0, count);
list._size = count;
return list;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards from beginning to end.
// The elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
public int IndexOf(T item)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return Array.IndexOf(_items, item, 0, _size);
}
int System.Collections.IList.IndexOf(object item)
{
if (IsCompatibleObject(item))
{
return IndexOf((T)item);
}
return -1;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and ending at count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
public int IndexOf(T item, int index)
{
if (index > _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, _size - index);
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and upto count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
public int IndexOf(T item, int index, int count)
{
if (index > _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
if (count < 0 || index > _size - count)
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count);
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, count);
}
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
public void Insert(int index, T item)
{
// Note that insertions at the end are legal.
if ((uint)index > (uint)_size)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_BiggerThanCollection);
}
Contract.EndContractBlock();
if (_size == _items.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
void System.Collections.IList.Insert(int index, object item)
{
if (item == null && !(default(T) == null))
throw new ArgumentNullException(nameof(item));
try
{
Insert(index, (T)item);
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, item, typeof(T)), nameof(item));
}
}
// Inserts the elements of the given collection at a given index. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger. Ranges may be added
// to the end of the list by setting index to the List's size.
public void InsertRange(int index, IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
if ((uint)index > (uint)_size)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{ // if collection is ICollection<T>
int count = c.Count;
if (count > 0)
{
EnsureCapacity(_size + count);
if (index < _size)
{
Array.Copy(_items, index, _items, index + count, _size - index);
}
// If we're inserting a List into itself, we want to be able to deal with that.
if (this == c)
{
// Copy first part of _items to insert location
Array.Copy(_items, 0, _items, index, index);
// Copy last part of _items back to inserted location
Array.Copy(_items, index + count, _items, index * 2, _size - index);
}
else
{
c.CopyTo(_items, index);
}
_size += count;
}
}
else
{
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Insert(index++, en.Current);
}
}
}
_version++;
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at the end
// and ending at the first element in the list. The elements of the list
// are compared to the given value using the Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
public int LastIndexOf(T item)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
if (_size == 0)
{ // Special case for empty list
return -1;
}
else
{
return LastIndexOf(item, _size - 1, _size);
}
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and ending at the first element in the list. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
public int LastIndexOf(T item, int index)
{
if (index >= _size)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
return LastIndexOf(item, index, index + 1);
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and upto count elements. The elements of
// the list are compared to the given value using the Object.Equals
// method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
public int LastIndexOf(T item, int index, int count)
{
if ((Count != 0) && (index < 0))
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if ((Count != 0) && (count < 0))
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
if (_size == 0)
{ // Special case for empty list
return -1;
}
if (index >= _size)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
if (count > index + 1)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_Count);
}
return Array.LastIndexOf(_items, item, index, count);
}
// Removes the element at the given index. The size of the list is
// decreased by one.
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
void System.Collections.IList.Remove(object item)
{
if (IsCompatibleObject(item))
{
Remove((T)item);
}
}
// This method removes all items which matches the predicate.
// The complexity is O(n).
public int RemoveAll(Predicate<T> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count));
Contract.EndContractBlock();
int freeIndex = 0; // the first free slot in items array
// Find the first item which needs to be removed.
while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++;
if (freeIndex >= _size) return 0;
int current = freeIndex + 1;
while (current < _size)
{
// Find the first item which needs to be kept.
while (current < _size && match(_items[current])) current++;
if (current < _size)
{
// copy item to the free slot.
_items[freeIndex++] = _items[current++];
}
}
Array.Clear(_items, freeIndex, _size - freeIndex);
int result = _size - freeIndex;
_size = freeIndex;
_version++;
return result;
}
// Removes the element at the given index. The size of the list is
// decreased by one.
public void RemoveAt(int index)
{
if ((uint)index >= (uint)_size)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
_size--;
if (index < _size)
{
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = default(T);
_version++;
}
// Removes a range of elements from this list.
public void RemoveRange(int index, int count)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (count > 0)
{
int i = _size;
_size -= count;
if (index < _size)
{
Array.Copy(_items, index + count, _items, index, _size - index);
}
Array.Clear(_items, _size, count);
_version++;
}
}
// Reverses the elements in this list.
public void Reverse()
{
Reverse(0, Count);
}
// Reverses the elements in a range of this list. Following a call to this
// method, an element in the range given by index and count
// which was previously located at index i will now be located at
// index index + (index + count - i - 1).
public void Reverse(int index, int count)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
// The non-generic Array.Reverse is not used because it does not perform
// well for non-primitive value types.
// If/when a generic Array.Reverse<T> becomes available, the below code
// can be deleted and replaced with a call to Array.Reverse<T>.
int i = index;
int j = index + count - 1;
T[] array = _items;
while (i < j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
_version++;
}
// Sorts the elements in this list. Uses the default comparer and
// Array.Sort.
public void Sort()
{
Sort(0, Count, null);
}
// Sorts the elements in this list. Uses Array.Sort with the
// provided comparer.
public void Sort(IComparer<T> comparer)
{
Sort(0, Count, comparer);
}
// Sorts the elements in a section of this list. The sort compares the
// elements to each other using the given IComparer interface. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented by all
// elements of the list.
//
// This method uses the Array.Sort method to sort the elements.
public void Sort(int index, int count, IComparer<T> comparer)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (count > 1)
{
Array.Sort<T>(_items, index, count, comparer);
}
_version++;
}
public void Sort(Comparison<T> comparison)
{
if (comparison == null)
{
throw new ArgumentNullException(nameof(comparison));
}
Contract.EndContractBlock();
if (_size > 1)
{
ArraySortHelper<T>.Sort(_items, 0, _size, comparison);
}
_version++;
}
// ToArray returns a new Object array containing the contents of the List.
// This requires copying the List, which is an O(n) operation.
public T[] ToArray()
{
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == Count);
if (_size == 0)
{
return s_emptyArray;
}
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
// Sets the capacity of this list to the size of the list. This method can
// be used to minimize a list's memory overhead once it is known that no
// new elements will be added to the list. To completely clear a list and
// release all memory referenced by the list, execute the following
// statements:
//
// list.Clear();
// list.TrimExcess();
public void TrimExcess()
{
int threshold = (int)(((double)_items.Length) * 0.9);
if (_size < threshold)
{
Capacity = _size;
}
}
public bool TrueForAll(Predicate<T> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
for (int i = 0; i < _size; i++)
{
if (!match(_items[i]))
{
return false;
}
}
return true;
}
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private List<T> _list;
private int _index;
private int _version;
private T _current;
internal Enumerator(List<T> list)
{
_list = list;
_index = 0;
_version = list._version;
_current = default(T);
}
public void Dispose()
{
}
public bool MoveNext()
{
List<T> localList = _list;
if (_version == localList._version && ((uint)_index < (uint)localList._size))
{
_current = localList._items[_index];
_index++;
return true;
}
return MoveNextRare();
}
private bool MoveNextRare()
{
if (_version != _list._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = _list._size + 1;
_current = default(T);
return false;
}
public T Current
{
get
{
return _current;
}
}
object System.Collections.IEnumerator.Current
{
get
{
if (_index == 0 || _index == _list._size + 1)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return Current;
}
}
void System.Collections.IEnumerator.Reset()
{
if (_version != _list._version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
_index = 0;
_current = default(T);
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: UnmanagedMemoryStream
**
** <OWNER>[....]</OWNER>
**
** Purpose: Create a stream over unmanaged memory, mostly
** useful for memory-mapped files.
**
** Date: October 20, 2000 (made public August 4, 2003)
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Diagnostics.Contracts;
#if !FEATURE_PAL && FEATURE_ASYNC_IO
using System.Threading.Tasks;
#endif // !FEATURE_PAL && FEATURE_ASYNC_IO
namespace System.IO {
/*
* This class is used to access a contiguous block of memory, likely outside
* the GC heap (or pinned in place in the GC heap, but a MemoryStream may
* make more sense in those cases). It's great if you have a pointer and
* a length for a section of memory mapped in by someone else and you don't
* want to copy this into the GC heap. UnmanagedMemoryStream assumes these
* two things:
*
* 1) All the memory in the specified block is readable or writable,
* depending on the values you pass to the constructor.
* 2) The lifetime of the block of memory is at least as long as the lifetime
* of the UnmanagedMemoryStream.
* 3) You clean up the memory when appropriate. The UnmanagedMemoryStream
* currently will do NOTHING to free this memory.
* 4) All calls to Write and WriteByte may not be threadsafe currently.
*
* It may become necessary to add in some sort of
* DeallocationMode enum, specifying whether we unmap a section of memory,
* call free, run a user-provided delegate to free the memory, etc etc.
* We'll suggest user write a subclass of UnmanagedMemoryStream that uses
* a SafeHandle subclass to hold onto the memory.
* Check for problems when using this in the negative parts of a
* process's address space. We may need to use unsigned longs internally
* and change the overflow detection logic.
*
* -----SECURITY MODEL AND SILVERLIGHT-----
* A few key notes about exposing UMS in silverlight:
* 1. No ctors are exposed to transparent code. This version of UMS only
* supports byte* (not SafeBuffer). Therefore, framework code can create
* a UMS and hand it to transparent code. Transparent code can use most
* operations on a UMS, but not operations that directly expose a
* pointer.
*
* 2. Scope of "unsafe" and non-CLS compliant operations reduced: The
* Whidbey version of this class has CLSCompliant(false) at the class
* level and unsafe modifiers at the method level. These were reduced to
* only where the unsafe operation is performed -- i.e. immediately
* around the pointer manipulation. Note that this brings UMS in line
* with recent changes in pu/clr to support SafeBuffer.
*
* 3. Currently, the only caller that creates a UMS is ResourceManager,
* which creates read-only UMSs, and therefore operations that can
* change the length will throw because write isn't supported. A
* conservative option would be to formalize the concept that _only_
* read-only UMSs can be creates, and enforce this by making WriteX and
* SetLength SecurityCritical. However, this is a violation of
* security inheritance rules, so we must keep these safe. The
* following notes make this acceptable for future use.
* a. a race condition in WriteX that could have allowed a thread to
* read from unzeroed memory was fixed
* b. memory region cannot be expanded beyond _capacity; in other
* words, a UMS creator is saying a writeable UMS is safe to
* write to anywhere in the memory range up to _capacity, specified
* in the ctor. Even if the caller doesn't specify a capacity, then
* length is used as the capacity.
*/
public class UnmanagedMemoryStream : Stream
{
//
private const long UnmanagedMemStreamMaxLength = Int64.MaxValue;
[System.Security.SecurityCritical] // auto-generated
private SafeBuffer _buffer;
[SecurityCritical]
private unsafe byte* _mem;
private long _length;
private long _capacity;
private long _position;
private long _offset;
private FileAccess _access;
internal bool _isOpen;
#if !FEATURE_PAL && FEATURE_ASYNC_IO
[NonSerialized]
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
#endif // FEATURE_PAL && FEATURE_ASYNC_IO
// Needed for subclasses that need to map a file, etc.
[System.Security.SecuritySafeCritical] // auto-generated
protected UnmanagedMemoryStream()
{
unsafe {
_mem = null;
}
_isOpen = false;
}
[System.Security.SecuritySafeCritical] // auto-generated
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) {
Initialize(buffer, offset, length, FileAccess.Read, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) {
Initialize(buffer, offset, length, access, false);
}
// We must create one of these without doing a security check. This
// class is created while security is trying to start up. Plus, doing
// a Demand from Assembly.GetManifestResourceStream isn't useful.
[System.Security.SecurityCritical] // auto-generated
internal UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
Initialize(buffer, offset, length, access, skipSecurityCheck);
}
[System.Security.SecuritySafeCritical] // auto-generated
protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) {
Initialize(buffer, offset, length, access, false);
}
[System.Security.SecurityCritical] // auto-generated
internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) {
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if (offset < 0) {
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (length < 0) {
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
if (buffer.ByteLength < (ulong)(offset + length)) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen"));
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
throw new ArgumentOutOfRangeException("access");
}
Contract.EndContractBlock();
if (_isOpen) {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
}
if (!skipSecurityCheck) {
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
}
// check for wraparound
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
buffer.AcquirePointer(ref pointer);
if ( (pointer + offset + length) < pointer) {
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
}
}
finally {
if (pointer != null) {
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_length = length;
_capacity = length;
_access = access;
_isOpen = true;
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length)
{
Initialize(pointer, length, length, FileAccess.Read, false);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access, false);
}
// We must create one of these without doing a security check. This
// class is created while security is trying to start up. Plus, doing
// a Demand from Assembly.GetManifestResourceStream isn't useful.
[System.Security.SecurityCritical] // auto-generated
internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
{
Initialize(pointer, length, capacity, access, skipSecurityCheck);
}
[System.Security.SecurityCritical] // auto-generated
[CLSCompliant(false)]
protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access, false);
}
[System.Security.SecurityCritical] // auto-generated
internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck)
{
if (pointer == null)
throw new ArgumentNullException("pointer");
if (length < 0 || capacity < 0)
throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (length > capacity)
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
Contract.EndContractBlock();
// Check for wraparound.
if (((byte*) ((long)pointer + capacity)) < pointer)
throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
if (_isOpen)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
if (!skipSecurityCheck)
#pragma warning disable 618
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
#pragma warning restore 618
_mem = pointer;
_offset = 0;
_length = length;
_capacity = capacity;
_access = access;
_isOpen = true;
}
public override bool CanRead {
[Pure]
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
public override bool CanSeek {
[Pure]
get { return _isOpen; }
}
public override bool CanWrite {
[Pure]
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
[System.Security.SecuritySafeCritical] // auto-generated
protected override void Dispose(bool disposing)
{
_isOpen = false;
unsafe { _mem = null; }
// Stream allocates WaitHandles for async calls. So for correctness
// call base.Dispose(disposing) for better perf, avoiding waiting
// for the finalizers to run on those types.
base.Dispose(disposing);
}
public override void Flush() {
if (!_isOpen) __Error.StreamIsClosed();
}
#if !FEATURE_PAL && FEATURE_ASYNC_IO
[HostProtection(ExternalThreading=true)]
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation(cancellationToken);
try {
Flush();
return Task.CompletedTask;
} catch(Exception ex) {
return Task.FromException(ex);
}
}
#endif // !FEATURE_PAL && FEATURE_ASYNC_IO
public override long Length {
get {
if (!_isOpen) __Error.StreamIsClosed();
return Interlocked.Read(ref _length);
}
}
public long Capacity {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity;
}
}
public override long Position {
get {
if (!CanSeek) __Error.StreamIsClosed();
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
[System.Security.SecuritySafeCritical] // auto-generated
set {
if (value < 0)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (!CanSeek) __Error.StreamIsClosed();
#if WIN32
unsafe {
// On 32 bit machines, ensure we don't wrap around.
if (value > (long) Int32.MaxValue || _mem + value < _mem)
throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
#endif
Interlocked.Exchange(ref _position, value);
}
}
[CLSCompliant(false)]
public unsafe byte* PositionPointer {
[System.Security.SecurityCritical] // auto-generated_required
get {
if (_buffer != null) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
}
// Use a temp to avoid a race
long pos = Interlocked.Read(ref _position);
if (pos > _capacity)
throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition"));
byte * ptr = _mem + pos;
if (!_isOpen) __Error.StreamIsClosed();
return ptr;
}
[System.Security.SecurityCritical] // auto-generated_required
set {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
// Note: subtracting pointers returns an Int64. Working around
// to avoid hitting compiler warning CS0652 on this line.
if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
if (value < _mem)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, value - _mem);
}
}
internal unsafe byte* Pointer {
[System.Security.SecurityCritical] // auto-generated
get {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
return _mem;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep this in [....] with contract validation in ReadAsync
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
// Use a local variable to avoid a race where another thread
// changes our position after we decide we can read some bytes.
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
long n = len - pos;
if (n > count)
n = count;
if (n <= 0)
return 0;
int nInt = (int) n; // Safe because n <= count, which is an Int32
if (nInt < 0)
nInt = 0; // _position could be beyond EOF
Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
if (_buffer != null) {
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(buffer, offset, pointer + pos + _offset, 0, nInt);
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
Buffer.Memcpy(buffer, offset, _mem + pos, 0, nInt);
}
}
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
#if !FEATURE_PAL && FEATURE_ASYNC_IO
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation<Int32>(cancellationToken);
try {
Int32 n = Read(buffer, offset, count);
Task<Int32> t = _lastReadTask;
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
} catch (Exception ex) {
Contract.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
#endif // !FEATURE_PAL && FEATURE_ASYNC_IO
[System.Security.SecuritySafeCritical] // auto-generated
public override int ReadByte() {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
if (pos >= len)
return -1;
Interlocked.Exchange(ref _position, pos + 1);
int result;
if (_buffer != null) {
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
result = *(pointer + pos + _offset);
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
result = _mem[pos];
}
}
return result;
}
public override long Seek(long offset, SeekOrigin loc) {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > UnmanagedMemStreamMaxLength)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
switch(loc) {
case SeekOrigin.Begin:
if (offset < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, offset);
break;
case SeekOrigin.Current:
long pos = Interlocked.Read(ref _position);
if (offset + pos < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, offset + pos);
break;
case SeekOrigin.End:
long len = Interlocked.Read(ref _length);
if (len + offset < 0)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
Interlocked.Exchange(ref _position, len + offset);
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
long finalPos = Interlocked.Read(ref _position);
Contract.Assert(finalPos >= 0, "_position >= 0");
return finalPos;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void SetLength(long value) {
if (value < 0)
throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
if (value > _capacity)
throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity"));
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
if (value > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, value-len);
}
}
Interlocked.Exchange(ref _length, value);
if (pos > value) {
Interlocked.Exchange(ref _position, value);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // Keep contract validation in [....] with WriteAsync(..)
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + count;
// Check for overflow
if (n < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (n > _capacity) {
throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
}
if (_buffer == null) {
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
if (pos > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, pos-len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
if (n > len) {
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null) {
long bytesLeft = _capacity - pos;
if (bytesLeft < count) {
throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
}
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
Buffer.Memcpy(pointer + pos + _offset, 0, buffer, offset, count);
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
Buffer.Memcpy(_mem + pos, 0, buffer, offset, count);
}
}
Interlocked.Exchange(ref _position, n);
return;
}
#if !FEATURE_PAL && FEATURE_ASYNC_IO
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(..)
if (cancellationToken.IsCancellationRequested)
return Task.FromCancellation(cancellationToken);
try {
Write(buffer, offset, count);
return Task.CompletedTask;
} catch (Exception ex) {
Contract.Assert(! (ex is OperationCanceledException));
return Task.FromException<Int32>(ex);
}
}
#endif // !FEATURE_PAL && FEATURE_ASYNC_IO
[System.Security.SecuritySafeCritical] // auto-generated
public override void WriteByte(byte value) {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + 1;
if (pos >= len) {
// Check for overflow
if (n < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (n > _capacity)
throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
if (_buffer == null) {
if (pos > len) {
unsafe {
Buffer.ZeroMemory(_mem+len, pos-len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
Interlocked.Exchange(ref _length, n);
}
}
if (_buffer != null) {
unsafe {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try {
_buffer.AcquirePointer(ref pointer);
*(pointer + pos + _offset) = value;
}
finally {
if (pointer != null) {
_buffer.ReleasePointer();
}
}
}
}
else {
unsafe {
_mem[pos] = value;
}
}
Interlocked.Exchange(ref _position, n);
}
}
}
| |
using UnityEngine;
using UnityEngine.InputNew;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Reflection;
[CustomEditor(typeof(ActionMap))]
public class ActionMapEditor : Editor
{
static class Styles
{
public static GUIContent iconToolbarPlus = EditorGUIUtility.IconContent("Toolbar Plus", "Add to list");
public static GUIContent iconToolbarMinus = EditorGUIUtility.IconContent("Toolbar Minus", "Remove from list");
public static GUIContent iconToolbarPlusMore = EditorGUIUtility.IconContent("Toolbar Plus More", "Choose to add to list");
public static Dictionary<InputControlType, string[]> controlTypeSubLabels;
static Styles()
{
controlTypeSubLabels = new Dictionary<InputControlType, string[]>();
controlTypeSubLabels[InputControlType.Vector2] = new string[] { "X", "Y" };
controlTypeSubLabels[InputControlType.Vector3] = new string[] { "X", "Y", "Z" };
controlTypeSubLabels[InputControlType.Vector4] = new string[] { "X", "Y", "Z", "W" };
controlTypeSubLabels[InputControlType.Quaternion] = new string[] { "X", "Y", "Z", "W" };
}
}
ActionMap m_ActionMapEditCopy;
int m_SelectedScheme = 0;
int m_SelectedDeviceIndex = 0;
[System.NonSerialized]
InputAction m_SelectedAction = null;
List<string> m_PropertyNames = new List<string>();
HashSet<string> m_PropertyBlacklist = new HashSet<string>();
Dictionary<string, string> m_PropertyErrors = new Dictionary<string, string>();
InputControlDescriptor m_SelectedSource = null;
ButtonAxisSource m_SelectedButtonAxisSource = null;
bool m_Modified = false;
int selectedScheme
{
get { return m_SelectedScheme; }
set
{
if (m_SelectedScheme == value)
return;
m_SelectedScheme = value;
}
}
InputAction selectedAction
{
get { return m_SelectedAction; }
set
{
if (m_SelectedAction == value)
return;
m_SelectedAction = value;
}
}
void OnEnable()
{
Revert();
RefreshPropertyNames();
CalculateBlackList();
}
public virtual void OnDisable ()
{
// When destroying the editor check if we have any unapplied modifications and ask about applying them.
if (m_Modified)
{
string dialogText = "Unapplied changes to ActionMap '" + serializedObject.targetObject.name + "'.";
if (EditorUtility.DisplayDialog ("Unapplied changes", dialogText, "Apply", "Revert"))
Apply();
}
}
void Apply()
{
EditorGUIUtility.keyboardControl = 0;
m_ActionMapEditCopy.name = target.name;
SerializedObject temp = new SerializedObject(m_ActionMapEditCopy);
temp.Update();
SerializedProperty prop = temp.GetIterator();
while (prop.Next(true))
serializedObject.CopyFromSerializedProperty(prop);
// Make sure references in control schemes to action map itself are stored correctly.
for (int i = 0; i < m_ActionMapEditCopy.controlSchemes.Count; i++)
serializedObject.FindProperty("m_ControlSchemes")
.GetArrayElementAtIndex(i)
.FindPropertyRelative("m_ActionMap").objectReferenceValue = target;
serializedObject.ApplyModifiedProperties();
var existingAssets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(target));
// Add action sub-assets.
ActionMap actionMap = (ActionMap)target;
for (int i = 0; i < m_ActionMapEditCopy.actions.Count; i++)
{
InputAction action = m_ActionMapEditCopy.actions[i];
action.actionMap = actionMap;
action.actionIndex = i;
if (existingAssets.Contains(action))
continue;
AssetDatabase.AddObjectToAsset(action, target);
}
m_Modified = false;
// Reimporting is needed in order for the sub-assets to show up.
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
UpdateActionMapScript();
}
void Revert ()
{
EditorGUIUtility.keyboardControl = 0;
ActionMap original = (ActionMap)serializedObject.targetObject;
m_ActionMapEditCopy = Instantiate<ActionMap>(original);
m_ActionMapEditCopy.name = original.name;
m_Modified = false;
}
void RefreshPropertyNames()
{
// Calculate property names.
m_PropertyNames.Clear();
for (int i = 0; i < m_ActionMapEditCopy.actions.Count; i++)
m_PropertyNames.Add(GetCamelCaseString(m_ActionMapEditCopy.actions[i].name, false));
// Calculate duplicates.
HashSet<string> duplicates = new HashSet<string>(m_PropertyNames.GroupBy(x => x).Where(group => group.Count() > 1).Select(group => group.Key));
// Calculate errors.
m_PropertyErrors.Clear();
for (int i = 0; i < m_PropertyNames.Count; i++)
{
string name = m_PropertyNames[i];
if (m_PropertyBlacklist.Contains(name))
m_PropertyErrors[name] = "Invalid action name: "+name+".";
else if (duplicates.Contains(name))
m_PropertyErrors[name] = "Duplicate action name: "+name+".";
}
}
void CalculateBlackList()
{
m_PropertyBlacklist = new HashSet<string>(typeof(ActionMapInput).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).Select(e => e.Name));
}
public override void OnInspectorGUI()
{
EditorGUI.BeginChangeCheck();
DrawControlSchemeSelection();
if (m_ActionMapEditCopy.controlSchemes.Count > 0)
{
EditorGUILayout.Space();
DrawControlSchemeGUI();
EditorGUILayout.Space();
DrawActionList();
if (selectedAction != null)
{
EditorGUILayout.Space();
DrawActionGUI();
}
EditorGUILayout.Space();
}
if (EditorGUI.EndChangeCheck())
{
EditorUtility.SetDirty(m_ActionMapEditCopy);
m_Modified = true;
}
ApplyRevertGUI();
}
void DrawControlSchemeSelection()
{
if (selectedScheme >= m_ActionMapEditCopy.controlSchemes.Count)
selectedScheme = m_ActionMapEditCopy.controlSchemes.Count - 1;
// Show schemes
EditorGUILayout.LabelField("Control Schemes");
EditorGUIUtility.GetControlID(FocusType.Passive);
EditorGUILayout.BeginVertical("Box");
for (int i = 0; i < m_ActionMapEditCopy.controlSchemes.Count; i++)
{
Rect rect = EditorGUILayout.GetControlRect();
if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition))
{
EditorGUIUtility.keyboardControl = 0;
selectedScheme = i;
Event.current.Use();
}
if (selectedScheme == i)
GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture);
EditorGUI.LabelField(rect, m_ActionMapEditCopy.controlSchemes[i].name);
}
EditorGUILayout.EndVertical();
// Control scheme remove and add buttons
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(15 * EditorGUI.indentLevel);
if (GUILayout.Button(Styles.iconToolbarMinus, GUIStyle.none))
RemoveControlScheme();
if (GUILayout.Button(Styles.iconToolbarPlus, GUIStyle.none))
AddControlScheme();
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
}
void AddControlScheme()
{
var controlScheme = new ControlScheme("New Control Scheme", m_ActionMapEditCopy);
for (int i = 0; i < m_ActionMapEditCopy.actions.Count; i++)
controlScheme.bindings.Add(new ControlBinding());
m_ActionMapEditCopy.controlSchemes.Add(controlScheme);
selectedScheme = m_ActionMapEditCopy.controlSchemes.Count - 1;
}
void RemoveControlScheme()
{
m_ActionMapEditCopy.controlSchemes.RemoveAt(selectedScheme);
if (selectedScheme >= m_ActionMapEditCopy.controlSchemes.Count)
selectedScheme = m_ActionMapEditCopy.controlSchemes.Count - 1;
}
void DrawControlSchemeGUI()
{
ControlScheme scheme = m_ActionMapEditCopy.controlSchemes[selectedScheme];
EditorGUI.BeginChangeCheck();
string schemeName = EditorGUILayout.TextField("Control Scheme Name", scheme.name);
if (EditorGUI.EndChangeCheck())
scheme.name = schemeName;
string[] deviceNames = InputDeviceUtility.GetDeviceNames();
for (int i = 0; i < scheme.serializableDeviceTypes.Count; i++)
{
Rect rect = EditorGUILayout.GetControlRect();
if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition))
{
m_SelectedDeviceIndex = i;
Repaint();
}
if (m_SelectedDeviceIndex == i)
GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture);
EditorGUI.BeginChangeCheck();
int deviceIndex = EditorGUI.Popup(
rect,
"Device Type",
InputDeviceUtility.GetDeviceIndex(scheme.serializableDeviceTypes[i]),
deviceNames);
if (EditorGUI.EndChangeCheck())
scheme.serializableDeviceTypes[i].value = InputDeviceUtility.GetDeviceType(deviceIndex);
}
// Device remove and add buttons
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(15 * EditorGUI.indentLevel);
if (GUILayout.Button(Styles.iconToolbarMinus, GUIStyle.none))
RemoveDevice();
if (GUILayout.Button(Styles.iconToolbarPlus, GUIStyle.none))
AddDevice();
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
// Pad this area with spacing so all control schemes use same heights,
// and the actions table below doesn't move when switching control scheme.
int maxDevices = 0;
for (int i = 0; i < m_ActionMapEditCopy.controlSchemes.Count; i++)
maxDevices = Mathf.Max(maxDevices, m_ActionMapEditCopy.controlSchemes[i].serializableDeviceTypes.Count);
int extraLines = maxDevices - scheme.serializableDeviceTypes.Count;
EditorGUILayout.GetControlRect(true, extraLines * (EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing));
}
void AddDevice()
{
ControlScheme scheme = m_ActionMapEditCopy.controlSchemes[selectedScheme];
scheme.serializableDeviceTypes.Add(new SerializableType(null));
}
void RemoveDevice()
{
ControlScheme scheme = m_ActionMapEditCopy.controlSchemes[selectedScheme];
if (m_SelectedDeviceIndex >= 0 && m_SelectedDeviceIndex < scheme.serializableDeviceTypes.Count)
{
scheme.serializableDeviceTypes.RemoveAt(m_SelectedDeviceIndex);
}
}
void DrawActionList()
{
// Show actions
EditorGUILayout.LabelField("Actions", m_ActionMapEditCopy.controlSchemes[selectedScheme].name + " Bindings");
EditorGUILayout.BeginVertical("Box");
{
foreach (var action in m_ActionMapEditCopy.actions)
{
DrawActionRow(action, selectedScheme);
}
if (m_ActionMapEditCopy.actions.Count == 0)
EditorGUILayout.GetControlRect();
}
EditorGUILayout.EndVertical();
// Action remove and add buttons
EditorGUILayout.BeginHorizontal();
{
GUILayout.Space(15 * EditorGUI.indentLevel);
if (GUILayout.Button(Styles.iconToolbarMinus, GUIStyle.none))
RemoveAction();
if (GUILayout.Button(Styles.iconToolbarPlus, GUIStyle.none))
AddAction();
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
}
void AddAction()
{
var action = ScriptableObject.CreateInstance<InputAction>();
action.name = "New Control";
m_ActionMapEditCopy.actions.Add(action);
for (int i = 0; i < m_ActionMapEditCopy.controlSchemes.Count; i++)
m_ActionMapEditCopy.controlSchemes[i].bindings.Add(new ControlBinding());
selectedAction = m_ActionMapEditCopy.actions[m_ActionMapEditCopy.actions.Count - 1];
RefreshPropertyNames();
}
void RemoveAction()
{
int actionIndex = m_ActionMapEditCopy.actions.IndexOf(selectedAction);
m_ActionMapEditCopy.actions.RemoveAt(actionIndex);
for (int i = 0; i < m_ActionMapEditCopy.controlSchemes.Count; i++)
m_ActionMapEditCopy.controlSchemes[i].bindings.RemoveAt(actionIndex);
ScriptableObject.DestroyImmediate(selectedAction, true);
if (m_ActionMapEditCopy.actions.Count == 0)
selectedAction = null;
else
selectedAction = m_ActionMapEditCopy.actions[Mathf.Min(actionIndex, m_ActionMapEditCopy.actions.Count - 1)];
RefreshPropertyNames();
}
void ApplyRevertGUI()
{
bool valid = true;
if (m_PropertyErrors.Count > 0)
{
valid = false;
EditorGUILayout.HelpBox(string.Join("\n", m_PropertyErrors.Values.ToArray()), MessageType.Error);
}
EditorGUI.BeginDisabledGroup(!m_Modified);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Revert"))
Revert();
EditorGUI.BeginDisabledGroup(!valid);
if (GUILayout.Button("Apply"))
Apply();
EditorGUI.EndDisabledGroup();
}
GUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
}
void DrawActionRow(InputAction action, int selectedScheme)
{
int actionIndex = m_ActionMapEditCopy.actions.IndexOf(action);
int sourceCount = 0;
for (int i = 0; i < m_ActionMapEditCopy.controlSchemes.Count; i++)
{
ControlBinding schemeBinding = m_ActionMapEditCopy.controlSchemes[i].bindings[actionIndex];
int count = schemeBinding.sources.Count + schemeBinding.buttonAxisSources.Count;
sourceCount = Mathf.Max(sourceCount, count);
}
int lines = Mathf.Max(1, sourceCount);
float height = EditorGUIUtility.singleLineHeight * lines + EditorGUIUtility.standardVerticalSpacing * (lines - 1) + 8;
Rect totalRect = GUILayoutUtility.GetRect(1, height);
Rect baseRect = totalRect;
baseRect.yMin += 4;
baseRect.yMax -= 4;
if (selectedAction == action)
GUI.DrawTexture(totalRect, EditorGUIUtility.whiteTexture);
// Show control fields
Rect rect = baseRect;
rect.height = EditorGUIUtility.singleLineHeight;
rect.width = EditorGUIUtility.labelWidth - 4;
EditorGUI.LabelField(rect, action.controlData.name);
// Show binding fields
ControlBinding binding = m_ActionMapEditCopy.controlSchemes[selectedScheme].bindings[actionIndex];
if (binding != null)
{
rect = baseRect;
rect.height = EditorGUIUtility.singleLineHeight;
rect.xMin += EditorGUIUtility.labelWidth;
if (binding.primaryIsButtonAxis)
{
DrawButtonAxisSources(ref rect, binding);
DrawSources(ref rect, binding);
}
else
{
DrawSources(ref rect, binding);
DrawButtonAxisSources(ref rect, binding);
}
}
if (Event.current.type == EventType.MouseDown && totalRect.Contains(Event.current.mousePosition))
{
EditorGUIUtility.keyboardControl = 0;
selectedAction = action;
Event.current.Use();
}
}
void DrawSources(ref Rect rect, ControlBinding binding)
{
for (int i = 0; i < binding.sources.Count; i++)
{
DrawSourceSummary(rect, binding.sources[i]);
rect.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
}
}
void DrawButtonAxisSources(ref Rect rect, ControlBinding binding)
{
for (int i = 0; i < binding.buttonAxisSources.Count; i++)
{
DrawButtonAxisSourceSummary(rect, binding.buttonAxisSources[i]);
rect.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
}
}
void DrawSourceSummary(Rect rect, InputControlDescriptor source)
{
EditorGUI.LabelField(rect, GetSourceString(source));
}
void DrawButtonAxisSourceSummary(Rect rect, ButtonAxisSource source)
{
if ((System.Type)(source.negative.deviceType) == (System.Type)(source.positive.deviceType))
EditorGUI.LabelField(rect,
string.Format("{0} {1} & {2}",
InputDeviceUtility.GetDeviceName(source.negative),
InputDeviceUtility.GetDeviceControlName(source.negative),
InputDeviceUtility.GetDeviceControlName(source.positive)
)
);
else
EditorGUI.LabelField(rect, string.Format("{0} & {1}", GetSourceString(source.negative), GetSourceString(source.positive)));
}
string GetSourceString(InputControlDescriptor source)
{
return string.Format("{0} {1}", InputDeviceUtility.GetDeviceName(source), InputDeviceUtility.GetDeviceControlName(source));
}
void UpdateActionMapScript () {
ActionMap original = (ActionMap)serializedObject.targetObject;
string className = GetCamelCaseString(original.name, true);
StringBuilder str = new StringBuilder();
str.AppendFormat(@"using UnityEngine;
using UnityEngine.InputNew;
// GENERATED FILE - DO NOT EDIT MANUALLY
public class {0} : ActionMapInput {{
public {0} (ActionMap actionMap) : base (actionMap) {{ }}
", className);
for (int i = 0; i < m_ActionMapEditCopy.actions.Count; i++)
{
InputControlType controlType = m_ActionMapEditCopy.actions[i].controlData.controlType;
string typeStr = string.Empty;
switch(controlType)
{
case InputControlType.Button:
typeStr = "ButtonInputControl";
break;
case InputControlType.AbsoluteAxis:
case InputControlType.RelativeAxis:
typeStr = "AxisInputControl";
break;
case InputControlType.Vector2:
typeStr = "Vector2InputControl";
break;
case InputControlType.Vector3:
typeStr = "Vector3InputControl";
break;
}
str.AppendFormat(" public {2} @{0} {{ get {{ return ({2})this[{1}]; }} }}\n", GetCamelCaseString(m_ActionMapEditCopy.actions[i].name, false), i, typeStr);
}
str.AppendLine(@"}");
string path = AssetDatabase.GetAssetPath(original);
path = path.Substring(0, path.Length - Path.GetExtension(path).Length) + ".cs";
File.WriteAllText(path, str.ToString());
AssetDatabase.ImportAsset(path);
original.SetMapTypeName(className+", "+"Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
}
string GetCamelCaseString(string input, bool capitalFirstLetter)
{
string output = string.Empty;
bool capitalize = capitalFirstLetter;
for (int i = 0; i < input.Length; i++)
{
char c = input[i];
if (c == ' ')
{
capitalize = true;
continue;
}
if (char.IsLetter(c))
{
if (capitalize)
output += char.ToUpper(c);
else if (output.Length == 0)
output += char.ToLower(c);
else
output += c;
capitalize = false;
continue;
}
if (char.IsDigit(c))
{
if (output.Length > 0)
{
output += c;
capitalize = false;
}
continue;
}
if (c == '_')
{
output += c;
capitalize = true;
continue;
}
}
return output;
}
void DrawActionGUI()
{
EditorGUI.BeginChangeCheck();
string name = EditorGUILayout.TextField("Name", selectedAction.controlData.name);
if (EditorGUI.EndChangeCheck())
{
InputControlData data = selectedAction.controlData;
data.name = name;
selectedAction.controlData = data;
selectedAction.name = name;
RefreshPropertyNames();
}
EditorGUI.BeginChangeCheck();
var type = (InputControlType)EditorGUILayout.EnumPopup("Type", selectedAction.controlData.controlType);
if (EditorGUI.EndChangeCheck())
{
InputControlData data = selectedAction.controlData;
data.controlType = type;
selectedAction.controlData = data;
}
EditorGUILayout.Space();
if (Styles.controlTypeSubLabels.ContainsKey(selectedAction.controlData.controlType))
{
DrawCompositeControl(selectedAction);
}
else
{
if (selectedScheme >= 0 && selectedScheme < m_ActionMapEditCopy.controlSchemes.Count)
{
int actionIndex = m_ActionMapEditCopy.actions.IndexOf(selectedAction);
DrawBinding(m_ActionMapEditCopy.controlSchemes[selectedScheme].bindings[actionIndex]);
}
}
}
void DrawCompositeControl(InputAction action)
{
string[] subLabels = Styles.controlTypeSubLabels[action.controlData.controlType];
if (action.controlData.componentControlIndices == null ||
action.controlData.componentControlIndices.Length != subLabels.Length)
{
var data = action.controlData;
data.componentControlIndices = new int[subLabels.Length];
action.controlData = data;
}
for (int i = 0; i < subLabels.Length; i++)
{
DrawCompositeSource(string.Format("Source ({0})", subLabels[i]), action, i);
}
}
void DrawCompositeSource(string label, InputAction action, int index)
{
EditorGUI.BeginChangeCheck();
string[] actionStrings = m_ActionMapEditCopy.actions.Select(e => e.name).ToArray();
int controlIndex = EditorGUILayout.Popup(label, action.controlData.componentControlIndices[index], actionStrings);
if (EditorGUI.EndChangeCheck())
{
action.controlData.componentControlIndices[index] = controlIndex;
}
}
void DrawBinding(ControlBinding binding)
{
if (binding.primaryIsButtonAxis)
{
DrawButtonAxisSources(binding);
DrawSources(binding);
}
else
{
DrawSources(binding);
DrawButtonAxisSources(binding);
}
// Remove and add buttons
EditorGUILayout.BeginHorizontal();
GUILayout.Space(15 * EditorGUI.indentLevel);
if (GUILayout.Button(Styles.iconToolbarMinus, GUIStyle.none))
{
if (m_SelectedSource != null)
binding.sources.Remove(m_SelectedSource);
if (m_SelectedButtonAxisSource != null)
binding.buttonAxisSources.Remove(m_SelectedButtonAxisSource);
}
Rect r = GUILayoutUtility.GetRect(Styles.iconToolbarPlusMore, GUIStyle.none);
if (GUI.Button(r, Styles.iconToolbarPlusMore, GUIStyle.none))
{
ShowAddOptions(r, binding);
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
}
void ShowAddOptions(Rect rect, ControlBinding binding)
{
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("Regular Source"), false, AddSource, binding);
menu.AddItem(new GUIContent("Button Axis Source"), false, AddButtonAxisSource, binding);
menu.DropDown(rect);
}
void AddSource(object data)
{
ControlBinding binding = (ControlBinding)data;
var source = new InputControlDescriptor();
binding.sources.Add(source);
m_SelectedButtonAxisSource = null;
m_SelectedSource = source;
}
void AddButtonAxisSource(object data)
{
ControlBinding binding = (ControlBinding)data;
var source = new ButtonAxisSource(new InputControlDescriptor(), new InputControlDescriptor());
binding.buttonAxisSources.Add(source);
m_SelectedSource = null;
m_SelectedButtonAxisSource = source;
}
void DrawSources(ControlBinding binding)
{
for (int i = 0; i < binding.sources.Count; i++)
{
DrawSourceSummary(binding.sources[i]);
}
}
void DrawButtonAxisSources(ControlBinding binding)
{
for (int i = 0; i < binding.buttonAxisSources.Count; i++)
{
DrawButtonAxisSourceSummary(binding.buttonAxisSources[i]);
}
}
void DrawSourceSummary(InputControlDescriptor source)
{
Rect rect = EditorGUILayout.GetControlRect();
if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition))
{
m_SelectedButtonAxisSource = null;
m_SelectedSource = source;
Repaint();
}
if (m_SelectedSource == source)
GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture);
DrawSourceSummary(rect, "Source", source);
EditorGUILayout.Space();
}
void DrawButtonAxisSourceSummary(ButtonAxisSource source)
{
Rect rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 2 + EditorGUIUtility.standardVerticalSpacing);
if (Event.current.type == EventType.MouseDown && rect.Contains(Event.current.mousePosition))
{
m_SelectedSource = null;
m_SelectedButtonAxisSource = source;
Repaint();
}
if (m_SelectedButtonAxisSource == source)
GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture);
rect.height = EditorGUIUtility.singleLineHeight;
DrawSourceSummary(rect, "Source (negative)", source.negative);
rect.y += EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
DrawSourceSummary(rect, "Source (positive)", source.positive);
EditorGUILayout.Space();
}
void DrawSourceSummary(Rect rect, string label, InputControlDescriptor source)
{
if (m_SelectedSource == source)
GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture);
rect = EditorGUI.PrefixLabel(rect, new GUIContent(label));
rect.width = (rect.width - 4) * 0.5f;
int indentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
List<System.Type> types = m_ActionMapEditCopy.controlSchemes[selectedScheme].deviceTypes.ToList();
string[] deviceNames = types.Select(e => e == null ? string.Empty : e.Name).ToArray();
EditorGUI.BeginChangeCheck();
int deviceIndex = EditorGUI.Popup(rect, types.IndexOf(source.deviceType), deviceNames);
if (EditorGUI.EndChangeCheck())
source.deviceType = types[deviceIndex];
rect.x += rect.width + 4;
string[] controlNames = InputDeviceUtility.GetDeviceControlNames(source.deviceType);
EditorGUI.BeginChangeCheck();
int controlIndex = EditorGUI.Popup(rect, source.controlIndex, controlNames);
if (EditorGUI.EndChangeCheck())
source.controlIndex = controlIndex;
EditorGUI.indentLevel = indentLevel;
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Capabilities;
using Microsoft.VisualStudio.Services.Agent.Listener.Configuration;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Common;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.Services.OAuth;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.Services.Agent.Listener
{
[ServiceLocator(Default = typeof(MessageListener))]
public interface IMessageListener : IAgentService
{
Task<Boolean> CreateSessionAsync(CancellationToken token);
Task DeleteSessionAsync();
Task<TaskAgentMessage> GetNextMessageAsync(CancellationToken token);
Task DeleteMessageAsync(TaskAgentMessage message);
}
public sealed class MessageListener : AgentService, IMessageListener
{
private long? _lastMessageId;
private AgentSettings _settings;
private ITerminal _term;
private IAgentServer _agentServer;
private TaskAgentSession _session;
private TimeSpan _getNextMessageRetryInterval;
private readonly TimeSpan _sessionCreationRetryInterval = TimeSpan.FromSeconds(30);
private readonly TimeSpan _sessionConflictRetryLimit = TimeSpan.FromMinutes(4);
private readonly TimeSpan _clockSkewRetryLimit = TimeSpan.FromMinutes(30);
private readonly Dictionary<string, int> _sessionCreationExceptionTracker = new Dictionary<string, int>();
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
_term = HostContext.GetService<ITerminal>();
_agentServer = HostContext.GetService<IAgentServer>();
}
public async Task<Boolean> CreateSessionAsync(CancellationToken token)
{
Trace.Entering();
// Settings
var configManager = HostContext.GetService<IConfigurationManager>();
_settings = configManager.LoadSettings();
var serverUrl = _settings.ServerUrl;
Trace.Info(_settings);
// Capabilities.
_term.WriteLine(StringUtil.Loc("ScanToolCapabilities"));
Dictionary<string, string> systemCapabilities = await HostContext.GetService<ICapabilitiesManager>().GetCapabilitiesAsync(_settings, token);
// Create connection.
Trace.Info("Loading Credentials");
var credMgr = HostContext.GetService<ICredentialManager>();
VssCredentials creds = credMgr.LoadCredentials();
var agent = new TaskAgentReference
{
Id = _settings.AgentId,
Name = _settings.AgentName,
Version = BuildConstants.AgentPackage.Version,
OSDescription = RuntimeInformation.OSDescription,
};
string sessionName = $"{Environment.MachineName ?? "AGENT"}";
var taskAgentSession = new TaskAgentSession(sessionName, agent, systemCapabilities);
string errorMessage = string.Empty;
bool encounteringError = false;
_term.WriteLine(StringUtil.Loc("ConnectToServer"));
while (true)
{
token.ThrowIfCancellationRequested();
Trace.Info($"Attempt to create session.");
try
{
Trace.Info("Connecting to the Agent Server...");
await _agentServer.ConnectAsync(new Uri(serverUrl), creds);
Trace.Info("VssConnection created");
_session = await _agentServer.CreateAgentSessionAsync(
_settings.PoolId,
taskAgentSession,
token);
Trace.Info($"Session created.");
if (encounteringError)
{
_term.WriteLine(StringUtil.Loc("QueueConnected", DateTime.UtcNow));
_sessionCreationExceptionTracker.Clear();
encounteringError = false;
}
return true;
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
Trace.Info("Session creation has been cancelled.");
throw;
}
catch (TaskAgentAccessTokenExpiredException)
{
Trace.Info("Agent OAuth token has been revoked. Session creation failed.");
throw;
}
catch (Exception ex)
{
Trace.Error("Catch exception during create session.");
Trace.Error(ex);
if (!IsSessionCreationExceptionRetriable(ex))
{
_term.WriteError(StringUtil.Loc("SessionCreateFailed", ex.Message));
return false;
}
if (!encounteringError) //print the message only on the first error
{
_term.WriteError(StringUtil.Loc("QueueConError", DateTime.UtcNow, ex.Message, _sessionCreationRetryInterval.TotalSeconds));
encounteringError = true;
}
Trace.Info("Sleeping for {0} seconds before retrying.", _sessionCreationRetryInterval.TotalSeconds);
await HostContext.Delay(_sessionCreationRetryInterval, token);
}
}
}
public async Task DeleteSessionAsync()
{
if (_session != null && _session.SessionId != Guid.Empty)
{
using (var ts = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
{
await _agentServer.DeleteAgentSessionAsync(_settings.PoolId, _session.SessionId, ts.Token);
}
}
}
public async Task<TaskAgentMessage> GetNextMessageAsync(CancellationToken token)
{
Trace.Entering();
ArgUtil.NotNull(_session, nameof(_session));
ArgUtil.NotNull(_settings, nameof(_settings));
bool encounteringError = false;
int continuousError = 0;
string errorMessage = string.Empty;
Stopwatch heartbeat = new Stopwatch();
heartbeat.Restart();
while (true)
{
token.ThrowIfCancellationRequested();
TaskAgentMessage message = null;
try
{
message = await _agentServer.GetAgentMessageAsync(_settings.PoolId,
_session.SessionId,
_lastMessageId,
token);
// Decrypt the message body if the session is using encryption
message = DecryptMessage(message);
if (message != null)
{
_lastMessageId = message.MessageId;
}
if (encounteringError) //print the message once only if there was an error
{
_term.WriteLine(StringUtil.Loc("QueueConnected", DateTime.UtcNow));
encounteringError = false;
continuousError = 0;
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
Trace.Info("Get next message has been cancelled.");
throw;
}
catch (TaskAgentAccessTokenExpiredException)
{
Trace.Info("Agent OAuth token has been revoked. Unable to pull message.");
throw;
}
catch (Exception ex)
{
Trace.Error("Catch exception during get next message.");
Trace.Error(ex);
// don't retry if SkipSessionRecover = true, DT service will delete agent session to stop agent from taking more jobs.
if (ex is TaskAgentSessionExpiredException && !_settings.SkipSessionRecover && await CreateSessionAsync(token))
{
Trace.Info($"{nameof(TaskAgentSessionExpiredException)} received, recovered by recreate session.");
}
else if (!IsGetNextMessageExceptionRetriable(ex))
{
throw;
}
else
{
continuousError++;
//retry after a random backoff to avoid service throttling
//in case of there is a service error happened and all agents get kicked off of the long poll and all agent try to reconnect back at the same time.
if (continuousError <= 5)
{
// random backoff [15, 30]
_getNextMessageRetryInterval = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), _getNextMessageRetryInterval);
}
else
{
// more aggressive backoff [30, 60]
_getNextMessageRetryInterval = BackoffTimerHelper.GetRandomBackoff(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(60), _getNextMessageRetryInterval);
}
if (!encounteringError)
{
//print error only on the first consecutive error
_term.WriteError(StringUtil.Loc("QueueConError", DateTime.UtcNow, ex.Message));
encounteringError = true;
}
// re-create VssConnection before next retry
await _agentServer.RefreshConnectionAsync(AgentConnectionType.MessageQueue, TimeSpan.FromSeconds(60));
Trace.Info("Sleeping for {0} seconds before retrying.", _getNextMessageRetryInterval.TotalSeconds);
await HostContext.Delay(_getNextMessageRetryInterval, token);
}
}
if (message == null)
{
if (heartbeat.Elapsed > TimeSpan.FromMinutes(30))
{
Trace.Info($"No message retrieved from session '{_session.SessionId}' within last 30 minutes.");
heartbeat.Restart();
}
else
{
Trace.Verbose($"No message retrieved from session '{_session.SessionId}'.");
}
continue;
}
Trace.Info($"Message '{message.MessageId}' received from session '{_session.SessionId}'.");
return message;
}
}
public async Task DeleteMessageAsync(TaskAgentMessage message)
{
Trace.Entering();
ArgUtil.NotNull(_session, nameof(_session));
if (message != null && _session.SessionId != Guid.Empty)
{
using (var cs = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
{
await _agentServer.DeleteAgentMessageAsync(_settings.PoolId, message.MessageId, _session.SessionId, cs.Token);
}
}
}
private TaskAgentMessage DecryptMessage(TaskAgentMessage message)
{
if (_session.EncryptionKey == null ||
_session.EncryptionKey.Value.Length == 0 ||
message == null ||
message.IV == null ||
message.IV.Length == 0)
{
return message;
}
using (var aes = Aes.Create())
using (var decryptor = GetMessageDecryptor(aes, message))
using (var body = new MemoryStream(Convert.FromBase64String(message.Body)))
using (var cryptoStream = new CryptoStream(body, decryptor, CryptoStreamMode.Read))
using (var bodyReader = new StreamReader(cryptoStream, Encoding.UTF8))
{
message.Body = bodyReader.ReadToEnd();
}
return message;
}
private ICryptoTransform GetMessageDecryptor(
Aes aes,
TaskAgentMessage message)
{
if (_session.EncryptionKey.Encrypted)
{
// The agent session encryption key uses the AES symmetric algorithm
var keyManager = HostContext.GetService<IRSAKeyManager>();
using (var rsa = keyManager.GetKey())
{
return aes.CreateDecryptor(rsa.Decrypt(_session.EncryptionKey.Value, RSAEncryptionPadding.OaepSHA1), message.IV);
}
}
else
{
return aes.CreateDecryptor(_session.EncryptionKey.Value, message.IV);
}
}
private bool IsGetNextMessageExceptionRetriable(Exception ex)
{
if (ex is TaskAgentNotFoundException ||
ex is TaskAgentPoolNotFoundException ||
ex is TaskAgentSessionExpiredException ||
ex is AccessDeniedException ||
ex is VssUnauthorizedException)
{
Trace.Info($"Non-retriable exception: {ex.Message}");
return false;
}
else
{
Trace.Info($"Retriable exception: {ex.Message}");
return true;
}
}
private bool IsSessionCreationExceptionRetriable(Exception ex)
{
if (ex is TaskAgentNotFoundException)
{
Trace.Info("The agent no longer exists on the server. Stopping the agent.");
_term.WriteError(StringUtil.Loc("MissingAgent"));
return false;
}
else if (ex is TaskAgentSessionConflictException)
{
Trace.Info("The session for this agent already exists.");
_term.WriteError(StringUtil.Loc("SessionExist"));
if (_sessionCreationExceptionTracker.ContainsKey(nameof(TaskAgentSessionConflictException)))
{
_sessionCreationExceptionTracker[nameof(TaskAgentSessionConflictException)]++;
if (_sessionCreationExceptionTracker[nameof(TaskAgentSessionConflictException)] * _sessionCreationRetryInterval.TotalSeconds >= _sessionConflictRetryLimit.TotalSeconds)
{
Trace.Info("The session conflict exception have reached retry limit.");
_term.WriteError(StringUtil.Loc("SessionExistStopRetry", _sessionConflictRetryLimit.TotalSeconds));
return false;
}
}
else
{
_sessionCreationExceptionTracker[nameof(TaskAgentSessionConflictException)] = 1;
}
Trace.Info("The session conflict exception haven't reached retry limit.");
return true;
}
else if (ex is VssOAuthTokenRequestException && ex.Message.Contains("Current server time is"))
{
Trace.Info("Local clock might skewed.");
_term.WriteError(StringUtil.Loc("LocalClockSkewed"));
if (_sessionCreationExceptionTracker.ContainsKey(nameof(VssOAuthTokenRequestException)))
{
_sessionCreationExceptionTracker[nameof(VssOAuthTokenRequestException)]++;
if (_sessionCreationExceptionTracker[nameof(VssOAuthTokenRequestException)] * _sessionCreationRetryInterval.TotalSeconds >= _clockSkewRetryLimit.TotalSeconds)
{
Trace.Info("The OAuth token request exception have reached retry limit.");
_term.WriteError(StringUtil.Loc("ClockSkewStopRetry", _clockSkewRetryLimit.TotalSeconds));
return false;
}
}
else
{
_sessionCreationExceptionTracker[nameof(VssOAuthTokenRequestException)] = 1;
}
Trace.Info("The OAuth token request exception haven't reached retry limit.");
return true;
}
else if (ex is TaskAgentPoolNotFoundException ||
ex is AccessDeniedException ||
ex is VssUnauthorizedException)
{
Trace.Info($"Non-retriable exception: {ex.Message}");
return false;
}
else
{
Trace.Info($"Retriable exception: {ex.Message}");
return true;
}
}
}
}
| |
/*
* 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 Lucene.Net.Support;
using NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using Directory = Lucene.Net.Store.Directory;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Index
{
/*
Verify we can read the pre-2.1 file format, do searches
against it, and add documents to it.*/
[TestFixture]
public class TestIndexFileDeleter:LuceneTestCase
{
[Test]
public virtual void TestDeleteLeftoverFiles()
{
Directory dir = new RAMDirectory();
IndexWriter writer = new IndexWriter(dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
writer.SetMaxBufferedDocs(10);
int i;
for (i = 0; i < 35; i++)
{
AddDoc(writer, i);
}
writer.UseCompoundFile = false;
for (; i < 45; i++)
{
AddDoc(writer, i);
}
writer.Close();
// Delete one doc so we get a .del file:
IndexReader reader = IndexReader.Open(dir, false);
Term searchTerm = new Term("id", "7");
int delCount = reader.DeleteDocuments(searchTerm);
Assert.AreEqual(1, delCount, "didn't delete the right number of documents");
// Set one norm so we get a .s0 file:
reader.SetNorm(21, "content", (float) 1.5);
reader.Close();
// Now, artificially create an extra .del file & extra
// .s0 file:
System.String[] files = dir.ListAll();
/*
for(int j=0;j<files.length;j++) {
System.out.println(j + ": " + files[j]);
}
*/
// The numbering of fields can vary depending on which
// JRE is in use. On some JREs we see content bound to
// field 0; on others, field 1. So, here we have to
// figure out which field number corresponds to
// "content", and then set our expected file names below
// accordingly:
CompoundFileReader cfsReader = new CompoundFileReader(dir, "_2.cfs");
FieldInfos fieldInfos = new FieldInfos(cfsReader, "_2.fnm");
int contentFieldIndex = - 1;
for (i = 0; i < fieldInfos.Size(); i++)
{
FieldInfo fi = fieldInfos.FieldInfo(i);
if (fi.name_ForNUnit.Equals("content"))
{
contentFieldIndex = i;
break;
}
}
cfsReader.Close();
Assert.IsTrue(contentFieldIndex != - 1, "could not locate the 'content' field number in the _2.cfs segment");
System.String normSuffix = "s" + contentFieldIndex;
// Create a bogus separate norms file for a
// segment/field that actually has a separate norms file
// already:
CopyFile(dir, "_2_1." + normSuffix, "_2_2." + normSuffix);
// Create a bogus separate norms file for a
// segment/field that actually has a separate norms file
// already, using the "not compound file" extension:
CopyFile(dir, "_2_1." + normSuffix, "_2_2.f" + contentFieldIndex);
// Create a bogus separate norms file for a
// segment/field that does not have a separate norms
// file already:
CopyFile(dir, "_2_1." + normSuffix, "_1_1." + normSuffix);
// Create a bogus separate norms file for a
// segment/field that does not have a separate norms
// file already using the "not compound file" extension:
CopyFile(dir, "_2_1." + normSuffix, "_1_1.f" + contentFieldIndex);
// Create a bogus separate del file for a
// segment that already has a separate del file:
CopyFile(dir, "_0_1.del", "_0_2.del");
// Create a bogus separate del file for a
// segment that does not yet have a separate del file:
CopyFile(dir, "_0_1.del", "_1_1.del");
// Create a bogus separate del file for a
// non-existent segment:
CopyFile(dir, "_0_1.del", "_188_1.del");
// Create a bogus segment file:
CopyFile(dir, "_0.cfs", "_188.cfs");
// Create a bogus fnm file when the CFS already exists:
CopyFile(dir, "_0.cfs", "_0.fnm");
// Create a deletable file:
CopyFile(dir, "_0.cfs", "deletable");
// Create some old segments file:
CopyFile(dir, "segments_3", "segments");
CopyFile(dir, "segments_3", "segments_2");
// Create a bogus cfs file shadowing a non-cfs segment:
CopyFile(dir, "_2.cfs", "_3.cfs");
System.String[] filesPre = dir.ListAll();
// Open & close a writer: it should delete the above 4
// files and nothing more:
writer = new IndexWriter(dir, new WhitespaceAnalyzer(), false, IndexWriter.MaxFieldLength.LIMITED);
writer.Close();
System.String[] files2 = dir.ListAll();
dir.Close();
System.Array.Sort(files);
System.Array.Sort(files2);
System.Collections.Hashtable dif = DifFiles(files, files2);
if (!CollectionsHelper.Equals(files, files2))
{
Assert.Fail("IndexFileDeleter failed to delete unreferenced extra files: should have deleted " + (filesPre.Length - files.Length) + " files but only deleted " + (filesPre.Length - files2.Length) + "; expected files:\n " + AsString(files) + "\n actual files:\n " + AsString(files2) + "\ndif: " + CollectionsHelper.CollectionToString(dif));
}
}
private static System.Collections.Hashtable DifFiles(System.String[] files1, System.String[] files2)
{
System.Collections.Hashtable set1 = new System.Collections.Hashtable();
System.Collections.Hashtable set2 = new System.Collections.Hashtable();
System.Collections.Hashtable extra = new System.Collections.Hashtable();
for (int x = 0; x < files1.Length; x++)
{
CollectionsHelper.AddIfNotContains(set1, files1[x]);
}
for (int x = 0; x < files2.Length; x++)
{
CollectionsHelper.AddIfNotContains(set2, files2[x]);
}
System.Collections.IEnumerator i1 = set1.GetEnumerator();
while (i1.MoveNext())
{
System.Object o = i1.Current;
if (!set2.Contains(o))
{
CollectionsHelper.AddIfNotContains(extra, o);
}
}
System.Collections.IEnumerator i2 = set2.GetEnumerator();
while (i2.MoveNext())
{
System.Object o = i2.Current;
if (!set1.Contains(o))
{
CollectionsHelper.AddIfNotContains(extra, o);
}
}
return extra;
}
private System.String AsString(System.String[] l)
{
System.String s = "";
for (int i = 0; i < l.Length; i++)
{
if (i > 0)
{
s += "\n ";
}
s += l[i];
}
return s;
}
public virtual void CopyFile(Directory dir, System.String src, System.String dest)
{
IndexInput in_Renamed = dir.OpenInput(src);
IndexOutput out_Renamed = dir.CreateOutput(dest);
byte[] b = new byte[1024];
long remainder = in_Renamed.Length();
while (remainder > 0)
{
int len = (int) System.Math.Min(b.Length, remainder);
in_Renamed.ReadBytes(b, 0, len);
out_Renamed.WriteBytes(b, len);
remainder -= len;
}
in_Renamed.Close();
out_Renamed.Close();
}
private void AddDoc(IndexWriter writer, int id)
{
Document doc = new Document();
doc.Add(new Field("content", "aaa", Field.Store.NO, Field.Index.ANALYZED));
doc.Add(new Field("id", System.Convert.ToString(id), Field.Store.YES, Field.Index.NOT_ANALYZED));
writer.AddDocument(doc);
}
}
}
| |
namespace KryptonPanelExamples
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.propertyGrid = new System.Windows.Forms.PropertyGrid();
this.buttonClose = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.panel4Office = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel3Office = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel2Office = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel1Office = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.panel4Blue = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel3Blue = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel2Blue = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel1Blue = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.panel4Custom = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel2Custom = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel3Custom = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.panel1Custom = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.groupBox4.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.panel4Office)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel3Office)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel2Office)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel1Office)).BeginInit();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.panel4Blue)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel3Blue)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel2Blue)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel1Blue)).BeginInit();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.panel4Custom)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel2Custom)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel3Custom)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel1Custom)).BeginInit();
this.SuspendLayout();
//
// groupBox4
//
this.groupBox4.Controls.Add(this.propertyGrid);
this.groupBox4.Location = new System.Drawing.Point(267, 12);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(322, 556);
this.groupBox4.TabIndex = 3;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Properties for Selected KryptonPanel";
//
// propertyGrid
//
this.propertyGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.propertyGrid.Location = new System.Drawing.Point(6, 19);
this.propertyGrid.Name = "propertyGrid";
this.propertyGrid.Size = new System.Drawing.Size(310, 531);
this.propertyGrid.TabIndex = 0;
this.propertyGrid.ToolbarVisible = false;
//
// buttonClose
//
this.buttonClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonClose.Location = new System.Drawing.Point(514, 574);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(75, 23);
this.buttonClose.TabIndex = 4;
this.buttonClose.Text = "&Close";
this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.panel4Office);
this.groupBox1.Controls.Add(this.panel3Office);
this.groupBox1.Controls.Add(this.panel2Office);
this.groupBox1.Controls.Add(this.panel1Office);
this.groupBox1.Location = new System.Drawing.Point(8, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(253, 144);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Professional - Office 2003";
//
// panel4Office
//
this.panel4Office.Location = new System.Drawing.Point(138, 84);
this.panel4Office.Name = "panel4Office";
this.panel4Office.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.ProfessionalOffice2003;
this.panel4Office.PanelBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.ControlClient;
this.panel4Office.Size = new System.Drawing.Size(100, 49);
this.panel4Office.TabIndex = 3;
this.panel4Office.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// panel3Office
//
this.panel3Office.Location = new System.Drawing.Point(20, 84);
this.panel3Office.Name = "panel3Office";
this.panel3Office.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.ProfessionalOffice2003;
this.panel3Office.PanelBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.HeaderSecondary;
this.panel3Office.Size = new System.Drawing.Size(100, 49);
this.panel3Office.TabIndex = 1;
this.panel3Office.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// panel2Office
//
this.panel2Office.Location = new System.Drawing.Point(138, 29);
this.panel2Office.Name = "panel2Office";
this.panel2Office.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.ProfessionalOffice2003;
this.panel2Office.PanelBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.HeaderPrimary;
this.panel2Office.Size = new System.Drawing.Size(100, 49);
this.panel2Office.TabIndex = 2;
this.panel2Office.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// panel1Office
//
this.panel1Office.Location = new System.Drawing.Point(20, 29);
this.panel1Office.Name = "panel1Office";
this.panel1Office.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.ProfessionalOffice2003;
this.panel1Office.Size = new System.Drawing.Size(100, 49);
this.panel1Office.TabIndex = 0;
this.panel1Office.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.panel4Blue);
this.groupBox2.Controls.Add(this.panel3Blue);
this.groupBox2.Controls.Add(this.panel2Blue);
this.groupBox2.Controls.Add(this.panel1Blue);
this.groupBox2.Location = new System.Drawing.Point(8, 162);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(253, 146);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Office 2007 - Blue";
//
// panel4Blue
//
this.panel4Blue.Location = new System.Drawing.Point(138, 84);
this.panel4Blue.Name = "panel4Blue";
this.panel4Blue.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
this.panel4Blue.PanelBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.ControlClient;
this.panel4Blue.Size = new System.Drawing.Size(100, 49);
this.panel4Blue.TabIndex = 3;
this.panel4Blue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// panel3Blue
//
this.panel3Blue.Location = new System.Drawing.Point(20, 84);
this.panel3Blue.Name = "panel3Blue";
this.panel3Blue.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
this.panel3Blue.PanelBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.HeaderSecondary;
this.panel3Blue.Size = new System.Drawing.Size(100, 49);
this.panel3Blue.TabIndex = 1;
this.panel3Blue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// panel2Blue
//
this.panel2Blue.Location = new System.Drawing.Point(138, 29);
this.panel2Blue.Name = "panel2Blue";
this.panel2Blue.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
this.panel2Blue.PanelBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.HeaderPrimary;
this.panel2Blue.Size = new System.Drawing.Size(100, 49);
this.panel2Blue.TabIndex = 2;
this.panel2Blue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// panel1Blue
//
this.panel1Blue.Location = new System.Drawing.Point(20, 29);
this.panel1Blue.Name = "panel1Blue";
this.panel1Blue.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Blue;
this.panel1Blue.Size = new System.Drawing.Size(100, 49);
this.panel1Blue.TabIndex = 0;
this.panel1Blue.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// groupBox3
//
this.groupBox3.Controls.Add(this.panel4Custom);
this.groupBox3.Controls.Add(this.panel2Custom);
this.groupBox3.Controls.Add(this.panel3Custom);
this.groupBox3.Controls.Add(this.panel1Custom);
this.groupBox3.Location = new System.Drawing.Point(8, 314);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(253, 254);
this.groupBox3.TabIndex = 2;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Custom Settings";
//
// panel4Custom
//
this.panel4Custom.Location = new System.Drawing.Point(138, 138);
this.panel4Custom.Name = "panel4Custom";
this.panel4Custom.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.ProfessionalSystem;
this.panel4Custom.Size = new System.Drawing.Size(100, 100);
this.panel4Custom.StateNormal.Color1 = System.Drawing.Color.White;
this.panel4Custom.StateNormal.Color2 = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192)))));
this.panel4Custom.StateNormal.ColorAngle = 45F;
this.panel4Custom.StateNormal.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Sigma;
this.panel4Custom.StateNormal.Image = ((System.Drawing.Image)(resources.GetObject("panel4Custom.StateNormal.Image")));
this.panel4Custom.StateNormal.ImageAlign = ComponentFactory.Krypton.Toolkit.PaletteRectangleAlign.Local;
this.panel4Custom.StateNormal.ImageStyle = ComponentFactory.Krypton.Toolkit.PaletteImageStyle.Inherit;
this.panel4Custom.TabIndex = 3;
this.panel4Custom.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// panel2Custom
//
this.panel2Custom.Location = new System.Drawing.Point(138, 32);
this.panel2Custom.Name = "panel2Custom";
this.panel2Custom.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.ProfessionalSystem;
this.panel2Custom.Size = new System.Drawing.Size(100, 100);
this.panel2Custom.StateNormal.Color1 = System.Drawing.Color.White;
this.panel2Custom.StateNormal.Color2 = System.Drawing.Color.Maroon;
this.panel2Custom.StateNormal.ColorAngle = 10F;
this.panel2Custom.StateNormal.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Sigma;
this.panel2Custom.StateNormal.ImageStyle = ComponentFactory.Krypton.Toolkit.PaletteImageStyle.Inherit;
this.panel2Custom.TabIndex = 2;
this.panel2Custom.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// panel3Custom
//
this.panel3Custom.Location = new System.Drawing.Point(20, 138);
this.panel3Custom.Name = "panel3Custom";
this.panel3Custom.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.ProfessionalSystem;
this.panel3Custom.Size = new System.Drawing.Size(100, 100);
this.panel3Custom.StateNormal.Color1 = System.Drawing.Color.White;
this.panel3Custom.StateNormal.Color2 = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.panel3Custom.StateNormal.ColorAngle = 45F;
this.panel3Custom.StateNormal.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Linear;
this.panel3Custom.StateNormal.Image = ((System.Drawing.Image)(resources.GetObject("panel3Custom.StateNormal.Image")));
this.panel3Custom.StateNormal.ImageStyle = ComponentFactory.Krypton.Toolkit.PaletteImageStyle.CenterMiddle;
this.panel3Custom.TabIndex = 1;
this.panel3Custom.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// panel1Custom
//
this.panel1Custom.Location = new System.Drawing.Point(20, 32);
this.panel1Custom.Name = "panel1Custom";
this.panel1Custom.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.ProfessionalSystem;
this.panel1Custom.Size = new System.Drawing.Size(100, 100);
this.panel1Custom.StateNormal.Color1 = System.Drawing.Color.White;
this.panel1Custom.StateNormal.Color2 = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
this.panel1Custom.StateNormal.ColorAngle = 60F;
this.panel1Custom.StateNormal.ColorStyle = ComponentFactory.Krypton.Toolkit.PaletteColorStyle.Rounded;
this.panel1Custom.StateNormal.ImageStyle = ComponentFactory.Krypton.Toolkit.PaletteImageStyle.Inherit;
this.panel1Custom.TabIndex = 0;
this.panel1Custom.MouseDown += new System.Windows.Forms.MouseEventHandler(this.kryptonPanel_MouseDown);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(601, 607);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.groupBox4);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.Text = "KryptonPanel Examples";
this.Load += new System.EventHandler(this.Form1_Load);
this.groupBox4.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.panel4Office)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel3Office)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel2Office)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel1Office)).EndInit();
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.panel4Blue)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel3Blue)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel2Blue)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel1Blue)).EndInit();
this.groupBox3.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.panel4Custom)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel2Custom)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel3Custom)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel1Custom)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button buttonClose;
private System.Windows.Forms.PropertyGrid propertyGrid;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.GroupBox groupBox4;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel1Office;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel2Office;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel3Office;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel4Office;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel1Blue;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel2Blue;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel3Blue;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel4Blue;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel1Custom;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel2Custom;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel3Custom;
private ComponentFactory.Krypton.Toolkit.KryptonPanel panel4Custom;
}
}
| |
// 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.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.PythonTools.Options {
class OptionsTreeView : TreeView {
private static ImageList _imageList;
internal const int TransparentIndex = 0;
public OptionsTreeView() {
InitializeImageList();
DrawMode = TreeViewDrawMode.OwnerDrawText;
ShowLines = ShowRootLines = ShowPlusMinus = true;
Scrollable = true;
VsShellUtilities.ApplyTreeViewThemeStyles(this);
}
protected override void OnGotFocus(EventArgs e) {
}
private void InitializeImageList() {
if (_imageList == null) {
_imageList = new ImageList();
Bitmap bmp = new Bitmap(16, 16);
// transparent image is the image we use for owner drawn icons
_imageList.TransparentColor = Color.Magenta;
using (var g = Graphics.FromImage(bmp)) {
g.FillRectangle(Brushes.Magenta, new Rectangle(0, 0, 16, 16));
}
_imageList.Images.Add(bmp);
}
StateImageList = _imageList;
}
protected override void OnMouseUp(MouseEventArgs e) {
var node = GetNodeAt(e.Location);
if (node == null) {
return;
}
OptionSettingNode settingsNode = node as OptionSettingNode;
if (settingsNode != null) {
if (settingsNode == SelectedNode) {
ToggleSetting(settingsNode);
} else {
SelectedNode = settingsNode;
}
}
}
private void ToggleSetting(OptionSettingNode settingsNode) {
settingsNode.ToggleSetting();
InvalidateNodeIcon(settingsNode);
OnAfterCheck(new TreeViewEventArgs(settingsNode));
}
private void InvalidateNodeIcon(TreeNode node) {
this.Invalidate(
((OptionNode)node).IconBounds
);
}
protected override void OnKeyPress(KeyPressEventArgs e) {
if (e.KeyChar == ' ') {
// toggling an option
var node = SelectedNode as OptionSettingNode;
if (node != null) {
ToggleSetting(node);
e.Handled = true;
} else {
var folder = SelectedNode as OptionFolderNode;
if (folder != null) {
if (folder.IsExpanded) {
folder.Collapse();
} else {
folder.Expand();
}
e.Handled = true;
}
}
}
}
protected override void OnDrawNode(DrawTreeNodeEventArgs e) {
OptionSettingNode setting = e.Node as OptionSettingNode;
if (setting != null) {
setting.DrawNode(e);
}
e.DrawDefault = true;
base.OnDrawNode(e);
}
protected override void OnAfterExpand(TreeViewEventArgs e) {
OptionFolderNode node = e.Node as OptionFolderNode;
if (node != null) {
InvalidateNodeIcon(node);
node.WasExpanded = true;
return;
}
base.OnAfterExpand(e);
}
protected override void OnAfterCollapse(TreeViewEventArgs e) {
OptionFolderNode node = e.Node as OptionFolderNode;
if (node != null) {
InvalidateNodeIcon(node);
node.WasExpanded = false;
return;
}
base.OnAfterCollapse(e);
}
protected override AccessibleObject CreateAccessibilityInstance() {
return new TreeAccessibleObject(this);
}
// Taken from C#
internal class TreeAccessibleObject : Control.ControlAccessibleObject {
private readonly OptionsTreeView _tree;
public TreeAccessibleObject(OptionsTreeView tree)
: base(tree) {
_tree = tree;
}
public override AccessibleObject GetChild(int index) {
return ((OptionNode)FindTreeNode(index)).AccessibleObject;
}
public override int GetChildCount() {
return _tree.GetNodeCount(true);
}
public override AccessibleObject HitTest(int x, int y) {
return ((OptionNode)_tree.GetNodeAt(x, y)).AccessibleObject;
}
public override AccessibleObject GetFocused() {
return ((OptionNode)_tree.SelectedNode).AccessibleObject;
}
public override AccessibleObject GetSelected() {
return ((OptionNode)_tree.SelectedNode).AccessibleObject;
}
public override void Select(AccessibleSelection flags) {
_tree.Select();
}
public override System.Drawing.Rectangle Bounds {
get { return _tree.RectangleToScreen(_tree.Bounds); }
}
public override AccessibleObject Navigate(AccessibleNavigation navdir) {
switch (navdir) {
case AccessibleNavigation.FirstChild:
case AccessibleNavigation.Down:
return GetChild(0);
case AccessibleNavigation.LastChild:
return GetChild(GetChildCount() - 1);
case AccessibleNavigation.Left:
case AccessibleNavigation.Previous:
return null;
case AccessibleNavigation.Next:
case AccessibleNavigation.Right:
return null;
case AccessibleNavigation.Up:
return Parent;
default:
System.Diagnostics.Debug.Assert(false, "What direction is this?");
return null;
}
}
private TreeNode FindTreeNode(int index) {
// Note this only handles 2 levels in the tree,
// but that's because until we have more, we won't
// know what index order the index will come in.
foreach (TreeNode outerNode in _tree.Nodes) {
if (index == 0) {
return outerNode;
}
--index;
for (int i = outerNode.Nodes.Count - 1; i >= 0; --i) {
TreeNode innerNode = outerNode.Nodes[i];
System.Diagnostics.Debug.Assert(innerNode.Nodes.Count == 0, "We don't handle tree's nested this deep");
if (index == 0) {
return innerNode;
}
--index;
}
}
System.Diagnostics.Debug.Assert(false, "Didn't find a node for index: " + index.ToString());
return null;
}
}
}
abstract class OptionNode : TreeNode {
public OptionNode(string text)
: base(text) {
}
public virtual AccessibleObject AccessibleObject {
get {
return new TreeNodeAccessibleObject(this);
}
}
public Rectangle IconBounds {
get {
return new Rectangle(
Bounds.Left - 21,
Bounds.Top,
20,
Bounds.Height
);
}
}
// Taken from C#
internal class TreeNodeAccessibleObject : Control.ControlAccessibleObject {
private readonly OptionNode _node;
public TreeNodeAccessibleObject(OptionNode node)
: base(node.TreeView) {
_node = node;
}
public override string Value {
get { return null; }
}
public override string DefaultAction {
get {
if (_node.IsExpanded) {
return "Collapse";
} else {
return "Expand";
}
}
}
public override void DoDefaultAction() {
_node.Toggle();
}
public override System.Drawing.Rectangle Bounds {
get { return _node.TreeView.RectangleToScreen(_node.Bounds); }
}
public override string Name {
get { return _node.Text; }
set { _node.Text = value; }
}
public override int GetChildCount() {
return 0;
}
public override AccessibleObject GetChild(int index) {
System.Diagnostics.Debug.Assert(false, "Nodes have no children, only the treeview does");
return null;
}
public override AccessibleObject Parent {
get { return _node.TreeView.AccessibilityObject; }
}
public override AccessibleObject Navigate(AccessibleNavigation navdir) {
switch (navdir) {
case AccessibleNavigation.Down:
case AccessibleNavigation.FirstChild:
case AccessibleNavigation.LastChild:
// TreeNodes don't have children.
return null;
case AccessibleNavigation.Left:
case AccessibleNavigation.Previous:
if (Index == 0) {
return null;
}
return _node.TreeView.AccessibilityObject.GetChild(Index - 1);
case AccessibleNavigation.Next:
case AccessibleNavigation.Right:
int count = _node.TreeView.AccessibilityObject.GetChildCount();
if (Index == count - 1) {
return null;
}
return _node.TreeView.AccessibilityObject.GetChild(Index + 1);
case AccessibleNavigation.Up:
return Parent;
default:
System.Diagnostics.Debug.Assert(false, "What direction is this?");
return null;
}
}
public override AccessibleStates State {
get {
AccessibleStates ret = AccessibleStates.Selectable | AccessibleStates.Focusable;
if (_node.IsSelected) {
ret |= AccessibleStates.Focused;
ret |= AccessibleStates.Selected;
}
if (_node.Nodes.Count != 0) {
if (_node.IsExpanded) {
ret |= AccessibleStates.Expanded;
} else {
ret |= AccessibleStates.Collapsed;
}
}
return ret;
}
}
public override void Select(AccessibleSelection flags) {
_node.TreeView.SelectedNode = _node;
}
public override AccessibleObject GetFocused() {
return ((OptionNode)_node.TreeView.SelectedNode).AccessibleObject;
}
public override AccessibleObject GetSelected() {
return ((OptionNode)_node.TreeView.SelectedNode).AccessibleObject;
}
public override AccessibleObject HitTest(int x, int y) {
return ((OptionNode)_node.TreeView.GetNodeAt(x, y)).AccessibleObject;
}
public int Index {
get {
int index = 0;
foreach (TreeNode outerNode in _node.TreeView.Nodes) {
if (_node == outerNode) {
return index;
}
index++;
for (int i = outerNode.Nodes.Count - 1; i >= 0; --i) {
TreeNode innerNode = outerNode.Nodes[i];
if (_node == innerNode) {
return index;
}
index++;
}
}
System.Diagnostics.Debug.Assert(false, "Couldn't find index for node");
return 0;
}
}
}
}
class OptionFolderNode : OptionNode {
public bool WasExpanded = true;
public OptionFolderNode(string name)
: base(name) { }
}
abstract class OptionSettingNode : OptionNode {
public OptionSettingNode(string text)
: base(text) {
StateImageIndex = SelectedImageIndex = ImageIndex = OptionsTreeView.TransparentIndex;
}
internal abstract object SettingValue {
get;
set;
}
internal virtual void DrawNode(DrawTreeNodeEventArgs e) {
e.Graphics.FillRectangle(SystemBrushes.ControlLightLight, IconBounds);
}
internal virtual void ToggleSetting() {
}
internal virtual void Connected() {
}
}
class BooleanCheckBoxNode : OptionSettingNode {
private bool _state;
public BooleanCheckBoxNode(string text)
: base(text) {
}
internal override object SettingValue {
get {
return _state;
}
set {
if (value is bool) {
_state = (bool)value;
} else {
throw new InvalidOperationException();
}
}
}
public override AccessibleObject AccessibleObject {
get { return new BooleanAccessibleObject(this); }
}
public class BooleanAccessibleObject : TreeNodeAccessibleObject {
private readonly BooleanCheckBoxNode _option;
public BooleanAccessibleObject(BooleanCheckBoxNode option)
: base(option) {
_option = option;
}
public override string DefaultAction {
get {
return _option._state ? "Uncheck" : "Check";
}
}
public override void DoDefaultAction() {
_option.ToggleSetting();
}
public override AccessibleStates State {
get {
return _option._state ? AccessibleStates.Checked : base.State;
}
}
public override AccessibleRole Role {
get { return AccessibleRole.CheckButton; }
}
}
internal override void ToggleSetting() {
switch (_state) {
case false: _state = true; break;
case true: _state = false; break;
}
}
internal override void DrawNode(DrawTreeNodeEventArgs e) {
var optNode = (OptionNode)e.Node;
CheckBoxRenderer.DrawCheckBox(
e.Graphics,
optNode.IconBounds.Location,
_state ?
CheckBoxState.CheckedNormal :
CheckBoxState.UncheckedNormal
);
}
}
class TriStateCheckBoxNode : OptionSettingNode {
private bool? _state;
public TriStateCheckBoxNode(string text)
: base(text) {
}
internal override object SettingValue {
get {
return _state;
}
set {
if (value == null || value is bool) {
_state = (bool?)value;
} else {
throw new InvalidOperationException();
}
}
}
public override AccessibleObject AccessibleObject {
get { return new TriStateAccessibleObject(this); }
}
public class TriStateAccessibleObject : TreeNodeAccessibleObject {
private readonly TriStateCheckBoxNode _option;
public TriStateAccessibleObject(TriStateCheckBoxNode option)
: base(option) {
_option = option;
}
public override string DefaultAction {
get {
switch (_option._state) {
case null: return "Check";
case true: return "Uncheck";
default: return "Mixed";
}
}
}
public override void DoDefaultAction() {
_option.ToggleSetting();
}
public override AccessibleStates State {
get {
switch (_option._state) {
case null: return AccessibleStates.Mixed;
case true: return AccessibleStates.Checked;
default: return base.State;
}
}
}
public override AccessibleRole Role {
get { return AccessibleRole.CheckButton; }
}
}
internal override void ToggleSetting() {
switch (_state) {
case false: _state = null; break;
case true: _state = false; break;
case null: _state = true; break;
}
}
internal override void DrawNode(DrawTreeNodeEventArgs e) {
var optNode = (OptionNode)e.Node;
CheckBoxRenderer.DrawCheckBox(
e.Graphics,
optNode.IconBounds.Location,
_state != null ?
_state.Value ?
CheckBoxState.CheckedNormal :
CheckBoxState.UncheckedNormal :
CheckBoxState.MixedNormal
);
}
}
sealed class IntegerNode : OptionSettingNode, IDisposable {
private int _value;
private readonly TextBox _textBox;
public IntegerNode(string text)
: base(text) {
_textBox = new TextBox();
_textBox.TextChanged += TextChanged;
_textBox.GotFocus += TextBoxGotFocus;
}
public void Dispose() {
_textBox.Dispose();
}
private void TextBoxGotFocus(object sender, EventArgs e) {
TreeView.SelectedNode = this;
}
private void TextChanged(object sender, EventArgs e) {
uint value;
if (UInt32.TryParse(_textBox.Text, out value)) {
_value = (int)value;
}
}
internal override void Connected() {
_textBox.Font = TreeView.Font;
TreeView.Controls.Add(_textBox);
TreeView.Invalidated += TreeViewInvalidated;
}
private void TreeViewInvalidated(object sender, InvalidateEventArgs e) {
if (IsVisible) {
_textBox.Show();
_textBox.Top = Bounds.Top;
_textBox.Left = Bounds.Right;
_textBox.Height = Bounds.Height - 4;
_textBox.Width = 40;
} else {
_textBox.Hide();
}
}
internal override object SettingValue {
get {
return _value;
}
set {
_value = (int)value;
_textBox.Text = _value.ToString();
}
}
internal string Value {
get {
return _textBox.Text;
}
}
// taken from C#
class IntegerAccessibleObject : TreeNodeAccessibleObject {
private readonly IntegerNode _option;
public IntegerAccessibleObject(IntegerNode option)
: base(option) {
_option = option;
}
public override AccessibleRole Role {
get { return AccessibleRole.Text; }
}
public override string Value {
get { return _option.Value; }
set { _option._value = (int)uint.Parse(value); }
}
}
public override System.Windows.Forms.AccessibleObject AccessibleObject {
get {
return new IntegerAccessibleObject(this);
}
}
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.