context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
//---------------------------------------------------------------------
// <copyright file="OffsetStream.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Archivers.Internal.Compression
{
using System;
using System.IO;
/// <summary>
/// Wraps a source stream and offsets all read/write/seek calls by a given value.
/// </summary>
/// <remarks>
/// This class is used to trick archive an packing or unpacking process
/// into reading or writing at an offset into a file, primarily for
/// self-extracting packages.
/// </remarks>
public class OffsetStream : Stream
{
private Stream source;
private long sourceOffset;
/// <summary>
/// Creates a new OffsetStream instance from a source stream
/// and using a specified offset.
/// </summary>
/// <param name="source">Underlying stream for which all calls will be offset.</param>
/// <param name="offset">Positive or negative number of bytes to offset.</param>
public OffsetStream(Stream source, long offset)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
this.source = source;
this.sourceOffset = offset;
this.source.Seek(this.sourceOffset, SeekOrigin.Current);
}
/// <summary>
/// Gets the underlying stream that this OffsetStream calls into.
/// </summary>
public Stream Source
{
get { return this.source; }
}
/// <summary>
/// Gets the number of bytes to offset all calls before
/// redirecting to the underlying stream.
/// </summary>
public long Offset
{
get { return this.sourceOffset; }
}
/// <summary>
/// Gets a value indicating whether the source stream supports reading.
/// </summary>
/// <value>true if the stream supports reading; otherwise, false.</value>
public override bool CanRead
{
get
{
return this.source.CanRead;
}
}
/// <summary>
/// Gets a value indicating whether the source stream supports writing.
/// </summary>
/// <value>true if the stream supports writing; otherwise, false.</value>
public override bool CanWrite
{
get
{
return this.source.CanWrite;
}
}
/// <summary>
/// Gets a value indicating whether the source stream supports seeking.
/// </summary>
/// <value>true if the stream supports seeking; otherwise, false.</value>
public override bool CanSeek
{
get
{
return this.source.CanSeek;
}
}
/// <summary>
/// Gets the effective length of the stream, which is equal to
/// the length of the source stream minus the offset.
/// </summary>
public override long Length
{
get { return this.source.Length - this.sourceOffset; }
}
/// <summary>
/// Gets or sets the effective position of the stream, which
/// is equal to the position of the source stream minus the offset.
/// </summary>
public override long Position
{
get { return this.source.Position - this.sourceOffset; }
set { this.source.Position = value + this.sourceOffset; }
}
/// <summary>
/// Reads a sequence of bytes from the source stream and advances
/// the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer
/// contains the specified byte array with the values between offset and
/// (offset + count - 1) replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin
/// storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer. This can be less
/// than the number of bytes requested if that many bytes are not currently available,
/// or zero (0) if the end of the stream has been reached.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
return this.source.Read(buffer, offset, count);
}
/// <summary>
/// Writes a sequence of bytes to the source stream and advances the
/// current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies count
/// bytes from buffer to the current stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which
/// to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the
/// current stream.</param>
public override void Write(byte[] buffer, int offset, int count)
{
this.source.Write(buffer, offset, count);
}
/// <summary>
/// Reads a byte from the stream and advances the position within the
/// source stream by one byte, or returns -1 if at the end of the stream.
/// </summary>
/// <returns>The unsigned byte cast to an Int32, or -1 if at the
/// end of the stream.</returns>
public override int ReadByte()
{
return this.source.ReadByte();
}
/// <summary>
/// Writes a byte to the current position in the source stream and
/// advances the position within the stream by one byte.
/// </summary>
/// <param name="value">The byte to write to the stream.</param>
public override void WriteByte(byte value)
{
this.source.WriteByte(value);
}
/// <summary>
/// Flushes the source stream.
/// </summary>
public override void Flush()
{
this.source.Flush();
}
/// <summary>
/// Sets the position within the current stream, which is
/// equal to the position within the source stream minus the offset.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type SeekOrigin indicating
/// the reference point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
return this.source.Seek(offset + (origin == SeekOrigin.Begin ? this.sourceOffset : 0), origin) - this.sourceOffset;
}
/// <summary>
/// Sets the effective length of the stream, which is equal to
/// the length of the source stream minus the offset.
/// </summary>
/// <param name="value">The desired length of the
/// current stream in bytes.</param>
public override void SetLength(long value)
{
this.source.SetLength(value + this.sourceOffset);
}
#if !CORECLR
/// <summary>
/// Closes the underlying stream.
/// </summary>
public override void Close()
{
this.source.Close();
}
#endif
/// <summary>
/// Disposes the underlying stream
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.source.Dispose();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace NearestStation.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// 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.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.noaccessibility004.noaccessibility004
{
// <Title>Call methods that have different accessibility</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Foo
{
protected internal int this[int x]
{
set
{
Test.Status = 0;
}
}
}
public class Test
{
public static int Status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = 3;
f[d] = -1;
return Status;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier
{
using System;
using System.Globalization;
using System.Reflection;
using System.Resources;
public enum ErrorElementId
{
None,
SK_METHOD, // method
SK_CLASS, // type
SK_NAMESPACE, // namespace
SK_FIELD, // field
SK_PROPERTY, // property
SK_UNKNOWN, // element
SK_VARIABLE, // variable
SK_EVENT, // event
SK_TYVAR, // type parameter
SK_ALIAS, // using alias
ERRORSYM, // <error>
NULL, // <null>
GlobalNamespace, // <global namespace>
MethodGroup, // method group
AnonMethod, // anonymous method
Lambda, // lambda expression
AnonymousType, // anonymous type
}
public enum ErrorMessageId
{
None,
BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
IntDivByZero, // Division by constant zero
BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}'
BadIndexCount, // Wrong number of indices inside []; expected '{0}'
BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}'
NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}'
NoExplicitConv, // Cannot convert type '{0}' to '{1}'
ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}'
AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}'
ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type
WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}'
NoSuchMember, // '{0}' does not contain a definition for '{1}'
ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}'
AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}'
BadAccess, // '{0}' is inaccessible due to its protection level
MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}'
AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer
NoConstructors, // The type '{0}' has no constructors defined
BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor
PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor
ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead
AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor)
AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only
AbstractBaseCall, // Cannot call an abstract base member: '{0}'
RefProperty, // A property or indexer may not be passed as an out or ref parameter
ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')
FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression
UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers
BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters
MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false
CheckedOverflow, // The operation overflows at compile time in checked mode
ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)
AmbigMember, // Ambiguity between '{0}' and '{1}'
SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}'
CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.
CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor.
BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression
NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)
InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible
InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible
BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments
BadTypeArgument, // The type '{0}' may not be used as a type argument
TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments
HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments
NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'
GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.
GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.
GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.
TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.
BadRetType, // '{1} {0}' has the wrong return type
CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.
MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?
RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'
ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'
CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}'
BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'
ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'
AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'
PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported
PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly
BindToBogus, // '{0}' is not supported by the language
CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor
BogusType, // '{0}' is a type not supported by the language
MissingPredefinedMember, // Missing compiler required member '{0}.{1}'
LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type
UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions
ConvertToStaticClass, // Cannot convert to static type '{0}'
GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments
PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer
NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)
ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates
BadArgCount, // No overload for method '{0}' takes '{1}' arguments
BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments
BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}'
RefLvalueExpected, // A ref or out argument must be an assignable variable
BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)
BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'
BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'
BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments
BadDelArgTypes, // Delegate '{0}' has some invalid arguments
AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only
RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only
ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable
BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword
// DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED)
BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword
AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)
RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor)
AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}'
RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}'
ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.
DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>'
BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments
BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments
BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}'
BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method.
NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified
BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}'
BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}'
DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times
NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given
}
public enum RuntimeErrorId
{
None,
// RuntimeBinderInternalCompilerException
InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation
// ArgumentException
BindRequireArguments, // Cannot bind call with no calling object
// RuntimeBinderException
BindCallFailedOverloadResolution, // Overload resolution failed
// ArgumentException
BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments
// ArgumentException
BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument
// RuntimeBinderException
BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property
// RuntimeBinderException
BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -=
// RuntimeBinderException
BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type
// ArgumentException
BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument
// ArgumentException
BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument
// ArgumentException
BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument
// RuntimeBinderException
BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference
// RuntimeBinderException
NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference
// RuntimeBinderException
BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute
// RuntimeBinderException
BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object'
// EE?
EmptyDynamicView, // No further information on this object could be discovered
// MissingMemberException
GetValueonWriteOnlyProperty, // Write Only properties are not supported
}
public class ErrorVerifier
{
private static Assembly s_asm;
private static ResourceManager s_rm1;
private static ResourceManager s_rm2;
public static string GetErrorElement(ErrorElementId id)
{
return string.Empty;
}
public static bool Verify(ErrorMessageId id, string actualError, params string[] args)
{
return true;
}
public static bool Verify(RuntimeErrorId id, string actualError, params string[] args)
{
return true;
}
private static bool CompareMessages(ResourceManager rm, string id, string actualError, params string[] args)
{
// should not happen
if (null == rm)
return false;
if (String.IsNullOrEmpty(id) || String.IsNullOrEmpty(actualError))
{
System.Console.WriteLine("Empty error id or actual message");
return false;
}
string message = rm.GetString(id, null);
if ((null != args) && (0 < args.Length))
{
message = String.Format(CultureInfo.InvariantCulture, message, args);
}
bool ret = 0 == String.CompareOrdinal(message, actualError);
// debug
if (!ret)
{
System.Console.WriteLine("*** Expected= {0}\r\n*** Actual= {1}", message, actualError);
}
return ret;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param012.param012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier;
// <Title>Call methods that have different parameter modifiers with dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(23,23\).*CS0649</Expects>
public struct myStruct
{
public int Field;
}
public class Foo
{
public int this[params int[] x]
{
set
{
}
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = "foo";
try
{
f[d] = 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.this[params int[]]"))
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param014.param014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier;
// <Title>Call methods that have different parameter modifiers with dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public struct myStruct
{
public int Field;
}
public class Foo
{
public int this[params int[] x]
{
set
{
}
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = "foo";
dynamic d2 = 3;
try
{
f[d2, d] = 3;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.this[params int[]]"))
return 0;
}
return 1;
}
}
// </Code>
}
| |
/*
* Created by: Leslie Sanford
*
* Last modified: 02/23/2005
*
* Contact: [email protected]
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
namespace Sanford.Collections.Immutable
{
/// <summary>
/// Implements Chris Okasaki's random access list.
/// </summary>
[ImmutableObject(true)]
public class RandomAccessList : IEnumerable
{
#region RandomAccessList Members
#region Class Fields
/// <summary>
/// Represents an empty random access list.
/// </summary>
public static readonly RandomAccessList Empty = new RandomAccessList();
#endregion
#region Instance Fields
// The number of elements in the random access list.
private readonly int count;
// The first top node in the list.
private readonly RalTopNode first;
// A random access list representing the head of the current list.
private RandomAccessList head = null;
// A random access list representing the tail of the current list.
private RandomAccessList tail = null;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the RandomAccessList class.
/// </summary>
public RandomAccessList()
{
count = 0;
first = null;
}
/// <summary>
/// Initializes a new instance of the RandomAccessList class with the
/// specified first top node and the number of elements in the list.
/// </summary>
/// <param name="first">
/// The first top node in the list.
/// </param>
/// <param name="count">
/// The number of nodes in the list.
/// </param>
private RandomAccessList(RalTopNode first, int count)
{
this.first = first;
this.count = count;
}
#endregion
#region Methods
/// <summary>
/// Prepends a value to the random access list.
/// </summary>
/// <param name="value">
/// The value to prepend to the list.
/// </param>
/// <returns>
/// A new random access list with the specified value prepended to the
/// list.
/// </returns>
public RandomAccessList Cons(object value)
{
RandomAccessList result;
// If the list is empty, or there is only one tree in the list, or
// the first tree is smaller than the second tree.
if(Count == 0 ||
first.NextNode == null ||
first.Root.Count < first.NextNode.Root.Count)
{
// Create a new first node with the specified value.
RalTreeNode newRoot = new RalTreeNode(value, null, null);
// Create a new random access list.
result = new RandomAccessList(
new RalTopNode(newRoot, first),
Count + 1);
}
// Else the first and second trees in the list are the same size.
else
{
Debug.Assert(first.Root.Count == first.NextNode.Root.Count);
// Create a new first node with the old first and second node
// as the left and right children respectively.
RalTreeNode newRoot = new RalTreeNode(
value,
first.Root,
first.NextNode.Root);
// Create a new random access list.
result = new RandomAccessList(
new RalTopNode(newRoot, first.NextNode.NextNode),
Count + 1);
}
return result;
}
/// <summary>
/// Gets the value at the specified position in the current
/// RandomAccessList.
/// </summary>
/// <param name="index">
/// An integer that represents the position of the RandomAccessList
/// element to get.
/// </param>
/// <returns>
/// The value at the specified position in the RandomAccessList.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// index is outside the range of valid indexes for the current
/// RandomAccessList.
/// </exception>
public object GetValue(int index)
{
// Precondition.
if(index < 0 || index >= Count)
{
throw new ArgumentOutOfRangeException("index", index,
"Index out of range.");
}
return first.GetValue(index);
}
/// <summary>
/// Sets the specified element in the current RandomAccessList to the
/// specified value.
/// </summary>
/// <param name="value">
/// The new value for the specified element.
/// </param>
/// <param name="index">
/// An integer that represents the position of the RandomAccessList
/// element to set.
/// </param>
/// <returns>
/// A new RandomAccessList with the element at the specified position
/// set to the specified value.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// index is outside the range of valid indexes for the current
/// RandomAccessList.
/// </exception>
public RandomAccessList SetValue(object value, int index)
{
// Precondition.
if(index < 0 || index >= Count)
{
throw new ArgumentOutOfRangeException("index", index,
"Index out of range.");
}
return new RandomAccessList(first.SetValue(value, index), Count);
}
#endregion
#region Properties
/// <summary>
/// Gets the number of elements in the RandomAccessList.
/// </summary>
public int Count
{
get
{
return count;
}
}
/// <summary>
/// Gets a RandomAccessList with first element of the current
/// RandomAccessList.
/// </summary>
/// <exception cref="InvalidOperationException">
/// If the RandomAccessList is empty.
/// </exception>
public RandomAccessList Head
{
get
{
// Preconditions.
if(Count == 0)
{
throw new InvalidOperationException(
"Cannot get the head of an empty random access list.");
}
if(head == null)
{
RalTreeNode newRoot = new RalTreeNode(
first.Root.Value, null, null);
RalTopNode newFirst = new RalTopNode(newRoot, null);
head = new RandomAccessList(newFirst, 1);
}
return head;
}
}
/// <summary>
/// Gets a RandomAccessList with all but the first element of the
/// current RandomAccessList.
/// </summary>
/// <exception cref="InvalidOperationException">
/// If the RandomAccessList is empty.
/// </exception>
public RandomAccessList Tail
{
get
{
// Precondition.
if(Count == 0)
{
throw new InvalidOperationException(
"Cannot get the tail of an empty random access list.");
}
if(tail == null)
{
if(Count == 1)
{
tail = Empty;
}
else
{
if(first.Root.Count > 1)
{
RalTreeNode left = first.Root.LeftChild;
RalTreeNode right = first.Root.RightChild;
RalTopNode newSecond = new RalTopNode(
right, first.NextNode);
RalTopNode newFirst = new RalTopNode(
left, newSecond);
tail = new RandomAccessList(newFirst, Count - 1);
}
else
{
tail = new RandomAccessList(first.NextNode, Count - 1);
}
}
}
return tail;
}
}
#endregion
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an IEnumerator for the RandomAccessList.
/// </summary>
/// <returns>
/// An IEnumerator for the RandomAccessList.
/// </returns>
public IEnumerator GetEnumerator()
{
return new RalEnumerator(first, Count);
}
#endregion
}
}
| |
/*
* @(#)BooleanAlgebra.cs 3.0.0 2016-05-07
*
* You may use this software under the condition of "Simplified BSD License"
*
* Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``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 <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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of MARIUSZ GROMADA.
*
* If you have any questions/bugs feel free to contact:
*
* Mariusz Gromada
* [email protected]
* http://mathparser.org
* http://mathspace.pl
* http://janetsudoku.mariuszgromada.org
* http://github.com/mariuszgromada/MathParser.org-mXparser
* http://mariuszgromada.github.io/MathParser.org-mXparser
* http://mxparser.sourceforge.net
* http://bitbucket.org/mariuszgromada/mxparser
* http://mxparser.codeplex.com
* http://github.com/mariuszgromada/Janet-Sudoku
* http://janetsudoku.codeplex.com
* http://sourceforge.net/projects/janetsudoku
* http://bitbucket.org/mariuszgromada/janet-sudoku
* http://github.com/mariuszgromada/MathParser.org-mXparser
*
* Asked if he believes in one God, a mathematician answered:
* "Yes, up to isomorphism."
*/
using System;
namespace org.mariuszgromada.math.mxparser.mathcollection {
/**
* BooleanAlgebra - class for boolean operators.
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:[email protected]">[email protected]</a><br>
* <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br>
* <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
* <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br>
* <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br>
* <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br>
* <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br>
* <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br>
* <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br>
* <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br>
* <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br>
*
* @version 3.0.0
*/
[CLSCompliant(true)]
public sealed class BooleanAlgebra {
/**
* False as integer
*/
public const int FALSE = 0;
/**
* True as integer
*/
public const int TRUE = 1;
/**
* Null as integer
*/
public const int NULL = 2;
/**
* False as double
*/
public const double F = 0;
/**
* True as double
*/
public const double T = 1;
/**
* Null as double
*/
public const double N = Double.NaN;
/**
* AND truth table
*/
public static double[,] AND_TRUTH_TABLE = {
/* F T N
/* F */ { F, F, F} ,
/* T */ { F, T, N} ,
/* N */ { F, N, N}
};
/**
* NAND truth table
*/
public static double[,] NAND_TRUTH_TABLE = {
/* F T N
/* F */ { T, T, T} ,
/* T */ { T, F, N} ,
/* N */ { T, N, N}
};
/**
* OR truth table
*/
public static double[,] OR_TRUTH_TABLE = {
/* F T N
/* F */ { F, T, N} ,
/* T */ { T, T, T} ,
/* N */ { N, T, N}
};
/**
* NOR truth table
*/
public static double[,] NOR_TRUTH_TABLE = {
/* F T N
/* F */ { T, F, N} ,
/* T */ { F, F, F} ,
/* N */ { N, F, N}
};
/**
* XOR truth table
*/
public static double[,] XOR_TRUTH_TABLE = {
/* F T N
/* F */ { F, T, N} ,
/* T */ { T, F, N} ,
/* N */ { N, N, N}
};
/**
* XNOR truth table
*/
public static double[,] XNOR_TRUTH_TABLE = {
/* F T N
/* F */ { T, F, N} ,
/* T */ { F, T, N} ,
/* N */ { N, N, N}
};
/**
* IMP truth table
*/
public static double[,] IMP_TRUTH_TABLE = {
/* F T N
/* F */ { T, T, T} ,
/* T */ { F, T, N} ,
/* N */ { N, T, N}
};
/**
* CIMP truth table
*/
public static double[,] CIMP_TRUTH_TABLE = {
/* F T N
/* F */ { T, F, N} ,
/* T */ { T, T, T} ,
/* N */ { T, N, N}
};
/**
* EQV truth table
*/
public static double[,] EQV_TRUTH_TABLE = {
/* F T N
/* F */ { T, F, N} ,
/* T */ { F, T, N} ,
/* N */ { N, N, N}
};
/**
* NIMP truth table
*/
public static double[,] NIMP_TRUTH_TABLE = {
/* F T N
/* F */ { F, F, F} ,
/* T */ { T, F, N} ,
/* N */ { N, F, N}
};
/**
* CNIMP truth table
*/
public static double[,] CNIMP_TRUTH_TABLE = {
/* F T N
/* F */ { F, T, N} ,
/* T */ { F, F, F} ,
/* N */ { F, N, N}
};
/**
* NOT truth table
*/
public static double[] NOT_TRUTH_TABLE = {
/* F T N */
T, F, N
};
/**
* Double to integer boolean translation
*
* @param a the double number
*
* @return If a = Double.NaN return NULL,
* else if a <> 0 return TRUE,
* else return FALSE.
*/
public static int double2IntBoolean(double a) {
if ( Double.IsNaN(a) )
return NULL;
else if ( a != 0 )
return TRUE;
else
return FALSE;
}
/**
* Boolean AND
*
* @param a the a number (a AND b)
* @param b the b number (a AND b)
*
* @return Truth table element AND[A][B] where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double and(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return AND_TRUTH_TABLE[A, B];
}
/**
* Boolean OR
*
* @param a the a number (a OR b)
* @param b the b number (a OR b)
*
* @return Truth table element OR[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double or(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return OR_TRUTH_TABLE[A, B];
}
/**
* Boolean XOR
*
* @param a the a number (a XOR b)
* @param b the b number (a XOR b)
*
* @return Truth table element XOR[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double xor(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return XOR_TRUTH_TABLE[A, B];
}
/**
* Boolean NAND
*
* @param a the a number (a NAND b)
* @param b the b number (a NAND b)
*
* @return Truth table element NAND[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double nand(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return NAND_TRUTH_TABLE[A, B];
}
/**
* Boolean NOR
*
* @param a the a number (a NOR b)
* @param b the b number (a NOR b)
*
* @return Truth table element NOR[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double nor(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return NOR_TRUTH_TABLE[A, B];
}
/**
* Boolean XNOR
*
* @param a the a number (a XNOR b)
* @param b the b number (a XNOR b)
*
* @return Truth table element XNOR[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double xnor(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return XNOR_TRUTH_TABLE[A, B];
}
/**
* Boolean IMP
*
* @param a the a number (a IMP b)
* @param b the b number (a IMP b)
*
* @return Truth table element IMP[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double imp(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return IMP_TRUTH_TABLE[A, B];
}
/**
* Boolean EQV
*
* @param a the a number (a EQV b)
* @param b the b number (a EQV b)
*
* @return Truth table element EQV[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double eqv(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return EQV_TRUTH_TABLE[A, B];
}
/**
* Boolean NOT
*
* @param a the a number (NOT a)
*
* @return Truth table element NOT[A]
* where A = double2IntBoolean(a)
*/
public static double not(double a) {
int A = double2IntBoolean(a);
return NOT_TRUTH_TABLE[A];
}
/**
* Boolean CIMP
*
* @param a the a number (a CIMP b)
* @param b the b number (a CIMP b)
*
* @return Truth table element CIMP[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double cimp(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return CIMP_TRUTH_TABLE[A, B];
}
/**
* Boolean NIMP
*
* @param a the a number (a NIMP b)
* @param b the b number (a NIMP b)
*
* @return Truth table element NIMP[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double nimp(double a, double b) {
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return NIMP_TRUTH_TABLE[A, B];
}
/**
* Boolean CNIMP
*
* @param a the a number (a CNIMP b)
* @param b the b number (a CNIMP b)
*
* @return Truth table element CNIMP[A][B]
* where A = double2IntBoolean(a), B = double2IntBoolean(b)
*/
public static double cnimp(double a, double b)
{
int A = double2IntBoolean(a);
int B = double2IntBoolean(b);
return CNIMP_TRUTH_TABLE[A, B];
}
}
}
| |
// 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 AndInt32()
{
var test = new SimpleBinaryOpTest__AndInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AndInt32 testClass)
{
var result = Sse2.And(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.And(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AndInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleBinaryOpTest__AndInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.And(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.And(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.And(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.And), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Sse2.And(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse2.And(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.And(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.And(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AndInt32();
var result = Sse2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AndInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Sse2.And(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.And(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.And(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.And(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(left[0] & right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(left[i] & right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.And)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.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 Southwind
{
/// <summary>
/// Strongly-typed collection for the Customerdemographic class.
/// </summary>
[Serializable]
public partial class CustomerdemographicCollection : ActiveList<Customerdemographic, CustomerdemographicCollection>
{
public CustomerdemographicCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>CustomerdemographicCollection</returns>
public CustomerdemographicCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
Customerdemographic o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the customerdemographics table.
/// </summary>
[Serializable]
public partial class Customerdemographic : ActiveRecord<Customerdemographic>, IActiveRecord
{
#region .ctors and Default Settings
public Customerdemographic()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public Customerdemographic(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public Customerdemographic(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public Customerdemographic(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("customerdemographics", TableType.Table, DataService.GetInstance("Southwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarCustomerTypeID = new TableSchema.TableColumn(schema);
colvarCustomerTypeID.ColumnName = "CustomerTypeID";
colvarCustomerTypeID.DataType = DbType.AnsiStringFixedLength;
colvarCustomerTypeID.MaxLength = 10;
colvarCustomerTypeID.AutoIncrement = false;
colvarCustomerTypeID.IsNullable = false;
colvarCustomerTypeID.IsPrimaryKey = true;
colvarCustomerTypeID.IsForeignKey = false;
colvarCustomerTypeID.IsReadOnly = false;
colvarCustomerTypeID.DefaultSetting = @"";
colvarCustomerTypeID.ForeignKeyTableName = "";
schema.Columns.Add(colvarCustomerTypeID);
TableSchema.TableColumn colvarCustomerDesc = new TableSchema.TableColumn(schema);
colvarCustomerDesc.ColumnName = "CustomerDesc";
colvarCustomerDesc.DataType = DbType.String;
colvarCustomerDesc.MaxLength = 0;
colvarCustomerDesc.AutoIncrement = false;
colvarCustomerDesc.IsNullable = true;
colvarCustomerDesc.IsPrimaryKey = false;
colvarCustomerDesc.IsForeignKey = false;
colvarCustomerDesc.IsReadOnly = false;
colvarCustomerDesc.DefaultSetting = @"";
colvarCustomerDesc.ForeignKeyTableName = "";
schema.Columns.Add(colvarCustomerDesc);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Southwind"].AddSchema("customerdemographics",schema);
}
}
#endregion
#region Props
[XmlAttribute("CustomerTypeID")]
[Bindable(true)]
public string CustomerTypeID
{
get { return GetColumnValue<string>(Columns.CustomerTypeID); }
set { SetColumnValue(Columns.CustomerTypeID, value); }
}
[XmlAttribute("CustomerDesc")]
[Bindable(true)]
public string CustomerDesc
{
get { return GetColumnValue<string>(Columns.CustomerDesc); }
set { SetColumnValue(Columns.CustomerDesc, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCustomerTypeID,string varCustomerDesc)
{
Customerdemographic item = new Customerdemographic();
item.CustomerTypeID = varCustomerTypeID;
item.CustomerDesc = varCustomerDesc;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(string varCustomerTypeID,string varCustomerDesc)
{
Customerdemographic item = new Customerdemographic();
item.CustomerTypeID = varCustomerTypeID;
item.CustomerDesc = varCustomerDesc;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn CustomerTypeIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CustomerDescColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string CustomerTypeID = @"CustomerTypeID";
public static string CustomerDesc = @"CustomerDesc";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Forums
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Adxstudio.Xrm.Core.Flighting;
using Adxstudio.Xrm.Notes;
using Adxstudio.Xrm.Web.Mvc;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Services.Query;
public class ForumThreadDataAdapter : IForumThreadDataAdapter
{
public ForumThreadDataAdapter(EntityReference forumThread, IDataAdapterDependencies dependencies)
{
if (forumThread == null)
{
throw new ArgumentNullException("forumThread");
}
if (forumThread.LogicalName != "adx_communityforumthread")
{
throw new ArgumentException(string.Format("Value must have logical name {0}.", forumThread.LogicalName), "forumThread");
}
if (dependencies == null)
{
throw new ArgumentNullException("dependencies");
}
ForumThread = forumThread;
Dependencies = dependencies;
}
public ForumThreadDataAdapter(IForumThread forumThread, IDataAdapterDependencies dependencies)
: this(forumThread.EntityReference, dependencies) { }
protected IDataAdapterDependencies Dependencies { get; private set; }
protected EntityReference ForumThread { get; private set; }
public IForumThread Select()
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Thread={0}: Start", ForumThread.Id));
var serviceContext = Dependencies.GetServiceContext();
var entity = SelectEntity(serviceContext);
if (entity == null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Thread={0}: Not Found", ForumThread.Id));
return null;
}
var securityProvider = Dependencies.GetSecurityProvider();
if (!securityProvider.TryAssert(serviceContext, entity, CrmEntityRight.Read))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Thread={0}: Not Found", ForumThread.Id));
return null;
}
var viewEntity = new PortalViewEntity(serviceContext, entity, securityProvider, Dependencies.GetUrlProvider());
var website = Dependencies.GetWebsite();
var threadInfo = serviceContext.FetchForumThreadInfo(entity.Id, website.Id);
var counterStrategy = Dependencies.GetCounterStrategy();
var thread = new ForumThread(
entity,
viewEntity,
threadInfo,
// Only lazily get the post count, because it's unlikely to be used in the common case.
// SelectPostCount will generally be used instead.
() => counterStrategy.GetForumThreadPostCount(serviceContext, entity));
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Thread={0}: End", ForumThread.Id));
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Forum, HttpContext.Current, "read_forum_thread", 1, thread.Entity.ToEntityReference(), "read");
}
return thread;
}
public void CreateAlert(EntityReference user)
{
if (user == null) throw new ArgumentNullException("user");
if (user.LogicalName != "contact")
{
throw new ArgumentException(string.Format("Value must have logical name '{0}'", user.LogicalName), "user");
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}:{1}", user.LogicalName, user.Id));
var serviceContext = Dependencies.GetServiceContextForWrite();
var existingAlert = SelectAlert(serviceContext, user);
if (existingAlert != null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}, Alert Exists", user.LogicalName, user.Id));
return;
}
var alert = new Entity("adx_communityforumalert");
alert["adx_subscriberid"] = user;
alert["adx_threadid"] = ForumThread;
serviceContext.AddObject(alert);
serviceContext.SaveChanges();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}", user.LogicalName, user.Id));
}
public IForumPost CreatePost(IForumPostSubmission forumPost, bool incrementForumThreadCount = false)
{
if (forumPost == null) throw new ArgumentNullException("forumPost");
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start");
var serviceContext = Dependencies.GetServiceContextForWrite();
var thread = Select();
var locked = thread.Locked;
if (locked) throw new InvalidOperationException("You can't create a new post because the forum is locked.");
var entity = new Entity("adx_communityforumpost");
entity["adx_forumthreadid"] = ForumThread;
entity["adx_name"] = Truncate(forumPost.Name, 100);
entity["adx_isanswer"] = forumPost.IsAnswer;
entity["adx_authorid"] = forumPost.Author.EntityReference;
entity["adx_date"] = forumPost.PostedOn;
entity["adx_content"] = forumPost.Content;
entity["adx_helpfulvotecount"] = forumPost.HelpfulVoteCount;
serviceContext.AddObject(entity);
serviceContext.SaveChanges();
var threadEntity = SelectEntity(serviceContext);
var threadUpdate = new Entity(threadEntity.LogicalName) { Id = threadEntity.Id };
threadUpdate["adx_lastpostdate"] = forumPost.PostedOn;
threadUpdate["adx_lastpostid"] = entity.ToEntityReference();
threadUpdate["adx_postcount"] = threadEntity.GetAttributeValue<int?>("adx_postcount").GetValueOrDefault() + 1;
if (threadEntity.GetAttributeValue<EntityReference>("adx_firstpostid") == null)
{
threadUpdate["adx_firstpostid"] = entity.ToEntityReference();
}
serviceContext.Detach(threadEntity);
serviceContext.Attach(threadUpdate);
serviceContext.UpdateObject(threadUpdate);
serviceContext.SaveChanges();
var entityReference = entity.ToEntityReference();
var forumDataAdapter = new ForumDataAdapter(threadEntity.GetAttributeValue<EntityReference>("adx_forumid"), Dependencies);
forumDataAdapter.UpdateLatestPost(entityReference, incrementForumThreadCount);
foreach (var attachment in forumPost.Attachments)
{
IAnnotationDataAdapter da = new AnnotationDataAdapter(Dependencies);
da.CreateAnnotation(entityReference, string.Empty, string.Empty, attachment.Name, attachment.ContentType,
attachment.Content);
}
var post = SelectPost(entityReference.Id);
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Forum, HttpContext.Current, "create_forum_post", 1, post.Entity.ToEntityReference(), "create");
}
return post;
}
public void UpdatePost(IForumPostSubmission forumPost)
{
if (forumPost == null) throw new ArgumentNullException("forumPost");
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start");
var entityReference = ((IForumPostInfo)forumPost).EntityReference;
var serviceContext = Dependencies.GetServiceContextForWrite();
var update = new Entity("adx_communityforumpost")
{
Id = entityReference.Id
};
if (forumPost.Name != null)
{
update["adx_name"] = Truncate(forumPost.Name, 100);
}
if (forumPost.Content != null)
{
update["adx_content"] = forumPost.Content;
}
if (update.Attributes.Any())
{
serviceContext.Attach(update);
serviceContext.UpdateObject(update);
serviceContext.SaveChanges();
}
foreach (var attachment in forumPost.Attachments)
{
IAnnotationDataAdapter da = new AnnotationDataAdapter(Dependencies);
da.CreateAnnotation(entityReference, string.Empty, string.Empty, attachment.Name, attachment.ContentType,
attachment.Content);
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Forum, HttpContext.Current, "edit_forum_post", 1, entityReference, "edit");
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");
}
public void DeleteAlert(EntityReference user)
{
if (user == null) throw new ArgumentNullException("user");
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}:{1}", user.LogicalName, user.Id));
var serviceContext = Dependencies.GetServiceContextForWrite();
var existingAlert = SelectAlert(serviceContext, user);
if (existingAlert == null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}, Alert Not Found", user.LogicalName, user.Id));
return;
}
serviceContext.DeleteObject(existingAlert);
serviceContext.SaveChanges();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}", user.LogicalName, user.Id));
}
public void DeletePost(EntityReference forumPost)
{
if (forumPost == null) throw new ArgumentNullException("forumPost");
var serviceContext = Dependencies.GetServiceContextForWrite();
var post = serviceContext.RetrieveSingle(new Fetch
{
Entity = new FetchEntity("adx_communityforumpost")
{
Filters = new[] { new Filter {
Conditions = new[]
{
new Condition("adx_communityforumpostid", ConditionOperator.Equal, forumPost.Id),
new Condition("adx_forumthreadid", ConditionOperator.Equal, this.ForumThread.Id)
} } }
}
});
if (post == null)
{
throw new ArgumentException("Unable to find {0} {1}.".FormatWith(forumPost.LogicalName, forumPost.Id), "forumPost");
}
var thread = SelectEntity(serviceContext);
if (thread == null)
{
serviceContext.DeleteObject(post);
serviceContext.SaveChanges();
return;
}
var postReference = post.ToEntityReference();
var counterStrategy = Dependencies.GetCounterStrategy();
var threadPostCount = counterStrategy.GetForumThreadPostCount(serviceContext, thread);
var threadUpdate = new Entity(thread.LogicalName) { Id = thread.Id };
threadUpdate["adx_postcount"] = threadPostCount < 1 ? 0 : threadPostCount - 1;
// If deleting first post, delete entire thread
if (Equals(thread.GetAttributeValue<EntityReference>("adx_firstpostid"), postReference))
{
var forumDataAdapter = new ForumDataAdapter(thread.GetAttributeValue<EntityReference>("adx_forumid"), Dependencies);
forumDataAdapter.DeleteThread(thread.ToEntityReference());
}
// Determine the new last post in the thread.
else if (Equals(thread.GetAttributeValue<EntityReference>("adx_lastpostid"), postReference))
{
var lastPostFetch = new Fetch
{
Entity = new FetchEntity("adx_communityforumpost")
{
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("adx_forumthreadid", ConditionOperator.Equal, thread.Id),
new Condition("adx_communityforumpostid", ConditionOperator.NotEqual, post.Id)
}
}
},
Orders = new[] { new Order("adx_date", OrderType.Descending) }
},
PageNumber = 1,
PageSize = 1
};
var lastPost = serviceContext.RetrieveSingle(lastPostFetch);
if (lastPost == null)
{
throw new InvalidOperationException("Unable to determine new last post in thread.");
}
threadUpdate["adx_lastpostid"] = lastPost.ToEntityReference();
threadUpdate["adx_lastpostdate"] = lastPost.GetAttributeValue<DateTime?>("adx_date");
serviceContext.Detach(thread);
serviceContext.Attach(threadUpdate);
serviceContext.UpdateObject(threadUpdate);
serviceContext.DeleteObject(post);
serviceContext.SaveChanges();
}
var forumId = thread.GetAttributeValue<EntityReference>("adx_forumid");
if (forumId == null)
{
return;
}
var forumServiceContext = Dependencies.GetServiceContextForWrite();
var forum = forumServiceContext.RetrieveSingle("adx_communityforum", "adx_communityforumid", forumId.Id, FetchAttribute.All);
if (forum == null)
{
return;
}
// Update forum counts and pointers.
var forumCounts = counterStrategy.GetForumCounts(forumServiceContext, forum);
var forumUpdate = new Entity(forum.LogicalName) { Id = forum.Id };
forumUpdate["adx_postcount"] = forumCounts.PostCount < 1 ? 0 : forumCounts.PostCount - 1;
var forumLastPost = forum.GetAttributeValue<EntityReference>("adx_lastpostid");
if (Equals(forumLastPost, postReference))
{
var lastUpdatedThreadFetch = new Fetch
{
Entity = new FetchEntity("adx_communityforumthread")
{
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("adx_forumid", ConditionOperator.Equal, forum.Id),
new Condition("adx_lastpostid", ConditionOperator.NotNull)
}
}
},
Orders = new[] { new Order("adx_lastpostdate", OrderType.Descending) }
},
PageNumber = 1,
PageSize = 1
};
var lastUpdatedThread = forumServiceContext.RetrieveSingle(lastUpdatedThreadFetch);
forumUpdate["adx_lastpostid"] = lastUpdatedThread == null
? null
: lastUpdatedThread.GetAttributeValue<EntityReference>("adx_lastpostid");
}
forumServiceContext.Detach(forum);
forumServiceContext.Attach(forumUpdate);
forumServiceContext.UpdateObject(forumUpdate);
forumServiceContext.SaveChanges();
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Forum, HttpContext.Current, "delete_forum_post", 1, forumPost, "delete");
}
}
public void MarkAsAnswer(Guid forumPostId)
{
if (forumPostId == null) throw new ArgumentNullException("forumPostId");
var serviceContext = Dependencies.GetServiceContextForWrite();
var postFetch = new Fetch
{
Entity = new FetchEntity("adx_communityforumpost")
{
Filters = new[] { new Filter
{
Conditions = new[]
{
new Condition("adx_communityforumpostid", ConditionOperator.Equal, forumPostId),
new Condition("adx_forumthreadid", ConditionOperator.Equal, this.ForumThread.Id)
}
} }
}
};
var post = serviceContext.RetrieveSingle(postFetch);
if (post == null)
{
throw new ArgumentException("Unable to find {0} {1}.".FormatWith("adx_communityforumpost", forumPostId), "forumPostId");
}
var thread = SelectEntity(serviceContext);
var postUpdate = new Entity(post.LogicalName) { Id = post.Id };
var threadUpdate = new Entity(thread.LogicalName) { Id = thread.Id };
postUpdate["adx_isanswer"] = true;
threadUpdate["adx_isanswered"] = true;
serviceContext.Detach(post);
serviceContext.Detach(thread);
serviceContext.Attach(postUpdate);
serviceContext.Attach(threadUpdate);
serviceContext.UpdateObject(postUpdate);
serviceContext.UpdateObject(threadUpdate);
serviceContext.SaveChanges();
}
public void UnMarkAsAnswer(Guid forumPostId)
{
if (forumPostId == null) throw new ArgumentNullException("forumPostId");
var serviceContext = Dependencies.GetServiceContextForWrite();
var answerPostsFetch = new Fetch
{
Entity = new FetchEntity("adx_communityforumpost")
{
Filters = new[] { new Filter
{
Conditions = new[]
{
new Condition("adx_isanswer", ConditionOperator.Equal, true),
new Condition("adx_forumthreadid", ConditionOperator.Equal, this.ForumThread.Id)
}
} }
}
};
var answerPosts = serviceContext.RetrieveMultiple(answerPostsFetch).Entities;
var post = answerPosts.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_communityforumpostid") == forumPostId);
if (post == null)
{
// The post was already not an answer, so do nothing.
return;
}
var thread = SelectEntity(serviceContext);
var postUpdate = new Entity(post.LogicalName) { Id = post.Id };
var threadUpdate = new Entity(thread.LogicalName) { Id = thread.Id };
postUpdate["adx_isanswer"] = false;
// If the thread will still have at least one other answer post, after the given post is updated, it is still answered.
threadUpdate["adx_isanswered"] = answerPosts.Count > 1;
serviceContext.Detach(thread);
serviceContext.Detach(post);
serviceContext.Attach(postUpdate);
serviceContext.Attach(threadUpdate);
serviceContext.UpdateObject(postUpdate);
serviceContext.UpdateObject(threadUpdate);
serviceContext.SaveChanges();
}
public bool HasAlert(EntityReference user)
{
if (user == null) throw new ArgumentNullException("user");
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}:{1}", user.LogicalName, user.Id));
var serviceContext = Dependencies.GetServiceContext();
var existingAlert = SelectAlert(serviceContext, user);
var hasAlert = existingAlert != null;
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}:{1}, {2}", user.LogicalName, user.Id, hasAlert));
return hasAlert;
}
public int SelectPostCount()
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start");
var serviceContext = Dependencies.GetServiceContext();
var entity = SelectEntity(serviceContext);
if (entity == null)
{
return 0;
}
var counterStrategy = Dependencies.GetCounterStrategy();
var postCount = counterStrategy.GetForumThreadPostCount(serviceContext, entity);
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");
return postCount;
}
public IEnumerable<IForumPost> SelectPosts()
{
return SelectPosts(0);
}
public IEnumerable<IForumPost> SelectPosts(bool descending)
{
return SelectPosts(descending, 0);
}
public IEnumerable<IForumPost> SelectPosts(int startRowIndex, int maximumRows = -1)
{
return SelectPosts(false, startRowIndex, maximumRows);
}
public IEnumerable<IForumPost> SelectPosts(bool descending, int startRowIndex, int maximumRows = -1)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("startRowIndex={0}, maximumRows={1}: Start", startRowIndex, maximumRows));
if (startRowIndex < 0)
{
throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
}
if (maximumRows == 0)
{
return new IForumPost[] { };
}
var serviceContext = Dependencies.GetServiceContext();
var securityProvider = Dependencies.GetSecurityProvider();
var query = serviceContext.CreateQuery("adx_communityforumpost")
.Where(e => e.GetAttributeValue<EntityReference>("adx_forumthreadid") == ForumThread);
query = descending
? query.OrderByDescending(e => e.GetAttributeValue<DateTime?>("adx_date"))
: query.OrderBy(e => e.GetAttributeValue<DateTime?>("adx_date"));
if (startRowIndex > 0)
{
query = query.Skip(startRowIndex);
}
if (maximumRows > 0)
{
query = query.Take(maximumRows);
}
var website = Dependencies.GetWebsite();
var entities = query.ToArray();
var firstPostEntity = entities.FirstOrDefault();
var cloudStorageAccount = AnnotationDataAdapter.GetStorageAccount(serviceContext);
var cloudStorageContainerName = AnnotationDataAdapter.GetStorageContainerName(serviceContext);
CloudBlobContainer cloudStorageContainer = null;
if (cloudStorageAccount != null)
{
cloudStorageContainer = AnnotationDataAdapter.GetBlobContainer(cloudStorageAccount, cloudStorageContainerName);
}
var postInfos = serviceContext.FetchForumPostInfos(entities.Select(e => e.Id), website.Id, cloudStorageContainer: cloudStorageContainer);
var urlProvider = Dependencies.GetUrlProvider();
var thread = Select();
var user = Dependencies.GetPortalUser();
var posts = entities.Select(entity =>
{
IForumPostInfo postInfo;
postInfo = postInfos.TryGetValue(entity.Id, out postInfo) ? postInfo : new UnknownForumPostInfo();
var viewEntity = new PortalViewEntity(serviceContext, entity, securityProvider, urlProvider);
return new ForumPost(entity, viewEntity, postInfo,
new Lazy<ApplicationPath>(() => Dependencies.GetEditPath(entity.ToEntityReference()), LazyThreadSafetyMode.None),
new Lazy<ApplicationPath>(() => Dependencies.GetDeletePath(entity.ToEntityReference()), LazyThreadSafetyMode.None),
new Lazy<bool>(() => thread.Editable, LazyThreadSafetyMode.None),
new Lazy<bool>(() =>
thread.ThreadType != null
&& thread.ThreadType.RequiresAnswer
&& (firstPostEntity == null || !firstPostEntity.ToEntityReference().Equals(entity.ToEntityReference()))
&& ((user != null && user.Equals(thread.Author.EntityReference)) || thread.Editable)
&& !thread.Locked,
LazyThreadSafetyMode.None),
canEdit: new Lazy<bool>(() =>
user != null
&& user.Equals(postInfo.Author.EntityReference)
&& !thread.Locked, LazyThreadSafetyMode.None));
}).ToArray();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");
return posts;
}
public IEnumerable<IForumPost> SelectPostsDescending()
{
return SelectPostsDescending(0);
}
public IEnumerable<IForumPost> SelectPostsDescending(int startRowIndex, int maximumRows = -1)
{
return SelectPosts(true, startRowIndex, maximumRows);
}
protected Entity SelectAlert(OrganizationServiceContext serviceContext, EntityReference user)
{
if (serviceContext == null) throw new ArgumentNullException("serviceContext");
if (user == null) throw new ArgumentNullException("user");
return serviceContext.RetrieveSingle(new Fetch
{
Entity = new FetchEntity("adx_communityforumalert")
{
Filters = new[]
{
new Filter
{
Conditions = new[] {
new Condition("adx_subscriberid", ConditionOperator.Equal, user.Id),
new Condition("adx_threadid", ConditionOperator.Equal, this.ForumThread.Id) }
}
}
}
});
}
public IForumPost SelectPost(Guid forumPostId)
{
var serviceContext = Dependencies.GetServiceContext();
var postFetch = new Fetch
{
Entity = new FetchEntity("adx_communityforumpost")
{
Filters = new[]
{
new Filter
{
Conditions = new[] {
new Condition("adx_communityforumpostid", ConditionOperator.Equal, forumPostId),
new Condition("adx_forumthreadid", ConditionOperator.Equal, this.ForumThread.Id) }
}
}
}
};
var entity = serviceContext.RetrieveSingle(postFetch);
if (entity == null) return null;
var website = Dependencies.GetWebsite();
var securityProvider = Dependencies.GetSecurityProvider();
var urlProvider = Dependencies.GetUrlProvider();
var viewEntity = new PortalViewEntity(serviceContext, entity, securityProvider, urlProvider);
var cloudStorageAccount = AnnotationDataAdapter.GetStorageAccount(serviceContext);
var cloudStorageContainerName = AnnotationDataAdapter.GetStorageContainerName(serviceContext);
CloudBlobContainer cloudStorageContainer = null;
if (cloudStorageAccount != null)
{
cloudStorageContainer = AnnotationDataAdapter.GetBlobContainer(cloudStorageAccount, cloudStorageContainerName);
}
var postInfo = serviceContext.FetchForumPostInfo(entity.Id, website.Id, cloudStorageContainer);
var user = Dependencies.GetPortalUser();
return new ForumPost(entity, viewEntity, postInfo,
new Lazy<ApplicationPath>(() => Dependencies.GetEditPath(entity.ToEntityReference()), LazyThreadSafetyMode.None),
new Lazy<ApplicationPath>(() => Dependencies.GetDeletePath(entity.ToEntityReference()), LazyThreadSafetyMode.None),
canEdit: new Lazy<bool>(() =>
user != null
&& user.Equals(postInfo.Author.EntityReference), LazyThreadSafetyMode.None));
}
public IForumPost SelectFirstPost()
{
var serviceContext = Dependencies.GetServiceContext();
var thread = serviceContext.RetrieveSingle(
"adx_communityforumthread",
"adx_communityforumthreadid",
this.ForumThread.Id,
new[] { new FetchAttribute("adx_firstpostid") });
return thread == null || thread.GetAttributeValue<EntityReference>("adx_firstpostid") == null
? null
: SelectPost(thread.GetAttributeValue<EntityReference>("adx_firstpostid").Id);
}
public IForumPost SelectLatestPost()
{
var serviceContext = Dependencies.GetServiceContext();
var thread = serviceContext.RetrieveSingle(
"adx_communityforumthread",
"adx_communityforumthreadid",
this.ForumThread.Id,
new[] { new FetchAttribute("adx_lastpostid") });
return thread == null || thread.GetAttributeValue<EntityReference>("adx_lastpostid") == null
? null
: SelectPost(thread.GetAttributeValue<EntityReference>("adx_lastpostid").Id);
}
private Entity SelectEntity(OrganizationServiceContext serviceContext)
{
var entity = serviceContext.RetrieveSingle(
"adx_communityforumthread",
"adx_communityforumthreadid",
this.ForumThread.Id,
FetchAttribute.All);
return entity;
}
private static string Truncate(string value, int maxLength)
{
if (value == null)
{
return null;
}
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
}
}
| |
// 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.
using System;
using System.IO;
using SharpDX.Direct3D11;
using SharpDX.IO;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A Texture 3D front end to <see cref="SharpDX.Direct3D11.Texture3D"/>.
/// </summary>
public class Texture3D : Texture3DBase
{
internal Texture3D(GraphicsDevice device, Texture3DDescription description3D, params DataBox[] dataBox)
: base(device, description3D, dataBox)
{
}
internal Texture3D(GraphicsDevice device, Direct3D11.Texture3D texture) : base(device, texture)
{
}
internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipMapSlice)
{
throw new System.NotSupportedException();
}
/// <summary>
/// Makes a copy of this texture.
/// </summary>
/// <remarks>
/// This method doesn't copy the content of the texture.
/// </remarks>
/// <returns>
/// A copy of this texture.
/// </returns>
public override Texture Clone()
{
return new Texture3D(GraphicsDevice, this.Description);
}
/// <summary>
/// Creates a new texture from a <see cref="Texture3DDescription"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="description">The description.</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(GraphicsDevice device, Texture3DDescription description)
{
return new Texture3D(device, description);
}
/// <summary>
/// Creates a new texture from a <see cref="Direct3D11.Texture3D"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="texture">The native texture <see cref="Direct3D11.Texture3D"/>.</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(GraphicsDevice device, Direct3D11.Texture3D texture)
{
return new Texture3D(device, texture);
}
/// <summary>
/// Creates a new <see cref="Texture3D"/> with a single mipmap.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(GraphicsDevice device, int width, int height, int depth, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default)
{
return New(device, width, height, depth, false, format, flags, usage);
}
/// <summary>
/// Creates a new <see cref="Texture3D"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(GraphicsDevice device, int width, int height, int depth, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default)
{
return new Texture3D(device, NewDescription(width, height, depth, format, flags, mipCount, usage));
}
/// <summary>
/// Creates a new <see cref="Texture3D" /> with texture data for the firs map.
/// </summary>
/// <typeparam name="T">Type of the data to upload to the texture</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="textureData">The texture data, width * height * depth data </param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>A new instance of <see cref="Texture3D" /> class.</returns>
/// <remarks>
/// The first dimension of mipMapTextures describes the number of is an array ot Texture3D Array
/// </remarks>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public unsafe static Texture3D New<T>(GraphicsDevice device, int width, int height, int depth, PixelFormat format, T[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) where T : struct
{
Texture3D tex = null;
Utilities.Pin(textureData, ptr =>
{
tex = New(device, width, height, depth, 1, format, new[] { GetDataBox(format, width, height, depth, textureData, ptr) }, flags, usage);
});
return tex;
}
/// <summary>
/// Creates a new <see cref="Texture3D"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param>
/// <param name="format">Describes the format to use.</param>
/// <param name="usage">The usage.</param>
/// <param name="textureData">DataBox used to fill texture data.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <returns>
/// A new instance of <see cref="Texture3D"/> class.
/// </returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(GraphicsDevice device, int width, int height, int depth, MipMapCount mipCount, PixelFormat format, DataBox[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Default)
{
// TODO Add check for number of texture data according to width/height/depth/mipCount.
return new Texture3D(device, NewDescription(width, height, depth, format, flags, mipCount, usage), textureData);
}
/// <summary>
/// Creates a new <see cref="Texture3D" /> directly from an <see cref="Image"/>.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="image">An image in CPU memory.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">The usage.</param>
/// <returns>A new instance of <see cref="Texture3D" /> class.</returns>
/// <msdn-id>ff476522</msdn-id>
/// <unmanaged>HRESULT ID3D11Device::CreateTexture3D([In] const D3D11_TEXTURE3D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture3D** ppTexture3D)</unmanaged>
/// <unmanaged-short>ID3D11Device::CreateTexture3D</unmanaged-short>
public static Texture3D New(GraphicsDevice device, Image image, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
if (image == null) throw new ArgumentNullException("image");
if (image.Description.Dimension != TextureDimension.Texture3D)
throw new ArgumentException("Invalid image. Must be 3D", "image");
return new Texture3D(device, CreateTextureDescriptionFromImage(image, flags, usage), image.ToDataBox());
}
/// <summary>
/// Loads a 3D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="stream">The stream to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 3D</exception>
/// <returns>A texture</returns>
public static new Texture3D Load(GraphicsDevice device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
var texture = Texture.Load(device, stream, flags, usage);
if (!(texture is Texture3D))
throw new ArgumentException(string.Format("Texture is not type of [Texture3D] but [{0}]", texture.GetType().Name));
return (Texture3D)texture;
}
/// <summary>
/// Loads a 3D texture from a stream.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/>.</param>
/// <param name="filePath">The file to load the texture from.</param>
/// <param name="flags">Sets the texture flags (for unordered access...etc.)</param>
/// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param>
/// <exception cref="ArgumentException">If the texture is not of type 3D</exception>
/// <returns>A texture</returns>
public static new Texture3D Load(GraphicsDevice device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable)
{
using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read))
return Load(device, stream, flags, usage);
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Configuration;
using System.Net.Sockets;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using ASC.Common.Logging;
using ASC.Common.Security.Authorizing;
using ASC.Common.Threading;
using ASC.Core;
using ASC.Web.Studio.PublicResources;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Api.Settings.Smtp
{
public class SmtpOperation
{
public const string OWNER = "SMTPOwner";
public const string SOURCE = "SMTPSource";
public const string PROGRESS = "SMTPProgress";
public const string RESULT = "SMTPResult";
public const string ERROR = "SMTPError";
public const string FINISHED = "SMTPFinished";
protected DistributedTask TaskInfo { get; set; }
protected CancellationToken CancellationToken { get; private set; }
protected int Progress { get; private set; }
protected string Source { get; private set; }
protected string Status { get; set; }
protected string Error { get; set; }
protected int CurrentTenant { get; private set; }
protected Guid CurrentUser { get; private set; }
protected ILog Logger { get; private set; }
public SmtpSettingsWrapper SmtpSettings { get; private set; }
private readonly string messageSubject;
private readonly string messageBody;
public SmtpOperation(SmtpSettingsWrapper smtpSettings, int tenant, Guid user)
{
SmtpSettings = smtpSettings;
CurrentTenant = tenant;
CurrentUser = user;
messageSubject = Web.Studio.Core.Notify.WebstudioNotifyPatternResource.subject_smtp_test;
messageBody = Web.Studio.Core.Notify.WebstudioNotifyPatternResource.pattern_smtp_test;
Source = "";
Progress = 0;
Status = "";
Error = "";
Source = "";
TaskInfo = new DistributedTask();
Logger = LogManager.GetLogger("ASC");
}
public void RunJob(DistributedTask _, CancellationToken cancellationToken)
{
try
{
CancellationToken = cancellationToken;
SetProgress(5, "Setup tenant");
CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);
SetProgress(10, "Setup user");
SecurityContext.AuthenticateMe(CurrentUser); //Core.Configuration.Constants.CoreSystem);
SetProgress(15, "Find user data");
var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
SetProgress(20, "Create mime message");
var toAddress = new MailboxAddress(currentUser.UserName, currentUser.Email);
var fromAddress = new MailboxAddress(SmtpSettings.SenderDisplayName, SmtpSettings.SenderAddress);
var mimeMessage = new MimeMessage
{
Subject = messageSubject
};
mimeMessage.From.Add(fromAddress);
mimeMessage.To.Add(toAddress);
var bodyBuilder = new BodyBuilder
{
TextBody = messageBody
};
mimeMessage.Body = bodyBuilder.ToMessageBody();
mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");
using (var client = GetSmtpClient())
{
SetProgress(40, "Connect to host");
client.Connect(SmtpSettings.Host, SmtpSettings.Port.GetValueOrDefault(25),
SmtpSettings.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None, cancellationToken);
if (SmtpSettings.EnableAuth)
{
SetProgress(60, "Authenticate");
client.Authenticate(SmtpSettings.CredentialsUserName,
SmtpSettings.CredentialsUserPassword, cancellationToken);
}
SetProgress(80, "Send test message");
client.Send(FormatOptions.Default, mimeMessage, cancellationToken);
}
}
catch (AuthorizingException authError)
{
Error = Resource.ErrorAccessDenied; // "No permissions to perform this action";
Logger.Error(Error, new SecurityException(Error, authError));
}
catch (AggregateException ae)
{
ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
}
catch (SocketException ex)
{
Error = ex.Message; //TODO: Add translates of ordinary cases
Logger.Error(ex.ToString());
}
catch (AuthenticationException ex)
{
Error = ex.Message; //TODO: Add translates of ordinary cases
Logger.Error(ex.ToString());
}
catch (Exception ex)
{
Error = ex.Message; //TODO: Add translates of ordinary cases
Logger.Error(ex.ToString());
}
finally
{
try
{
TaskInfo.SetProperty(FINISHED, true);
PublishTaskInfo();
SecurityContext.Logout();
}
catch (Exception ex)
{
Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
}
}
}
public SmtpClient GetSmtpClient()
{
var sslCertificatePermit = ConfigurationManagerExtension.AppSettings["mail.certificate-permit"] != null &&
Convert.ToBoolean(ConfigurationManagerExtension.AppSettings["mail.certificate-permit"]);
var client = new SmtpClient
{
Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds
};
if (sslCertificatePermit)
client.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
return client;
}
public virtual DistributedTask GetDistributedTask()
{
FillDistributedTask();
return TaskInfo;
}
protected virtual void FillDistributedTask()
{
TaskInfo.SetProperty(SOURCE, Source);
TaskInfo.SetProperty(OWNER, CurrentTenant);
TaskInfo.SetProperty(PROGRESS, Progress < 100 ? Progress : 100);
TaskInfo.SetProperty(RESULT, Status);
TaskInfo.SetProperty(ERROR, Error);
//TaskInfo.SetProperty(PROCESSED, successProcessed);
}
protected int GetProgress()
{
return Progress;
}
const string PROGRESS_STRING = "Progress: {0}% {1} {2}";
public void SetProgress(int? currentPercent = null, string currentStatus = null, string currentSource = null)
{
if (!currentPercent.HasValue && currentStatus == null && currentSource == null)
return;
if (currentPercent.HasValue)
Progress = currentPercent.Value;
if (currentStatus != null)
Status = currentStatus;
if (currentSource != null)
Source = currentSource;
Logger.InfoFormat(PROGRESS_STRING, Progress, Status, Source);
PublishTaskInfo();
}
protected void PublishTaskInfo()
{
FillDistributedTask();
TaskInfo.PublishChanges();
}
}
}
| |
// 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.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Caching.Configuration;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace System.Runtime.Caching
{
internal sealed class MemoryCacheStatistics : IDisposable
{
private const int MEMORYSTATUS_INTERVAL_5_SECONDS = 5 * 1000;
private const int MEMORYSTATUS_INTERVAL_30_SECONDS = 30 * 1000;
private int _configCacheMemoryLimitMegabytes;
private int _configPhysicalMemoryLimitPercentage;
private int _configPollingInterval;
private int _inCacheManagerThread;
private int _disposed;
private long _lastTrimCount;
private long _lastTrimDurationTicks; // used only for debugging
private int _lastTrimGen2Count;
private int _lastTrimPercent;
private DateTime _lastTrimTime;
private int _pollingInterval;
private GCHandleRef<Timer> _timerHandleRef;
private Object _timerLock;
private long _totalCountBeforeTrim;
private CacheMemoryMonitor _cacheMemoryMonitor;
private MemoryCache _memoryCache;
private PhysicalMemoryMonitor _physicalMemoryMonitor;
// private
private MemoryCacheStatistics()
{
//hide default ctor
}
private void AdjustTimer()
{
lock (_timerLock)
{
if (_timerHandleRef == null)
return;
Timer timer = _timerHandleRef.Target;
// the order of these if statements is important
// When above the high pressure mark, interval should be 5 seconds or less
if (_physicalMemoryMonitor.IsAboveHighPressure() || _cacheMemoryMonitor.IsAboveHighPressure())
{
if (_pollingInterval > MEMORYSTATUS_INTERVAL_5_SECONDS)
{
_pollingInterval = MEMORYSTATUS_INTERVAL_5_SECONDS;
timer.Change(_pollingInterval, _pollingInterval);
}
return;
}
// When above half the low pressure mark, interval should be 30 seconds or less
if ((_cacheMemoryMonitor.PressureLast > _cacheMemoryMonitor.PressureLow / 2)
|| (_physicalMemoryMonitor.PressureLast > _physicalMemoryMonitor.PressureLow / 2))
{
// allow interval to fall back down when memory pressure goes away
int newPollingInterval = Math.Min(_configPollingInterval, MEMORYSTATUS_INTERVAL_30_SECONDS);
if (_pollingInterval != newPollingInterval)
{
_pollingInterval = newPollingInterval;
timer.Change(_pollingInterval, _pollingInterval);
}
return;
}
// there is no pressure, interval should be the value from config
if (_pollingInterval != _configPollingInterval)
{
_pollingInterval = _configPollingInterval;
timer.Change(_pollingInterval, _pollingInterval);
}
}
}
// timer callback
private void CacheManagerTimerCallback(object state)
{
CacheManagerThread(0);
}
internal long GetLastSize()
{
return _cacheMemoryMonitor.PressureLast;
}
private int GetPercentToTrim()
{
int gen2Count = GC.CollectionCount(2);
// has there been a Gen 2 Collection since the last trim?
if (gen2Count != _lastTrimGen2Count)
{
return Math.Max(_physicalMemoryMonitor.GetPercentToTrim(_lastTrimTime, _lastTrimPercent), _cacheMemoryMonitor.GetPercentToTrim(_lastTrimTime, _lastTrimPercent));
}
else
{
return 0;
}
}
private void InitializeConfiguration(NameValueCollection config)
{
MemoryCacheElement element = null;
if (!_memoryCache.ConfigLess)
{
MemoryCacheSection section = ConfigurationManager.GetSection("system.runtime.caching/memoryCache") as MemoryCacheSection;
if (section != null)
{
element = section.NamedCaches[_memoryCache.Name];
}
}
if (element != null)
{
_configCacheMemoryLimitMegabytes = element.CacheMemoryLimitMegabytes;
_configPhysicalMemoryLimitPercentage = element.PhysicalMemoryLimitPercentage;
double milliseconds = element.PollingInterval.TotalMilliseconds;
_configPollingInterval = (milliseconds < (double)Int32.MaxValue) ? (int)milliseconds : Int32.MaxValue;
}
else
{
_configPollingInterval = ConfigUtil.DefaultPollingTimeMilliseconds;
_configCacheMemoryLimitMegabytes = 0;
_configPhysicalMemoryLimitPercentage = 0;
}
if (config != null)
{
_configPollingInterval = ConfigUtil.GetIntValueFromTimeSpan(config, ConfigUtil.PollingInterval, _configPollingInterval);
_configCacheMemoryLimitMegabytes = ConfigUtil.GetIntValue(config, ConfigUtil.CacheMemoryLimitMegabytes, _configCacheMemoryLimitMegabytes, true, Int32.MaxValue);
_configPhysicalMemoryLimitPercentage = ConfigUtil.GetIntValue(config, ConfigUtil.PhysicalMemoryLimitPercentage, _configPhysicalMemoryLimitPercentage, true, 100);
}
}
private void InitDisposableMembers()
{
bool dispose = true;
try
{
_cacheMemoryMonitor = new CacheMemoryMonitor(_memoryCache, _configCacheMemoryLimitMegabytes);
Timer timer;
// Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever
bool restoreFlow = false;
try
{
if (!ExecutionContext.IsFlowSuppressed())
{
ExecutionContext.SuppressFlow();
restoreFlow = true;
}
timer = new Timer(new TimerCallback(CacheManagerTimerCallback), null, _configPollingInterval, _configPollingInterval);
}
finally
{
// Restore the current ExecutionContext
if (restoreFlow)
ExecutionContext.RestoreFlow();
}
_timerHandleRef = new GCHandleRef<Timer>(timer);
dispose = false;
}
finally
{
if (dispose)
{
Dispose();
}
}
}
private void SetTrimStats(long trimDurationTicks, long totalCountBeforeTrim, long trimCount)
{
_lastTrimDurationTicks = trimDurationTicks;
int gen2Count = GC.CollectionCount(2);
// has there been a Gen 2 Collection since the last trim?
if (gen2Count != _lastTrimGen2Count)
{
_lastTrimTime = DateTime.UtcNow;
_totalCountBeforeTrim = totalCountBeforeTrim;
_lastTrimCount = trimCount;
}
else
{
// we've done multiple trims between Gen 2 collections, so only add to the trim count
_lastTrimCount += trimCount;
}
_lastTrimGen2Count = gen2Count;
_lastTrimPercent = (int)((_lastTrimCount * 100L) / _totalCountBeforeTrim);
}
private void Update()
{
_physicalMemoryMonitor.Update();
_cacheMemoryMonitor.Update();
}
// public/internal
internal long CacheMemoryLimit
{
get
{
return _cacheMemoryMonitor.MemoryLimit;
}
}
internal long PhysicalMemoryLimit
{
get
{
return _physicalMemoryMonitor.MemoryLimit;
}
}
internal TimeSpan PollingInterval
{
get
{
return TimeSpan.FromMilliseconds(_configPollingInterval);
}
}
internal MemoryCacheStatistics(MemoryCache memoryCache, NameValueCollection config)
{
_memoryCache = memoryCache;
_lastTrimGen2Count = -1;
_lastTrimTime = DateTime.MinValue;
_timerLock = new Object();
InitializeConfiguration(config);
_pollingInterval = _configPollingInterval;
_physicalMemoryMonitor = new PhysicalMemoryMonitor(_configPhysicalMemoryLimitPercentage);
InitDisposableMembers();
}
internal long CacheManagerThread(int minPercent)
{
if (Interlocked.Exchange(ref _inCacheManagerThread, 1) != 0)
return 0;
try
{
if (_disposed == 1)
{
return 0;
}
#if DEBUG
Dbg.Trace("MemoryCacheStats", "**BEG** CacheManagerThread " + DateTime.Now.ToString("T", CultureInfo.InvariantCulture));
#endif
// The timer thread must always call Update so that the CacheManager
// knows the size of the cache.
Update();
AdjustTimer();
int percent = Math.Max(minPercent, GetPercentToTrim());
long beginTotalCount = _memoryCache.GetCount();
Stopwatch sw = Stopwatch.StartNew();
long trimmedOrExpired = _memoryCache.Trim(percent);
sw.Stop();
// 1) don't update stats if the trim happend because MAX_COUNT was exceeded
// 2) don't update stats unless we removed at least one entry
if (percent > 0 && trimmedOrExpired > 0)
{
SetTrimStats(sw.Elapsed.Ticks, beginTotalCount, trimmedOrExpired);
}
#if DEBUG
Dbg.Trace("MemoryCacheStats", "**END** CacheManagerThread: "
+ ", percent=" + percent
+ ", beginTotalCount=" + beginTotalCount
+ ", trimmed=" + trimmedOrExpired
+ ", Milliseconds=" + sw.ElapsedMilliseconds);
#endif
#if PERF
Debug.WriteLine("CacheCommon.CacheManagerThread:"
+ " minPercent= " + minPercent
+ ", percent= " + percent
+ ", beginTotalCount=" + beginTotalCount
+ ", trimmed=" + trimmedOrExpired
+ ", Milliseconds=" + sw.ElapsedMilliseconds + "\n");
#endif
return trimmedOrExpired;
}
finally
{
Interlocked.Exchange(ref _inCacheManagerThread, 0);
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{
lock (_timerLock)
{
GCHandleRef<Timer> timerHandleRef = _timerHandleRef;
if (timerHandleRef != null && Interlocked.CompareExchange(ref _timerHandleRef, null, timerHandleRef) == timerHandleRef)
{
timerHandleRef.Dispose();
Dbg.Trace("MemoryCacheStats", "Stopped CacheMemoryTimers");
}
}
while (_inCacheManagerThread != 0)
{
Thread.Sleep(100);
}
if (_cacheMemoryMonitor != null)
{
_cacheMemoryMonitor.Dispose();
}
// Don't need to call GC.SuppressFinalize(this) for sealed types without finalizers.
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")]
internal void UpdateConfig(NameValueCollection config)
{
int pollingInterval = ConfigUtil.GetIntValueFromTimeSpan(config, ConfigUtil.PollingInterval, _configPollingInterval);
int cacheMemoryLimitMegabytes = ConfigUtil.GetIntValue(config, ConfigUtil.CacheMemoryLimitMegabytes, _configCacheMemoryLimitMegabytes, true, Int32.MaxValue);
int physicalMemoryLimitPercentage = ConfigUtil.GetIntValue(config, ConfigUtil.PhysicalMemoryLimitPercentage, _configPhysicalMemoryLimitPercentage, true, 100);
if (pollingInterval != _configPollingInterval)
{
lock (_timerLock)
{
_configPollingInterval = pollingInterval;
}
}
if (cacheMemoryLimitMegabytes == _configCacheMemoryLimitMegabytes
&& physicalMemoryLimitPercentage == _configPhysicalMemoryLimitPercentage)
{
return;
}
try
{
try
{
}
finally
{
// prevent ThreadAbortEx from interrupting
while (Interlocked.Exchange(ref _inCacheManagerThread, 1) != 0)
{
Thread.Sleep(100);
}
}
if (_disposed == 0)
{
if (cacheMemoryLimitMegabytes != _configCacheMemoryLimitMegabytes)
{
_cacheMemoryMonitor.SetLimit(cacheMemoryLimitMegabytes);
_configCacheMemoryLimitMegabytes = cacheMemoryLimitMegabytes;
}
if (physicalMemoryLimitPercentage != _configPhysicalMemoryLimitPercentage)
{
_physicalMemoryMonitor.SetLimit(physicalMemoryLimitPercentage);
_configPhysicalMemoryLimitPercentage = physicalMemoryLimitPercentage;
}
}
}
finally
{
Interlocked.Exchange(ref _inCacheManagerThread, 0);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Collections.ObjectModel;
namespace OpenQA.Selenium
{
[TestFixture]
public class CorrectEventFiringTest : DriverTestFixture
{
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.Chrome, "Webkit bug 22261")]
public void ShouldFireFocusEventWhenClicking()
{
driver.Url = javascriptPage;
ClickOnElementWhichRecordsEvents();
AssertEventFired("focus");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Android)]
public void ShouldFireClickEventWhenClicking()
{
driver.Url = javascriptPage;
ClickOnElementWhichRecordsEvents();
AssertEventFired("click");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Android)]
public void ShouldFireMouseDownEventWhenClicking()
{
driver.Url = javascriptPage;
ClickOnElementWhichRecordsEvents();
AssertEventFired("mousedown");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Android)]
public void ShouldFireMouseUpEventWhenClicking()
{
driver.Url = javascriptPage;
ClickOnElementWhichRecordsEvents();
AssertEventFired("mouseup");
}
[Test]
[Category("Javascript")]
public void ShouldFireMouseOverEventWhenClicking()
{
driver.Url = javascriptPage;
ClickOnElementWhichRecordsEvents();
AssertEventFired("mouseover");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Chrome, "Chrome does not report mouse move event when clicking")]
[IgnoreBrowser(Browser.Firefox, "Firefox does not report mouse move event when clicking")]
public void ShouldFireMouseMoveEventWhenClicking()
{
driver.Url = javascriptPage;
ClickOnElementWhichRecordsEvents();
AssertEventFired("mousemove");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldNotThrowIfEventHandlerThrows()
{
driver.Url = javascriptPage;
driver.FindElement(By.Id("throwing-mouseover")).Click();
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.Chrome, "Webkit bug 22261")]
public void ShouldFireEventsInTheRightOrder()
{
driver.Url = javascriptPage;
ClickOnElementWhichRecordsEvents();
string text = driver.FindElement(By.Id("result")).Text;
int lastIndex = -1;
List<string> eventList = new List<string>() { "mousedown", "focus", "mouseup", "click" };
foreach (string eventName in eventList)
{
int index = text.IndexOf(eventName);
Assert.IsTrue(index != -1, eventName + " did not fire at all. Text is " + text);
Assert.IsTrue(index > lastIndex, eventName + " did not fire in the correct order. Text is " + text);
lastIndex = index;
}
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Android)]
public void ShouldIssueMouseDownEvents()
{
driver.Url = javascriptPage;
driver.FindElement(By.Id("mousedown")).Click();
String result = driver.FindElement(By.Id("result")).Text;
Assert.AreEqual(result, "mouse down");
}
[Test]
[Category("Javascript")]
public void ShouldIssueClickEvents()
{
driver.Url = javascriptPage;
driver.FindElement(By.Id("mouseclick")).Click();
String result = driver.FindElement(By.Id("result")).Text;
Assert.AreEqual(result, "mouse click");
}
[Test]
[Category("Javascript")]
public void ShouldIssueMouseUpEvents()
{
driver.Url = javascriptPage;
driver.FindElement(By.Id("mouseup")).Click();
String result = driver.FindElement(By.Id("result")).Text;
Assert.AreEqual(result, "mouse up");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IPhone)]
public void MouseEventsShouldBubbleUpToContainingElements()
{
driver.Url = javascriptPage;
driver.FindElement(By.Id("child")).Click();
String result = driver.FindElement(By.Id("result")).Text;
Assert.AreEqual(result, "mouse down");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IPhone)]
public void ShouldEmitOnChangeEventsWhenSelectingElements()
{
driver.Url = javascriptPage;
//Intentionally not looking up the select tag. See selenium r7937 for details.
ReadOnlyCollection<IWebElement> allOptions = driver.FindElements(By.XPath("//select[@id='selector']//option"));
String initialTextValue = driver.FindElement(By.Id("result")).Text;
IWebElement foo = allOptions[0];
IWebElement bar = allOptions[1];
foo.Click();
Assert.AreEqual(driver.FindElement(By.Id("result")).Text, initialTextValue);
bar.Click();
Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "bar");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IE, "IE does not fire change event when clicking on checkbox")]
public void ShouldEmitOnChangeEventsWhenChangingTheStateOfACheckbox()
{
driver.Url = javascriptPage;
IWebElement checkbox = driver.FindElement(By.Id("checkbox"));
checkbox.Click();
Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "checkbox thing");
}
[Test]
[Category("Javascript")]
public void ShouldEmitClickEventWhenClickingOnATextInputElement()
{
driver.Url = javascriptPage;
IWebElement clicker = driver.FindElement(By.Id("clickField"));
clicker.Click();
Assert.AreEqual(clicker.GetAttribute("value"), "Clicked");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Android)]
public void ShouldFireTwoClickEventsWhenClickingOnALabel()
{
driver.Url = javascriptPage;
driver.FindElement(By.Id("labelForCheckbox")).Click();
IWebElement result = driver.FindElement(By.Id("result"));
Assert.IsTrue(WaitFor(() => { return result.Text.Contains("labelclick chboxclick"); }), "Did not find text: " + result.Text);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.Android)]
public void ClearingAnElementShouldCauseTheOnChangeHandlerToFire()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("clearMe"));
element.Clear();
IWebElement result = driver.FindElement(By.Id("result"));
Assert.AreEqual(result.Text, "Cleared");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IPhone, "SendKeys implementation is incorrect.")]
[IgnoreBrowser(Browser.Android)]
public void SendingKeysToAnotherElementShouldCauseTheBlurEventToFire()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("theworks"));
element.SendKeys("foo");
IWebElement element2 = driver.FindElement(By.Id("changeable"));
element2.SendKeys("bar");
AssertEventFired("blur");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IPhone, "SendKeys implementation is incorrect.")]
[IgnoreBrowser(Browser.Android)]
public void SendingKeysToAnElementShouldCauseTheFocusEventToFire()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("theworks"));
element.SendKeys("foo");
AssertEventFired("focus");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IPhone, "Input elements are blurred when the keyboard is closed.")]
public void SendingKeysToAFocusedElementShouldNotBlurThatElement()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("theworks"));
element.Click();
//Wait until focused
bool focused = false;
IWebElement result = driver.FindElement(By.Id("result"));
for (int i = 0; i < 5; ++i)
{
string fired = result.Text;
if (fired.Contains("focus"))
{
focused = true;
break;
}
try
{
System.Threading.Thread.Sleep(200);
}
catch (Exception e)
{
throw e;
}
}
if (!focused)
{
Assert.Fail("Clicking on element didn't focus it in time - can't proceed so failing");
}
element.SendKeys("a");
AssertEventNotFired("blur");
}
[Test]
[Category("Javascript")]
public void SubmittingFormFromFormElementShouldFireOnSubmitForThatForm()
{
driver.Url = javascriptPage;
IWebElement formElement = driver.FindElement(By.Id("submitListeningForm"));
formElement.Submit();
AssertEventFired("form-onsubmit");
}
[Test]
[Category("Javascript")]
public void SubmittingFormFromFormInputSubmitElementShouldFireOnSubmitForThatForm()
{
driver.Url = javascriptPage;
IWebElement submit = driver.FindElement(By.Id("submitListeningForm-submit"));
submit.Submit();
AssertEventFired("form-onsubmit");
}
[Test]
[Category("Javascript")]
public void SubmittingFormFromFormInputTextElementShouldFireOnSubmitForThatFormAndNotClickOnThatInput()
{
driver.Url = javascriptPage;
IWebElement submit = driver.FindElement(By.Id("submitListeningForm-submit"));
submit.Submit();
AssertEventFired("form-onsubmit");
AssertEventNotFired("text-onclick");
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")]
[IgnoreBrowser(Browser.Android, "Does not yet support file uploads")]
[IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")]
public void UploadingFileShouldFireOnChangeEvent()
{
driver.Url = formsPage;
IWebElement uploadElement = driver.FindElement(By.Id("upload"));
IWebElement result = driver.FindElement(By.Id("fileResults"));
Assert.AreEqual(string.Empty, result.Text);
System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt");
System.IO.StreamWriter inputFileWriter = inputFile.CreateText();
inputFileWriter.WriteLine("Hello world");
inputFileWriter.Close();
uploadElement.SendKeys(inputFile.FullName);
// Shift focus to something else because send key doesn't make the focus leave
driver.FindElement(By.Id("id-name1")).Click();
inputFile.Delete();
Assert.AreEqual("changed", result.Text);
}
[Test]
[Category("Javascript")]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldReportTheXAndYCoordinatesWhenClicking()
{
driver.Url = clickEventPage;
IWebElement element = driver.FindElement(By.Id("eventish"));
element.Click();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2));
string clientX = driver.FindElement(By.Id("clientX")).Text;
string clientY = driver.FindElement(By.Id("clientY")).Text;
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0));
Assert.AreNotEqual("0", clientX);
Assert.AreNotEqual("0", clientY);
}
private void AssertEventNotFired(string eventName)
{
IWebElement result = driver.FindElement(By.Id("result"));
string text = result.Text;
Assert.IsFalse(text.Contains(eventName), eventName + " fired: " + text);
}
private void ClickOnElementWhichRecordsEvents()
{
driver.FindElement(By.Id("plainButton")).Click();
}
private void AssertEventFired(String eventName)
{
IWebElement result = driver.FindElement(By.Id("result"));
string text = result.Text;
Assert.IsTrue(text.Contains(eventName), "No " + eventName + " fired: " + text);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole
//
// 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 NUnit.Framework.Internal;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// ThrowsConstraint is used to test the exception thrown by
/// a delegate by applying a constraint to it.
/// </summary>
public class ThrowsConstraint : PrefixConstraint
{
private Exception caughtException;
/// <summary>
/// Initializes a new instance of the <see cref="ThrowsConstraint"/> class,
/// using a constraint to be applied to the exception.
/// </summary>
/// <param name="baseConstraint">A constraint to apply to the caught exception.</param>
public ThrowsConstraint(Constraint baseConstraint)
: base(baseConstraint) { }
/// <summary>
/// Get the actual exception thrown - used by Assert.Throws.
/// </summary>
public Exception ActualException
{
get { return caughtException; }
}
#region Constraint Overrides
/// <summary>
/// Executes the code of the delegate and captures any exception.
/// If a non-null base constraint was provided, it applies that
/// constraint to the exception.
/// </summary>
/// <param name="actual">A delegate representing the code to be tested</param>
/// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns>
public override bool Matches(object actual)
{
caughtException = ExceptionInterceptor.Intercept(actual);
if (caughtException == null)
return false;
return baseConstraint == null || baseConstraint.Matches(caughtException);
}
/// <summary>
/// Converts an ActualValueDelegate to a TestDelegate
/// before calling the primary overload.
/// </summary>
#if CLR_2_0 || CLR_4_0
public override bool Matches<T>(ActualValueDelegate<T> del)
{
return Matches(new GenericInvocationDescriptor<T>(del));
}
#else
public override bool Matches(ActualValueDelegate del)
{
return Matches(new ObjectInvocationDescriptor(del));
}
#endif
/// <summary>
/// Write the constraint description to a MessageWriter
/// </summary>
/// <param name="writer">The writer on which the description is displayed</param>
public override void WriteDescriptionTo(MessageWriter writer)
{
if (baseConstraint == null)
writer.WritePredicate("an exception");
else
baseConstraint.WriteDescriptionTo(writer);
}
/// <summary>
/// Write the actual value for a failing constraint test to a
/// MessageWriter. The default implementation simply writes
/// the raw value of actual, leaving it to the writer to
/// perform any formatting.
/// </summary>
/// <param name="writer">The writer on which the actual value is displayed</param>
public override void WriteActualValueTo(MessageWriter writer)
{
if (caughtException == null)
writer.Write("no exception thrown");
else if (baseConstraint != null)
baseConstraint.WriteActualValueTo(writer);
else
writer.WriteActualValue(caughtException);
}
#endregion
/// <summary>
/// Returns the string representation of this constraint
/// </summary>
protected override string GetStringRepresentation()
{
if (baseConstraint == null)
return "<throws>";
return base.GetStringRepresentation();
}
}
#region ExceptionInterceptor
internal class ExceptionInterceptor
{
private ExceptionInterceptor() { }
internal static Exception Intercept(object invocation)
{
IInvocationDescriptor invocationDescriptor = GetInvocationDescriptor(invocation);
#if NET_4_5
if (AsyncInvocationRegion.IsAsyncOperation(invocationDescriptor.Delegate))
{
using (AsyncInvocationRegion region = AsyncInvocationRegion.Create(invocationDescriptor.Delegate))
{
object result = invocationDescriptor.Invoke();
try
{
region.WaitForPendingOperationsToComplete(result);
return null;
}
catch (Exception ex)
{
return ex;
}
}
}
else
#endif
{
try
{
invocationDescriptor.Invoke();
return null;
}
catch (Exception ex)
{
return ex;
}
}
}
private static IInvocationDescriptor GetInvocationDescriptor(object actual)
{
IInvocationDescriptor invocationDescriptor = actual as IInvocationDescriptor;
if (invocationDescriptor == null)
{
TestDelegate testDelegate = actual as TestDelegate;
if (testDelegate == null)
throw new ArgumentException(
String.Format("The actual value must be a TestDelegate or ActualValueDelegate but was {0}", actual.GetType().Name),
"actual");
invocationDescriptor = new VoidInvocationDescriptor(testDelegate);
}
return invocationDescriptor;
}
}
#endregion
#region InvocationDescriptor
internal class VoidInvocationDescriptor : IInvocationDescriptor
{
private readonly TestDelegate _del;
public VoidInvocationDescriptor(TestDelegate del)
{
_del = del;
}
public object Invoke()
{
_del();
return null;
}
public Delegate Delegate
{
get { return _del; }
}
}
#if CLR_2_0 || CLR_4_0
internal class GenericInvocationDescriptor<T> : IInvocationDescriptor
{
private readonly ActualValueDelegate<T> _del;
public GenericInvocationDescriptor(ActualValueDelegate<T> del)
{
_del = del;
}
public object Invoke()
{
return _del();
}
public Delegate Delegate
{
get { return _del; }
}
}
#else
internal class ObjectInvocationDescriptor : IInvocationDescriptor
{
private readonly ActualValueDelegate _del;
public ObjectInvocationDescriptor(ActualValueDelegate del)
{
_del = del;
}
public object Invoke()
{
return _del();
}
public Delegate Delegate
{
get { return _del; }
}
}
#endif
internal interface IInvocationDescriptor
{
object Invoke();
Delegate Delegate { get; }
}
#endregion
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// .Net client wrapper for the REST API for Azure ApiManagement Service
/// </summary>
public static partial class GroupsOperationsExtensions
{
/// <summary>
/// Creates new group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Create(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, GroupCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).CreateAsync(resourceGroupName, serviceName, gid, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates new group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, GroupCreateParameters parameters)
{
return operations.CreateAsync(resourceGroupName, serviceName, gid, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes specific group of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).DeleteAsync(resourceGroupName, serviceName, gid, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes specific group of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, string etag)
{
return operations.DeleteAsync(resourceGroupName, serviceName, gid, etag, CancellationToken.None);
}
/// <summary>
/// Gets specific group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <returns>
/// Get Group operation response details.
/// </returns>
public static GroupGetResponse Get(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).GetAsync(resourceGroupName, serviceName, gid);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets specific group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <returns>
/// Get Group operation response details.
/// </returns>
public static Task<GroupGetResponse> GetAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid)
{
return operations.GetAsync(resourceGroupName, serviceName, gid, CancellationToken.None);
}
/// <summary>
/// List all groups.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public static GroupListResponse List(this IGroupsOperations operations, string resourceGroupName, string serviceName, QueryParameters query)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).ListAsync(resourceGroupName, serviceName, query);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List all groups.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public static Task<GroupListResponse> ListAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, QueryParameters query)
{
return operations.ListAsync(resourceGroupName, serviceName, query, CancellationToken.None);
}
/// <summary>
/// List next groups page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public static GroupListResponse ListNext(this IGroupsOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List next groups page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public static Task<GroupListResponse> ListNextAsync(this IGroupsOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Patches specific group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Update(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, GroupUpdateParameters parameters, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).UpdateAsync(resourceGroupName, serviceName, gid, parameters, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patches specific group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> UpdateAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, GroupUpdateParameters parameters, string etag)
{
return operations.UpdateAsync(resourceGroupName, serviceName, gid, parameters, etag, CancellationToken.None);
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
\*---------------------------------------------------------------------------------*/
#endregion License
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
namespace JsonFx.Json
{
/// <summary>
/// Writer for producing JSON data
/// </summary>
public class JsonWriter : IDisposable
{
#region Constants
public const string JsonMimeType = "application/json";
public const string JsonFileExtension = ".json";
private const string AnonymousTypePrefix = "<>f__AnonymousType";
private const string ErrorMaxDepth = "The maxiumum depth of {0} was exceeded. Check for cycles in object graph.";
private const string ErrorIDictionaryEnumerator = "Types which implement Generic IDictionary<TKey, TValue> must have an IEnumerator which implements IDictionaryEnumerator. ({0})";
#endregion Constants
#region Fields
private readonly TextWriter Writer;
private JsonWriterSettings settings;
private int depth;
#endregion Fields
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">TextWriter for writing</param>
public JsonWriter(TextWriter output)
: this(output, new JsonWriterSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">TextWriter for writing</param>
/// <param name="settings">JsonWriterSettings</param>
public JsonWriter(TextWriter output, JsonWriterSettings settings)
{
if (output == null)
{
throw new ArgumentNullException("output");
}
if (settings == null)
{
throw new ArgumentNullException("settings");
}
this.Writer = output;
this.settings = settings;
this.Writer.NewLine = this.settings.NewLine;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">Stream for writing</param>
public JsonWriter(Stream output)
: this(output, new JsonWriterSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">Stream for writing</param>
/// <param name="settings">JsonWriterSettings</param>
public JsonWriter(Stream output, JsonWriterSettings settings)
{
if (output == null)
{
throw new ArgumentNullException("output");
}
if (settings == null)
{
throw new ArgumentNullException("settings");
}
this.Writer = new StreamWriter(output, Encoding.UTF8);
this.settings = settings;
this.Writer.NewLine = this.settings.NewLine;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">file name for writing</param>
public JsonWriter(string outputFileName)
: this(outputFileName, new JsonWriterSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">file name for writing</param>
/// <param name="settings">JsonWriterSettings</param>
public JsonWriter(string outputFileName, JsonWriterSettings settings)
{
if (outputFileName == null)
{
throw new ArgumentNullException("outputFileName");
}
if (settings == null)
{
throw new ArgumentNullException("settings");
}
Stream stream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read);
this.Writer = new StreamWriter(stream, Encoding.UTF8);
this.settings = settings;
this.Writer.NewLine = this.settings.NewLine;
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">StringBuilder for appending</param>
public JsonWriter(StringBuilder output)
: this(output, new JsonWriterSettings())
{
}
/// <summary>
/// Ctor
/// </summary>
/// <param name="output">StringBuilder for appending</param>
/// <param name="settings">JsonWriterSettings</param>
public JsonWriter(StringBuilder output, JsonWriterSettings settings)
{
if (output == null)
{
throw new ArgumentNullException("output");
}
if (settings == null)
{
throw new ArgumentNullException("settings");
}
this.Writer = new StringWriter(output, System.Globalization.CultureInfo.InvariantCulture);
this.settings = settings;
this.Writer.NewLine = this.settings.NewLine;
}
#endregion Init
#region Properties
/// <summary>
/// Gets and sets the property name used for type hinting
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public string TypeHintName
{
get { return this.settings.TypeHintName; }
set { this.settings.TypeHintName = value; }
}
/// <summary>
/// Gets and sets if JSON will be formatted for human reading
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public bool PrettyPrint
{
get { return this.settings.PrettyPrint; }
set { this.settings.PrettyPrint = value; }
}
/// <summary>
/// Gets and sets the string to use for indentation
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public string Tab
{
get { return this.settings.Tab; }
set { this.settings.Tab = value; }
}
/// <summary>
/// Gets and sets the line terminator string
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public string NewLine
{
get { return this.settings.NewLine; }
set { this.Writer.NewLine = this.settings.NewLine = value; }
}
/// <summary>
/// Gets the current nesting depth
/// </summary>
protected int Depth
{
get { return this.depth; }
}
/// <summary>
/// Gets and sets the maximum depth to be serialized
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public int MaxDepth
{
get { return this.settings.MaxDepth; }
set { this.settings.MaxDepth = value; }
}
/// <summary>
/// Gets and sets if should use XmlSerialization Attributes
/// </summary>
/// <remarks>
/// Respects XmlIgnoreAttribute, ...
/// </remarks>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public bool UseXmlSerializationAttributes
{
get { return this.settings.UseXmlSerializationAttributes; }
set { this.settings.UseXmlSerializationAttributes = value; }
}
/// <summary>
/// Gets and sets a proxy formatter to use for DateTime serialization
/// </summary>
[Obsolete("This has been deprecated in favor of JsonWriterSettings object")]
public WriteDelegate<DateTime> DateTimeSerializer
{
get { return this.settings.DateTimeSerializer; }
set { this.settings.DateTimeSerializer = value; }
}
/// <summary>
/// Gets the underlying TextWriter
/// </summary>
public TextWriter TextWriter
{
get { return this.Writer; }
}
/// <summary>
/// Gets and sets the JsonWriterSettings
/// </summary>
public JsonWriterSettings Settings
{
get { return this.settings; }
set
{
if (value == null)
{
value = new JsonWriterSettings();
}
this.settings = value;
}
}
#endregion Properties
#region Static Methods
/// <summary>
/// A helper method for serializing an object to JSON
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string Serialize(object value)
{
StringBuilder output = new StringBuilder();
using (JsonWriter writer = new JsonWriter(output))
{
writer.Write(value);
}
return output.ToString();
}
#endregion Static Methods
#region Public Methods
public void Write(object value)
{
this.Write(value, false);
}
protected virtual void Write(object value, bool isProperty)
{
if (isProperty && this.settings.PrettyPrint)
{
this.Writer.Write(' ');
}
if (value == null)
{
this.Writer.Write(JsonReader.LiteralNull);
return;
}
if (value is IJsonSerializable)
{
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
((IJsonSerializable)value).WriteJson(this);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
return;
}
// must test enumerations before value types
if (value is Enum)
{
this.Write((Enum)value);
return;
}
// Type.GetTypeCode() allows us to more efficiently switch type
// plus cannot use 'is' for ValueTypes
Type type = value.GetType();
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
{
this.Write((Boolean)value);
return;
}
case TypeCode.Byte:
{
this.Write((Byte)value);
return;
}
case TypeCode.Char:
{
this.Write((Char)value);
return;
}
case TypeCode.DateTime:
{
this.Write((DateTime)value);
return;
}
case TypeCode.DBNull:
case TypeCode.Empty:
{
this.Writer.Write(JsonReader.LiteralNull);
return;
}
case TypeCode.Decimal:
{
// From MSDN:
// Conversions from Char, SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, and UInt64
// to Decimal are widening conversions that never lose information or throw exceptions.
// Conversions from Single or Double to Decimal throw an OverflowException
// if the result of the conversion is not representable as a Decimal.
this.Write((Decimal)value);
return;
}
case TypeCode.Double:
{
this.Write((Double)value);
return;
}
case TypeCode.Int16:
{
this.Write((Int16)value);
return;
}
case TypeCode.Int32:
{
this.Write((Int32)value);
return;
}
case TypeCode.Int64:
{
this.Write((Int64)value);
return;
}
case TypeCode.SByte:
{
this.Write((SByte)value);
return;
}
case TypeCode.Single:
{
this.Write((Single)value);
return;
}
case TypeCode.String:
{
this.Write((String)value);
return;
}
case TypeCode.UInt16:
{
this.Write((UInt16)value);
return;
}
case TypeCode.UInt32:
{
this.Write((UInt32)value);
return;
}
case TypeCode.UInt64:
{
this.Write((UInt64)value);
return;
}
default:
case TypeCode.Object:
{
// all others must be explicitly tested
break;
}
}
if (value is Guid)
{
this.Write((Guid)value);
return;
}
if (value is Uri)
{
this.Write((Uri)value);
return;
}
if (value is TimeSpan)
{
this.Write((TimeSpan)value);
return;
}
if (value is Version)
{
this.Write((Version)value);
return;
}
if (value is byte[]) {
this.Write((byte[])value);
return;
}
// IDictionary test must happen BEFORE IEnumerable test
// since IDictionary implements IEnumerable
if (value is IDictionary)
{
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
this.WriteObject((IDictionary)value);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
return;
}
if (type.GetInterface(JsonReader.TypeGenericIDictionary) != null)
{
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
this.WriteDictionary((IEnumerable)value);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
return;
}
// IDictionary test must happen BEFORE IEnumerable test
// since IDictionary implements IEnumerable
if (value is IEnumerable)
{
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
this.WriteArray((IEnumerable)value);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
return;
}
// structs and classes
try
{
if (isProperty)
{
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
this.WriteLine();
}
this.WriteObject(value, type);
}
finally
{
if (isProperty)
{
this.depth--;
}
}
}
public virtual void Write(byte[] value) {
if (this.settings.ByteArraySerializer != null)
{
this.settings.ByteArraySerializer(this, value);
return;
}
this.WriteArray((IEnumerable)value);
}
public virtual void WriteBase64(byte[] value)
{
this.Write(Convert.ToBase64String(value));
}
public virtual void WriteHexString(byte[] value)
{
if (value == null || value.Length == 0)
{
this.Write(String.Empty);
return;
}
StringBuilder builder = new StringBuilder();
// Loop through each byte of the binary data
// and format each one as a hexadecimal string
for (int i=0; i<value.Length; i++)
{
builder.Append(value[i].ToString("x2"));
}
// the hexadecimal string
this.Write(builder.ToString());
}
public virtual void Write(DateTime value)
{
if (this.settings.DateTimeSerializer != null)
{
this.settings.DateTimeSerializer(this, value);
return;
}
switch (value.Kind)
{
case DateTimeKind.Local:
{
value = value.ToUniversalTime();
goto case DateTimeKind.Utc;
}
case DateTimeKind.Utc:
{
// UTC DateTime in ISO-8601
this.Write(String.Format("{0:s}Z", value));
break;
}
default:
{
// DateTime in ISO-8601
this.Write(String.Format("{0:s}", value));
break;
}
}
}
public virtual void Write(Guid value)
{
this.Write(value.ToString("D"));
}
public virtual void Write(Enum value)
{
if (settings.EncodeEnumsAsNumber) {
this.Write(Convert.ToInt32(value));
return;
}
string enumName = null;
Type type = value.GetType();
if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value))
{
Enum[] flags = JsonWriter.GetFlagList(type, value);
string[] flagNames = new string[flags.Length];
for (int i=0; i<flags.Length; i++)
{
flagNames[i] = JsonNameAttribute.GetJsonName(flags[i]);
if (String.IsNullOrEmpty(flagNames[i]))
{
flagNames[i] = flags[i].ToString("f");
}
}
enumName = String.Join(", ", flagNames);
}
else
{
enumName = JsonNameAttribute.GetJsonName(value);
if (String.IsNullOrEmpty(enumName))
{
enumName = value.ToString("f");
}
}
this.Write(enumName);
}
public virtual void Write(string value)
{
if (value == null)
{
this.Writer.Write(JsonReader.LiteralNull);
return;
}
int start = 0,
length = value.Length;
this.Writer.Write(JsonReader.OperatorStringDelim);
for (int i=start; i<length; i++)
{
char ch = value[i];
if (ch <= '\u001F' ||
ch >= '\u007F' ||
ch == '<' || // improves compatibility within script blocks
ch == JsonReader.OperatorStringDelim ||
ch == JsonReader.OperatorCharEscape)
{
if (i > start)
{
this.Writer.Write(value.Substring(start, i-start));
}
start = i+1;
switch (ch)
{
case JsonReader.OperatorStringDelim:
case JsonReader.OperatorCharEscape:
{
this.Writer.Write(JsonReader.OperatorCharEscape);
this.Writer.Write(ch);
continue;
}
case '\b':
{
this.Writer.Write("\\b");
continue;
}
case '\f':
{
this.Writer.Write("\\f");
continue;
}
case '\n':
{
this.Writer.Write("\\n");
continue;
}
case '\r':
{
this.Writer.Write("\\r");
continue;
}
case '\t':
{
this.Writer.Write("\\t");
continue;
}
default:
{
this.Writer.Write("\\u");
this.Writer.Write(Char.ConvertToUtf32(value, i).ToString("X4"));
continue;
}
}
}
}
if (length > start)
{
this.Writer.Write(value.Substring(start, length-start));
}
this.Writer.Write(JsonReader.OperatorStringDelim);
}
#endregion Public Methods
#region Primative Writer Methods
public virtual void Write(bool value)
{
this.Writer.Write(value ? JsonReader.LiteralTrue : JsonReader.LiteralFalse);
}
public virtual void Write(byte value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(sbyte value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(short value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(ushort value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(int value)
{
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(uint value)
{
if (this.InvalidIeee754(value))
{
// emit as string since Number cannot represent
this.Write(value.ToString("g", CultureInfo.InvariantCulture));
return;
}
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(long value)
{
if (this.InvalidIeee754(value))
{
// emit as string since Number cannot represent
this.Write(value.ToString("g", CultureInfo.InvariantCulture));
return;
}
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(ulong value)
{
if (this.InvalidIeee754(value))
{
// emit as string since Number cannot represent
this.Write(value.ToString("g", CultureInfo.InvariantCulture));
return;
}
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(float value)
{
if (Single.IsNaN(value) || Single.IsInfinity(value))
{
this.Writer.Write(JsonReader.LiteralNull);
}
else
{
this.Writer.Write(value.ToString("r", CultureInfo.InvariantCulture));
}
}
public virtual void Write(double value)
{
if (Double.IsNaN(value) || Double.IsInfinity(value))
{
this.Writer.Write(JsonReader.LiteralNull);
}
else
{
this.Writer.Write(value.ToString("r", CultureInfo.InvariantCulture));
}
}
public virtual void Write(decimal value)
{
if (this.InvalidIeee754(value))
{
// emit as string since Number cannot represent
this.Write(value.ToString("g", CultureInfo.InvariantCulture));
return;
}
this.Writer.Write(value.ToString("g", CultureInfo.InvariantCulture));
}
public virtual void Write(char value)
{
this.Write(new String(value, 1));
}
public virtual void Write(TimeSpan value)
{
this.Write(value.Ticks);
}
public virtual void Write(Uri value)
{
this.Write(value.ToString());
}
public virtual void Write(Version value)
{
this.Write(value.ToString());
}
#endregion Primative Writer Methods
#region Writer Methods
protected internal virtual void WriteArray(IEnumerable value)
{
bool appendDelim = false;
this.Writer.Write(JsonReader.OperatorArrayStart);
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
try
{
var enumerator = TypeCoercionUtility.GetEnumerator(value);
if (enumerator == null) {
throw new JsonTypeCoercionException(string.Format("Requested to get an IEnumerator of a value that doesn't implement the IEnumerable interface.\nValue: {0}\nValue's type: {1}",value,value.GetType().FullName));
}
while (enumerator.MoveNext())
{
object item = enumerator.Current;
if (appendDelim)
{
this.WriteArrayItemDelim();
}
else
{
appendDelim = true;
}
this.WriteLine();
this.WriteArrayItem(item);
}
IDisposable disposable = enumerator as IDisposable;
if (disposable != null) {
disposable.Dispose ();
}
}
finally
{
this.depth--;
}
if (appendDelim)
{
this.WriteLine();
}
this.Writer.Write(JsonReader.OperatorArrayEnd);
}
protected virtual void WriteArrayItem(object item)
{
this.Write(item, false);
}
protected virtual void WriteObject(IDictionary value)
{
this.WriteDictionary((IEnumerable)value);
}
private static Dictionary<Type,MethodInfo> getEnumeratorMethods = new Dictionary<Type, MethodInfo>();
private static object[] emptyArgs = new object[] {};
protected virtual void WriteDictionary(IEnumerable value)
{
object candidateEnumerator = value.GetEnumerator();
if (candidateEnumerator == null)
{
UnityEngine.Debug.LogError("IEnumerable has no GetEnumerator() result at all");
throw new JsonSerializationException(String.Format(JsonWriter.ErrorIDictionaryEnumerator, value.GetType()));
}
IDictionaryEnumerator enumerator = null;
if (candidateEnumerator is System.String)
{
MethodInfo getEnumeratorMethodInfo = null;
if (getEnumeratorMethods.TryGetValue(value.GetType(), out getEnumeratorMethodInfo))
{
enumerator = getEnumeratorMethodInfo.Invoke(value, emptyArgs) as IDictionaryEnumerator;
}
else
{
UnityEngine.Debug.LogWarning("Doing AOT GetEnumerator workaround");
foreach(MethodInfo methodInfo in value.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
{
if (methodInfo.Name.Contains("GetEnumerator"))
{
UnityEngine.Debug.Log ("Invoking a method " + methodInfo.ReturnType + " " + methodInfo.Name);
try
{
enumerator = methodInfo.Invoke(value, new object[] {}) as IDictionaryEnumerator;
}
catch(Exception ex)
{
UnityEngine.Debug.LogWarning("Error invoking. " + ex);
}
if (enumerator != null)
{
UnityEngine.Debug.Log ("Success on AOT GetEnumerator workaround - got an enumerator with reflection");
getEnumeratorMethods[value.GetType()] = methodInfo;
break;
}
}
}
}
}
else
enumerator = candidateEnumerator as IDictionaryEnumerator;
if (enumerator == null)
throw new JsonSerializationException(String.Format(JsonWriter.ErrorIDictionaryEnumerator, value.GetType()));
bool appendDelim = false;
this.Writer.Write(JsonReader.OperatorObjectStart);
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
try
{
while (enumerator.MoveNext())
{
if (appendDelim)
{
this.WriteObjectPropertyDelim();
}
else
{
appendDelim = true;
}
this.WriteObjectProperty(Convert.ToString(enumerator.Entry.Key), enumerator.Entry.Value);
}
}
finally
{
this.depth--;
}
if (appendDelim)
{
this.WriteLine();
}
this.Writer.Write(JsonReader.OperatorObjectEnd);
}
private void WriteObjectProperty(string key, object value)
{
this.WriteLine();
this.WriteObjectPropertyName(key);
this.Writer.Write(JsonReader.OperatorNameDelim);
this.WriteObjectPropertyValue(value);
}
protected virtual void WriteObjectPropertyName(string name)
{
this.Write(name);
}
protected virtual void WriteObjectPropertyValue(object value)
{
this.Write(value, true);
}
protected virtual void WriteObject(object value, Type type)
{
bool appendDelim = false;
this.Writer.Write(JsonReader.OperatorObjectStart);
this.depth++;
if (this.depth > this.settings.MaxDepth)
{
throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
}
try
{
if (!String.IsNullOrEmpty(this.settings.TypeHintName))
{
if (appendDelim)
{
this.WriteObjectPropertyDelim();
}
else
{
appendDelim = true;
}
this.WriteObjectProperty(this.settings.TypeHintName, type.FullName+", "+type.Assembly.GetName().Name);
}
bool anonymousType = type.IsGenericType && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix);
if (this.settings.SerializeProperties) {
// serialize public properties
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
if (!property.CanRead)
{
continue;
}
if (!property.CanWrite && !anonymousType)
{
continue;
}
if (this.IsIgnored(type, property, value))
{
continue;
}
object propertyValue = property.GetValue(value, null);
if (this.IsDefaultValue(property, propertyValue))
{
continue;
}
if (appendDelim)
{
this.WriteObjectPropertyDelim();
}
else
{
appendDelim = true;
}
// use Attributes here to control naming
string propertyName = JsonNameAttribute.GetJsonName(property);
if (String.IsNullOrEmpty(propertyName))
{
propertyName = property.Name;
}
this.WriteObjectProperty(propertyName, propertyValue);
}
}
// serialize public fields
FieldInfo[] fields = type.GetFields();
foreach (FieldInfo field in fields)
{
if (!field.IsPublic || field.IsStatic)
{
continue;
}
if (this.IsIgnored(type, field, value))
{
continue;
}
object fieldValue = field.GetValue(value);
if (this.IsDefaultValue(field, fieldValue))
{
continue;
}
if (appendDelim)
{
this.WriteObjectPropertyDelim();
this.WriteLine();
}
else
{
appendDelim = true;
}
// use Attributes here to control naming
string fieldName = JsonNameAttribute.GetJsonName(field);
if (String.IsNullOrEmpty(fieldName))
{
fieldName = field.Name;
}
this.WriteObjectProperty(fieldName, fieldValue);
}
}
finally
{
this.depth--;
}
if (appendDelim)
{
this.WriteLine();
}
this.Writer.Write(JsonReader.OperatorObjectEnd);
}
protected virtual void WriteArrayItemDelim()
{
this.Writer.Write(JsonReader.OperatorValueDelim);
}
protected virtual void WriteObjectPropertyDelim()
{
this.Writer.Write(JsonReader.OperatorValueDelim);
}
protected virtual void WriteLine()
{
if (!this.settings.PrettyPrint)
{
return;
}
this.Writer.WriteLine();
for (int i=0; i<this.depth; i++)
{
this.Writer.Write(this.settings.Tab);
}
}
#endregion Writer Methods
#region Private Methods
/// <summary>
/// Determines if the property or field should not be serialized.
/// </summary>
/// <param name="objType"></param>
/// <param name="member"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <remarks>
/// Checks these in order, if any returns true then this is true:
/// - is flagged with the JsonIgnoreAttribute property
/// - has a JsonSpecifiedProperty which returns false
/// </remarks>
private bool IsIgnored(Type objType, MemberInfo member, object obj)
{
if (JsonIgnoreAttribute.IsJsonIgnore(member))
{
return true;
}
string specifiedProperty = JsonSpecifiedPropertyAttribute.GetJsonSpecifiedProperty(member);
if (!String.IsNullOrEmpty(specifiedProperty))
{
PropertyInfo specProp = objType.GetProperty(specifiedProperty);
if (specProp != null)
{
object isSpecified = specProp.GetValue(obj, null);
if (isSpecified is Boolean && !Convert.ToBoolean(isSpecified))
{
return true;
}
}
}
if (this.settings.UseXmlSerializationAttributes)
{
if (JsonIgnoreAttribute.IsXmlIgnore(member))
{
return true;
}
PropertyInfo specProp = objType.GetProperty(member.Name+"Specified");
if (specProp != null)
{
object isSpecified = specProp.GetValue(obj, null);
if (isSpecified is Boolean && !Convert.ToBoolean(isSpecified))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Determines if the member value matches the DefaultValue attribute
/// </summary>
/// <returns>if has a value equivalent to the DefaultValueAttribute</returns>
private bool IsDefaultValue(MemberInfo member, object value)
{
DefaultValueAttribute attribute = Attribute.GetCustomAttribute(member, typeof(DefaultValueAttribute)) as DefaultValueAttribute;
if (attribute == null)
{
return false;
}
if (attribute.Value == null)
{
return (value == null);
}
return (attribute.Value.Equals(value));
}
#endregion Private Methods
#region Utility Methods
/// <summary>
/// Splits a bitwise-OR'd set of enums into a list.
/// </summary>
/// <param name="enumType">the enum type</param>
/// <param name="value">the combined value</param>
/// <returns>list of flag enums</returns>
/// <remarks>
/// from PseudoCode.EnumHelper
/// </remarks>
private static Enum[] GetFlagList(Type enumType, object value)
{
ulong longVal = Convert.ToUInt64(value);
Array enumValues = Enum.GetValues(enumType);
List<Enum> enums = new List<Enum>(enumValues.Length);
// check for empty
if (longVal == 0L)
{
// Return the value of empty, or zero if none exists
enums.Add((Enum)Convert.ChangeType(value, enumType));
return enums.ToArray();
}
for (int i = enumValues.Length-1; i >= 0; i--)
{
ulong enumValue = Convert.ToUInt64(enumValues.GetValue(i));
if ((i == 0) && (enumValue == 0L))
{
continue;
}
// matches a value in enumeration
if ((longVal & enumValue) == enumValue)
{
// remove from val
longVal -= enumValue;
// add enum to list
enums.Add(enumValues.GetValue(i) as Enum);
}
}
if (longVal != 0x0L)
{
enums.Add(Enum.ToObject(enumType, longVal) as Enum);
}
return enums.ToArray();
}
/// <summary>
/// Determines if a numberic value cannot be represented as IEEE-754.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
protected virtual bool InvalidIeee754(decimal value)
{
// http://stackoverflow.com/questions/1601646
try
{
return (decimal)((double)value) != value;
}
catch
{
return true;
}
}
#endregion Utility Methods
#region IDisposable Members
void IDisposable.Dispose()
{
if (this.Writer != null)
{
this.Writer.Dispose();
}
}
#endregion IDisposable Members
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
/// <summary>
/// Represents a Task item. Properties available on tasks are defined in the TaskSchema class.
/// </summary>
[Attachable]
[ServiceObjectDefinition(XmlElementNames.Task)]
public class Task : Item
{
/// <summary>
/// Initializes an unsaved local instance of <see cref="Task"/>. To bind to an existing task, use Task.Bind() instead.
/// </summary>
/// <param name="service">The ExchangeService instance to which this task is bound.</param>
public Task(ExchangeService service)
: base(service)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Task"/> class.
/// </summary>
/// <param name="parentAttachment">The parent attachment.</param>
internal Task(ItemAttachment parentAttachment)
: base(parentAttachment)
{
}
/// <summary>
/// Binds to an existing task and loads the specified set of properties.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="service">The service to use to bind to the task.</param>
/// <param name="id">The Id of the task to bind to.</param>
/// <param name="propertySet">The set of properties to load.</param>
/// <returns>A Task instance representing the task corresponding to the specified Id.</returns>
public static new Task Bind(
ExchangeService service,
ItemId id,
PropertySet propertySet)
{
return service.BindToItem<Task>(id, propertySet);
}
/// <summary>
/// Binds to an existing task and loads its first class properties.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="service">The service to use to bind to the task.</param>
/// <param name="id">The Id of the task to bind to.</param>
/// <returns>A Task instance representing the task corresponding to the specified Id.</returns>
public static new Task Bind(ExchangeService service, ItemId id)
{
return Task.Bind(
service,
id,
PropertySet.FirstClassProperties);
}
/// <summary>
/// Internal method to return the schema associated with this type of object.
/// </summary>
/// <returns>The schema associated with this type of object.</returns>
internal override ServiceObjectSchema GetSchema()
{
return TaskSchema.Instance;
}
/// <summary>
/// Gets the minimum required server version.
/// </summary>
/// <returns>Earliest Exchange version in which this service object type is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2007_SP1;
}
/// <summary>
/// Gets a value indicating whether a time zone SOAP header should be emitted in a CreateItem
/// or UpdateItem request so this item can be property saved or updated.
/// </summary>
/// <param name="isUpdateOperation">Indicates whether the operation being petrformed is an update operation.</param>
/// <returns>
/// <c>true</c> if a time zone SOAP header should be emitted; otherwise, <c>false</c>.
/// </returns>
internal override bool GetIsTimeZoneHeaderRequired(bool isUpdateOperation)
{
return true;
}
/// <summary>
/// Deletes the current occurrence of a recurring task. After the current occurrence isdeleted,
/// the task represents the next occurrence. Developers should call Load to retrieve the new property
/// values of the task. Calling this method results in a call to EWS.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
public void DeleteCurrentOccurrence(DeleteMode deleteMode)
{
this.InternalDelete(
deleteMode,
null,
AffectedTaskOccurrence.SpecifiedOccurrenceOnly);
}
/// <summary>
/// Applies the local changes that have been made to this task. Calling this method results in at least one call to EWS.
/// Mutliple calls to EWS might be made if attachments have been added or removed.
/// </summary>
/// <param name="conflictResolutionMode">Specifies how conflicts should be resolved.</param>
/// <returns>
/// A Task object representing the completed occurrence if the task is recurring and the update marks it as completed; or
/// a Task object representing the current occurrence if the task is recurring and the uypdate changed its recurrence
/// pattern; or null in every other case.
/// </returns>
public new Task Update(ConflictResolutionMode conflictResolutionMode)
{
return (Task)this.InternalUpdate(
null /* parentFolder */,
conflictResolutionMode,
MessageDisposition.SaveOnly,
null);
}
#region Properties
/// <summary>
/// Gets or sets the actual amount of time that is spent on the task.
/// </summary>
public int? ActualWork
{
get { return (int?)this.PropertyBag[TaskSchema.ActualWork]; }
set { this.PropertyBag[TaskSchema.ActualWork] = value; }
}
/// <summary>
/// Gets the date and time the task was assigned.
/// </summary>
public DateTime? AssignedTime
{
get { return (DateTime?)this.PropertyBag[TaskSchema.AssignedTime]; }
}
/// <summary>
/// Gets or sets the billing information of the task.
/// </summary>
public string BillingInformation
{
get { return (string)this.PropertyBag[TaskSchema.BillingInformation]; }
set { this.PropertyBag[TaskSchema.BillingInformation] = value; }
}
/// <summary>
/// Gets the number of times the task has changed since it was created.
/// </summary>
public int ChangeCount
{
get { return (int)this.PropertyBag[TaskSchema.ChangeCount]; }
}
/// <summary>
/// Gets or sets a list of companies associated with the task.
/// </summary>
public StringList Companies
{
get { return (StringList)this.PropertyBag[TaskSchema.Companies]; }
set { this.PropertyBag[TaskSchema.Companies] = value; }
}
/// <summary>
/// Gets or sets the date and time on which the task was completed.
/// </summary>
public DateTime? CompleteDate
{
get { return (DateTime?)this.PropertyBag[TaskSchema.CompleteDate]; }
set { this.PropertyBag[TaskSchema.CompleteDate] = value; }
}
/// <summary>
/// Gets or sets a list of contacts associated with the task.
/// </summary>
public StringList Contacts
{
get { return (StringList)this.PropertyBag[TaskSchema.Contacts]; }
set { this.PropertyBag[TaskSchema.Contacts] = value; }
}
/// <summary>
/// Gets the current delegation state of the task.
/// </summary>
public TaskDelegationState DelegationState
{
get { return (TaskDelegationState)this.PropertyBag[TaskSchema.DelegationState]; }
}
/// <summary>
/// Gets the name of the delegator of this task.
/// </summary>
public string Delegator
{
get { return (string)this.PropertyBag[TaskSchema.Delegator]; }
}
/// <summary>
/// Gets or sets the date and time on which the task is due.
/// </summary>
public DateTime? DueDate
{
get { return (DateTime?)this.PropertyBag[TaskSchema.DueDate]; }
set { this.PropertyBag[TaskSchema.DueDate] = value; }
}
/// <summary>
/// Gets a value indicating the mode of the task.
/// </summary>
public TaskMode Mode
{
get { return (TaskMode)this.PropertyBag[TaskSchema.Mode]; }
}
/// <summary>
/// Gets a value indicating whether the task is complete.
/// </summary>
public bool IsComplete
{
get { return (bool)this.PropertyBag[TaskSchema.IsComplete]; }
}
/// <summary>
/// Gets a value indicating whether the task is recurring.
/// </summary>
public bool IsRecurring
{
get { return (bool)this.PropertyBag[TaskSchema.IsRecurring]; }
}
/// <summary>
/// Gets a value indicating whether the task is a team task.
/// </summary>
public bool IsTeamTask
{
get { return (bool)this.PropertyBag[TaskSchema.IsTeamTask]; }
}
/// <summary>
/// Gets or sets the mileage of the task.
/// </summary>
public string Mileage
{
get { return (string)this.PropertyBag[TaskSchema.Mileage]; }
set { this.PropertyBag[TaskSchema.Mileage] = value; }
}
/// <summary>
/// Gets the name of the owner of the task.
/// </summary>
public string Owner
{
get { return (string)this.PropertyBag[TaskSchema.Owner]; }
}
/// <summary>
/// Gets or sets the completeion percentage of the task. PercentComplete must be between 0 and 100.
/// </summary>
public double PercentComplete
{
get { return (double)this.PropertyBag[TaskSchema.PercentComplete]; }
set { this.PropertyBag[TaskSchema.PercentComplete] = value; }
}
/// <summary>
/// Gets or sets the recurrence pattern for this task. Available recurrence pattern classes include
/// Recurrence.DailyPattern, Recurrence.MonthlyPattern and Recurrence.YearlyPattern.
/// </summary>
public Recurrence Recurrence
{
get { return (Recurrence)this.PropertyBag[TaskSchema.Recurrence]; }
set { this.PropertyBag[TaskSchema.Recurrence] = value; }
}
/// <summary>
/// Gets or sets the date and time on which the task starts.
/// </summary>
public DateTime? StartDate
{
get { return (DateTime?)this.PropertyBag[TaskSchema.StartDate]; }
set { this.PropertyBag[TaskSchema.StartDate] = value; }
}
/// <summary>
/// Gets or sets the status of the task.
/// </summary>
public TaskStatus Status
{
get { return (TaskStatus)this.PropertyBag[TaskSchema.Status]; }
set { this.PropertyBag[TaskSchema.Status] = value; }
}
/// <summary>
/// Gets a string representing the status of the task, localized according to the PreferredCulture
/// property of the ExchangeService object the task is bound to.
/// </summary>
public string StatusDescription
{
get { return (string)this.PropertyBag[TaskSchema.StatusDescription]; }
}
/// <summary>
/// Gets or sets the total amount of work spent on the task.
/// </summary>
public int? TotalWork
{
get { return (int?)this.PropertyBag[TaskSchema.TotalWork]; }
set { this.PropertyBag[TaskSchema.TotalWork] = value; }
}
/// <summary>
/// Gets the default setting for how to treat affected task occurrences on Delete.
/// </summary>
/// <value>AffectedTaskOccurrence.AllOccurrences: All affected Task occurrences will be deleted.</value>
internal override AffectedTaskOccurrence? DefaultAffectedTaskOccurrences
{
get { return AffectedTaskOccurrence.AllOccurrences; }
}
#endregion
}
}
| |
using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation.Media;
using Skewworks.NETMF;
using Skewworks.NETMF.Controls;
namespace Skewworks.Tinkr.Controls
{
[Serializable]
public class Appbar : Control
{
#region Variables
// Appearance
private Font _font;
private Font _timeFont;
private Color _bkg;
private Color _fore;
private DockLocation _dock;
private bool _displayTime;
private TimeFormat _timeFormat;
private bool _expanded;
private bool _farAlign;
private int _selIndex;
// Metrics
private int _x, _y, _w, _h;
private int _dW, _dH;
// Time Keeping
private Thread _mon;
private int _min;
// Children
private AppbarIcon[] _icons;
private AppbarMenuItem[] _menus;
// Ellipsis
private readonly Bitmap _elli;
private rect _elliRect;
// Expand/Collapse
//private bool _eDown;
// Scrolling
private int _scrollValue;
private rect _scrollArea;
private bool _sDown;
private bool _moved;
private int _requiredDisplaySize;
private int _scrollValueRange;
private int _gripSize;
#endregion
#region Constructor
public Appbar(string name, int size, Font timeFont, Font menuFont, DockLocation dock)
{
Name = name;
_timeFont = timeFont;
_font = menuFont;
_dock = dock;
_timeFormat = TimeFormat.Hour12;
_displayTime = true;
Metrics(size);
_bkg = ColorUtility.ColorFromRGB(30, 30, 30);
_fore = Colors.White;
_elli = new Bitmap(4, 4);
_elliRect = new rect(Left, Top, 64, 64);
UpdateEllipsis();
}
public Appbar(string name, int size, Font timeFont, Font menuFont, DockLocation dock, bool displayTime)
{
Name = name;
_timeFont = timeFont;
_font = menuFont;
_dock = dock;
_timeFormat = TimeFormat.Hour12;
_displayTime = displayTime;
Metrics(size);
_bkg = ColorUtility.ColorFromRGB(30, 30, 30);
_fore = Colors.White;
_elli = new Bitmap(4, 4);
_elliRect = new rect(Left, Top, 64, 64);
UpdateEllipsis();
}
#endregion
#region Properties
public Color BackColor
{
get { return _bkg; }
set
{
if (_bkg == value)
return;
_bkg = value;
UpdateEllipsis();
Invalidate();
}
}
public int BaseHeight
{
get { return _dH; }
}
public int BaseWidth
{
get { return _dW; }
}
/// <summary>
/// Location to dock AppBar
/// </summary>
public DockLocation Dock
{
get { return _dock; }
set
{
if (_dock == value)
return;
int size;
if (value == DockLocation.Bottom || value == DockLocation.Top)
{
size = _dH;
}
else
{
size = _dW;
}
_dock = value;
_expanded = false;
Metrics(size);
Invalidate();
}
}
/// <summary>
/// Displays time when true
/// </summary>
public bool DisplayTime
{
get { return _displayTime; }
set
{
if (_displayTime == value)
return;
_displayTime = value;
Invalidate();
}
}
public bool Expanded
{
get { return _expanded; }
set
{
if (_expanded == value)
return;
_expanded = !value;
ShowHideDock();
}
}
public bool FarAlignment
{
get { return _farAlign; }
set
{
if (_farAlign == value)
return;
_farAlign = value;
Invalidate();
}
}
public Color ForeColor
{
get { return _fore; }
set
{
if (_fore == value)
return;
_fore = value;
UpdateEllipsis();
Invalidate();
}
}
public Font Font
{
get { return _font; }
set
{
if (_font == value)
return;
_font = value;
Invalidate();
}
}
public override int Height
{
get
{
if (_expanded)
return _h;
return _dH;
}
set
{
if (_dH == value)
return;
_dH = value;
if (!_expanded)
Invalidate();
}
}
public AppbarIcon[] Icons
{
get { return _icons; }
}
public AppbarMenuItem[] Menus
{
get { return _menus; }
}
/// <summary>
/// Gets/Sets containing parent
/// </summary>
public override IContainer Parent
{
get { return base.Parent; }
set
{
base.Parent = value;
if (value != null)
{
if (_mon == null || !_mon.IsAlive)
{
_mon = new Thread(MonitorTime);
_mon.Start();
}
}
else if (_mon != null)
_mon.Abort();
}
}
public Font TimeFont
{
get { return _timeFont; }
set
{
if (_timeFont == value)
return;
_timeFont = value;
Invalidate();
}
}
public TimeFormat TimeFormat
{
get { return _timeFormat; }
set
{
if (_timeFormat == value)
return;
_timeFormat = value;
Invalidate();
}
}
public override int Width
{
get
{
if (_expanded)
return _w;
return _dW;
}
set
{
if (_dW == value)
return;
_dW = value;
if (!_expanded)
Invalidate();
}
}
public override int X
{
get { return _x; }
set { } // throw new Exception("Cannot modify Appbar X"); }
}
public override int Y
{
get { return _y; }
set { } // throw new Exception("Cannot modify Appbar Y"); }
}
#endregion
#region Buttons
bool _btnDown;
protected override void ButtonPressedMessage(int buttonId, ref bool handled)
{
if (!_expanded || _menus == null || _menus.Length == 0)
{
return;
}
if (buttonId == (int)ButtonIDs.Up)
{
_btnDown = true;
_selIndex -= 1;
if (_selIndex < 0)
{
_selIndex = 0;
}
Invalidate();
}
else if (buttonId == (int)ButtonIDs.Down)
{
_btnDown = true;
_selIndex += 1;
if (_selIndex > _menus.Length - 1)
{
_selIndex = _menus.Length - 1;
}
Invalidate();
}
handled = true;
}
// ReSharper disable once RedundantAssignment
protected override void ButtonReleasedMessage(int buttonId, ref bool handled)
{
if (_btnDown)
{
_btnDown = false;
if (buttonId == (int)ButtonIDs.Select)
{
ShowHideDock();
_menus[_selIndex].SendTouchDown(this, new point(_menus[_selIndex].X, _menus[_selIndex].Y));
_menus[_selIndex].SendTouchUp(this, new point(_menus[_selIndex].X, _menus[_selIndex].Y));
}
}
handled = true;
}
#endregion
#region Keyboard
#endregion
#region Touch
protected override void TouchDownMessage(object sender, point point, ref bool handled)
{
if (_elliRect.Contains(point))
{
//_eDown = true;
//handled = true;
return;
}
int i;
if (_icons != null)
{
for (i = 0; i < _icons.Length; i++)
{
if (_icons[i].HitTest(point))
{
_icons[i].SendTouchDown(this, point);
//handled = true;
return;
}
}
}
if (_expanded)
{
if (!_scrollArea.Contains(point))
return;
_sDown = true;
for (i = 0; i < _menus.Length; i++)
{
if (_menus[i].HitTest(point))
{
_menus[i].SendTouchDown(this, point);
//handled = true;
Invalidate();
return;
}
}
}
}
protected override void TouchMoveMessage(object sender, point point, ref bool handled)
{
if (_sDown && (_moved || (point.Y - LastTouch.Y) >= 12))
{
_moved = true;
int dest = _scrollValue - (point.Y - LastTouch.Y);
if (dest < 0)
{
dest = 0;
}
else if (dest > _requiredDisplaySize - _scrollArea.Height)
{
dest = _requiredDisplaySize - _scrollArea.Height;
}
if (_scrollValue != dest && dest > 0)
{
_scrollValue = dest;
Invalidate();
}
LastTouch = point;
}
base.TouchMoveMessage(sender, point, ref handled);
}
protected override void TouchUpMessage(object sender, point point, ref bool handled)
{
try
{
_sDown = false;
//if (_moved)
// return;
if (_elliRect.Contains(point))
{
ShowHideDock();
handled = true;
return;
}
int i;
if (_icons != null)
{
for (i = 0; i < _icons.Length; i++)
{
if (_icons[i].Touching || _icons[i].HitTest(point))
{
handled = true;
_icons[i].SendTouchUp(this, point);
}
}
if (handled)
{
return;
}
}
if (_expanded)
{
for (i = 0; i < _menus.Length; i++)
{
if (_menus[i].Touching)
{
handled = true;
if (!_moved)
{
if (_menus[i].HitTest(point))
ShowHideDock();
_menus[i].SendTouchUp(this, point);
}
else
{
_menus[i].SendTouchUp(this, new point(_menus[i].ScreenBounds.X - 10, 0));
Invalidate();
}
return;
}
if (_menus[i].HitTest(point))
{
// ReSharper disable once RedundantAssignment ??
handled = true;
if (_moved)
{
_menus[i].SendTouchUp(this, new point(_menus[i].ScreenBounds.X - 10, 0));
}
else
{
_menus[i].SendTouchUp(this, point);
}
}
}
}
}
finally
{
base.TouchUpMessage(sender, point, ref handled);
}
}
#endregion
#region Public Methods
public void AddIcon(AppbarIcon icon)
{
// Update Array Size
if (_icons == null)
_icons = new AppbarIcon[1];
else
{
var tmp = new AppbarIcon[_icons.Length + 1];
Array.Copy(_icons, tmp, _icons.Length);
_icons = tmp;
}
// Update Owner
if (icon.Owner != null)
icon.Owner.RemoveIcon(icon);
icon.Owner = this;
// Assign Value
_icons[_icons.Length - 1] = icon;
Invalidate();
}
public void AddMenuItem(AppbarMenuItem menu)
{
if (_menus == null)
{
_menus = new[] { menu };
}
else
{
var tmp = new AppbarMenuItem[_menus.Length + 1];
Array.Copy(_menus, tmp, _menus.Length);
tmp[tmp.Length - 1] = menu;
_menus = tmp;
}
if (_expanded)
{
Invalidate();
}
}
public void ClearIcons()
{
if (_icons == null)
return;
_icons = null;
Invalidate();
}
public void ClearMenuItems()
{
if (_menus == null)
return;
_menus = null;
if (_expanded)
Invalidate();
}
public AppbarIcon GetIconByName(string name)
{
if (_icons == null)
return null;
for (int i = 0; i < _icons.Length; i++)
{
if (_icons[i].Name == name)
return _icons[i];
}
return null;
}
public AppbarMenuItem GetMenuByName(string name)
{
if (_menus == null)
return null;
for (int i = 0; i < _menus.Length; i++)
{
if (_menus[i].Name == name)
return _menus[i];
}
return null;
}
public void RemoveIcon(AppbarIcon icon)
{
if (_icons == null)
return;
for (int i = 0; i < _icons.Length; i++)
{
if (_icons[i] == icon)
{
RemoveIconAt(i);
return;
}
}
}
public void RemoveIconAt(int index)
{
if (_icons == null || index < 0 || index >= _icons.Length)
return;
if (_icons.Length == 1)
{
ClearIcons();
return;
}
Suspended = true;
_icons[index].Owner = null;
var tmp = new AppbarIcon[_icons.Length - 1];
int c = 0;
for (int i = 0; i < _icons.Length; i++)
{
if (i != index)
tmp[c++] = _icons[i];
}
_icons = tmp;
Suspended = false;
}
public void RemoveMenuItem(AppbarMenuItem menu)
{
if (_menus == null)
return;
for (int i = 0; i < _menus.Length; i++)
{
if (_menus[i] == menu)
{
RemoveMenuItemAt(i);
return;
}
}
}
public void RemoveMenuItemAt(int index)
{
if (_menus == null || index < 0 || index >= _menus.Length)
return;
if (_menus.Length == 1)
{
ClearMenuItems();
return;
}
if (_expanded)
Suspended = true;
var tmp = new AppbarMenuItem[_menus.Length - 1];
int c = 0;
for (int i = 0; i < _menus.Length; i++)
{
if (i != index)
tmp[c++] = _menus[i];
}
_menus = tmp;
if (_expanded)
Suspended = false;
}
#endregion
#region GUI
protected override void OnRender(int x, int y, int width, int height)
{
Core.Screen.DrawRectangle(0, 0, Left, Top, Width, Height, 0, 0, _bkg, 0, 0, _bkg, 0, 0, 256);
switch (_dock)
{
case DockLocation.Bottom:
RenderBottom(FontManager.ComputeExtentEx(_timeFont, "XX:XX PM").Width);
break;
case DockLocation.Left:
RenderLeft(_timeFont.Height * 2);
break;
case DockLocation.Right:
RenderRight(_timeFont.Height * 2);
break;
case DockLocation.Top:
RenderTop(FontManager.ComputeExtentEx(_timeFont, "XX:XX PM").Width);
break;
}
}
private void RenderBottom(int tw)
{
int x = Left + 64;
int y = Top;
// Ellipsis
if (_menus != null)
{
Core.Screen.DrawImage(Left + 7, Top + 7, _elli, 0, 0, 4, 4);
Core.Screen.DrawImage(Left + 17, Top + 7, _elli, 0, 0, 4, 4);
Core.Screen.DrawImage(Left + 27, Top + 7, _elli, 0, 0, 4, 4);
}
// Icons
if (_icons != null)
{
if (_displayTime)
{
Core.Screen.SetClippingRectangle(Left + 64, Top, Width - 70 - tw, _dH);
if (_farAlign)
x = Width - 8 - tw;
}
else
{
Core.Screen.SetClippingRectangle(Left + 64, Top, Width - 70, _dH);
if (_farAlign)
x = Width - 8;
}
int i;
for (i = 0; i < _icons.Length; i++)
{
if (_icons[i].Image != null)
{
if (_farAlign)
x -= _icons[i].Width;
_icons[i].X = x;
_icons[i].Y = y + (_dH / 2 - _icons[i].Height / 2);
Core.Screen.DrawImage(x, _icons[i].Y, _icons[i].Image, 0, 0, _icons[i].Width, _icons[i].Height);
if (_farAlign)
x -= 8;
else
x += _icons[i].Width + 8;
}
}
}
// Time
if (_displayTime)
{
Core.Screen.SetClippingRectangle(Left + Width - tw - 8, Top, tw, _dH);
Core.Screen.DrawText(FormatTime(), _timeFont, _fore, Left + Width - tw - 8, Top + (_dH / 2 - _timeFont.Height / 2));
}
// Menu Items
if (_expanded)
DrawMenuItems();
}
private void RenderLeft(int tw)
{
int x = Left + _w - _dW;
int y = Top + 64;
// Ellipsis
if (_menus != null)
{
Core.Screen.DrawImage(Left + _w - 11, Top + 7, _elli, 0, 0, 4, 4);
Core.Screen.DrawImage(Left + _w - 11, Top + 17, _elli, 0, 0, 4, 4);
Core.Screen.DrawImage(Left + _w - 11, Top + 27, _elli, 0, 0, 4, 4);
}
// Icons
if (_icons != null)
{
if (_displayTime)
{
Core.Screen.SetClippingRectangle(x, Top + 64, _dW, Height - 70 - tw);
if (_farAlign)
y = Height - 8 - tw;
}
else
{
Core.Screen.SetClippingRectangle(x, Top + 64, _dW, Height - 70);
if (_farAlign)
y = Height - 8 - tw;
}
for (int i = 0; i < _icons.Length; i++)
{
if (_icons[i].Image != null)
{
if (_farAlign)
y -= _icons[i].Height;
_icons[i].X = x + (_dW / 2 - _icons[i].Width / 2);
_icons[i].Y = y;
Core.Screen.DrawImage(_icons[i].X, _icons[i].Y, _icons[i].Image, 0, 0, _icons[i].Width, _icons[i].Height);
if (_farAlign)
y -= 8;
else
y += _icons[i].Height + 8;
}
}
}
// Time
if (_displayTime)
{
Core.Screen.SetClippingRectangle(Left + 4 + _w - _dW, Top + _h - tw - 8, _dW - 8, tw);
Core.Screen.DrawTextInRect(FormatTime(), Left + 4 + _w - _dW, Top + _h - tw - 8, _dW - 8, tw, Bitmap.DT_AlignmentCenter, _fore, _timeFont);
}
if (_expanded)
DrawMenuItems();
}
private void RenderRight(int tw)
{
int x = Left;
int y = Top + 64;
// Ellipsis
if (_menus != null)
{
Core.Screen.DrawImage(Left + 7, Top + 7, _elli, 0, 0, 4, 4);
Core.Screen.DrawImage(Left + 7, Top + 17, _elli, 0, 0, 4, 4);
Core.Screen.DrawImage(Left + 7, Top + 27, _elli, 0, 0, 4, 4);
}
// Icons
if (_icons != null)
{
if (_displayTime)
{
Core.Screen.SetClippingRectangle(x, Top + 64, _dW, Height - 70 - tw);
if (_farAlign)
y = Height - 8 - tw;
}
else
{
Core.Screen.SetClippingRectangle(x, Top + 64, _dW, Height - 70);
if (_farAlign)
y = Height - 8 - tw;
}
for (int i = 0; i < _icons.Length; i++)
{
if (_icons[i].Image != null)
{
if (_farAlign)
y -= _icons[i].Height;
_icons[i].X = x + (_dW / 2 - _icons[i].Width / 2);
_icons[i].Y = y;
Core.Screen.DrawImage(_icons[i].X, _icons[i].Y, _icons[i].Image, 0, 0, _icons[i].Width, _icons[i].Height);
if (_farAlign)
y -= 8;
else
y += _icons[i].Height + 8;
}
}
}
// Time
if (_displayTime)
{
Core.Screen.SetClippingRectangle(Left + 4, Top + _h - tw - 8, _dW - 8, tw);
Core.Screen.DrawTextInRect(FormatTime(), Left + 4, Top + _h - tw - 8, _dW - 8, tw, Bitmap.DT_AlignmentCenter, _fore, _timeFont);
}
if (_expanded)
DrawMenuItems();
}
private void RenderTop(int tw)
{
int x = Left + 64;
int y = Top;
// Ellipsis
if (_menus != null)
{
Core.Screen.DrawImage(Left + 7, Top + _h - 11, _elli, 0, 0, 4, 4);
Core.Screen.DrawImage(Left + 17, Top + _h - 11, _elli, 0, 0, 4, 4);
Core.Screen.DrawImage(Left + 27, Top + _h - 11, _elli, 0, 0, 4, 4);
}
// Icons
if (_icons != null)
{
if (_displayTime)
{
Core.Screen.SetClippingRectangle(Left + 64, Top + _h - _dH, Width - 70 - tw, _dH);
if (_farAlign)
x = Width - 8 - tw;
}
else
{
Core.Screen.SetClippingRectangle(Left + 64, Top + _h - _dH, Width - 70, _dH);
if (_farAlign)
x = Width - 8;
}
for (int i = 0; i < _icons.Length; i++)
{
if (_icons[i].Image != null)
{
if (_farAlign)
x -= _icons[i].Width;
_icons[i].X = x;
_icons[i].Y = y + _h - _dH + (_dH / 2 - _icons[i].Height / 2);
Core.Screen.DrawImage(x, _icons[i].Y, _icons[i].Image, 0, 0, _icons[i].Width, _icons[i].Height);
if (_farAlign)
x -= 8;
else
x += _icons[i].Width + 8;
}
}
}
// Time
if (DisplayTime)
{
Core.Screen.SetClippingRectangle(Left + Width - tw - 8, Top + _h - _dH, tw, _dH);
Core.Screen.DrawText(FormatTime(), _timeFont, _fore, Left + Width - tw - 8, Top + _h - _dH + (_dH / 2 - _timeFont.Height / 2));
}
// Menu Items
if (_expanded)
DrawMenuItems();
}
private void DrawMenuItems()
{
if (_menus == null)
return;
int y = _scrollArea.Y - _scrollValue;
int x = _scrollArea.X;
int i;
Core.Screen.SetClippingRectangle(_scrollArea.X, _scrollArea.Y, _scrollArea.Width, _scrollArea.Height);
for (i = 0; i < _menus.Length; i++)
{
if (_menus[i].Touching || _selIndex == i)
{
Core.Screen.DrawRectangle(0, 0, x, y - 2, _scrollArea.Width, _font.Height + 4, 0, 0,
Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 256);
Core.Screen.DrawText(_menus[i].Text, _font, Core.SystemColors.SelectedFontColor, x, y + 2);
}
else
Core.Screen.DrawText(_menus[i].Text, _font, _fore, x, y + 2);
_menus[i].X = x;
_menus[i].Y = y;
if (_menus[i].Width == 0)
{
_menus[i].Width = _scrollArea.Width;
_menus[i].Height = _font.Height;
}
y += _font.Height + 4;
}
// Scrolling
if (_requiredDisplaySize > _scrollArea.Height)
{
Core.Screen.DrawRectangle(0, 0, _scrollArea.X + _scrollArea.Width - 4, _scrollArea.Y, 4, _scrollArea.Height, 0, 0,
Core.SystemColors.ScrollbarBackground, 0, 0, Core.SystemColors.ScrollbarBackground, 0, 0, 128);
i = (int)((_scrollArea.Height - _gripSize) * (_scrollValue / (float)_scrollValueRange));
Core.Screen.DrawRectangle(0, 0, _scrollArea.X + _scrollArea.Width - 4, _scrollArea.Y + i, 4, _gripSize, 0, 0,
Core.SystemColors.ScrollbarGrip, 0, 0, Core.SystemColors.ScrollbarGrip, 0, 0, 128);
}
}
#endregion
#region Private Methods
private string FormatTime()
{
int h = DateTime.Now.Hour;
string m = DateTime.Now.Minute.ToString();
string ap = " AM";
if (m.Length == 1)
m = "0" + m;
if (_timeFormat == TimeFormat.Hour12)
{
if (h > 12)
{
h -= 12;
ap = " PM";
}
else if (h == 12)
ap = " PM";
else if (h == 0)
h = 12;
_min = DateTime.Now.Minute;
return h + ":" + m + ap;
}
if (h < 10)
{
return "0" + h + ":" + m;
}
return h + ":" + m;
}
private void Metrics(int size)
{
switch (_dock)
{
case DockLocation.Bottom:
_x = 0;
_w = Core.ScreenWidth;
_h = size;
_y = Core.ScreenHeight - _h;
break;
case DockLocation.Left:
_x = 0;
_y = 0;
_w = size;
_h = Core.ScreenHeight;
break;
case DockLocation.Right:
_x = Core.ScreenWidth - size;
_y = 0;
_w = size;
_h = Core.ScreenHeight;
break;
default:
_x = 0;
_y = 0;
_h = size;
_w = Core.ScreenWidth;
break;
}
_dH = _h;
_dW = _w;
}
private void MonitorTime()
{
while (Parent != null)
{
if (_displayTime && DateTime.Now.Minute != _min)
{
_min = DateTime.Now.Minute;
Invalidate();
}
Thread.Sleep(1000);
}
}
private void ShowHideDock()
{
_selIndex = -1;
_expanded = !_expanded;
if (!_expanded)
{
UpdateDock();
Parent.Invalidate();
return;
}
int i, d;
Parent.BringControlToFront(this);
// Calculate size required to display all menus
_requiredDisplaySize = (_font.Height + 4) * _menus.Length;
switch (_dock)
{
case DockLocation.Bottom:
// Calculate new height
i = _dH + _requiredDisplaySize;
// Restrict height to 1/2 parent height
if (_dH + i > Parent.Height / 2)
i = Parent.Height / 2 - _dH;
// Update Y & Height
_h += i;
_y -= i;
// Define Scrollable Area
_scrollArea = new rect(Left + 8, Top + _dH + 8, _w - 8, _h - _dH - 8);
// Calculate Scroll Value Range
_scrollValueRange = _requiredDisplaySize - _scrollArea.Height;
// Calculate Grip Size
if (_scrollValueRange > 0)
_gripSize = _scrollArea.Height / (_requiredDisplaySize / _scrollArea.Height);
else
_gripSize = 8;
// Enforce minimum grip size
if (_gripSize < 8)
_gripSize = 8;
// Update Ellipsis Rect
_elliRect = new rect(Left, Top, 64, 64);
break;
case DockLocation.Left:
// Calculate new width
d = 0;
for (i = 0; i < _menus.Length; i++)
{
_gripSize = FontManager.ComputeExtentEx(_font, _menus[i].Text).Width;
if (_gripSize > d)
d = _gripSize;
}
i = _dW + d;
// Restrict width to 1/2 parent width
if (_dW + i > Parent.Width / 2)
i = Parent.Width / 2 - _dW;
// Update Width
_w += i;
// Define Scrollable Area
_scrollArea = new rect(Left + 8, Top + 8, _w - _dW - 8, _h - 16);
// Calculate Scroll Value Range
if (_scrollValueRange > 0)
_scrollValueRange = _requiredDisplaySize - _scrollArea.Height;
else
_gripSize = 8;
// Calculate Grip Size
_gripSize = _scrollArea.Height / (_requiredDisplaySize / _scrollArea.Height);
// Enforce minimum grip size
if (_gripSize < 8)
_gripSize = 8;
// Update Ellipsis Rect
_elliRect = new rect(Left + _w - _dW, Top, 64, 64);
break;
case DockLocation.Right:
// Calculate new width
d = 0;
for (i = 0; i < _menus.Length; i++)
{
_gripSize = FontManager.ComputeExtentEx(_font, _menus[i].Text).Width;
if (_gripSize > d)
d = _gripSize;
}
i = _dW + d;
// Restrict width to 1/2 parent width
if (_dW + i > Parent.Width / 2)
i = Parent.Width / 2 - _dW;
// Update X & Width
_x -= i;
_w += i;
// Define Scrollable Area
_scrollArea = new rect(Left + 8 + _dW, Top + 8, _w - _dW - 8, _h - 16);
// Calculate Scroll Value Range
_scrollValueRange = _requiredDisplaySize - _scrollArea.Height;
// Calculate Grip Size
if (_scrollValueRange > 0)
_gripSize = _scrollArea.Height / (_requiredDisplaySize / _scrollArea.Height);
else
_gripSize = 8;
// Enforce minimum grip size
if (_gripSize < 8)
_gripSize = 8;
// Update Ellipsis Rect
_elliRect = new rect(Left, Top, 64, 64);
break;
default:
// Calculate new height
i = _dH + _requiredDisplaySize;
// Restrict height to 1/2 parent height
if (_dH + i > Parent.Height / 2)
i = Parent.Height / 2 - _dH;
// Update Height
_h += i;
// Define Scrollable Area
_scrollArea = new rect(Left + 8, Top + 8, _w - 8, _h - _dH - 8);
// Calculate Scroll Value Range
_scrollValueRange = _requiredDisplaySize - _scrollArea.Height;
// Calculate Grip Size
if (_scrollValueRange > 0)
_gripSize = _scrollArea.Height / (_requiredDisplaySize / _scrollArea.Height);
else
_gripSize = 8;
// Enforce minimum grip size
if (_gripSize < 8)
_gripSize = 8;
// Update Ellipsis Rect
_elliRect = new rect(Left, Top + _h - 64, 64, 64);
break;
}
_scrollValue = 0;
Invalidate();
}
private void UpdateDock()
{
switch (_dock)
{
case DockLocation.Bottom:
_x = 0;
_w = Core.ScreenWidth;
_h = _dH;
_y = Core.ScreenHeight - _dH;
break;
case DockLocation.Left:
_x = 0;
_y = 0;
_w = _dW;
_h = Core.ScreenHeight;
break;
case DockLocation.Right:
_x = Core.ScreenWidth - _dW;
_y = 0;
_w = _dW;
_h = Core.ScreenHeight;
break;
default:
_x = 0;
_y = 0;
_h = _dH;
_w = Core.ScreenWidth;
break;
}
_elliRect = new rect(Left, Top, 64, 64);
}
private void UpdateEllipsis()
{
_elli.DrawRectangle(0, 0, 0, 0, 4, 4, 0, 0, _bkg, 0, 0, _bkg, 0, 0, 256);
_elli.DrawRectangle(0, 0, 1, 0, 1, 4, 0, 0, _fore, 0, 0, _fore, 0, 0, 256);
_elli.DrawRectangle(0, 0, 2, 1, 1, 2, 0, 0, _fore, 0, 0, _fore, 0, 0, 256);
_elli.DrawRectangle(0, 0, 0, 0, 1, 1, 0, 0, _fore, 0, 0, _fore, 0, 0, 35);
_elli.DrawRectangle(0, 0, 0, 3, 1, 1, 0, 0, _fore, 0, 0, _fore, 0, 0, 35);
_elli.DrawRectangle(0, 0, 0, 1, 1, 2, 0, 0, _fore, 0, 0, _fore, 0, 0, 199);
_elli.DrawRectangle(0, 0, 3, 0, 1, 1, 0, 0, _fore, 0, 0, _fore, 0, 0, 35);
_elli.DrawRectangle(0, 0, 3, 3, 1, 1, 0, 0, _fore, 0, 0, _fore, 0, 0, 35);
_elli.DrawRectangle(0, 0, 2, 0, 1, 1, 0, 0, _fore, 0, 0, _fore, 0, 0, 199);
_elli.DrawRectangle(0, 0, 2, 3, 1, 1, 0, 0, _fore, 0, 0, _fore, 0, 0, 199);
_elli.DrawRectangle(0, 0, 2, 3, 1, 1, 0, 0, _fore, 0, 0, _fore, 0, 0, 199);
_elli.DrawRectangle(0, 0, 3, 1, 1, 2, 0, 0, _fore, 0, 0, _fore, 0, 0, 199);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using angular.Areas.HelpPage.Models;
namespace angular.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using CslaGenerator.Metadata;
using DBSchemaInfo.Base;
using DBSchemaInfo.MsSql;
namespace CslaGenerator.Controls
{
/// <summary>
/// Summary description for DbColumns.
/// </summary>
public class DbColumns : UserControl
{
private Panel _panelTop;
private Panel _panel2;
private Panel _panel3;
private PaneCaption _paneCaption1;
private Panel _panelBottom;
private Panel _panelTrim;
private Panel _panel4;
private Panel _panelBody;
private PropertyGrid _pgdColumn;
private Splitter _splitter1;
private ListBox _lstColumns;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public DbColumns()
{
// This call is required by the Windows.Forms Form Designer.
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 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._panelTop = new System.Windows.Forms.Panel();
this._panel2 = new System.Windows.Forms.Panel();
this._panel3 = new System.Windows.Forms.Panel();
this._paneCaption1 = new CslaGenerator.Controls.PaneCaption();
this._panelBottom = new System.Windows.Forms.Panel();
this._panelTrim = new System.Windows.Forms.Panel();
this._panel4 = new System.Windows.Forms.Panel();
this._panelBody = new System.Windows.Forms.Panel();
this._pgdColumn = new System.Windows.Forms.PropertyGrid();
this._splitter1 = new System.Windows.Forms.Splitter();
this._lstColumns = new System.Windows.Forms.ListBox();
this._panelTop.SuspendLayout();
this._panel2.SuspendLayout();
this._panel3.SuspendLayout();
this._panelBottom.SuspendLayout();
this._panelTrim.SuspendLayout();
this._panel4.SuspendLayout();
this._panelBody.SuspendLayout();
this.SuspendLayout();
//
// panelTop
//
this._panelTop.Controls.Add(this._panel2);
this._panelTop.Dock = System.Windows.Forms.DockStyle.Top;
this._panelTop.DockPadding.All = 3;
this._panelTop.Location = new System.Drawing.Point(0, 0);
this._panelTop.Name = "_panelTop";
this._panelTop.Size = new System.Drawing.Size(288, 32);
this._panelTop.TabIndex = 11;
//
// panel2
//
this._panel2.BackColor = System.Drawing.SystemColors.ControlDark;
this._panel2.Controls.Add(this._panel3);
this._panel2.Dock = System.Windows.Forms.DockStyle.Fill;
this._panel2.DockPadding.All = 1;
this._panel2.Location = new System.Drawing.Point(3, 3);
this._panel2.Name = "_panel2";
this._panel2.Size = new System.Drawing.Size(282, 26);
this._panel2.TabIndex = 13;
//
// panel3
//
this._panel3.BackColor = System.Drawing.SystemColors.Control;
this._panel3.Controls.Add(this._paneCaption1);
this._panel3.Dock = System.Windows.Forms.DockStyle.Fill;
this._panel3.DockPadding.All = 3;
this._panel3.Location = new System.Drawing.Point(1, 1);
this._panel3.Name = "_panel3";
this._panel3.Size = new System.Drawing.Size(280, 24);
this._panel3.TabIndex = 13;
//
// paneCaption1
//
this._paneCaption1.AllowActive = false;
this._paneCaption1.AntiAlias = false;
this._paneCaption1.Caption = "Columns";
this._paneCaption1.Dock = System.Windows.Forms.DockStyle.Fill;
this._paneCaption1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this._paneCaption1.InactiveGradientHighColor = System.Drawing.Color.FromArgb(((System.Byte)(149)), ((System.Byte)(184)), ((System.Byte)(245)));
this._paneCaption1.InactiveGradientLowColor = System.Drawing.Color.White;
this._paneCaption1.Location = new System.Drawing.Point(3, 3);
this._paneCaption1.Name = "_paneCaption1";
this._paneCaption1.Size = new System.Drawing.Size(274, 18);
this._paneCaption1.TabIndex = 11;
//
// panelBottom
//
this._panelBottom.Controls.Add(this._panelTrim);
this._panelBottom.Dock = System.Windows.Forms.DockStyle.Fill;
this._panelBottom.DockPadding.Bottom = 3;
this._panelBottom.DockPadding.Left = 3;
this._panelBottom.DockPadding.Right = 3;
this._panelBottom.DockPadding.Top = 1;
this._panelBottom.Location = new System.Drawing.Point(0, 32);
this._panelBottom.Name = "_panelBottom";
this._panelBottom.Size = new System.Drawing.Size(288, 448);
this._panelBottom.TabIndex = 12;
//
// panelTrim
//
this._panelTrim.BackColor = System.Drawing.SystemColors.ControlDark;
this._panelTrim.Controls.Add(this._panel4);
this._panelTrim.Dock = System.Windows.Forms.DockStyle.Fill;
this._panelTrim.DockPadding.All = 1;
this._panelTrim.Location = new System.Drawing.Point(3, 1);
this._panelTrim.Name = "_panelTrim";
this._panelTrim.Size = new System.Drawing.Size(282, 444);
this._panelTrim.TabIndex = 10;
//
// panel4
//
this._panel4.BackColor = System.Drawing.SystemColors.Control;
this._panel4.Controls.Add(this._panelBody);
this._panel4.Dock = System.Windows.Forms.DockStyle.Fill;
this._panel4.DockPadding.All = 3;
this._panel4.Location = new System.Drawing.Point(1, 1);
this._panel4.Name = "_panel4";
this._panel4.Size = new System.Drawing.Size(280, 442);
this._panel4.TabIndex = 11;
//
// panelBody
//
this._panelBody.BackColor = System.Drawing.SystemColors.Control;
this._panelBody.Controls.Add(this._pgdColumn);
this._panelBody.Controls.Add(this._splitter1);
this._panelBody.Controls.Add(this._lstColumns);
this._panelBody.Dock = System.Windows.Forms.DockStyle.Fill;
this._panelBody.DockPadding.All = 2;
this._panelBody.Location = new System.Drawing.Point(3, 3);
this._panelBody.Name = "_panelBody";
this._panelBody.Size = new System.Drawing.Size(274, 436);
this._panelBody.TabIndex = 11;
//
// pgdColumn
//
this._pgdColumn.CommandsVisibleIfAvailable = true;
this._pgdColumn.Dock = System.Windows.Forms.DockStyle.Fill;
this._pgdColumn.HelpVisible = false;
this._pgdColumn.LargeButtons = false;
this._pgdColumn.LineColor = System.Drawing.SystemColors.ScrollBar;
this._pgdColumn.Location = new System.Drawing.Point(2, 227);
this._pgdColumn.Name = "_pgdColumn";
this._pgdColumn.Size = new System.Drawing.Size(270, 207);
this._pgdColumn.PropertySort = PropertySort.NoSort;
this._pgdColumn.TabIndex = 5;
this._pgdColumn.Text = "propertyGrid1";
this._pgdColumn.ViewBackColor = System.Drawing.SystemColors.Window;
this._pgdColumn.ViewForeColor = System.Drawing.SystemColors.WindowText;
//
// splitter1
//
this._splitter1.Dock = System.Windows.Forms.DockStyle.Top;
this._splitter1.Location = new System.Drawing.Point(2, 222);
this._splitter1.Name = "_splitter1";
this._splitter1.Size = new System.Drawing.Size(270, 5);
this._splitter1.TabIndex = 6;
this._splitter1.TabStop = false;
//
// lstColumns
//
this._lstColumns.DisplayMember = "ColumnName";
this._lstColumns.Dock = System.Windows.Forms.DockStyle.Top;
this._lstColumns.IntegralHeight = false;
this._lstColumns.Location = new System.Drawing.Point(2, 2);
this._lstColumns.Name = "_lstColumns";
this._lstColumns.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
this._lstColumns.Size = new System.Drawing.Size(270, 220);
this._lstColumns.TabIndex = 7;
this._lstColumns.ValueMember = "key";
this._lstColumns.MouseUp += new System.Windows.Forms.MouseEventHandler(this.lstColumns_MouseUp);
//
// DbColumns
//
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this._panelBottom);
this.Controls.Add(this._panelTop);
this.Name = "DbColumns";
this.Size = new System.Drawing.Size(288, 480);
this.Load += new System.EventHandler(this.DbColumns_Load);
this._panelTop.ResumeLayout(false);
this._panel2.ResumeLayout(false);
this._panel3.ResumeLayout(false);
this._panelBottom.ResumeLayout(false);
this._panelTrim.ResumeLayout(false);
this._panel4.ResumeLayout(false);
this._panelBody.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void DbColumns_Load(object sender, EventArgs e)
{
//this.lstColumns.Height = (int)((double)0.75 * (double)this.panelBody.Height);
}
internal void Clear()
{
// clear list and hash table that stores last selected columns
_lstColumns.Items.Clear();
if (_lastSelectedHt != null)
_lastSelectedHt.Clear();
}
internal void SelectAll(DbSchemaPanel dbSchemaPanel, CslaGeneratorUnit currentUnit)
{
/*
currentUnit.Params.CreateReadOnlyObjectsCopySoftDelete
*/
// select all columns in list, except for the exceptions
for (var i = 0; i < _lstColumns.Items.Count; i++)
{
var columnName = ((SqlColumnInfo)_lstColumns.Items[i]).ColumnName;
var columnNativeType = ((SqlColumnInfo)_lstColumns.Items[i]).NativeType;
// exception for soft delete column
if (dbSchemaPanel.UseBoolSoftDelete &&
currentUnit.Params.SpBoolSoftDeleteColumn == columnName)
{
continue;
}
// exception for auditing columns
if (!currentUnit.Params.ReadOnlyObjectsCopyAuditing &&
IsAuditingColumn(currentUnit, columnName))
{
continue;
}
// exception for NativeType timestamp
if (!currentUnit.Params.ReadOnlyObjectsCopyTimestamp &&
columnNativeType == "timestamp")
{
continue;
}
// none of the exceptions, so go ahead
_lstColumns.SetSelected(i, true);
}
RefreshColumns();
}
private static bool IsAuditingColumn(CslaGeneratorUnit currentUnit, string columnName)
{
if (currentUnit.Params.CreationDateColumn == columnName)
return true;
if (currentUnit.Params.CreationUserColumn == columnName)
return true;
if (currentUnit.Params.ChangedDateColumn == columnName)
return true;
if (currentUnit.Params.ChangedUserColumn == columnName)
return true;
return false;
}
internal void SelectAll(string exclude)
{
// select all columns in list
for (int i = 0; i < _lstColumns.Items.Count; i++)
{
if (((SqlColumnInfo)_lstColumns.Items[i]).ColumnName != exclude)
_lstColumns.SetSelected(i, true);
}
RefreshColumns();
}
internal void SelectAll()
{
SelectAll("");
}
internal void UnSelectAll()
{
// unselect all columns in list
for (int i = 0; i < _lstColumns.Items.Count; i++)
{
_lstColumns.SetSelected(i, false);
}
if (_lastSelectedHt != null)
_lastSelectedHt.Clear();
RefreshColumns();
}
// hash table to store the last selected (i.e. most recent) columns
private Dictionary<string, IColumnInfo> _lastSelectedHt = new Dictionary<string, IColumnInfo>();
private void lstColumns_MouseUp(object sender, MouseEventArgs e)
{
RefreshColumns();
}
private void RefreshColumns()
{
var lbx = _lstColumns;
IColumnInfo col;
var currSelectedHt = new Dictionary<string, IColumnInfo>();
var lastFound = false;
if (lbx.SelectedItems.Count == 0)
{
if (_pgdColumn.SelectedObjects.Length > 0)
_pgdColumn.SelectedObject = null;
_lastSelectedHt.Clear();
SetDbColumnsPctHeight(73);
}
else if (lbx.SelectedItems.Count > 0)
{
for (var i = 0; i < lbx.SelectedItems.Count; i++)
{
col = (IColumnInfo)lbx.SelectedItems[i];
try
{
currSelectedHt.Add(col.ColumnName, col);
if (!_lastSelectedHt.ContainsKey(col.ColumnName))
{
//found new selected row
_pgdColumn.SelectedObject = col;
_lstColumns.Height = (int)(0.55 * _panelBody.Height);
lastFound = true;
}
}
catch (Exception ex)
{
var sb = new System.Text.StringBuilder();
sb.AppendFormat("Error adding column \"{0}\" to seleccion list. Make sure it's not duplicated.", col.ColumnName);
sb.AppendLine();
sb.AppendLine("Details:");
sb.AppendLine(ex.Message);
sb.AppendLine(ex.StackTrace);
MessageBox.Show(sb.ToString(), @"Error selecting columns", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
if (lastFound)
{
_lastSelectedHt = currSelectedHt;
return;
}
foreach (var last in _lastSelectedHt.Values)
{
if (!lbx.SelectedItems.Contains(last))
{
//found new unselected row
_pgdColumn.SelectedObject = last;
lastFound = true;
}
}
_lastSelectedHt = currSelectedHt;
return;
}
}
#region Properties
internal ListBox ListColumns
{
get { return _lstColumns; }
}
// used to set list height to a % of panel height
internal void SetDbColumnsPctHeight(double pct)
{
if (pct > 0 && pct < 100)
{
_lstColumns.Height = (int)(pct / 100 * _panelBody.Height);
Invalidate();
}
}
internal PropertyGrid PropertyGridColumn
{
get { return _pgdColumn; }
}
internal Dictionary<string, IColumnInfo> SelectedIndices
{
get { return _lastSelectedHt; }
}
internal int SelectedIndicesCount
{
get { return _lastSelectedHt.Count; }
}
#endregion
}
}
| |
using System;
using NHibernate;
using NUnit.Framework;
using ProjectTracker.Library.Tests.Framework;
using ProjectTracker.Library.Tests.ResourceTests;
namespace ProjectTracker.Library.Tests.ProjectTests
{
#region Test factory class
/// <summary>
/// Represents a class that creates saved and unsaved <see cref="Project"/> objects.
/// </summary>
internal class ProjectFactory
{
/// <summary>
/// Returns a populated new, unsaved <see cref="Project"/> object.
/// </summary>
/// <returns>A <see cref="Project"/> instance object.</returns>
internal static Project NewProject()
{
Project project = Project.NewProject();
project.Name = "The project name";
project.Description = "Description of the project";
return project;
}
/// <summary>
/// Factory method to create a new, unsaved <see cref="Project"/> object
/// with an associated <see cref="ProjectResource"/> object.
/// </summary>
/// <returns>A <see cref="Project"/> instance object.</returns>
internal static Project NewProjectWithResource()
{
// Create a new project
Project project = NewProject();
Assert.IsNotNull(project);
// Use the resource factory to get a resource (already in DB)
Resource resource = ResourceFactory.ExistingResource();
Assert.IsNotNull(resource);
// Assign the resource to the project
project.Resources.Assign(resource.Id);
return project;
}
/// <summary>
/// Returns an existing <see cref="Project"/> object.
/// </summary>
/// <returns>A <see cref="Project"/> instance object.</returns>
internal static Project ExistingProject()
{
Project project = NewProject();
project = project.Save();
return project;
}
/// <summary>
/// Returns an existing <see cref="Project"/> object.
/// with an associated <see cref="ProjectResource"/> object.
/// </summary>
/// <returns>A <see cref="Project"/> instance object.</returns>
internal static Project ExistingProjectWithResource()
{
Project project = NewProjectWithResource();
project = project.Save();
return project;
}
/// <summary>
/// Tests for the existence of a <see cref="Project"/>.
/// </summary>
/// <param name="projectId">Unique identifier of the <see cref="Project"/>.</param>
/// <returns>
/// <lang>true</lang> if the <see cref="Project"/> exists; <lang>false</lang> otherwise.
/// </returns>
internal static bool ProjectExists(Guid projectId)
{
bool returnValue;
// Test if a project exists by trying to get it
try
{
// Try and get the project
Project project = Project.GetProject(projectId);
// If we get here then the project is in the DB
Assert.IsNotNull(project);
returnValue = true;
}
catch (Exception ex)
{
// The [ObjectNotFoundException] is nested inside 2 Data Portal exceptions
Exception actualException = ex.InnerException.InnerException;
Type targetType = typeof(ObjectNotFoundException);
// If the actual Exception is not the correct type then throw it again
if (!targetType.IsInstanceOfType(actualException))
throw;
// If we're in here then we have the right exception we expected
returnValue = false;
}
return returnValue;
}
}
#endregion
#region DeleteProject() method tests
[TestFixture]
public class DeleteProject : AuthenticatedProjectManagerTestBase
{
[Test]
public void Existing()
{
// Create an existing object
Project existingProject = ProjectFactory.ExistingProject();
// Delete the project
Guid projectId = existingProject.Id;
Project.DeleteProject(projectId);
// Check if the Project exists now
bool exists = ProjectFactory.ProjectExists(projectId);
Assert.IsFalse(exists);
}
[Test]
public void ExistingWithResource()
{
// Get an existing Resource with an Assignment
Project existingProject = ProjectFactory.ExistingProjectWithResource();
// Delete the project
Guid projectId = existingProject.Id;
Project.DeleteProject(projectId);
// Check if the Project exists now
bool exists = ProjectFactory.ProjectExists(projectId);
Assert.IsFalse(exists);
}
}
#endregion
#region GetProject() method tests
/// <summary>
/// Unit tests for the <see cref="GetProject"/> method.
/// </summary>
[TestFixture]
public class GetProject : AuthenticatedProjectManagerTestBase
{
private Project _project = null;
/// <summary>
/// Tests result when an invalid identifier is used.
/// </summary>
/// <remarks>
/// Test written with the expectation of an <see cref="ObjectNotFoundException"/>
/// even though a Data Portal exception will actually occur.
/// </remarks>
[Test]
[ExpectedException(typeof(ObjectNotFoundException))]
public void InvalidProjectId()
{
try
{
// Try and get the project using an invalid identifier
Guid projectId = Guid.Empty;
_project = Project.GetProject(projectId);
}
catch (Exception ex)
{
// The [ObjectNotFoundException] is nested inside 2 Data Portal exceptions
if (!ReferenceEquals(ex.InnerException, null))
if (!ReferenceEquals(ex.InnerException.InnerException, null))
throw ex.InnerException.InnerException;
// If there were no inner exceptions then something else went wrong...
// ...so just throw the original Exception
throw;
}
}
[Test]
public void Existing()
{
// Create an existing project
Project existingProject = ProjectFactory.ExistingProject();
// Get the Project to a different variable
Guid projectId = existingProject.Id;
_project = Project.GetProject(projectId);
// Check objects match
Assert.IsNotNull(_project);
Assert.AreEqual(existingProject.Id, _project.Id);
// Check CSLA properties
Assert.IsFalse(_project.IsDeleted);
Assert.IsFalse(_project.IsDirty);
Assert.IsFalse(_project.IsNew);
Assert.IsFalse(_project.IsSavable);
Assert.IsTrue(_project.IsValid);
}
[Test]
public void ExistingWithResource()
{
// Create an existing project
Project existingProject = ProjectFactory.ExistingProjectWithResource();
// Get the resource
// Get the Project to a different variable
Guid projectId = existingProject.Id;
_project = Project.GetProject(projectId);
// Check objects match
Assert.IsNotNull(_project);
Assert.AreEqual(existingProject.Id, _project.Id);
// Check CSLA properties
Assert.IsFalse(_project.IsDeleted);
Assert.IsFalse(_project.IsDirty);
Assert.IsFalse(_project.IsNew);
Assert.IsFalse(_project.IsSavable);
Assert.IsTrue(_project.IsValid);
// Check child object
Assert.IsNotNull(_project.Resources);
Assert.Greater(_project.Resources.Count, 0);
}
}
#endregion
#region NewProject() method tests
/// <summary>
/// Unit tests for the <see cref="NewProject"/> method.
/// </summary>
[TestFixture]
public class NewProject : AuthenticatedProjectManagerTestBase
{
/// <summary>
/// Unit test for the parameterless <see cref="NewProject"/> factory method.
/// </summary>
/// <remarks>
/// Checks some key CSLA properties are set correctly after initialization.
/// Values for IsValid and IsSavable are specific to each BO based on the BusinessRules used.
/// </remarks>
[Test]
public void Parameterless()
{
Project project = Project.NewProject();
Assert.IsNotNull(project);
Assert.IsTrue(project.IsNew);
Assert.IsTrue(project.IsDirty);
Assert.IsFalse(project.IsDeleted);
Assert.IsFalse(project.IsValid);
Assert.IsFalse(project.IsSavable);
}
}
#endregion
#region Save() method tests
/// <summary>
/// Unit tests for the <see cref="Save"/> method.
/// </summary>
[TestFixture]
public class Save : BusinessTestBase<Project>
{
#region Save() method unit tests with a new instance
[Test]
public void WithNewInstanceWithNoAssignments()
{
BusinessObject = ProjectFactory.NewProject();
SaveBusinessObject();
}
/// <summary>
/// This test verifies the NHibernate version control is working correctly.
/// </summary>
[Test]
public void WithNewInstanceWithNoAssignmentsThenEditSameInstance()
{
// Execute the code that adds a new instance
WithNewInstanceWithNoAssignments();
// Save the version number
int savedVersion = BusinessObject.Version;
// Change some data and save it
BusinessObject.Description = "Description revised by NUnit";
SaveBusinessObject();
// Test that the version number has changed
Assert.AreNotEqual(savedVersion, BusinessObject.Version);
}
[Test]
public void WithNewInstanceWithResource()
{
BusinessObject = ProjectFactory.NewProjectWithResource();
SaveBusinessObject();
}
[Test]
public void WithNewInstanceWithAssignmentsThenEditSameInstance()
{
// Execute the code that adds a new instance with a resource
WithNewInstanceWithResource();
// Save the version number of the instances
int savedBusinessObjectVersion = BusinessObject.Version;
int savedAssignmentVersion = BusinessObject.Resources[0].Version;
// Change the role of the Resource
BusinessObject.Resources[0].Role += 1;
// Check the objects are "dirty"
Assert.IsTrue(BusinessObject.Resources[0].IsDirty);
Assert.IsTrue(BusinessObject.IsDirty);
// Save the BO again
SaveBusinessObject();
// Test that the version number is the same for the root BO...
Assert.AreEqual(savedBusinessObjectVersion, BusinessObject.Version);
// ... but different for the Assignment that changed
Assert.AreNotEqual(savedAssignmentVersion, BusinessObject.Resources[0].Version);
}
#endregion
#region Save() method tests with an existing instance with (child) resources doing a deferred delete
[Test]
public void ExistingThenDeferredDeleteParent()
{
// Get a Project that exists in the database (no children)
Project project = ProjectFactory.ExistingProject();
// Save the ID for use later
Guid projectId = project.Id;
// Mark the project for "deferred" deletion
project.Delete();
// Now call the Save(), which will actually delete the object
project = project.Save();
Assert.IsNotNull(project);
// Check the instance returned by the Save()...
// ... has no (child) resources ...
Assert.AreEqual(0, project.Resources.Count);
// ... is marked as "new" ...
Assert.IsTrue(project.IsNew);
// Check the database to see if the Project exists there
bool exists = ProjectFactory.ProjectExists(projectId);
Assert.IsFalse(exists);
}
[Test]
public void ExistingWithResourceThenDeferredDeleteParent()
{
// Get a Project that exists in the database (with children)
Project project = ProjectFactory.ExistingProjectWithResource();
// Save the ID for use later
Guid projectId = project.Id;
// Mark the project for "deferred" deletion
project.Delete();
// Now call the Save(), which will actually delete the object
project = project.Save();
Assert.IsNotNull(project);
// Check the instance returned by the Save()...
// ... has no (child) resources ...
Assert.AreEqual(0, project.Resources.Count);
// ... is marked as "new" ...
Assert.IsTrue(project.IsNew);
// Check the database to see if the Project exists there
bool exists = ProjectFactory.ProjectExists(projectId);
Assert.IsFalse(exists);
}
[Test]
public void ExistingWithResourceThenDeferredDeleteChild()
{
// Get an existing object with assignments
Project project = ProjectFactory.ExistingProjectWithResource();
// Save the ID for use later
Guid projectId = project.Id;
// Remove the (child) Resource (i.e. a child deferred delete)
int resourceId = project.Resources[0].ResourceId;
project.Resources.Remove(resourceId);
// Now call the Save(), which will actually delete the object
project = project.Save();
Assert.IsNotNull(project);
// Check the instance returned by the Save()...
// ... has no (child) resources ...
Assert.AreEqual(0, project.Resources.Count);
// ... is marked as "old" ...
Assert.IsFalse(project.IsNew);
// And finally do a double check, by getting the project from the DB again ...
project = Project.GetProject(projectId);
Assert.IsNotNull(project);
// ... and check there are no (child) resources
Assert.AreEqual(0, project.Resources.Count);
}
#endregion
}
#endregion
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System.Collections.Generic;
using System.Linq;
using SIO = System.IO;
using NUnit.Framework;
using NSubstitute;
using NUnit.Engine.Internal.FileSystemAccess;
namespace NUnit.Engine.Internal
{
public class DirectoryFinderTests
{
private Dictionary<string, IDirectory> fakedDirectories;
private Dictionary<string, IFile> fakedFiles;
private IFileSystem fileSystem;
[SetUp]
public void CreateFileSystem()
{
var directories = new[]
{
"tools/frobuscator/tests/abc",
"tools/frobuscator/tests/def",
"tools/metamorphosator/addins/empty",
"tools/metamorphosator/addins/morph",
"tools/metamorphosator/tests/v1",
"tools/metamorphosator/tests/v1/tmp",
"tools/metamorphosator/tests/v2"
};
var files = new[]
{
"tools/frobuscator/tests/config.cfg",
"tools/frobuscator/tests/abc/tests.abc.dll",
"tools/frobuscator/tests/abc/tests.123.dll",
"tools/frobuscator/tests/def/tests.def.dll",
"tools/metamorphosator/addins/readme.txt",
"tools/metamorphosator/addins/morph/setup.ini",
"tools/metamorphosator/addins/morph/code.cs",
"tools/metamorphosator/tests/v1/test-assembly.dll",
"tools/metamorphosator/tests/v1/test-assembly.pdb",
"tools/metamorphosator/tests/v1/result.xml",
"tools/metamorphosator/tests/v1/tmp/tmp.dat",
"tools/metamorphosator/tests/v2/test-assembly.dll",
"tools/metamorphosator/tests/v2/test-assembly.pdb",
"tools/metamorphosator/tests/v2/result.xml",
};
this.fileSystem = Substitute.For<IFileSystem>();
this.fakedDirectories = new Dictionary<string, IDirectory>();
// Create fakes and configure their properties.
this.fakedDirectories[GetRoot()] = Substitute.For<IDirectory>();
this.fakedDirectories[GetRoot()].FullName.Returns(GetRoot());
foreach (var path in directories)
{
var parts = path.Split('/');
for (var i = 0; i < parts.Length; i++)
{
var absolutePath = CreateAbsolutePath(parts.Take(i+1));
if (!fakedDirectories.ContainsKey(absolutePath))
{
var fake = Substitute.For<IDirectory>();
fake.FullName.Returns(absolutePath);
fake.Parent.Returns(i == 0 ? fakedDirectories[GetRoot()] : fakedDirectories[CreateAbsolutePath(parts.Take(i))]);
fakedDirectories.Add(absolutePath, fake);
this.fileSystem.GetDirectory(absolutePath).Returns(fake);
}
}
}
foreach (var directory in this.fakedDirectories.Values)
{
directory.GetDirectories("*", SIO.SearchOption.AllDirectories).Returns(this.fakedDirectories.Where(kvp => kvp.Key.StartsWith(directory.FullName + SIO.Path.DirectorySeparatorChar)).Select(kvp => kvp.Value));
directory.GetDirectories("*", SIO.SearchOption.TopDirectoryOnly)
.Returns(this.fakedDirectories
.Where(kvp => kvp.Key.StartsWith(directory.FullName + SIO.Path.DirectorySeparatorChar) && kvp.Key.LastIndexOf(SIO.Path.DirectorySeparatorChar) <= directory.FullName.Length)
.Select(kvp => kvp.Value));
// NSubstitute will automatically return empty enumerables for calls that were not set up.
}
this.fakedFiles = new Dictionary<string, IFile>();
foreach (var filePath in files)
{
var fileName = filePath.Split('/').Reverse().Take(1);
var directory = GetFakeDirectory(filePath.Split('/').Reverse().Skip(1).Reverse().ToArray());
var file = Substitute.For<IFile>();
file.FullName.Returns(CreateAbsolutePath(filePath.Split('/')));
file.Parent.Returns(directory);
this.fakedFiles.Add(file.FullName, file);
}
foreach (var directory in this.fakedDirectories.Values)
{
var directoryContent = this.fakedFiles.Values.Where(x => x.Parent == directory).ToArray();
directory.GetFiles("*").Returns(directoryContent);
}
}
[Test]
public void GetDirectories_Asterisk_Tools()
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools");
var expected = new[] { CombinePath(baseDir.FullName, "metamorphosator"), CombinePath(baseDir.FullName, "frobuscator") };
var result = finder.GetDirectories(baseDir, "*");
var actual = result.Select(x => x.FullName);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories("*", SIO.SearchOption.TopDirectoryOnly);
this.GetFakeDirectory("tools", "frobuscator").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
this.GetFakeDirectory("tools", "metamorphosator").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
}
[Test]
public void GetDirectories_Asterisk_Metamorphosator()
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "metamorphosator");
var expected = new[] { CombinePath(baseDir.FullName, "addins"), CombinePath(baseDir.FullName, "tests") };
var result = finder.GetDirectories(baseDir, "*");
var actual = result.Select(x => x.FullName);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
this.GetFakeDirectory("tools", "frobuscator").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
this.GetFakeDirectory("tools", "metamorphosator", "addins").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
this.GetFakeDirectory("tools", "metamorphosator", "tests").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
}
[Test]
public void GetDirectories_Greedy_Tools()
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools");
var expected = this.fakedDirectories.Values.Select(x => x.FullName).Where(x => x != GetRoot());
var result = finder.GetDirectories(baseDir, "**");
var actual = result.Select(x => x.FullName);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories("*", SIO.SearchOption.AllDirectories);
this.GetFakeDirectory("tools", "frobuscator").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
this.GetFakeDirectory("tools", "metamorphosator").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
}
[Test]
public void GetDirectories_Greedy_Metamorphosator()
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "metamorphosator");
var expected = new[]
{
CombinePath(baseDir.FullName),
CombinePath(baseDir.FullName, "addins"),
CombinePath(baseDir.FullName, "tests"),
CombinePath(baseDir.FullName, "tests", "v1"),
CombinePath(baseDir.FullName, "tests", "v1", "tmp"),
CombinePath(baseDir.FullName, "tests", "v2"),
CombinePath(baseDir.FullName, "addins", "morph"),
CombinePath(baseDir.FullName, "addins", "empty")
};
var result = finder.GetDirectories(baseDir, "**");
var actual = result.Select(x => x.FullName);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories("*", SIO.SearchOption.AllDirectories);
this.GetFakeDirectory("tools", "frobuscator").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
}
[TestCase("*ddi*")]
[TestCase("addi*")]
[TestCase("addins")]
public void GetDirectories_WordWithWildcard_NoMatch(string pattern)
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools");
var result = finder.GetDirectories(baseDir, pattern);
Assert.That(result, Is.Empty);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories(pattern, SIO.SearchOption.TopDirectoryOnly);
}
[TestCase("*din*")]
[TestCase("addi*")]
[TestCase("addins")]
[TestCase("a?dins")]
[TestCase("a?din?")]
public void GetDirectories_WordWithWildcard_OneMatch(string pattern)
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "metamorphosator");
baseDir.GetDirectories(pattern, SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { this.GetFakeDirectory("tools", "metamorphosator", "addins") });
var expected = new[] { CombinePath(baseDir.FullName, "addins") };
var result = finder.GetDirectories(baseDir, pattern);
var actual = result.Select(x => x.FullName);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories(pattern, SIO.SearchOption.TopDirectoryOnly);
}
[TestCase("v*")]
[TestCase("*")]
[TestCase("v?")]
public void GetDirectories_WordWithWildcard_MultipleMatches(string pattern)
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "metamorphosator", "tests");
baseDir.GetDirectories(pattern, SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1"), this.GetFakeDirectory("tools", "metamorphosator", "tests", "v2") });
var expected = new[] { CombinePath(baseDir.FullName, "v1"), CombinePath(baseDir.FullName, "v2") };
var result = finder.GetDirectories(baseDir, pattern);
var actual = result.Select(x => x.FullName);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories(pattern, SIO.SearchOption.TopDirectoryOnly);
}
[TestCase("tests/v*")]
[TestCase("tests/*")]
[TestCase("tests/v?")]
[TestCase("*/v*")]
[TestCase("*/v?")]
[TestCase("**/v*")]
[TestCase("**/v?")]
[TestCase("te*/v*")]
[TestCase("te*/*")]
[TestCase("te*/v?")]
[TestCase("t?sts/v*")]
[TestCase("t?sts/*")]
[TestCase("t?sts/v?")]
[TestCase("./tests/v*")]
[TestCase("./tests/*")]
[TestCase("./tests/v?")]
[TestCase("./*/v*")]
[TestCase("./*/v?")]
[TestCase("./**/v*")]
[TestCase("./**/v?")]
[TestCase("./te*/v*")]
[TestCase("./te*/*")]
[TestCase("./te*/v?")]
[TestCase("./t?sts/v*")]
[TestCase("./t?sts/*")]
[TestCase("./t?sts/v?")]
[TestCase("**/tests/v*")]
[TestCase("**/tests/*")]
[TestCase("**/tests/v?")]
[TestCase("**/*/v*")]
[TestCase("**/*/v?")]
[TestCase("**/te*/v*")]
[TestCase("**/te*/*")]
[TestCase("**/te*/v?")]
[TestCase("**/t?sts/v*")]
[TestCase("**/t?sts/*")]
[TestCase("**/t?sts/v?")]
public void GetDirectories_MultipleComponents_MultipleMatches(string pattern)
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "metamorphosator");
var testsDir = this.GetFakeDirectory("tools", "metamorphosator", "tests");
var baseDirContent = new[] { testsDir };
var testsDirContent = new[] { this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1"), this.GetFakeDirectory("tools", "metamorphosator", "tests", "v2") };
baseDir.GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly).Returns(baseDirContent);
baseDir.GetDirectories("te*", SIO.SearchOption.TopDirectoryOnly).Returns(baseDirContent);
baseDir.GetDirectories("t?sts", SIO.SearchOption.TopDirectoryOnly).Returns(baseDirContent);
testsDir.GetDirectories("v*", SIO.SearchOption.TopDirectoryOnly).Returns(testsDirContent);
testsDir.GetDirectories("*", SIO.SearchOption.TopDirectoryOnly).Returns(testsDirContent);
testsDir.GetDirectories("v?", SIO.SearchOption.TopDirectoryOnly).Returns(testsDirContent);
var expected = new[] { CombinePath(baseDir.FullName, "tests", "v1"), CombinePath(baseDir.FullName, "tests", "v2") };
var result = finder.GetDirectories(baseDir, pattern);
var actual = result.Select(x => x.FullName);
CollectionAssert.AreEquivalent(expected, actual);
}
[TestCase("*/tests/v*")]
[TestCase("**/tests/v*")]
public void GetDirectories_MultipleComponents_MultipleMatches_Asterisk(string pattern)
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools");
var frobuscatorDir = this.GetFakeDirectory("tools", "frobuscator");
var metamorphosatorDir = this.GetFakeDirectory("tools", "metamorphosator");
var testsDir = this.GetFakeDirectory("tools", "frobuscator", "tests");
var testsDir2 = this.GetFakeDirectory("tools", "metamorphosator", "tests");
frobuscatorDir.GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { testsDir });
metamorphosatorDir.GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { testsDir2 });
testsDir2.GetDirectories("v*", SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1"), this.GetFakeDirectory("tools", "metamorphosator", "tests", "v2") });
testsDir2.GetDirectories("v?", SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1"), this.GetFakeDirectory("tools", "metamorphosator", "tests", "v2") });
var expected = new[] { CombinePath(baseDir.FullName, "metamorphosator", "tests", "v1"), CombinePath(baseDir.FullName, "metamorphosator", "tests", "v2") };
var result = finder.GetDirectories(baseDir, pattern);
var actual = result.Select(x => x.FullName);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
testsDir.Received().GetDirectories("v*", SIO.SearchOption.TopDirectoryOnly);
}
[TestCase("*/tests/v?")]
[TestCase("**/tests/v?")]
public void GetDirectories_MultipleComponents_MultipleMatches_QuestionMark(string pattern)
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools");
var frobuscatorDir = this.GetFakeDirectory("tools", "frobuscator");
var metamorphosatorDir = this.GetFakeDirectory("tools", "metamorphosator");
var testsDir = this.GetFakeDirectory("tools", "frobuscator", "tests");
var testsDir2 = this.GetFakeDirectory("tools", "metamorphosator", "tests");
frobuscatorDir.GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { testsDir });
metamorphosatorDir.GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { testsDir2 });
testsDir2.GetDirectories("v*", SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1"), this.GetFakeDirectory("tools", "metamorphosator", "tests", "v2") });
testsDir2.GetDirectories("v?", SIO.SearchOption.TopDirectoryOnly).Returns(new IDirectory[] { this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1"), this.GetFakeDirectory("tools", "metamorphosator", "tests", "v2") });
var expected = new[] { CombinePath(baseDir.FullName, "metamorphosator", "tests", "v1"), CombinePath(baseDir.FullName, "metamorphosator", "tests", "v2") };
var result = finder.GetDirectories(baseDir, pattern);
var actual = result.Select(x => x.FullName);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
testsDir.Received().GetDirectories("v?", SIO.SearchOption.TopDirectoryOnly);
}
[TestCase("./**/*")]
[TestCase("**/*")]
public void GetDirectories_MultipleComponents_AllDirectories(string pattern)
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.fakedDirectories[GetRoot()];
var expected = this.fakedDirectories.Values.Where(x => x != baseDir);
var actual = finder.GetDirectories(baseDir, pattern);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories("*", SIO.SearchOption.AllDirectories);
foreach (var dir in this.fakedDirectories.Values.Where(x => x != baseDir))
{
dir.Received().GetDirectories("*", SIO.SearchOption.TopDirectoryOnly);
}
}
[Test]
public void GetDirectories_GreedyThenWordThenGreedy()
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools");
this.GetFakeDirectory("tools", "frobuscator").GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly).Returns(new[] { this.GetFakeDirectory("tools", "frobuscator", "tests") });
this.GetFakeDirectory("tools", "metamorphosator").GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly).Returns(new[] { this.GetFakeDirectory("tools", "metamorphosator", "tests") });
var expected = new[]
{
this.GetFakeDirectory("tools", "frobuscator", "tests"),
this.GetFakeDirectory("tools", "frobuscator", "tests", "abc"),
this.GetFakeDirectory("tools", "frobuscator", "tests", "def"),
this.GetFakeDirectory("tools", "metamorphosator", "tests"),
this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1"),
this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1", "tmp"),
this.GetFakeDirectory("tools", "metamorphosator", "tests", "v2")
};
var actual = finder.GetDirectories(baseDir, "**/tests/**");
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories("*", SIO.SearchOption.AllDirectories);
this.GetFakeDirectory("tools", "frobuscator").Received().GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly);
this.GetFakeDirectory("tools", "metamorphosator").Received().GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly);
this.GetFakeDirectory("tools", "frobuscator", "tests").Received().GetDirectories("*", SIO.SearchOption.AllDirectories);
this.GetFakeDirectory("tools", "metamorphosator", "tests").Received().GetDirectories("*", SIO.SearchOption.AllDirectories);
}
[Test]
public void GetDirectories_WordWithAsteriskThenGreedyThenWord()
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools");
baseDir.GetDirectories("meta*", SIO.SearchOption.TopDirectoryOnly).Returns(new[] { this.GetFakeDirectory("tools", "metamorphosator") });
this.GetFakeDirectory("tools", "metamorphosator", "tests").GetDirectories("v1", SIO.SearchOption.TopDirectoryOnly).Returns(new[] { this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1") });
this.GetFakeDirectory("tools", "metamorphosator").GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly).Returns(new[] { this.GetFakeDirectory("tools", "metamorphosator", "tests") });
var expected = new[] { this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1") };
var actual = finder.GetDirectories(baseDir, "meta*/**/v1");
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Received().GetDirectories("meta*", SIO.SearchOption.TopDirectoryOnly);
this.GetFakeDirectory("tools", "frobuscator").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
this.GetFakeDirectory("tools", "metamorphosator").Received().GetDirectories("*", SIO.SearchOption.AllDirectories);
this.GetFakeDirectory("tools", "metamorphosator", "tests").Received().GetDirectories("v1", SIO.SearchOption.TopDirectoryOnly);
}
[Test]
public void GetDirectories_Parent()
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "frobuscator");
var expected = new[] { this.GetFakeDirectory("tools") };
var actual = finder.GetDirectories(baseDir, "../");
CollectionAssert.AreEquivalent(expected, actual);
baseDir.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
}
[Test]
public void GetDirectories_ParentThenParentThenWordThenWord()
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "frobuscator", "tests");
this.GetFakeDirectory("tools").GetDirectories("metamorphosator", SIO.SearchOption.TopDirectoryOnly).Returns(new[] { this.GetFakeDirectory("tools", "metamorphosator") });
this.GetFakeDirectory("tools", "metamorphosator").GetDirectories("addins", SIO.SearchOption.TopDirectoryOnly).Returns(new[] { this.GetFakeDirectory("tools", "metamorphosator", "addins") });
var expected = new[] { this.GetFakeDirectory("tools", "metamorphosator", "addins") };
var actual = finder.GetDirectories(baseDir, "../../metamorphosator/addins");
CollectionAssert.AreEquivalent(expected, actual);
baseDir.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
baseDir.Parent.Parent.Received().GetDirectories("metamorphosator", SIO.SearchOption.TopDirectoryOnly);
this.GetFakeDirectory("tools", "metamorphosator").Received().GetDirectories("addins", SIO.SearchOption.TopDirectoryOnly);
}
[Test]
public void GetDirectories_StartDirectoryIsNull()
{
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
Assert.That(() => finder.GetDirectories((IDirectory)null, "notused"), Throws.ArgumentNullException.With.Message.Contains(" startDirectory "));
}
[Test]
public void GetDirectories_PatternIsNull()
{
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
Assert.That(() => finder.GetDirectories(Substitute.For<IDirectory>(), null), Throws.ArgumentNullException.With.Message.Contains(" pattern "));
}
[Test]
public void GetDirectories_PatternIsEmpty()
{
var directory = Substitute.For<IDirectory>();
var sut = new DirectoryFinder(Substitute.For<IFileSystem>());
var directories = sut.GetDirectories(directory, string.Empty);
Assert.That(directories, Has.Count.EqualTo(1));
Assert.That(directories.First(), Is.EqualTo(directory));
}
[TestCase("tests.*.dll")]
[TestCase("tests.???.dll")]
[TestCase("t*.???.dll")]
public void GetFiles_WordWithWildcard(string pattern)
{
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "frobuscator", "tests", "abc");
baseDir.GetFiles(pattern).Returns(new[] { this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.abc.dll"), this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.123.dll") });
var expected = new[] { this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.abc.dll"), this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.123.dll") };
var actual = finder.GetFiles(baseDir, pattern);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Received().GetFiles(pattern);
baseDir.Parent.DidNotReceive().GetFiles(Arg.Any<string>());
}
[TestCase("*/tests.*.dll")]
[TestCase("*/tests.???.dll")]
[TestCase("*/t*.???.dll")]
public void GetFiles_AsteriskThenWordWithWildcard(string pattern)
{
var filePattern = pattern.Split('/')[1];
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "frobuscator", "tests");
var abcDir = this.GetFakeDirectory("tools", "frobuscator", "tests", "abc");
var defDir = this.GetFakeDirectory("tools", "frobuscator", "tests", "def");
abcDir.GetFiles(filePattern).Returns(new[] { this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.abc.dll"), this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.123.dll") });
defDir.GetFiles(filePattern).Returns(new[] { this.GetFakeFile("tools", "frobuscator", "tests", "def", "tests.def.dll") });
var expected = new[] { this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.abc.dll"), this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.123.dll"), this.GetFakeFile("tools", "frobuscator", "tests", "def", "tests.def.dll") };
var actual = finder.GetFiles(baseDir, pattern);
CollectionAssert.AreEquivalent(expected, actual);
abcDir.Received().GetFiles(filePattern);
defDir.Received().GetFiles(filePattern);
baseDir.Parent.DidNotReceive().GetFiles(Arg.Any<string>());
baseDir.DidNotReceive().GetFiles(Arg.Any<string>());
abcDir.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
defDir.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
}
[TestCase("**/test*.dll")]
[TestCase("**/t*.???")]
public void GetFiles_GreedyThenWordWithWildcard(string pattern)
{
var filePattern = pattern.Split('/')[1];
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools");
var abcDir = this.GetFakeDirectory("tools", "frobuscator", "tests", "abc");
var defDir = this.GetFakeDirectory("tools", "frobuscator", "tests", "def");
var v1Dir = this.GetFakeDirectory("tools", "metamorphosator", "tests", "v1");
var v2Dir = this.GetFakeDirectory("tools", "metamorphosator", "tests", "v2");
abcDir.GetFiles(filePattern).Returns(new[] { this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.abc.dll"), this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.123.dll") });
defDir.GetFiles(filePattern).Returns(new[] { this.GetFakeFile("tools", "frobuscator", "tests", "def", "tests.def.dll") });
v1Dir.GetFiles(filePattern).Returns(new[] { this.GetFakeFile("tools", "metamorphosator", "tests", "v1", "test-assembly.dll"), this.GetFakeFile("tools", "metamorphosator", "tests", "v1", "test-assembly.pdb") });
v2Dir.GetFiles(filePattern).Returns(new[] { this.GetFakeFile("tools", "metamorphosator", "tests", "v2", "test-assembly.dll"), this.GetFakeFile("tools", "metamorphosator", "tests", "v2", "test-assembly.pdb") });
var expected = new[]
{
this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.abc.dll"),
this.GetFakeFile("tools", "frobuscator", "tests", "abc", "tests.123.dll"),
this.GetFakeFile("tools", "frobuscator", "tests", "def", "tests.def.dll"),
this.GetFakeFile("tools", "metamorphosator", "tests", "v1", "test-assembly.dll"),
this.GetFakeFile("tools", "metamorphosator", "tests", "v1", "test-assembly.pdb"),
this.GetFakeFile("tools", "metamorphosator", "tests", "v2", "test-assembly.dll"),
this.GetFakeFile("tools", "metamorphosator", "tests", "v2", "test-assembly.pdb")
};
var actual = finder.GetFiles(baseDir, pattern);
CollectionAssert.AreEquivalent(expected, actual);
foreach (var dir in this.fakedDirectories.Values.Where(x => x.FullName != GetRoot()))
{
dir.Received().GetFiles(filePattern);
}
baseDir.Parent.DidNotReceive().GetFiles(Arg.Any<string>());
abcDir.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
defDir.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
v1Dir.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
v2Dir.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
}
[Test]
public void GetFiles_WordThenParentThenWordWithWildcardThenWord()
{
var filename = "readme.txt";
var pattern = "tests/../addin?/" + filename;
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "metamorphosator");
var targetDir = this.GetFakeDirectory("tools", "metamorphosator", "addins");
baseDir.GetDirectories("tests", SIO.SearchOption.TopDirectoryOnly).Returns(new[] { this.GetFakeDirectory("tools", "metamorphosator", "tests") });
this.GetFakeDirectory("tools", "metamorphosator").GetDirectories("addin?", SIO.SearchOption.TopDirectoryOnly).Returns(new[] { targetDir });
targetDir.GetFiles(filename).Returns(new[] { this.GetFakeFile("tools", "metamorphosator", "addins", filename) });
var expected = new[] { this.GetFakeFile("tools", "metamorphosator", "addins", filename) };
var actual = finder.GetFiles(baseDir, pattern);
CollectionAssert.AreEquivalent(expected, actual);
targetDir.Received().GetFiles(filename);
foreach (var dir in this.fakedDirectories.Values.Where(x => x != targetDir))
{
dir.DidNotReceive().GetFiles(Arg.Any<string>());
}
targetDir.Received().GetFiles(filename);
targetDir.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
GetFakeDirectory("tools", "frobuscator").DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
}
[Test]
public void GetFiles_CurrentDirThenAsterisk()
{
var pattern = "./*";
var finder = new DirectoryFinder(this.fileSystem);
var baseDir = this.GetFakeDirectory("tools", "metamorphosator", "addins", "morph");
var expected = new[] { this.GetFakeFile("tools", "metamorphosator", "addins", "morph", "setup.ini"), this.GetFakeFile("tools", "metamorphosator", "addins", "morph", "code.cs") };
baseDir.GetFiles("*").Returns(expected);
var actual = finder.GetFiles(baseDir, pattern);
CollectionAssert.AreEquivalent(expected, actual);
baseDir.Received().GetFiles("*");
baseDir.Parent.DidNotReceive().GetFiles(Arg.Any<string>());
baseDir.Parent.DidNotReceive().GetDirectories(Arg.Any<string>(), Arg.Any<SIO.SearchOption>());
}
[Test]
public void GetFiles_StartDirectoryIsNull()
{
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
Assert.That(() => finder.GetFiles((IDirectory)null, "notused"), Throws.ArgumentNullException.With.Message.Contains(" startDirectory "));
}
[Test]
public void GetFiles_PatternIsNull()
{
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
Assert.That(() => finder.GetDirectories(Substitute.For<IDirectory>(), null), Throws.ArgumentNullException.With.Message.Contains(" pattern "));
}
[Test]
public void GetFiles_PatternIsEmpty()
{
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
Assert.That(() => finder.GetFiles(Substitute.For<IDirectory>(), string.Empty), Throws.ArgumentException.With.Message.Contains(" pattern "));
}
private static string CreateAbsolutePath(IEnumerable<string> parts)
{
return CreateAbsolutePath(parts.ToArray());
}
private static string CreateAbsolutePath(params string[] parts)
{
string relativePath = CombinePath(parts);
return SIO.Path.DirectorySeparatorChar == '\\' ? "c:\\" + relativePath : "/" + relativePath;
}
private IDirectory GetFakeDirectory(params string[] parts)
{
return this.fakedDirectories[CreateAbsolutePath(parts)];
}
private IFile GetFakeFile(params string[] parts)
{
return this.fakedFiles[CreateAbsolutePath(parts)];
}
private static string CombinePath(params string[] parts)
{
var path = parts[0];
for (int i = 1; i < parts.Length; i++)
{
path = SIO.Path.Combine(path, parts[i]);
}
return path;
}
private static string GetRoot()
{
if (SIO.Path.DirectorySeparatorChar == '\\')
{
return "c:";
}
else
{
return string.Empty;
}
}
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.Management.Automation.Tracing;
using System.IO;
using System.Threading;
using System.Security.Principal;
using System.Management.Automation.Internal;
using Microsoft.Win32.SafeHandles;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting.Server
{
internal abstract class OutOfProcessMediatorBase
{
#region Protected Data
protected TextReader originalStdIn;
protected OutOfProcessTextWriter originalStdOut;
protected OutOfProcessTextWriter originalStdErr;
protected OutOfProcessServerSessionTransportManager sessionTM;
protected OutOfProcessUtils.DataProcessingDelegates callbacks;
protected static object SyncObject = new object();
protected object _syncObject = new object();
protected string _initialCommand;
protected ManualResetEvent allcmdsClosedEvent;
// Thread impersonation.
protected WindowsIdentity _windowsIdentityToImpersonate;
/// <summary>
/// Count of commands in progress
/// </summary>
protected int _inProgressCommandsCount = 0;
protected PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource();
protected bool _exitProcessOnError;
#endregion
#region Constructor
protected OutOfProcessMediatorBase(bool exitProcessOnError)
{
_exitProcessOnError = exitProcessOnError;
// Set up data handling callbacks.
callbacks = new OutOfProcessUtils.DataProcessingDelegates();
callbacks.DataPacketReceived += new OutOfProcessUtils.DataPacketReceived(OnDataPacketReceived);
callbacks.DataAckPacketReceived += new OutOfProcessUtils.DataAckPacketReceived(OnDataAckPacketReceived);
callbacks.CommandCreationPacketReceived += new OutOfProcessUtils.CommandCreationPacketReceived(OnCommandCreationPacketReceived);
callbacks.CommandCreationAckReceived += new OutOfProcessUtils.CommandCreationAckReceived(OnCommandCreationAckReceived);
callbacks.ClosePacketReceived += new OutOfProcessUtils.ClosePacketReceived(OnClosePacketReceived);
callbacks.CloseAckPacketReceived += new OutOfProcessUtils.CloseAckPacketReceived(OnCloseAckPacketReceived);
callbacks.SignalPacketReceived += new OutOfProcessUtils.SignalPacketReceived(OnSignalPacketReceived);
callbacks.SignalAckPacketReceived += new OutOfProcessUtils.SignalAckPacketReceived(OnSignalAckPacketReceived);
allcmdsClosedEvent = new ManualResetEvent(true);
}
#endregion
#region Data Processing handlers
protected void ProcessingThreadStart(object state)
{
try
{
#if !CORECLR
// CurrentUICulture is not available in Thread Class in CSS
// WinBlue: 621775. Thread culture is not properly set
// for local background jobs causing experience differences
// between local console and local background jobs.
Thread.CurrentThread.CurrentUICulture = Microsoft.PowerShell.NativeCultureResolver.UICulture;
Thread.CurrentThread.CurrentCulture = Microsoft.PowerShell.NativeCultureResolver.Culture;
#endif
string data = state as string;
OutOfProcessUtils.ProcessData(data, callbacks);
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
PSEtwLog.LogOperationalError(
PSEventId.TransportError, PSOpcode.Open, PSTask.None,
PSKeyword.UseAlwaysOperational,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
PSEtwLog.LogAnalyticError(
PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
// notify the remote client of any errors and fail gracefully
if (_exitProcessOnError)
{
originalStdErr.WriteLine(e.Message + e.StackTrace);
Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION);
}
}
}
protected void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid)
{
string streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_STDIN;
if (stream.Equals(DataPriorityType.PromptResponse.ToString(), StringComparison.OrdinalIgnoreCase))
{
streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE;
}
if (Guid.Empty == psGuid)
{
lock (_syncObject)
{
sessionTM.ProcessRawData(rawData, streamTemp);
}
}
else
{
// this is for a command
AbstractServerTransportManager cmdTM = null;
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
if (null != cmdTM)
{
// not throwing when there is no associated command as the command might have
// legitimately closed while the client is sending data. however the client
// should die after timeout as we are not sending an ACK back.
cmdTM.ProcessRawData(rawData, streamTemp);
}
else
{
// There is no command transport manager to process the input data.
// However, we still need to acknowledge to the client that this input data
// was received. This can happen with some cmdlets such as Select-Object -First
// where the cmdlet completes before all input data is received.
originalStdOut.WriteLine(OutOfProcessUtils.CreateDataAckPacket(psGuid));
}
}
}
protected void OnDataAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_DATA_ACK_TAG);
}
protected void OnCommandCreationPacketReceived(Guid psGuid)
{
lock (_syncObject)
{
sessionTM.CreateCommandTransportManager(psGuid);
if (_inProgressCommandsCount == 0)
allcmdsClosedEvent.Reset();
_inProgressCommandsCount++;
tracer.WriteMessage("OutOfProcessMediator.OnCommandCreationPacketReceived, in progress command count : " + _inProgressCommandsCount + " psGuid : " + psGuid.ToString());
}
}
protected void OnCommandCreationAckReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_COMMAND_ACK_TAG);
}
protected void OnSignalPacketReceived(Guid psGuid)
{
if (psGuid == Guid.Empty)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCNoSignalForSession, RemotingErrorIdStrings.IPCNoSignalForSession,
OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_TAG);
}
else
{
// this is for a command
AbstractServerTransportManager cmdTM = null;
try
{
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
// dont throw if there is no cmdTM as it might have legitimately closed
if (null != cmdTM)
{
cmdTM.Close(null);
}
}
finally
{
// Always send ack signal to avoid hang in client.
originalStdOut.WriteLine(OutOfProcessUtils.CreateSignalAckPacket(psGuid));
}
}
}
protected void OnSignalAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_ACK_TAG);
}
protected void OnClosePacketReceived(Guid psGuid)
{
PowerShellTraceSource tracer = PowerShellTraceSourceFactory.GetTraceSource();
if (psGuid == Guid.Empty)
{
tracer.WriteMessage("BEGIN calling close on session transport manager");
bool waitForAllcmdsClosedEvent = false;
lock (_syncObject)
{
if (_inProgressCommandsCount > 0)
waitForAllcmdsClosedEvent = true;
}
// Wait outside sync lock if required for all cmds to be closed
//
if (waitForAllcmdsClosedEvent)
allcmdsClosedEvent.WaitOne();
lock (_syncObject)
{
tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString());
if (sessionTM != null)
{
// it appears that when closing PowerShell ISE, therefore closing OutOfProcServerMediator, there are 2 Close command requests
// changing PSRP/IPC at this point is too risky, therefore protecting about this duplication
sessionTM.Close(null);
}
tracer.WriteMessage("END calling close on session transport manager");
sessionTM = null;
}
}
else
{
tracer.WriteMessage("Closing command with GUID " + psGuid.ToString());
// this is for a command
AbstractServerTransportManager cmdTM = null;
lock (_syncObject)
{
cmdTM = sessionTM.GetCommandTransportManager(psGuid);
}
// dont throw if there is no cmdTM as it might have legitimately closed
if (null != cmdTM)
{
cmdTM.Close(null);
}
lock (_syncObject)
{
tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be greater than zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString());
_inProgressCommandsCount--;
if (_inProgressCommandsCount == 0)
allcmdsClosedEvent.Set();
}
}
// send close ack
originalStdOut.WriteLine(OutOfProcessUtils.CreateCloseAckPacket(psGuid));
}
protected void OnCloseAckPacketReceived(Guid psGuid)
{
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived,
OutOfProcessUtils.PS_OUT_OF_PROC_CLOSE_ACK_TAG);
}
#endregion
#region Methods
protected OutOfProcessServerSessionTransportManager CreateSessionTransportManager(string configurationName, PSRemotingCryptoHelperServer cryptoHelper)
{
PSSenderInfo senderInfo;
#if !UNIX
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
PSPrincipal userPrincipal = new PSPrincipal(new PSIdentity("", true, currentIdentity.Name, null),
currentIdentity);
senderInfo = new PSSenderInfo(userPrincipal, "http://localhost");
#else
PSPrincipal userPrincipal = new PSPrincipal(new PSIdentity("", true, "", null),
null);
senderInfo = new PSSenderInfo(userPrincipal, "http://localhost");
#endif
OutOfProcessServerSessionTransportManager tm = new OutOfProcessServerSessionTransportManager(originalStdOut, originalStdErr, cryptoHelper);
ServerRemoteSession srvrRemoteSession = ServerRemoteSession.CreateServerRemoteSession(senderInfo,
_initialCommand, tm, configurationName);
return tm;
}
protected void Start(string initialCommand, PSRemotingCryptoHelperServer cryptoHelper, string configurationName = null)
{
_initialCommand = initialCommand;
sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper);
try
{
do
{
string data = originalStdIn.ReadLine();
lock (_syncObject)
{
if (sessionTM == null)
{
sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper);
}
}
if (string.IsNullOrEmpty(data))
{
lock (_syncObject)
{
// give a chance to runspace/pipelines to close (as it looks like the client died
// intermittently)
sessionTM.Close(null);
sessionTM = null;
}
throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived,
RemotingErrorIdStrings.IPCUnknownElementReceived, string.Empty);
}
// process data in a thread pool thread..this way Runspace, Command
// data can be processed concurrently.
#if CORECLR
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessingThreadStart), data);
#else
Utils.QueueWorkItemWithImpersonation(
_windowsIdentityToImpersonate,
new WaitCallback(ProcessingThreadStart),
data);
#endif
} while (true);
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
PSEtwLog.LogOperationalError(
PSEventId.TransportError, PSOpcode.Open, PSTask.None,
PSKeyword.UseAlwaysOperational,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
PSEtwLog.LogAnalyticError(
PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None,
PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
Guid.Empty.ToString(),
Guid.Empty.ToString(),
OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION,
e.Message,
e.StackTrace);
if (_exitProcessOnError)
{
// notify the remote client of any errors and fail gracefully
originalStdErr.WriteLine(e.Message);
Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION);
}
}
}
#endregion
#region Static Methods
internal static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs args)
{
// args can never be null.
Exception exception = (Exception)args.ExceptionObject;
// log the exception to crimson event logs
PSEtwLog.LogOperationalError(PSEventId.AppDomainUnhandledException,
PSOpcode.Close, PSTask.None,
PSKeyword.UseAlwaysOperational,
exception.GetType().ToString(), exception.Message,
exception.StackTrace);
PSEtwLog.LogAnalyticError(PSEventId.AppDomainUnhandledException_Analytic,
PSOpcode.Close, PSTask.None,
PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
exception.GetType().ToString(), exception.Message,
exception.StackTrace);
}
#endregion
}
internal sealed class OutOfProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static OutOfProcessMediator s_singletonInstance;
#endregion
#region Constructors
/// <summary>
/// The mediator will take actions from the StdIn stream and responds to them.
/// It will replace StdIn,StdOut and StdErr stream with TextWriter.Null's. This is
/// to make sure these streams are totally used by our Mediator.
/// </summary>
private OutOfProcessMediator() : base(true)
{
// Create input stream reader from Console standard input stream.
// We don't use the provided Console.In TextReader because it can have
// an incorrect encoding, e.g., Hyper-V Container console where the
// TextReader has incorrect default console encoding instead of the actual
// stream encoding. This way the stream encoding is determined by the
// stream BOM as needed.
originalStdIn = new StreamReader(Console.OpenStandardInput(), true);
// replacing StdIn with Null so that no other app messes with the
// original stream.
Console.SetIn(TextReader.Null);
// replacing StdOut with Null so that no other app messes with the
// original stream
originalStdOut = new OutOfProcessTextWriter(Console.Out);
Console.SetOut(TextWriter.Null);
// replacing StdErr with Null so that no other app messes with the
// original stream
originalStdErr = new OutOfProcessTextWriter(Console.Error);
Console.SetError(TextWriter.Null);
}
#endregion
#region Static Methods
/// <summary>
/// </summary>
internal static void Run(string initialCommand)
{
lock (SyncObject)
{
if (null != s_singletonInstance)
{
Dbg.Assert(false, "Run should not be called multiple times");
return;
}
s_singletonInstance = new OutOfProcessMediator();
}
#if !CORECLR // AppDomain is not available in CoreCLR
// Setup unhandled exception to log events
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException);
#endif
s_singletonInstance.Start(initialCommand, new PSRemotingCryptoHelperServer());
}
#endregion
}
internal sealed class SSHProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static SSHProcessMediator s_singletonInstance;
#endregion
#region Constructors
private SSHProcessMediator() : base(true)
{
#if !UNIX
var inputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Input);
originalStdIn = new StreamReader(
new FileStream(new SafeFileHandle(inputHandle, false), FileAccess.Read));
var outputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Output);
originalStdOut = new OutOfProcessTextWriter(
new StreamWriter(
new FileStream(new SafeFileHandle(outputHandle, false), FileAccess.Write)));
var errorHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Error);
originalStdErr = new OutOfProcessTextWriter(
new StreamWriter(
new FileStream(new SafeFileHandle(errorHandle, false), FileAccess.Write)));
#else
originalStdIn = new StreamReader(Console.OpenStandardInput(), true);
originalStdOut = new OutOfProcessTextWriter(
new StreamWriter(Console.OpenStandardOutput()));
originalStdErr = new OutOfProcessTextWriter(
new StreamWriter(Console.OpenStandardError()));
#endif
}
#endregion
#region Static Methods
/// <summary>
///
/// </summary>
/// <param name="initialCommand"></param>
internal static void Run(string initialCommand)
{
lock (SyncObject)
{
if (s_singletonInstance != null)
{
Dbg.Assert(false, "Run should not be called multiple times");
return;
}
s_singletonInstance = new SSHProcessMediator();
}
PSRemotingCryptoHelperServer cryptoHelper;
#if !UNIX
cryptoHelper = new PSRemotingCryptoHelperServer();
#else
cryptoHelper = null;
#endif
s_singletonInstance.Start(initialCommand, cryptoHelper);
}
#endregion
}
internal sealed class NamedPipeProcessMediator : OutOfProcessMediatorBase
{
#region Private Data
private static NamedPipeProcessMediator s_singletonInstance;
private readonly RemoteSessionNamedPipeServer _namedPipeServer;
#endregion
#region Properties
internal bool IsDisposed
{
get { return _namedPipeServer.IsDisposed; }
}
#endregion
#region Constructors
private NamedPipeProcessMediator() : base(false) { }
private NamedPipeProcessMediator(
RemoteSessionNamedPipeServer namedPipeServer) : base(false)
{
if (namedPipeServer == null)
{
throw new PSArgumentNullException("namedPipeServer");
}
_namedPipeServer = namedPipeServer;
// Create transport reader/writers from named pipe.
originalStdIn = namedPipeServer.TextReader;
originalStdOut = new OutOfProcessTextWriter(namedPipeServer.TextWriter);
originalStdErr = new NamedPipeErrorTextWriter(namedPipeServer.TextWriter);
// Flow impersonation if requested.
WindowsIdentity currentIdentity = null;
try
{
currentIdentity = WindowsIdentity.GetCurrent();
}
catch (System.Security.SecurityException) { }
_windowsIdentityToImpersonate = ((currentIdentity != null) && (currentIdentity.ImpersonationLevel == TokenImpersonationLevel.Impersonation)) ?
currentIdentity : null;
}
#endregion
#region Static Methods
internal static void Run(
string initialCommand,
RemoteSessionNamedPipeServer namedPipeServer)
{
lock (SyncObject)
{
if (s_singletonInstance != null && !s_singletonInstance.IsDisposed)
{
Dbg.Assert(false, "Run should not be called multiple times, unless the singleton was disposed.");
return;
}
s_singletonInstance = new NamedPipeProcessMediator(namedPipeServer);
}
#if !CORECLR
// AppDomain is not available in CoreCLR
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException);
#endif
s_singletonInstance.Start(initialCommand, new PSRemotingCryptoHelperServer(), namedPipeServer.ConfigurationName);
}
#endregion
}
internal sealed class NamedPipeErrorTextWriter : OutOfProcessTextWriter
{
#region Private Members
private const string _errorPrepend = "__NamedPipeError__:";
#endregion
#region Properties
internal static string ErrorPrepend
{
get { return _errorPrepend; }
}
#endregion
#region Constructors
internal NamedPipeErrorTextWriter(
TextWriter textWriter) : base(textWriter)
{ }
#endregion
#region Base class overrides
internal override void WriteLine(string data)
{
string dataToWrite = (data != null) ? _errorPrepend + data : null;
base.WriteLine(dataToWrite);
}
#endregion
}
internal sealed class HyperVSocketMediator : OutOfProcessMediatorBase
{
#region Private Data
private static HyperVSocketMediator s_instance;
private readonly RemoteSessionHyperVSocketServer _hypervSocketServer;
#endregion
#region Properties
internal bool IsDisposed
{
get { return _hypervSocketServer.IsDisposed; }
}
#endregion
#region Constructors
private HyperVSocketMediator()
: base(false)
{
_hypervSocketServer = new RemoteSessionHyperVSocketServer(false);
originalStdIn = _hypervSocketServer.TextReader;
originalStdOut = new OutOfProcessTextWriter(_hypervSocketServer.TextWriter);
originalStdErr = new HyperVSocketErrorTextWriter(_hypervSocketServer.TextWriter);
}
#endregion
#region Static Methods
internal static void Run(
string initialCommand,
string configurationName)
{
lock (SyncObject)
{
s_instance = new HyperVSocketMediator();
}
#if !CORECLR
// AppDomain is not available in CoreCLR
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException);
#endif
s_instance.Start(initialCommand, new PSRemotingCryptoHelperServer(), configurationName);
}
#endregion
}
internal sealed class HyperVSocketErrorTextWriter : OutOfProcessTextWriter
{
#region Private Members
private const string _errorPrepend = "__HyperVSocketError__:";
#endregion
#region Properties
internal static string ErrorPrepend
{
get { return _errorPrepend; }
}
#endregion
#region Constructors
internal HyperVSocketErrorTextWriter(
TextWriter textWriter)
: base(textWriter)
{ }
#endregion
#region Base class overrides
internal override void WriteLine(string data)
{
string dataToWrite = (data != null) ? _errorPrepend + data : null;
base.WriteLine(dataToWrite);
}
#endregion
}
}
| |
using DeveImageOptimizer.FileProcessing;
using DeveImageOptimizer.Helpers;
using DeveImageOptimizer.State;
using DeveImageOptimizer.Tests.ExternalTools;
using DeveImageOptimizer.Tests.TestConfig;
using DeveImageOptimizer.Tests.TestHelpers;
using System;
using System.IO;
using System.Threading.Tasks;
using Xunit;
namespace DeveImageOptimizer.Tests.FileProcessingFileOptimizer
{
public class FileOptimizerProcessorFacts
{
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesLandscapeImage()
{
await OptimizeFileTest("Image1A.JPG");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesStandingRotatedImage()
{
await OptimizeFileTest("Image2A.JPG");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesPexelsPhoto()
{
await OptimizeFileTest("pexels-photo.jpg");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesVimPicture()
{
await OptimizeFileTest("vim16x16_1.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesGifImage()
{
await OptimizeFileTest("devtools-full_1.gif");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesVersioningImage()
{
await OptimizeFileTest("versioning-1_1.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesTimelineSelectorImage()
{
await OptimizeFileTest("TimelineSelector.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesSnakeImage()
{
await OptimizeFileTest("snake.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True), Trait(TraitNames.FailingTest, Trait.True)]
public async Task CorrectlyOptimizesCraDynamicImportImage()
{
await OptimizeFileTest("cra-dynamic-import_1.gif");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesDevtoolsSidePaneImage()
{
await OptimizeFileTest("devtools-side-pane_1.gif");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesImageSharpImage1()
{
await OptimizeFileTest("Imagesharp/Resize_IsAppliedToAllFrames_Rgba32_giphy.gif");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesImageSharpImage2()
{
await OptimizeFileTest("Imagesharp/ResizeFromSourceRectangle_Rgba32_CalliphoraPartial.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesImageSharpImage3()
{
await OptimizeFileTest("Imagesharp/ResizeWithBoxPadMode_Rgba32_CalliphoraPartial.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesImageSharpImage4()
{
await OptimizeFileTest("Imagesharp/ResizeWithPadMode_Rgba32_CalliphoraPartial.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesGifSourceImage()
{
await OptimizeFileTest("Source.gif");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesIconImage()
{
await OptimizeFileTest("icon_1.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesGoProImage()
{
await OptimizeFileTest("GoProBison.JPG");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesSmileFaceBmpImage()
{
await OptimizeFileTest("SmileFaceBmp.bmp");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesPezImageWithSpaceInName()
{
await OptimizeFileTest("pez image with space.jpg");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesAfterJpgImage()
{
await OptimizeFileTest("After.JPG");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesRuthImage()
{
//As of 31-10-2018: This is the only failing test
await OptimizeFileTest("baberuth_1.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesAlreadyOptimizedOwl()
{
await OptimizeFileTest("AlreadyOptimizedOwl.jpg");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesOfficeLensImage()
{
await OptimizeFileTest("OfficeLensImage.jpg");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesImageSharpGeneratedImage()
{
await OptimizeFileTest("Generated_0.jpg");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizes01png()
{
await OptimizeFileTest("01.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizes03png()
{
await OptimizeFileTest("03.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizes031png()
{
await OptimizeFileTest("03_1.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizes05png()
{
await OptimizeFileTest("05.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizes05_3png()
{
await OptimizeFileTest("05_3.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizes08_01png()
{
await OptimizeFileTest("08_1.png");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesBrokenstickmanJpg()
{
await OptimizeFileTest("Brokenstickman.JPG");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesSmileEnzoImage()
{
await OptimizeFileTest("SmileEnzo.jpg");
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesReadOnlyFile()
{
var fileName = "ReadOnlyJpg.jpg";
var filePath = Path.Combine(FolderHelperMethods.Internal_AssemblyDirectory.Value, "TestImages", fileName);
new FileInfo(filePath).IsReadOnly = true;
await OptimizeFileTest(fileName);
}
[SkippableFact, Trait(TraitNames.CallsFileOptimizer, Trait.True)]
public async Task CorrectlyOptimizesBlockedFile()
{
var fileName = "BlockedJpg.jpg";
var filePath = Path.Combine(FolderHelperMethods.Internal_AssemblyDirectory.Value, "TestImages", fileName);
if (OperatingSystem.IsWindows())
{
using (var zoneIdentifier = new ZoneIdentifier(filePath))
{
zoneIdentifier.Zone = UrlZone.Internet;
}
}
await OptimizeFileTest(fileName);
}
private async Task OptimizeFileTest(string fileName)
{
var config = ConfigCreator.CreateTestConfig(true, directMode: true);
var fop = new FileOptimizerProcessor(config);
var image1path = Path.Combine(FolderHelperMethods.Internal_AssemblyDirectory.Value, "TestImages", fileName);
var tempfortestdir = FolderHelperMethods.Internal_TempForTestDirectory.Value;
var image1temppath = Path.Combine(tempfortestdir, RandomFileNameHelper.RandomizeFileName(fileName));
Directory.CreateDirectory(tempfortestdir);
File.Copy(image1path, image1temppath, true);
try
{
var fileToOptimize = new OptimizableFile(image1temppath, null, new FileInfo(image1temppath).Length);
await fop.OptimizeFile(fileToOptimize);
Assert.Equal(OptimizationResult.Success, fileToOptimize.OptimizationResult);
var fileOptimized = new FileInfo(image1temppath);
var fileUnoptimized = new FileInfo(image1path);
//Verify that the new file is actually smaller
Assert.True(fileOptimized.Length <= fileUnoptimized.Length);
}
finally
{
File.Delete(image1temppath);
}
}
}
}
| |
using Lucene.Net.Documents;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Index
{
/*
* 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 Analyzer = Lucene.Net.Analysis.Analyzer;
using BooleanQuery = Lucene.Net.Search.BooleanQuery;
using BytesRef = Lucene.Net.Util.BytesRef;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using Lucene3xCodec = Lucene.Net.Codecs.Lucene3x.Lucene3xCodec;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using Occur = Lucene.Net.Search.Occur;
using TermQuery = Lucene.Net.Search.TermQuery;
using TestUtil = Lucene.Net.Util.TestUtil;
using TokenStream = Lucene.Net.Analysis.TokenStream;
using TopDocs = Lucene.Net.Search.TopDocs;
[TestFixture]
public class TestIndexableField : LuceneTestCase
{
private class MyField : IIndexableField
{
private readonly TestIndexableField OuterInstance;
internal readonly int Counter;
internal readonly IIndexableFieldType fieldType;
public MyField()
{
fieldType = new IndexableFieldTypeAnonymousInnerClassHelper(this);
}
private class IndexableFieldTypeAnonymousInnerClassHelper : IIndexableFieldType
{
private MyField OuterInstance;
public IndexableFieldTypeAnonymousInnerClassHelper(MyField outerInstance)
{
OuterInstance = outerInstance;
}
public bool IsIndexed
{
get { return (OuterInstance.Counter % 10) != 3; }
}
public bool IsStored
{
get { return (OuterInstance.Counter & 1) == 0 || (OuterInstance.Counter % 10) == 3; }
}
public bool IsTokenized
{
get { return true; }
}
public bool StoreTermVectors
{
get { return IsIndexed && OuterInstance.Counter % 2 == 1 && OuterInstance.Counter % 10 != 9; }
}
public bool StoreTermVectorOffsets
{
get { return StoreTermVectors && OuterInstance.Counter % 10 != 9; }
}
public bool StoreTermVectorPositions
{
get { return StoreTermVectors && OuterInstance.Counter % 10 != 9; }
}
public bool StoreTermVectorPayloads
{
get
{
#pragma warning disable 612, 618
if (Codec.Default is Lucene3xCodec)
#pragma warning restore 612, 618
{
return false; // 3.x doesnt support
}
else
{
return StoreTermVectors && OuterInstance.Counter % 10 != 9;
}
}
}
public bool OmitNorms
{
get { return false; }
}
public IndexOptions IndexOptions
{
get { return Index.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; }
}
public DocValuesType DocValueType
{
get { return DocValuesType.NONE; }
}
}
public MyField(TestIndexableField outerInstance, int counter)
: this()
{
this.OuterInstance = outerInstance;
this.Counter = counter;
}
public string Name
{
get { return "f" + Counter; }
}
public float Boost
{
get { return 1.0f + (float)Random().NextDouble(); }
}
public BytesRef GetBinaryValue()
{
if ((Counter % 10) == 3)
{
var bytes = new byte[10];
for (int idx = 0; idx < bytes.Length; idx++)
{
bytes[idx] = (byte)(Counter + idx);
}
return new BytesRef(bytes, 0, bytes.Length);
}
else
{
return null;
}
}
public string GetStringValue()
{
int fieldID = Counter % 10;
if (fieldID != 3 && fieldID != 7)
{
return "text " + Counter;
}
else
{
return null;
}
}
// LUCENENET specific - created overload so we can format an underlying numeric type using specified provider
public virtual string GetStringValue(IFormatProvider provider)
{
return GetStringValue();
}
// LUCENENET specific - created overload so we can format an underlying numeric type using specified format
public virtual string GetStringValue(string format)
{
return GetStringValue();
}
// LUCENENET specific - created overload so we can format an underlying numeric type using specified format and provider
public virtual string GetStringValue(string format, IFormatProvider provider)
{
return GetStringValue();
}
public TextReader GetReaderValue()
{
if (Counter % 10 == 7)
{
return new StringReader("text " + Counter);
}
else
{
return null;
}
}
public object GetNumericValue()
{
return null;
}
// LUCENENET specific - Since we have no numeric reference types in .NET, this method was added to check
// the numeric type of the inner field without boxing/unboxing.
public virtual NumericFieldType NumericType
{
get { return NumericFieldType.NONE; }
}
// LUCENENET specific - created overload for Byte, since we have no Number class in .NET
public virtual byte? GetByteValue()
{
return null;
}
// LUCENENET specific - created overload for Short, since we have no Number class in .NET
public virtual short? GetInt16Value()
{
return null;
}
// LUCENENET specific - created overload for Int32, since we have no Number class in .NET
public virtual int? GetInt32Value()
{
return null;
}
// LUCENENET specific - created overload for Int64, since we have no Number class in .NET
public virtual long? GetInt64Value()
{
return null;
}
// LUCENENET specific - created overload for Single, since we have no Number class in .NET
public virtual float? GetSingleValue()
{
return null;
}
// LUCENENET specific - created overload for Double, since we have no Number class in .NET
public virtual double? GetDoubleValue()
{
return null;
}
public IIndexableFieldType IndexableFieldType
{
get { return fieldType; }
}
public TokenStream GetTokenStream(Analyzer analyzer)
{
return GetReaderValue() != null ? analyzer.GetTokenStream(Name, GetReaderValue()) : analyzer.GetTokenStream(Name, new StringReader(GetStringValue()));
}
}
// Silly test showing how to index documents w/o using Lucene's core
// Document nor Field class
[Test]
public virtual void TestArbitraryFields()
{
Directory dir = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);
int NUM_DOCS = AtLeast(27);
if (VERBOSE)
{
Console.WriteLine("TEST: " + NUM_DOCS + " docs");
}
int[] fieldsPerDoc = new int[NUM_DOCS];
int baseCount = 0;
for (int docCount = 0; docCount < NUM_DOCS; docCount++)
{
int fieldCount = TestUtil.NextInt(Random(), 1, 17);
fieldsPerDoc[docCount] = fieldCount - 1;
int finalDocCount = docCount;
if (VERBOSE)
{
Console.WriteLine("TEST: " + fieldCount + " fields in doc " + docCount);
}
int finalBaseCount = baseCount;
baseCount += fieldCount - 1;
w.AddDocument(new IterableAnonymousInnerClassHelper(this, fieldCount, finalDocCount, finalBaseCount));
}
IndexReader r = w.Reader;
w.Dispose();
IndexSearcher s = NewSearcher(r);
int counter = 0;
for (int id = 0; id < NUM_DOCS; id++)
{
if (VERBOSE)
{
Console.WriteLine("TEST: verify doc id=" + id + " (" + fieldsPerDoc[id] + " fields) counter=" + counter);
}
TopDocs hits = s.Search(new TermQuery(new Term("id", "" + id)), 1);
Assert.AreEqual(1, hits.TotalHits);
int docID = hits.ScoreDocs[0].Doc;
Document doc = s.Doc(docID);
int endCounter = counter + fieldsPerDoc[id];
while (counter < endCounter)
{
string name = "f" + counter;
int fieldID = counter % 10;
bool stored = (counter & 1) == 0 || fieldID == 3;
bool binary = fieldID == 3;
bool indexed = fieldID != 3;
string stringValue;
if (fieldID != 3 && fieldID != 9)
{
stringValue = "text " + counter;
}
else
{
stringValue = null;
}
// stored:
if (stored)
{
IIndexableField f = doc.GetField(name);
Assert.IsNotNull(f, "doc " + id + " doesn't have field f" + counter);
if (binary)
{
Assert.IsNotNull(f, "doc " + id + " doesn't have field f" + counter);
BytesRef b = f.GetBinaryValue();
Assert.IsNotNull(b);
Assert.AreEqual(10, b.Length);
for (int idx = 0; idx < 10; idx++)
{
Assert.AreEqual((byte)(idx + counter), b.Bytes[b.Offset + idx]);
}
}
else
{
Debug.Assert(stringValue != null);
Assert.AreEqual(stringValue, f.GetStringValue());
}
}
if (indexed)
{
bool tv = counter % 2 == 1 && fieldID != 9;
if (tv)
{
Terms tfv = r.GetTermVectors(docID).GetTerms(name);
Assert.IsNotNull(tfv);
TermsEnum termsEnum = tfv.GetIterator(null);
Assert.AreEqual(new BytesRef("" + counter), termsEnum.Next());
Assert.AreEqual(1, termsEnum.TotalTermFreq);
DocsAndPositionsEnum dpEnum = termsEnum.DocsAndPositions(null, null);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(1, dpEnum.Freq);
Assert.AreEqual(1, dpEnum.NextPosition());
Assert.AreEqual(new BytesRef("text"), termsEnum.Next());
Assert.AreEqual(1, termsEnum.TotalTermFreq);
dpEnum = termsEnum.DocsAndPositions(null, dpEnum);
Assert.IsTrue(dpEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
Assert.AreEqual(1, dpEnum.Freq);
Assert.AreEqual(0, dpEnum.NextPosition());
Assert.IsNull(termsEnum.Next());
// TODO: offsets
}
else
{
Fields vectors = r.GetTermVectors(docID);
Assert.IsTrue(vectors == null || vectors.GetTerms(name) == null);
}
BooleanQuery bq = new BooleanQuery();
bq.Add(new TermQuery(new Term("id", "" + id)), Occur.MUST);
bq.Add(new TermQuery(new Term(name, "text")), Occur.MUST);
TopDocs hits2 = s.Search(bq, 1);
Assert.AreEqual(1, hits2.TotalHits);
Assert.AreEqual(docID, hits2.ScoreDocs[0].Doc);
bq = new BooleanQuery();
bq.Add(new TermQuery(new Term("id", "" + id)), Occur.MUST);
bq.Add(new TermQuery(new Term(name, "" + counter)), Occur.MUST);
TopDocs hits3 = s.Search(bq, 1);
Assert.AreEqual(1, hits3.TotalHits);
Assert.AreEqual(docID, hits3.ScoreDocs[0].Doc);
}
counter++;
}
}
r.Dispose();
dir.Dispose();
}
private class IterableAnonymousInnerClassHelper : IEnumerable<IIndexableField>
{
private readonly TestIndexableField OuterInstance;
private int FieldCount;
private int FinalDocCount;
private int FinalBaseCount;
public IterableAnonymousInnerClassHelper(TestIndexableField outerInstance, int fieldCount, int finalDocCount, int finalBaseCount)
{
this.OuterInstance = outerInstance;
this.FieldCount = fieldCount;
this.FinalDocCount = finalDocCount;
this.FinalBaseCount = finalBaseCount;
}
public virtual IEnumerator<IIndexableField> GetEnumerator()
{
return new IteratorAnonymousInnerClassHelper(this, OuterInstance);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private class IteratorAnonymousInnerClassHelper : IEnumerator<IIndexableField>
{
private readonly IterableAnonymousInnerClassHelper OuterInstance;
private readonly TestIndexableField OuterTextIndexableField;
public IteratorAnonymousInnerClassHelper(IterableAnonymousInnerClassHelper outerInstance, TestIndexableField outerTextIndexableField)
{
this.OuterInstance = outerInstance;
OuterTextIndexableField = outerTextIndexableField;
}
internal int fieldUpto;
private IIndexableField current;
public bool MoveNext()
{
if (fieldUpto >= OuterInstance.FieldCount)
{
return false;
}
Debug.Assert(fieldUpto < OuterInstance.FieldCount);
if (fieldUpto == 0)
{
fieldUpto = 1;
current = OuterTextIndexableField.NewStringField("id", "" + OuterInstance.FinalDocCount, Field.Store.YES);
}
else
{
current = new MyField(OuterTextIndexableField, OuterInstance.FinalBaseCount + (fieldUpto++ - 1));
}
return true;
}
public IIndexableField Current
{
get { return current; }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
}
public void Reset()
{
throw new NotImplementedException();
}
}
}
}
}
| |
namespace System.Workflow.ComponentModel
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Workflow.ComponentModel.Compiler;
#region Class ComponentDispenser
internal static class ComponentDispenser
{
private static IDictionary<Type, List<IExtenderProvider>> componentExtenderMap = new Dictionary<Type, List<IExtenderProvider>>();
//it is super critical to note that even though we pass activity instead of a System.Type
//here, the method impl does not rely on any objectness but relies only on typeness
//- this is done to keep a static type level executor metadata (and not instance level)
// scoped in an app domain
internal static ActivityExecutor[] CreateActivityExecutors(Activity activity)
{
if (activity == null)
throw new ArgumentNullException("activity");
List<ActivityExecutor> executors = new List<ActivityExecutor>();
if (activity.SupportsSynchronization)
executors.Add(new SynchronizationFilter());
if (activity.SupportsTransaction)
executors.Add(new TransactedContextFilter());
if (activity is CompositeActivity)
{
if (activity is ICompensatableActivity)
executors.Add(new CompensationHandlingFilter());
executors.Add(new FaultAndCancellationHandlingFilter());
executors.Add(new CompositeActivityExecutor<CompositeActivity>());
}
else
executors.Add(new ActivityExecutor<Activity>());
return executors.ToArray();
}
internal static object[] CreateComponents(Type objectType, Type componentTypeAttribute)
{
//*******DO NOT CHANGE THE ORDER OF THE EXECUTION AS IT HAS SIGNIFICANCE AT RUNTIME
Dictionary<Type, object> components = new Dictionary<Type, object>();
// Goto all the attributes and collect matching attributes and component factories
ArrayList supportsTransactionComponents = new ArrayList();
ArrayList supportsCancelHandlerComponents = new ArrayList();
ArrayList supportsSynchronizationComponents = new ArrayList();
ArrayList supportsCompensationHandlerComponents = new ArrayList();
// dummy calls to make sure that attributes are in good shape
GetCustomAttributes(objectType, typeof(ActivityCodeGeneratorAttribute), true);
GetCustomAttributes(objectType, typeof(ActivityValidatorAttribute), true);
GetCustomAttributes(objectType, typeof(System.ComponentModel.DesignerAttribute), true);
GetCustomAttributes(objectType, typeof(System.ComponentModel.Design.Serialization.DesignerSerializerAttribute), true);
if (objectType.GetCustomAttributes(typeof(SupportsTransactionAttribute), true).Length > 0)
{
if (componentTypeAttribute == typeof(ActivityValidatorAttribute))
supportsTransactionComponents.Add(new TransactionContextValidator());
}
if (objectType.GetCustomAttributes(typeof(SupportsSynchronizationAttribute), true).Length > 0)
{
if (componentTypeAttribute == typeof(ActivityValidatorAttribute))
supportsSynchronizationComponents.Add(new SynchronizationValidator());
}
// IMPORTANT: sequence of these components is really critical
AddComponents(components, supportsSynchronizationComponents.ToArray());
AddComponents(components, supportsTransactionComponents.ToArray());
AddComponents(components, supportsCompensationHandlerComponents.ToArray());
AddComponents(components, supportsCancelHandlerComponents.ToArray());
//Goto all the interfaces and collect matching attributes and component factories
ArrayList customAttributes = new ArrayList();
foreach (Type interfaceType in objectType.GetInterfaces())
customAttributes.AddRange(ComponentDispenser.GetCustomAttributes(interfaceType, componentTypeAttribute, true));
//Add all the component's attributes
customAttributes.AddRange(ComponentDispenser.GetCustomAttributes(objectType, componentTypeAttribute, true));
string typeName = null;
foreach (Attribute attribute in customAttributes)
{
Type expectedBaseType = null;
if (componentTypeAttribute == typeof(ActivityCodeGeneratorAttribute))
{
typeName = ((ActivityCodeGeneratorAttribute)attribute).CodeGeneratorTypeName;
expectedBaseType = typeof(ActivityCodeGenerator);
}
else if (componentTypeAttribute == typeof(ActivityValidatorAttribute))
{
typeName = ((ActivityValidatorAttribute)attribute).ValidatorTypeName;
expectedBaseType = typeof(Validator);
}
else
{
System.Diagnostics.Debug.Assert(false, "wrong attribute type");
}
object component = null;
try
{
if (!String.IsNullOrEmpty(typeName))
component = ComponentDispenser.CreateComponentInstance(typeName, objectType);
}
catch
{
}
if ((component != null && expectedBaseType != null && expectedBaseType.IsAssignableFrom(component.GetType())))
{
if (!components.ContainsKey(component.GetType()))
components.Add(component.GetType(), component);
}
else
{
throw new InvalidOperationException(SR.GetString(SR.Error_InvalidAttribute, componentTypeAttribute.Name, objectType.FullName));
}
}
return new ArrayList(components.Values).ToArray();
}
private static void AddComponents(Dictionary<Type, object> components, object[] attribComponents)
{
foreach (object component in attribComponents)
{
if (!components.ContainsKey(component.GetType()))
components.Add(component.GetType(), component);
}
}
internal static void RegisterComponentExtenders(Type extendingType, IExtenderProvider[] extenders)
{
//Make sure that there are no previous registered components
List<IExtenderProvider> extenderProviders = null;
if (!componentExtenderMap.ContainsKey(extendingType))
{
extenderProviders = new List<IExtenderProvider>();
componentExtenderMap.Add(extendingType, extenderProviders);
}
else
{
extenderProviders = componentExtenderMap[extendingType];
}
extenderProviders.AddRange(extenders);
}
internal static IList<IExtenderProvider> Extenders
{
get
{
List<IExtenderProvider> extenders = new List<IExtenderProvider>();
foreach (IList<IExtenderProvider> registeredExtenders in componentExtenderMap.Values)
extenders.AddRange(registeredExtenders);
return extenders.AsReadOnly();
}
}
// The referenceType parameter provides a way to identify the assembly in which to look for the type.
private static object CreateComponentInstance(string typeName, Type referenceType)
{
object component = null;
Type componentType = null;
try
{
string typeFullName = typeName;
int squareBracketCloseIndex = typeName.LastIndexOf(']');
if (squareBracketCloseIndex != -1)
{
typeFullName = typeName.Substring(0, squareBracketCloseIndex + 1);
}
else
{
int commaIndex = typeName.IndexOf(',');
if (commaIndex != -1)
typeFullName = typeName.Substring(0, commaIndex);
}
componentType = referenceType.Assembly.GetType(typeFullName, false);
}
catch
{
}
if (componentType == null)
{
try
{
componentType = Type.GetType(typeName, false);
}
catch
{
}
}
string message = null;
if (componentType != null)
{
try
{
component = Activator.CreateInstance(componentType);
}
catch (Exception ex)
{
message = ex.Message;
// Process error condition below
}
}
if (component == null)
{
System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager("System.Workflow.ComponentModel.StringResources", typeof(System.Workflow.ComponentModel.Activity).Assembly);
if (resourceManager != null)
message = string.Format(CultureInfo.CurrentCulture, resourceManager.GetString("Error_CantCreateInstanceOfComponent"), new object[] { typeName, message });
throw new Exception(message);
}
return component;
}
private static object[] GetCustomAttributes(Type objectType, Type attributeType, bool inherit)
{
object[] attribs = null;
try
{
if (attributeType == null)
attribs = objectType.GetCustomAttributes(inherit);
else
attribs = objectType.GetCustomAttributes(attributeType, inherit);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.GetString(SR.Error_InvalidAttributes, objectType.FullName), e);
}
return attribs;
}
}
#endregion
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="SizeKeyFrameCollection.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This collection is used in conjunction with a KeyFrameSizeAnimation
/// to animate a Size property value along a set of key frames.
/// </summary>
public class SizeKeyFrameCollection : Freezable, IList
{
#region Data
private List<SizeKeyFrame> _keyFrames;
private static SizeKeyFrameCollection s_emptyCollection;
#endregion
#region Constructors
/// <Summary>
/// Creates a new SizeKeyFrameCollection.
/// </Summary>
public SizeKeyFrameCollection()
: base()
{
_keyFrames = new List< SizeKeyFrame>(2);
}
#endregion
#region Static Methods
/// <summary>
/// An empty SizeKeyFrameCollection.
/// </summary>
public static SizeKeyFrameCollection Empty
{
get
{
if (s_emptyCollection == null)
{
SizeKeyFrameCollection emptyCollection = new SizeKeyFrameCollection();
emptyCollection._keyFrames = new List< SizeKeyFrame>(0);
emptyCollection.Freeze();
s_emptyCollection = emptyCollection;
}
return s_emptyCollection;
}
}
#endregion
#region Freezable
/// <summary>
/// Creates a freezable copy of this SizeKeyFrameCollection.
/// </summary>
/// <returns>The copy</returns>
public new SizeKeyFrameCollection Clone()
{
return (SizeKeyFrameCollection)base.Clone();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new SizeKeyFrameCollection();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
SizeKeyFrameCollection sourceCollection = (SizeKeyFrameCollection) sourceFreezable;
base.CloneCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< SizeKeyFrame>(count);
for (int i = 0; i < count; i++)
{
SizeKeyFrame keyFrame = (SizeKeyFrame)sourceCollection._keyFrames[i].Clone();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(System.Windows.Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
SizeKeyFrameCollection sourceCollection = (SizeKeyFrameCollection) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< SizeKeyFrame>(count);
for (int i = 0; i < count; i++)
{
SizeKeyFrame keyFrame = (SizeKeyFrame)sourceCollection._keyFrames[i].CloneCurrentValue();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(System.Windows.Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable sourceFreezable)
{
SizeKeyFrameCollection sourceCollection = (SizeKeyFrameCollection) sourceFreezable;
base.GetAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< SizeKeyFrame>(count);
for (int i = 0; i < count; i++)
{
SizeKeyFrame keyFrame = (SizeKeyFrame)sourceCollection._keyFrames[i].GetAsFrozen();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(System.Windows.Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable)
{
SizeKeyFrameCollection sourceCollection = (SizeKeyFrameCollection) sourceFreezable;
base.GetCurrentValueAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< SizeKeyFrame>(count);
for (int i = 0; i < count; i++)
{
SizeKeyFrame keyFrame = (SizeKeyFrame)sourceCollection._keyFrames[i].GetCurrentValueAsFrozen();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
///
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
for (int i = 0; i < _keyFrames.Count && canFreeze; i++)
{
canFreeze &= Freezable.Freeze(_keyFrames[i], isChecking);
}
return canFreeze;
}
#endregion
#region IEnumerable
/// <summary>
/// Returns an enumerator of the SizeKeyFrames in the collection.
/// </summary>
public IEnumerator GetEnumerator()
{
ReadPreamble();
return _keyFrames.GetEnumerator();
}
#endregion
#region ICollection
/// <summary>
/// Returns the number of SizeKeyFrames in the collection.
/// </summary>
public int Count
{
get
{
ReadPreamble();
return _keyFrames.Count;
}
}
/// <summary>
/// See <see cref="System.Collections.ICollection.IsSynchronized">ICollection.IsSynchronized</see>.
/// </summary>
public bool IsSynchronized
{
get
{
ReadPreamble();
return (IsFrozen || Dispatcher != null);
}
}
/// <summary>
/// See <see cref="System.Collections.ICollection.SyncRoot">ICollection.SyncRoot</see>.
/// </summary>
public object SyncRoot
{
get
{
ReadPreamble();
return ((ICollection)_keyFrames).SyncRoot;
}
}
/// <summary>
/// Copies all of the SizeKeyFrames in the collection to an
/// array.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
ReadPreamble();
((ICollection)_keyFrames).CopyTo(array, index);
}
/// <summary>
/// Copies all of the SizeKeyFrames in the collection to an
/// array of SizeKeyFrames.
/// </summary>
public void CopyTo(SizeKeyFrame[] array, int index)
{
ReadPreamble();
_keyFrames.CopyTo(array, index);
}
#endregion
#region IList
/// <summary>
/// Adds a SizeKeyFrame to the collection.
/// </summary>
int IList.Add(object keyFrame)
{
return Add((SizeKeyFrame)keyFrame);
}
/// <summary>
/// Adds a SizeKeyFrame to the collection.
/// </summary>
public int Add(SizeKeyFrame keyFrame)
{
if (keyFrame == null)
{
throw new ArgumentNullException("keyFrame");
}
WritePreamble();
OnFreezablePropertyChanged(null, keyFrame);
_keyFrames.Add(keyFrame);
WritePostscript();
return _keyFrames.Count - 1;
}
/// <summary>
/// Removes all SizeKeyFrames from the collection.
/// </summary>
public void Clear()
{
WritePreamble();
if (_keyFrames.Count > 0)
{
for (int i = 0; i < _keyFrames.Count; i++)
{
OnFreezablePropertyChanged(_keyFrames[i], null);
}
_keyFrames.Clear();
WritePostscript();
}
}
/// <summary>
/// Returns true of the collection contains the given SizeKeyFrame.
/// </summary>
bool IList.Contains(object keyFrame)
{
return Contains((SizeKeyFrame)keyFrame);
}
/// <summary>
/// Returns true of the collection contains the given SizeKeyFrame.
/// </summary>
public bool Contains(SizeKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.Contains(keyFrame);
}
/// <summary>
/// Returns the index of a given SizeKeyFrame in the collection.
/// </summary>
int IList.IndexOf(object keyFrame)
{
return IndexOf((SizeKeyFrame)keyFrame);
}
/// <summary>
/// Returns the index of a given SizeKeyFrame in the collection.
/// </summary>
public int IndexOf(SizeKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.IndexOf(keyFrame);
}
/// <summary>
/// Inserts a SizeKeyFrame into a specific location in the collection.
/// </summary>
void IList.Insert(int index, object keyFrame)
{
Insert(index, (SizeKeyFrame)keyFrame);
}
/// <summary>
/// Inserts a SizeKeyFrame into a specific location in the collection.
/// </summary>
public void Insert(int index, SizeKeyFrame keyFrame)
{
if (keyFrame == null)
{
throw new ArgumentNullException("keyFrame");
}
WritePreamble();
OnFreezablePropertyChanged(null, keyFrame);
_keyFrames.Insert(index, keyFrame);
WritePostscript();
}
/// <summary>
/// Returns true if the collection is frozen.
/// </summary>
public bool IsFixedSize
{
get
{
ReadPreamble();
return IsFrozen;
}
}
/// <summary>
/// Returns true if the collection is frozen.
/// </summary>
public bool IsReadOnly
{
get
{
ReadPreamble();
return IsFrozen;
}
}
/// <summary>
/// Removes a SizeKeyFrame from the collection.
/// </summary>
void IList.Remove(object keyFrame)
{
Remove((SizeKeyFrame)keyFrame);
}
/// <summary>
/// Removes a SizeKeyFrame from the collection.
/// </summary>
public void Remove(SizeKeyFrame keyFrame)
{
WritePreamble();
if (_keyFrames.Contains(keyFrame))
{
OnFreezablePropertyChanged(keyFrame, null);
_keyFrames.Remove(keyFrame);
WritePostscript();
}
}
/// <summary>
/// Removes the SizeKeyFrame at the specified index from the collection.
/// </summary>
public void RemoveAt(int index)
{
WritePreamble();
OnFreezablePropertyChanged(_keyFrames[index], null);
_keyFrames.RemoveAt(index);
WritePostscript();
}
/// <summary>
/// Gets or sets the SizeKeyFrame at a given index.
/// </summary>
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (SizeKeyFrame)value;
}
}
/// <summary>
/// Gets or sets the SizeKeyFrame at a given index.
/// </summary>
public SizeKeyFrame this[int index]
{
get
{
ReadPreamble();
return _keyFrames[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "SizeKeyFrameCollection[{0}]", index));
}
WritePreamble();
if (value != _keyFrames[index])
{
OnFreezablePropertyChanged(_keyFrames[index], value);
_keyFrames[index] = value;
Debug.Assert(_keyFrames[index] != null);
WritePostscript();
}
}
}
#endregion
}
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Tilde.Framework.Controller;
using Tilde.Framework.View;
namespace Tilde.LuaDebugger
{
[ToolWindowAttribute(Group = "Debug")]
public partial class ThreadsWindow : Tilde.Framework.View.ToolWindow
{
class ListItemTag
{
public ListItemTag(ThreadDetails details, int index, int indent)
{
m_details = details;
m_index = index;
m_indent = indent;
}
public ThreadDetails m_details;
public int m_index;
public int m_indent;
}
class ListViewItemComparer : System.Collections.IComparer
{
public int m_sortColumn;
public int m_sortOrder;
public ListViewItemComparer()
{
m_sortColumn = 1;
m_sortOrder = 1;
}
public int Compare(object x, object y)
{
ListViewItem lhsItem = x as ListViewItem;
ListViewItem rhsItem = y as ListViewItem;
ListItemTag lhsTag = lhsItem.Tag as ListItemTag;
ListItemTag rhsTag = rhsItem.Tag as ListItemTag;
ThreadDetails lhs = lhsTag.m_details;
ThreadDetails rhs = rhsTag.m_details;
switch (m_sortColumn)
{
case 0: return m_sortOrder * String.Compare(lhs.Name, rhs.Name);
case 1: return m_sortOrder * ((int)lhs.ID - (int)rhs.ID);
case 2: return m_sortOrder * String.Compare(lhs.Location, rhs.Location);
case 3: return m_sortOrder * ((int)lhs.State - (int)rhs.State);
case 4: return m_sortOrder * Math.Sign(lhs.PeakTime - rhs.PeakTime);
case 5: return m_sortOrder * Math.Sign(lhs.AverageTime - rhs.AverageTime);
case 6: return m_sortOrder * (lhs.StackSize - rhs.StackSize);
case 7: return m_sortOrder * (lhs.StackUsed - rhs.StackUsed);
default: return 0;
}
}
}
protected DebugManager mDebugger;
private ListViewItemComparer m_comparer;
private LuaValue m_breakedThread;
private Font m_boldFont;
public ThreadsWindow(IManager manager)
{
InitializeComponent();
m_comparer = new ListViewItemComparer();
threadListView.ListViewItemSorter = m_comparer;
mDebugger = ((LuaPlugin)manager.GetPlugin(typeof(LuaPlugin))).Debugger;
mDebugger.DebuggerConnected += new DebuggerConnectedEventHandler(Debugger_DebuggerConnected);
mDebugger.DebuggerDisconnecting += new DebuggerDisconnectingEventHandler(Debugger_DebuggerDisconnecting);
m_boldFont = new Font(threadListView.Font, FontStyle.Bold);
}
void Debugger_DebuggerDisconnecting(DebugManager sender, Target target)
{
threadListView.Items.Clear();
target.ThreadUpdate -= new ThreadUpdateEventHandler(target_ThreadUpdate);
target.StateUpdate -= new StateUpdateEventHandler(target_StateUpdate);
}
void Debugger_DebuggerConnected(DebugManager sender, Target target)
{
target.StateUpdate += new StateUpdateEventHandler(target_StateUpdate);
target.ThreadUpdate += new ThreadUpdateEventHandler(target_ThreadUpdate);
}
void target_StateUpdate(Target sender, StateUpdateEventArgs args)
{
m_breakedThread = args.Thread;
UpdateStates();
}
void SetItemBackColor(ListViewItem item, Color colour)
{
foreach(ListViewItem.ListViewSubItem subitem in item.SubItems)
{
subitem.BackColor = colour;
}
}
void SetItemForeColor(ListViewItem item, Color colour)
{
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
{
subitem.ForeColor = colour;
}
}
void target_ThreadUpdate(Target sender, ThreadUpdateEventArgs args)
{
threadListView.BeginUpdate();
threadListView.ListViewItemSorter = null;
for (int index = 0; index < threadListView.Items.Count; )
{
ListViewItem item = threadListView.Items[index];
if (item.BackColor == Color.LightPink)
{
threadListView.Items.RemoveAt(index);
}
else
{
SetItemForeColor(item, threadListView.ForeColor);
SetItemBackColor(item, threadListView.BackColor);
++index;
}
}
foreach (ThreadDetails thread in args.Threads)
{
ListViewItem item = threadListView.Items[thread.Thread.ToString()];
if (!thread.Valid)
{
if(item != null)
SetItemBackColor(item, Color.LightPink);
}
else
{
if (item == null)
{
item = CreateItem(thread, threadListView.Items.Count, 0);
threadListView.Items.Add(item);
SetItemBackColor(item, Color.LightBlue);
UpdateItem(item, thread, false);
}
else
{
UpdateItem(item, thread, true);
}
}
}
UpdateStates();
UpdateSorting();
threadListView.EndUpdate();
}
private void UpdateStates()
{
foreach (ListViewItem item in threadListView.Items)
{
ListItemTag tag = item.Tag as ListItemTag;
if (tag.m_details.Thread.Equals(mDebugger.CurrentThread))
item.ImageIndex = 0;
else
item.ImageIndex = -1;
if (tag.m_details.Thread.Equals(m_breakedThread))
item.StateImageIndex = 1;
else
item.StateImageIndex = -1;
}
}
private void UpdateItem(ListViewItem item, ThreadDetails thread, bool modified)
{
((ListItemTag)item.Tag).m_details = thread;
string[] subitem = new string[item.SubItems.Count];
subitem[1] = thread.ID < 0 ? "--" : thread.ID.ToString();
subitem[2] = thread.Location;
subitem[3] = thread.State.ToString();
subitem[4] = thread.PeakTime < 0 ? "--" : (thread.PeakTime).ToString("0.0000");
subitem[5] = thread.AverageTime < 0 ? "--" : (thread.AverageTime).ToString("0.0000");
subitem[6] = thread.StackSize < 0 ? "--" : thread.StackSize.ToString();
subitem[7] = thread.StackUsed < 0 ? "--" : thread.StackUsed.ToString();
if (modified)
{
for (int index = 1; index < item.SubItems.Count; ++index)
if (item.SubItems[index].Text != subitem[index])
item.SubItems[index].ForeColor = Color.Red;
}
item.SubItems[1].Text = subitem[1];
item.SubItems[2].Text = subitem[2];
item.SubItems[3].Text = subitem[3];
item.SubItems[4].Text = subitem[4];
item.SubItems[5].Text = subitem[5];
item.SubItems[6].Text = subitem[6];
item.SubItems[7].Text = subitem[7];
}
private ListViewItem CreateItem(ThreadDetails thread, int index, int indent)
{
//ListViewItem item = new ListViewItem(mDebugger.ValueCache.Get(thread.Thread));
ListViewItem item = new ListViewItem(thread.Name);//"Thread " + thread.Thread.Value.ToString() + " (" + thread.Parent.Value.ToString() + ")");
item.Name = thread.Thread.ToString();
item.Tag = new ListItemTag(thread, index, indent);
item.UseItemStyleForSubItems = false;
item.SubItems.Add("");
item.SubItems.Add("");
item.SubItems.Add("");
item.SubItems.Add("");
item.SubItems.Add("");
item.SubItems.Add("");
item.SubItems.Add("");
return item;
}
private void InsertChildren(List<KeyValuePair<ThreadDetails, ListViewItem> > items, long parent, int parentIndex, int indent)
{
foreach (KeyValuePair<ThreadDetails, ListViewItem> pair in items)
{
ThreadDetails thread = pair.Key;
ListViewItem item = pair.Value;
if (thread.Parent.Value == parent)
{
item.IndentCount = indent;
threadListView.Items.Add(item);
InsertChildren(items, thread.Thread.Value, item.Index, indent + 1);
}
}
}
private void UpdateHierarchy()
{
List<KeyValuePair<ThreadDetails, ListViewItem>> items = new List<KeyValuePair<ThreadDetails, ListViewItem>>();
foreach(ListViewItem item in threadListView.Items)
{
items.Add(new KeyValuePair<ThreadDetails, ListViewItem>(((ListItemTag) item.Tag).m_details, item));
}
items.Sort(
delegate(KeyValuePair<ThreadDetails, ListViewItem> lhs, KeyValuePair<ThreadDetails, ListViewItem> rhs)
{
return lhs.Key.ID - rhs.Key.ID;
}
);
threadListView.BeginUpdate();
threadListView.Items.Clear();
InsertChildren(items, 0, -1, 0);
threadListView.EndUpdate();
}
private void UpdateSorting()
{
if (m_comparer.m_sortColumn == 0 && m_comparer.m_sortOrder == 0)
{
threadListView.ListViewItemSorter = null;
UpdateHierarchy();
}
else
{
threadListView.ListViewItemSorter = m_comparer;
foreach (ListViewItem item in threadListView.Items)
{
item.IndentCount = 0;
}
threadListView.Sort();
}
}
private void threadListView_ColumnClick(object sender, ColumnClickEventArgs e)
{
int order = m_comparer.m_sortOrder;
if (e.Column == 0)
{
if (e.Column == m_comparer.m_sortColumn)
{
order = order + 1;
if (order > 1)
order = -1;
}
else
order = 0;
}
else
{
if (e.Column == m_comparer.m_sortColumn)
order = order * -1;
else
order = 1;
}
m_comparer.m_sortColumn = e.Column;
m_comparer.m_sortOrder = order;
UpdateSorting();
}
private void threadListView_ItemActivate(object sender, EventArgs e)
{
if (threadListView.SelectedItems.Count == 1 && mDebugger.CurrentStackFrame != null)
{
ListItemTag tag = threadListView.SelectedItems[0].Tag as ListItemTag;
mDebugger.CurrentThread = tag.m_details.Thread;
}
}
private void buttonRefresh_Click(object sender, EventArgs e)
{
if (mDebugger.ConnectedTarget != null)
mDebugger.ConnectedTarget.RetrieveThreads();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Logic
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Rest.Azure.OData;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// WorkflowTriggerHistoriesOperations operations.
/// </summary>
internal partial class WorkflowTriggerHistoriesOperations : IServiceOperations<LogicManagementClient>, IWorkflowTriggerHistoriesOperations
{
/// <summary>
/// Initializes a new instance of the WorkflowTriggerHistoriesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal WorkflowTriggerHistoriesOperations(LogicManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the LogicManagementClient
/// </summary>
public LogicManagementClient Client { get; private set; }
/// <summary>
/// Gets a list of workflow trigger histories.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='triggerName'>
/// The workflow trigger name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<WorkflowTriggerHistory>>> ListWithHttpMessagesAsync(string resourceGroupName, string workflowName, string triggerName, ODataQuery<WorkflowTriggerHistoryFilter> odataQuery = default(ODataQuery<WorkflowTriggerHistoryFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (workflowName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "workflowName");
}
if (triggerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "triggerName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workflowName", workflowName);
tracingParameters.Add("triggerName", triggerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/triggers/{triggerName}/histories").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName));
_url = _url.Replace("{triggerName}", System.Uri.EscapeDataString(triggerName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<WorkflowTriggerHistory>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkflowTriggerHistory>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a workflow trigger history.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='workflowName'>
/// The workflow name.
/// </param>
/// <param name='triggerName'>
/// The workflow trigger name.
/// </param>
/// <param name='historyName'>
/// The workflow trigger history name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<WorkflowTriggerHistory>> GetWithHttpMessagesAsync(string resourceGroupName, string workflowName, string triggerName, string historyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (workflowName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "workflowName");
}
if (triggerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "triggerName");
}
if (historyName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "historyName");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("workflowName", workflowName);
tracingParameters.Add("triggerName", triggerName);
tracingParameters.Add("historyName", historyName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/triggers/{triggerName}/histories/{historyName}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName));
_url = _url.Replace("{triggerName}", System.Uri.EscapeDataString(triggerName));
_url = _url.Replace("{historyName}", System.Uri.EscapeDataString(historyName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<WorkflowTriggerHistory>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkflowTriggerHistory>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of workflow trigger histories.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<WorkflowTriggerHistory>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<WorkflowTriggerHistory>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkflowTriggerHistory>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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.ComponentModel;
using System.Globalization;
using System.IO;
using System.Net.NetworkInformation;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Mail
{
public delegate void SendCompletedEventHandler(object sender, AsyncCompletedEventArgs e);
public enum SmtpDeliveryMethod
{
Network,
SpecifiedPickupDirectory,
PickupDirectoryFromIis
}
// EAI Settings
public enum SmtpDeliveryFormat
{
SevenBit = 0, // Legacy
International = 1, // SMTPUTF8 - Email Address Internationalization (EAI)
}
public class SmtpClient : IDisposable
{
private string _host;
private int _port;
private bool _inCall;
private bool _cancelled;
private bool _timedOut;
private string _targetName = null;
private SmtpDeliveryMethod _deliveryMethod = SmtpDeliveryMethod.Network;
private SmtpDeliveryFormat _deliveryFormat = SmtpDeliveryFormat.SevenBit; // Non-EAI default
private string _pickupDirectoryLocation = null;
private SmtpTransport _transport;
private MailMessage _message; //required to prevent premature finalization
private MailWriter _writer;
private MailAddressCollection _recipients;
private SendOrPostCallback _onSendCompletedDelegate;
private Timer _timer;
private ContextAwareResult _operationCompletedResult = null;
private AsyncOperation _asyncOp = null;
private static AsyncCallback s_contextSafeCompleteCallback = new AsyncCallback(ContextSafeCompleteCallback);
private const int DefaultPort = 25;
internal string clientDomain = null;
private bool _disposed = false;
private ServicePoint _servicePoint;
// (async only) For when only some recipients fail. We still send the e-mail to the others.
private SmtpFailedRecipientException _failedRecipientException;
// ports above this limit are invalid
private const int MaxPortValue = 65535;
public event SendCompletedEventHandler SendCompleted;
public SmtpClient()
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
Initialize();
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
public SmtpClient(string host)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host);
try
{
_host = host;
Initialize();
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
public SmtpClient(string host, int port)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host, port);
try
{
if (port < 0)
{
throw new ArgumentOutOfRangeException(nameof(port));
}
_host = host;
_port = port;
Initialize();
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
private void Initialize()
{
_transport = new SmtpTransport(this);
if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _transport);
_onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback);
if (_host != null && _host.Length != 0)
{
_host = _host.Trim();
}
if (_port == 0)
{
_port = DefaultPort;
}
if (_targetName == null)
_targetName = "SMTPSVC/" + _host;
if (clientDomain == null)
{
// We use the local host name as the default client domain
// for the client's EHLO or HELO message. This limits the
// information about the host that we share. Additionally, the
// FQDN is not available to us or useful to the server (internal
// machine connecting to public server).
// SMTP RFC's require ASCII only host names in the HELO/EHLO message.
string clientDomainRaw = IPGlobalProperties.GetIPGlobalProperties().HostName;
IdnMapping mapping = new IdnMapping();
try
{
clientDomainRaw = mapping.GetAscii(clientDomainRaw);
}
catch (ArgumentException) { }
// For some inputs GetAscii may fail (bad Unicode, etc). If that happens
// we must strip out any non-ASCII characters.
// If we end up with no characters left, we use the string "LocalHost". This
// matches Outlook behavior.
StringBuilder sb = new StringBuilder();
char ch;
for (int i = 0; i < clientDomainRaw.Length; i++)
{
ch = clientDomainRaw[i];
if ((ushort)ch <= 0x7F)
sb.Append(ch);
}
if (sb.Length > 0)
clientDomain = sb.ToString();
else
clientDomain = "LocalHost";
}
}
public string Host
{
get
{
return _host;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value == string.Empty)
{
throw new ArgumentException(SR.net_emptystringset, nameof(value));
}
value = value.Trim();
if (value != _host)
{
_host = value;
_servicePoint = null;
}
}
}
public int Port
{
get
{
return _port;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value != _port)
{
_port = value;
_servicePoint = null;
}
}
}
public bool UseDefaultCredentials
{
get
{
return ReferenceEquals(_transport.Credentials, CredentialCache.DefaultNetworkCredentials);
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
_transport.Credentials = value ? CredentialCache.DefaultNetworkCredentials : null;
}
}
public ICredentialsByHost Credentials
{
get
{
return _transport.Credentials;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
_transport.Credentials = value;
}
}
public int Timeout
{
get
{
return _transport.Timeout;
}
set
{
if (InCall)
{
throw new InvalidOperationException(SR.SmtpInvalidOperationDuringSend);
}
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_transport.Timeout = value;
}
}
public ServicePoint ServicePoint
{
get
{
CheckHostAndPort();
if (_servicePoint == null)
{
// This differs from desktop, where it uses an internal overload of FindServicePoint that just
// takes a string host and an int port, bypassing the need for a Uri. We workaround that here by
// creating an http Uri, simply for the purposes of getting an appropriate ServicePoint instance.
// This has some subtle impact on behavior, e.g. the returned ServicePoint's Address property will
// be usable, whereas in desktop it throws an exception that "This property is not supported for
// protocols that do not use URI."
_servicePoint = ServicePointManager.FindServicePoint(new Uri("mailto:" + _host + ":" + _port));
}
return _servicePoint;
}
}
public SmtpDeliveryMethod DeliveryMethod
{
get
{
return _deliveryMethod;
}
set
{
_deliveryMethod = value;
}
}
public SmtpDeliveryFormat DeliveryFormat
{
get
{
return _deliveryFormat;
}
set
{
_deliveryFormat = value;
}
}
public string PickupDirectoryLocation
{
get
{
return _pickupDirectoryLocation;
}
set
{
_pickupDirectoryLocation = value;
}
}
/// <summary>
/// <para>Set to true if we need SSL</para>
/// </summary>
public bool EnableSsl
{
get
{
return _transport.EnableSsl;
}
set
{
_transport.EnableSsl = value;
}
}
/// <summary>
/// Certificates used by the client for establishing an SSL connection with the server.
/// </summary>
public X509CertificateCollection ClientCertificates
{
get
{
return _transport.ClientCertificates;
}
}
public string TargetName
{
set { _targetName = value; }
get { return _targetName; }
}
private bool ServerSupportsEai
{
get
{
return _transport.ServerSupportsEai;
}
}
private bool IsUnicodeSupported()
{
if (DeliveryMethod == SmtpDeliveryMethod.Network)
{
return (ServerSupportsEai && (DeliveryFormat == SmtpDeliveryFormat.International));
}
else
{ // Pickup directories
return (DeliveryFormat == SmtpDeliveryFormat.International);
}
}
internal MailWriter GetFileMailWriter(string pickupDirectory)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"{nameof(pickupDirectory)}={pickupDirectory}");
if (!Path.IsPathRooted(pickupDirectory))
throw new SmtpException(SR.SmtpNeedAbsolutePickupDirectory);
string filename;
string pathAndFilename;
while (true)
{
filename = Guid.NewGuid().ToString() + ".eml";
pathAndFilename = Path.Combine(pickupDirectory, filename);
if (!File.Exists(pathAndFilename))
break;
}
FileStream fileStream = new FileStream(pathAndFilename, FileMode.CreateNew);
return new MailWriter(fileStream);
}
protected void OnSendCompleted(AsyncCompletedEventArgs e)
{
SendCompleted?.Invoke(this, e);
}
private void SendCompletedWaitCallback(object operationState)
{
OnSendCompleted((AsyncCompletedEventArgs)operationState);
}
public void Send(string from, string recipients, string subject, string body)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
//validation happends in MailMessage constructor
MailMessage mailMessage = new MailMessage(from, recipients, subject, body);
Send(mailMessage);
}
public void Send(MailMessage message)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, message);
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
try
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(this, $"DeliveryMethod={DeliveryMethod}");
NetEventSource.Associate(this, message);
}
SmtpFailedRecipientException recipientException = null;
if (InCall)
{
throw new InvalidOperationException(SR.net_inasync);
}
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (DeliveryMethod == SmtpDeliveryMethod.Network)
CheckHostAndPort();
MailAddressCollection recipients = new MailAddressCollection();
if (message.From == null)
{
throw new InvalidOperationException(SR.SmtpFromRequired);
}
if (message.To != null)
{
foreach (MailAddress address in message.To)
{
recipients.Add(address);
}
}
if (message.Bcc != null)
{
foreach (MailAddress address in message.Bcc)
{
recipients.Add(address);
}
}
if (message.CC != null)
{
foreach (MailAddress address in message.CC)
{
recipients.Add(address);
}
}
if (recipients.Count == 0)
{
throw new InvalidOperationException(SR.SmtpRecipientRequired);
}
_transport.IdentityRequired = false; // everything completes on the same thread.
try
{
InCall = true;
_timedOut = false;
_timer = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
bool allowUnicode = false;
string pickupDirectory = PickupDirectoryLocation;
MailWriter writer;
switch (DeliveryMethod)
{
case SmtpDeliveryMethod.PickupDirectoryFromIis:
throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
case SmtpDeliveryMethod.SpecifiedPickupDirectory:
if (EnableSsl)
{
throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
}
allowUnicode = IsUnicodeSupported(); // Determend by the DeliveryFormat paramiter
ValidateUnicodeRequirement(message, recipients, allowUnicode);
writer = GetFileMailWriter(pickupDirectory);
break;
case SmtpDeliveryMethod.Network:
default:
GetConnection();
// Detected durring GetConnection(), restrictable using the DeliveryFormat paramiter
allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(message, recipients, allowUnicode);
writer = _transport.SendMail(message.Sender ?? message.From, recipients,
message.BuildDeliveryStatusNotificationString(), allowUnicode, out recipientException);
break;
}
_message = message;
message.Send(writer, DeliveryMethod != SmtpDeliveryMethod.Network, allowUnicode);
writer.Close();
_transport.ReleaseConnection();
//throw if we couldn't send to any of the recipients
if (DeliveryMethod == SmtpDeliveryMethod.Network && recipientException != null)
{
throw recipientException;
}
}
catch (Exception e)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
{
throw;
}
Abort();
if (_timedOut)
{
throw new SmtpException(SR.net_timeout);
}
if (e is SecurityException ||
e is AuthenticationException ||
e is SmtpException)
{
throw;
}
throw new SmtpException(SR.SmtpSendMailFailure, e);
}
finally
{
InCall = false;
if (_timer != null)
{
_timer.Dispose();
}
}
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
public void SendAsync(string from, string recipients, string subject, string body, object userToken)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
SendAsync(new MailMessage(from, recipients, subject, body), userToken);
}
public void SendAsync(MailMessage message, object userToken)
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, message, userToken, _transport);
try
{
if (InCall)
{
throw new InvalidOperationException(SR.net_inasync);
}
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (DeliveryMethod == SmtpDeliveryMethod.Network)
CheckHostAndPort();
_recipients = new MailAddressCollection();
if (message.From == null)
{
throw new InvalidOperationException(SR.SmtpFromRequired);
}
if (message.To != null)
{
foreach (MailAddress address in message.To)
{
_recipients.Add(address);
}
}
if (message.Bcc != null)
{
foreach (MailAddress address in message.Bcc)
{
_recipients.Add(address);
}
}
if (message.CC != null)
{
foreach (MailAddress address in message.CC)
{
_recipients.Add(address);
}
}
if (_recipients.Count == 0)
{
throw new InvalidOperationException(SR.SmtpRecipientRequired);
}
try
{
InCall = true;
_cancelled = false;
_message = message;
string pickupDirectory = PickupDirectoryLocation;
CredentialCache cache;
// Skip token capturing if no credentials are used or they don't include a default one.
// Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
_transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));
_asyncOp = AsyncOperationManager.CreateOperation(userToken);
switch (DeliveryMethod)
{
case SmtpDeliveryMethod.PickupDirectoryFromIis:
throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);
case SmtpDeliveryMethod.SpecifiedPickupDirectory:
{
if (EnableSsl)
{
throw new SmtpException(SR.SmtpPickupDirectoryDoesnotSupportSsl);
}
_writer = GetFileMailWriter(pickupDirectory);
bool allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(message, _recipients, allowUnicode);
message.Send(_writer, true, allowUnicode);
if (_writer != null)
_writer.Close();
_transport.ReleaseConnection();
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, _asyncOp.UserSuppliedState);
InCall = false;
_asyncOp.PostOperationCompleted(_onSendCompletedDelegate, eventArgs);
break;
}
case SmtpDeliveryMethod.Network:
default:
_operationCompletedResult = new ContextAwareResult(_transport.IdentityRequired, true, null, this, s_contextSafeCompleteCallback);
lock (_operationCompletedResult.StartPostingAsyncOp())
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
_transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host, Port);
_operationCompletedResult.FinishPostingAsyncOp();
}
break;
}
}
catch (Exception e)
{
InCall = false;
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
{
throw;
}
Abort();
if (_timedOut)
{
throw new SmtpException(SR.net_timeout);
}
if (e is SecurityException ||
e is AuthenticationException ||
e is SmtpException)
{
throw;
}
throw new SmtpException(SR.SmtpSendMailFailure, e);
}
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
private bool IsSystemNetworkCredentialInCache(CredentialCache cache)
{
// Check if SystemNetworkCredential is in given cache.
foreach (NetworkCredential credential in cache)
{
if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
{
return true;
}
}
return false;
}
public void SendAsyncCancel()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
if (!InCall || _cancelled)
{
return;
}
_cancelled = true;
Abort();
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
//************* Task-based async public methods *************************
public Task SendMailAsync(string from, string recipients, string subject, string body)
{
var message = new MailMessage(from, recipients, subject, body);
return SendMailAsync(message);
}
public Task SendMailAsync(MailMessage message)
{
// Create a TaskCompletionSource to represent the operation
var tcs = new TaskCompletionSource<object>();
// Register a handler that will transfer completion results to the TCS Task
SendCompletedEventHandler handler = null;
handler = (sender, e) => HandleCompletion(tcs, e, handler);
SendCompleted += handler;
// Start the async operation.
try
{
SendAsync(message, tcs);
}
catch
{
SendCompleted -= handler;
throw;
}
// Return the task to represent the asynchronous operation
return tcs.Task;
}
private void HandleCompletion(TaskCompletionSource<object> tcs, AsyncCompletedEventArgs e, SendCompletedEventHandler handler)
{
if (e.UserState == tcs)
{
try { SendCompleted -= handler; }
finally
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(null);
}
}
}
//*********************************
// private methods
//********************************
internal bool InCall
{
get
{
return _inCall;
}
set
{
_inCall = value;
}
}
private void CheckHostAndPort()
{
if (_host == null || _host.Length == 0)
{
throw new InvalidOperationException(SR.UnspecifiedHost);
}
if (_port <= 0 || _port > MaxPortValue)
{
throw new InvalidOperationException(SR.InvalidPort);
}
}
private void TimeOutCallback(object state)
{
if (!_timedOut)
{
_timedOut = true;
Abort();
}
}
private void Complete(Exception exception, IAsyncResult result)
{
ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState;
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
if (_cancelled)
{
//any exceptions were probably caused by cancellation, clear it.
exception = null;
Abort();
}
// An individual failed recipient exception is benign, only abort here if ALL the recipients failed.
else if (exception != null && (!(exception is SmtpFailedRecipientException) || ((SmtpFailedRecipientException)exception).fatal))
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
Abort();
if (!(exception is SmtpException))
{
exception = new SmtpException(SR.SmtpSendMailFailure, exception);
}
}
else
{
if (_writer != null)
{
try
{
_writer.Close();
}
// Close may result in a DataStopCommand and the server may return error codes at this time.
catch (SmtpException se)
{
exception = se;
}
}
_transport.ReleaseConnection();
}
}
finally
{
operationCompletedResult.InvokeCallback(exception);
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Complete");
}
private static void ContextSafeCompleteCallback(IAsyncResult ar)
{
ContextAwareResult result = (ContextAwareResult)ar;
SmtpClient client = (SmtpClient)ar.AsyncState;
Exception exception = result.Result as Exception;
AsyncOperation asyncOp = client._asyncOp;
AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(exception, client._cancelled, asyncOp.UserSuppliedState);
client.InCall = false;
client._failedRecipientException = null; // Reset before the next send.
asyncOp.PostOperationCompleted(client._onSendCompletedDelegate, eventArgs);
}
private void SendMessageCallback(IAsyncResult result)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
_message.EndSend(result);
// If some recipients failed but not others, throw AFTER sending the message.
Complete(_failedRecipientException, result);
}
catch (Exception e)
{
Complete(e, result);
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
private void SendMailCallback(IAsyncResult result)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
_writer = _transport.EndSendMail(result);
// If some recipients failed but not others, send the e-mail anyways, but then return the
// "Non-fatal" exception reporting the failures. The sync code path does it this way.
// Fatal exceptions would have thrown above at transport.EndSendMail(...)
SendMailAsyncResult sendResult = (SendMailAsyncResult)result;
// Save these and throw them later in SendMessageCallback, after the message has sent.
_failedRecipientException = sendResult.GetFailedRecipientException();
}
catch (Exception e)
{
Complete(e, result);
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
return;
}
try
{
if (_cancelled)
{
Complete(null, result);
}
else
{
_message.BeginSend(_writer, DeliveryMethod != SmtpDeliveryMethod.Network,
ServerSupportsEai, new AsyncCallback(SendMessageCallback), result.AsyncState);
}
}
catch (Exception e)
{
Complete(e, result);
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
private void ConnectCallback(IAsyncResult result)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
try
{
_transport.EndGetConnection(result);
if (_cancelled)
{
Complete(null, result);
}
else
{
// Detected durring Begin/EndGetConnection, restrictable using DeliveryFormat
bool allowUnicode = IsUnicodeSupported();
ValidateUnicodeRequirement(_message, _recipients, allowUnicode);
_transport.BeginSendMail(_message.Sender ?? _message.From, _recipients,
_message.BuildDeliveryStatusNotificationString(), allowUnicode,
new AsyncCallback(SendMailCallback), result.AsyncState);
}
}
catch (Exception e)
{
Complete(e, result);
}
finally
{
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
}
// After we've estabilished a connection and initilized ServerSupportsEai,
// check all the addresses for one that contains unicode in the username/localpart.
// The localpart is the only thing we cannot succesfully downgrade.
private void ValidateUnicodeRequirement(MailMessage message, MailAddressCollection recipients, bool allowUnicode)
{
// Check all recipients, to, from, sender, bcc, cc, etc...
// GetSmtpAddress will throw if !allowUnicode and the username contains non-ascii
foreach (MailAddress address in recipients)
{
address.GetSmtpAddress(allowUnicode);
}
if (message.Sender != null)
{
message.Sender.GetSmtpAddress(allowUnicode);
}
message.From.GetSmtpAddress(allowUnicode);
}
private void GetConnection()
{
if (!_transport.IsConnected)
{
_transport.GetConnection(_host, _port);
}
}
private void Abort()
{
try
{
_transport.Abort();
}
catch
{
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
if (InCall && !_cancelled)
{
_cancelled = true;
Abort();
}
if ((_transport != null))
{
_transport.ReleaseConnection();
}
if (_timer != null)
{
_timer.Dispose();
}
_disposed = true;
}
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
// Based on https://github.com/JohnACarruthers/Opus.NET
namespace Voxalia.ClientGame.AudioSystem.OpusWrapper
{
/// <summary>
/// Opus codec wrapper.
/// </summary>
public class OpusEncoder : IDisposable
{
/// <summary>
/// Creates a new Opus encoder.
/// </summary>
/// <param name="inputSamplingRate">Sampling rate of the input signal (Hz). This must be one of 8000, 12000, 16000, 24000, or 48000.</param>
/// <param name="inputChannels">Number of channels (1 or 2) in input signal.</param>
/// <param name="application">Coding mode.</param>
/// <returns>A new <c>OpusEncoder</c></returns>
public static OpusEncoder Create(int inputSamplingRate, int inputChannels, Application application)
{
if (inputSamplingRate != 8000 &&
inputSamplingRate != 12000 &&
inputSamplingRate != 16000 &&
inputSamplingRate != 24000 &&
inputSamplingRate != 48000)
{
throw new ArgumentOutOfRangeException("inputSamplingRate");
}
if (inputChannels != 1 && inputChannels != 2)
{
throw new ArgumentOutOfRangeException("inputChannels");
}
IntPtr error;
IntPtr encoder = OpusAPI.opus_encoder_create(inputSamplingRate, inputChannels, (int)application, out error);
if ((Errors)error != Errors.OK)
{
throw new Exception("Exception occured while creating encoder");
}
return new OpusEncoder(encoder, inputSamplingRate, inputChannels, application);
}
private IntPtr _encoder;
private OpusEncoder(IntPtr encoder, int inputSamplingRate, int inputChannels, Application application)
{
_encoder = encoder;
InputSamplingRate = inputSamplingRate;
InputChannels = inputChannels;
Application = application;
MaxDataBytes = 4000;
}
/// <summary>
/// Produces Opus encoded audio from PCM samples.
/// </summary>
/// <param name="inputPcmSamples">PCM samples to encode.</param>
/// <returns>Opus encoded audio buffer.</returns>
public byte[] Encode(byte[] inputPcmSamples)
{
int frames = FrameCount(inputPcmSamples);
IntPtr encodedPtr = Marshal.AllocHGlobal(MaxDataBytes);
IntPtr inputPtr = Marshal.AllocHGlobal(inputPcmSamples.Length);
Marshal.Copy(inputPcmSamples, 0, inputPtr, inputPcmSamples.Length);
int length = OpusAPI.opus_encode(_encoder, inputPtr, frames, encodedPtr, MaxDataBytes);
Marshal.FreeHGlobal(inputPtr);
byte[] encodedBytes = new byte[length];
Marshal.Copy(encodedPtr, encodedBytes, 0, length);
Marshal.FreeHGlobal(encodedPtr);
if (length < 0)
{
throw new Exception("Encoding failed - " + ((Errors)length).ToString());
}
return encodedBytes;
}
/// <summary>
/// Determines the number of frames in the PCM samples.
/// </summary>
/// <param name="pcmSamples"></param>
/// <returns></returns>
public int FrameCount(byte[] pcmSamples)
{
// seems like bitrate should be required
int bitrate = 16;
int bytesPerSample = (bitrate / 8) * InputChannels;
return pcmSamples.Length / bytesPerSample;
}
/// <summary>
/// Helper method to determine how many bytes are required for encoding to work.
/// </summary>
/// <param name="frameCount">Target frame size.</param>
/// <returns></returns>
public int FrameByteCount(int frameCount)
{
int bitrate = 16;
int bytesPerSample = (bitrate / 8) * InputChannels;
return frameCount * bytesPerSample;
}
/// <summary>
/// Gets the input sampling rate of the encoder.
/// </summary>
public int InputSamplingRate;
/// <summary>
/// Gets the number of channels of the encoder.
/// </summary>
public int InputChannels;
/// <summary>
/// Gets the coding mode of the encoder.
/// </summary>
public Application Application;
/// <summary>
/// Gets or sets the size of memory allocated for reading encoded data.
/// 4000 is recommended.
/// </summary>
public int MaxDataBytes;
/// <summary>
/// Gets or sets the bitrate setting of the encoding.
/// </summary>
public int Bitrate
{
get
{
int bitrate;
var ret = OpusAPI.opus_encoder_ctl(_encoder, Ctl.GetBitrateRequest, out bitrate);
if (ret < 0)
{
throw new Exception("Encoder error - " + ((Errors)ret).ToString());
}
return bitrate;
}
set
{
var ret = OpusAPI.opus_encoder_ctl(_encoder, Ctl.SetBitrateRequest, value);
if (ret < 0)
{
throw new Exception("Encoder error - " + ((Errors)ret).ToString());
}
}
}
/// <summary>
/// Gets or sets whether Forward Error Correction is enabled.
/// </summary>
public bool ForwardErrorCorrection
{
get
{
int fec;
int ret = OpusAPI.opus_encoder_ctl(_encoder, Ctl.GetInbandFECRequest, out fec);
if (ret < 0)
{
throw new Exception("Encoder error - " + ((Errors)ret).ToString());
}
return fec > 0;
}
set
{
var ret = OpusAPI.opus_encoder_ctl(_encoder, Ctl.SetInbandFECRequest, value ? 1 : 0);
if (ret < 0)
{
throw new Exception("Encoder error - " + ((Errors)ret).ToString());
}
}
}
~OpusEncoder()
{
Dispose();
}
private bool disposed;
public void Dispose()
{
if (disposed)
{
return;
}
GC.SuppressFinalize(this);
if (_encoder != IntPtr.Zero)
{
OpusAPI.opus_encoder_destroy(_encoder);
_encoder = IntPtr.Zero;
}
disposed = true;
}
}
}
| |
// 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 is used internally to create best fit behavior as per the original windows best fit behavior.
//
using System.Diagnostics;
using System.Globalization;
using System.Threading;
namespace System.Text
{
internal class InternalEncoderBestFitFallback : EncoderFallback
{
// Our variables
internal Encoding _encoding;
internal char[]? _arrayBestFit = null;
internal InternalEncoderBestFitFallback(Encoding encoding)
{
// Need to load our replacement characters table.
_encoding = encoding;
}
public override EncoderFallbackBuffer CreateFallbackBuffer() =>
new InternalEncoderBestFitFallbackBuffer(this);
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount => 1;
public override bool Equals(object? value) =>
value is InternalEncoderBestFitFallback that &&
_encoding.CodePage == that._encoding.CodePage;
public override int GetHashCode() => _encoding.CodePage;
}
internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer
{
// Our variables
private char _cBestFit = '\0';
private readonly InternalEncoderBestFitFallback _oFallback;
private int _iCount = -1;
private int _iSize;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static object? s_InternalSyncObject;
private static object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange<object?>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
// Constructor
public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback)
{
_oFallback = fallback;
if (_oFallback._arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
lock (InternalSyncObject)
{
// Double check before we do it again.
_oFallback._arrayBestFit ??= fallback._encoding.GetBestFitUnicodeToBytesData();
}
}
}
// Fallback methods
public override bool Fallback(char charUnknown, int index)
{
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
// Shouldn't be able to get here for all of our code pages, table would have to be messed up.
Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(non surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
_iCount = _iSize = 1;
_cBestFit = TryBestFit(charUnknown);
if (_cBestFit == '\0')
_cBestFit = '?';
return true;
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
// Double check input surrogate pair
if (!char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
SR.Format(SR.ArgumentOutOfRange_Range,
0xD800, 0xDBFF));
if (!char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
SR.Format(SR.ArgumentOutOfRange_Range,
0xDC00, 0xDFFF));
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array. 0 is processing last character, < 0 is not falling back
// Shouldn't be able to get here, table would have to be messed up.
Debug.Assert(_iCount < 1, "[InternalEncoderBestFitFallbackBuffer.Fallback(surrogate)] Fallback char " + ((int)_cBestFit).ToString("X4", CultureInfo.InvariantCulture) + " caused recursive fallback");
// Go ahead and get our fallback, surrogates don't have best fit
_cBestFit = '?';
_iCount = _iSize = 2;
return true;
}
// Default version is overridden in EncoderReplacementFallback.cs
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
_iCount--;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (_iCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (_iCount == int.MaxValue)
{
_iCount = -1;
return '\0';
}
// Return the best fit character
return _cBestFit;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
if (_iCount >= 0)
_iCount++;
// Return true if we could do it.
return _iCount >= 0 && _iCount <= _iSize;
}
// How many characters left to output?
public override int Remaining => (_iCount > 0) ? _iCount : 0;
// Clear the buffer
public override unsafe void Reset()
{
_iCount = -1;
charStart = null;
bFallingBack = false;
}
// private helper methods
private char TryBestFit(char cUnknown)
{
// Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array
int lowBound = 0;
Debug.Assert(_oFallback._arrayBestFit != null);
int highBound = _oFallback._arrayBestFit.Length;
int index;
// Binary search the array
int iDiff;
while ((iDiff = (highBound - lowBound)) > 6)
{
// Look in the middle, which is complicated by the fact that we have 2 #s for each pair,
// so we don't want index to be odd because we want to be on word boundaries.
// Also note that index can never == highBound (because diff is rounded down)
index = ((iDiff / 2) + lowBound) & 0xFFFE;
char cTest = _oFallback._arrayBestFit[index];
if (cTest == cUnknown)
{
// We found it
Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback._arrayBestFit[index + 1];
}
else if (cTest < cUnknown)
{
// We weren't high enough
lowBound = index;
}
else
{
// We weren't low enough
highBound = index;
}
}
for (index = lowBound; index < highBound; index += 2)
{
if (_oFallback._arrayBestFit[index] == cUnknown)
{
// We found it
Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length,
"[InternalEncoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array");
return _oFallback._arrayBestFit[index + 1];
}
}
// Char wasn't in our table
return '\0';
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using System.Xml.Linq;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Publishing;
namespace Umbraco.Core.Services
{
/// <summary>
/// A temporary interface until we are in v8, this is used to return a different result for the same method and this interface gets implemented
/// explicitly. These methods will replace the normal ones in IContentService in v8 and this will be removed.
/// </summary>
public interface IContentServiceOperations
{
//TODO: Remove this class in v8
//TODO: There's probably more that needs to be added like the EmptyRecycleBin, etc...
/// <summary>
/// Saves a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
Attempt<OperationStatus> Save(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves a collection of <see cref="IContent"/> objects.
/// </summary>
/// <param name="contents">Collection of <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
Attempt<OperationStatus> Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Permanently deletes an <see cref="IContent"/> object.
/// </summary>
/// <remarks>
/// This method will also delete associated media files, child content and possibly associated domains.
/// </remarks>
/// <remarks>Please note that this method will completely remove the Content from the database</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
Attempt<OperationStatus> Delete(IContent content, int userId = 0);
/// <summary>
/// Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>The published status attempt</returns>
Attempt<PublishStatus> Publish(IContent content, int userId = 0);
/// <summary>
/// Publishes a <see cref="IContent"/> object and all its children
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish along with its children</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="includeUnpublished"></param>
/// <returns>The list of statuses for all published items</returns>
IEnumerable<Attempt<PublishStatus>> PublishWithChildren(IContent content, int userId = 0, bool includeUnpublished = false);
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
Attempt<PublishStatus> SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin
/// </summary>
/// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
Attempt<OperationStatus> MoveToRecycleBin(IContent content, int userId = 0);
/// <summary>
/// UnPublishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if unpublishing succeeded, otherwise False</returns>
Attempt<UnPublishStatus> UnPublish(IContent content, int userId = 0);
}
/// <summary>
/// Defines the ContentService, which is an easy access to operations involving <see cref="IContent"/>
/// </summary>
public interface IContentService : IService
{
/// <summary>
/// Gets all XML entries found in the cmsContentXml table based on the given path
/// </summary>
/// <param name="path">Path starts with</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records the query would return without paging</param>
/// <returns>A paged enumerable of XML entries of content items</returns>
/// <remarks>
/// If -1 is passed, then this will return all content xml entries, otherwise will return all descendents from the path
/// </remarks>
IEnumerable<XElement> GetPagedXmlEntries(string path, long pageIndex, int pageSize, out long totalRecords);
/// <summary>
/// This builds the Xml document used for the XML cache
/// </summary>
/// <returns></returns>
XmlDocument BuildXmlCache();
/// <summary>
/// Rebuilds all xml content in the cmsContentXml table for all documents
/// </summary>
/// <param name="contentTypeIds">
/// Only rebuild the xml structures for the content type ids passed in, if none then rebuilds the structures
/// for all content
/// </param>
void RebuildXmlStructures(params int[] contentTypeIds);
int CountPublished(string contentTypeAlias = null);
int Count(string contentTypeAlias = null);
int CountChildren(int parentId, string contentTypeAlias = null);
int CountDescendants(int parentId, string contentTypeAlias = null);
/// <summary>
/// Used to bulk update the permissions set for a content item. This will replace all permissions
/// assigned to an entity with a list of user id & permission pairs.
/// </summary>
/// <param name="permissionSet"></param>
void ReplaceContentPermissions(EntityPermissionSet permissionSet);
/// <summary>
/// Assigns a single permission to the current content item for the specified user ids
/// </summary>
/// <param name="entity"></param>
/// <param name="permission"></param>
/// <param name="userIds"></param>
void AssignContentPermission(IContent entity, char permission, IEnumerable<int> userIds);
/// <summary>
/// Gets the list of permissions for the content item
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
IEnumerable<EntityPermission> GetPermissionsForEntity(IContent content);
bool SendToPublication(IContent content, int userId = 0);
IEnumerable<IContent> GetByIds(IEnumerable<int> ids);
/// <summary>
/// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IContent without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new content objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parentId">Id of Parent for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContent(string name, int parentId, string contentTypeAlias, int userId = 0);
/// <summary>
/// Creates an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IContent without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new content objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContent(string name, IContent parent, string contentTypeAlias, int userId = 0);
/// <summary>
/// Gets an <see cref="IContent"/> object by Id
/// </summary>
/// <param name="id">Id of the Content to retrieve</param>
/// <returns><see cref="IContent"/></returns>
IContent GetById(int id);
/// <summary>
/// Gets an <see cref="IContent"/> object by its 'UniqueId'
/// </summary>
/// <param name="key">Guid key of the Content to retrieve</param>
/// <returns><see cref="IContent"/></returns>
IContent GetById(Guid key);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by the Id of the <see cref="IContentType"/>
/// </summary>
/// <param name="id">Id of the <see cref="IContentType"/></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentOfContentType(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Level
/// </summary>
/// <param name="level">The level to retrieve Content from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetByLevel(int level);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetChildren(int id);
[Obsolete("Use the overload with 'long' parameter types instead")]
[EditorBrowsable(EditorBrowsableState.Never)]
IEnumerable<IContent> GetPagedChildren(int id, int pageIndex, int pageSize, out int totalRecords,
string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, string filter);
[Obsolete("Use the overload with 'long' parameter types instead")]
[EditorBrowsable(EditorBrowsableState.Never)]
IEnumerable<IContent> GetPagedDescendants(int id, int pageIndex, int pageSize, out int totalRecords,
string orderBy = "path", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy = "path", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, string filter);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter"></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, IQuery<IContent> filter);
/// <summary>
/// Gets a collection of an <see cref="IContent"/> objects versions by its Id
/// </summary>
/// <param name="id"></param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetVersions(int id);
/// <summary>
/// Gets a list of all version Ids for the given content item ordered so latest is first
/// </summary>
/// <param name="id"></param>
/// <param name="maxRows">The maximum number of rows to return</param>
/// <returns></returns>
IEnumerable<Guid> GetVersionIds(int id, int maxRows);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which reside at the first level / root
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetRootContent();
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which has an expiration date greater then today
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentForExpiration();
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which has a release date greater then today
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentForRelease();
/// <summary>
/// Gets a collection of an <see cref="IContent"/> objects, which resides in the Recycle Bin
/// </summary>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetContentInRecycleBin();
/// <summary>
/// Saves a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
void Save(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves a collection of <see cref="IContent"/> objects.
/// </summary>
/// <param name="contents">Collection of <see cref="IContent"/> to save</param>
/// <param name="userId">Optional Id of the User saving the Content</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
void Save(IEnumerable<IContent> contents, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Deletes all content of specified type. All children of deleted content is moved to Recycle Bin.
/// </summary>
/// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks>
/// <param name="contentTypeId">Id of the <see cref="IContentType"/></param>
/// <param name="userId">Optional Id of the user issueing the delete operation</param>
void DeleteContentOfType(int contentTypeId, int userId = 0);
/// <summary>
/// Permanently deletes versions from an <see cref="IContent"/> object prior to a specific date.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> object to delete versions from</param>
/// <param name="versionDate">Latest version date</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersions(int id, DateTime versionDate, int userId = 0);
/// <summary>
/// Permanently deletes a specific version from an <see cref="IContent"/> object.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> object to delete a version from</param>
/// <param name="versionId">Id of the version to delete</param>
/// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0);
/// <summary>
/// Deletes an <see cref="IContent"/> object by moving it to the Recycle Bin
/// </summary>
/// <remarks>Move an item to the Recycle Bin will result in the item being unpublished</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
void MoveToRecycleBin(IContent content, int userId = 0);
/// <summary>
/// Moves an <see cref="IContent"/> object to a new location
/// </summary>
/// <param name="content">The <see cref="IContent"/> to move</param>
/// <param name="parentId">Id of the Content's new Parent</param>
/// <param name="userId">Optional Id of the User moving the Content</param>
void Move(IContent content, int parentId, int userId = 0);
/// <summary>
/// Empties the Recycle Bin by deleting all <see cref="IContent"/> that resides in the bin
/// </summary>
void EmptyRecycleBin();
/// <summary>
/// Rollback an <see cref="IContent"/> object to a previous version.
/// This will create a new version, which is a copy of all the old data.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/>being rolled back</param>
/// <param name="versionId">Id of the version to rollback to</param>
/// <param name="userId">Optional Id of the User issueing the rollback of the Content</param>
/// <returns>The newly created <see cref="IContent"/> object</returns>
IContent Rollback(int id, Guid versionId, int userId = 0);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by its name or partial name
/// </summary>
/// <param name="parentId">Id of the Parent to retrieve Children from</param>
/// <param name="name">Full or partial name of the children</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetChildrenByName(int parentId, string name);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetDescendants(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects by Parent Id
/// </summary>
/// <param name="content"><see cref="IContent"/> item to retrieve Descendants from</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetDescendants(IContent content);
/// <summary>
/// Gets a specific version of an <see cref="IContent"/> item.
/// </summary>
/// <param name="versionId">Id of the version to retrieve</param>
/// <returns>An <see cref="IContent"/> item</returns>
IContent GetByVersion(Guid versionId);
/// <summary>
/// Gets the published version of an <see cref="IContent"/> item
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> to retrieve version from</param>
/// <returns>An <see cref="IContent"/> item</returns>
IContent GetPublishedVersion(int id);
/// <summary>
/// Gets the published version of a <see cref="IContent"/> item.
/// </summary>
/// <param name="content">The content item.</param>
/// <returns>The published version, if any; otherwise, null.</returns>
IContent GetPublishedVersion(IContent content);
/// <summary>
/// Checks whether an <see cref="IContent"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/></param>
/// <returns>True if the content has any children otherwise False</returns>
bool HasChildren(int id);
/// <summary>
/// Checks whether an <see cref="IContent"/> item has any published versions
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/></param>
/// <returns>True if the content has any published version otherwise False</returns>
bool HasPublishedVersion(int id);
/// <summary>
/// Re-Publishes all Content
/// </summary>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
bool RePublishAll(int userId = 0);
/// <summary>
/// Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
bool Publish(IContent content, int userId = 0);
/// <summary>
/// Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>The published status attempt</returns>
Attempt<PublishStatus> PublishWithStatus(IContent content, int userId = 0);
/// <summary>
/// Publishes a <see cref="IContent"/> object and all its children
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish along with its children</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use PublishWithChildrenWithStatus instead, that method will provide more detailed information on the outcome and also allows the includeUnpublished flag")]
bool PublishWithChildren(IContent content, int userId = 0);
/// <summary>
/// Publishes a <see cref="IContent"/> object and all its children
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish along with its children</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="includeUnpublished"></param>
/// <returns>The list of statuses for all published items</returns>
IEnumerable<Attempt<PublishStatus>> PublishWithChildrenWithStatus(IContent content, int userId = 0, bool includeUnpublished = false);
/// <summary>
/// UnPublishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <returns>True if unpublishing succeeded, otherwise False</returns>
bool UnPublish(IContent content, int userId = 0);
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
[Obsolete("Use SaveAndPublishWithStatus instead, that method will provide more detailed information on the outcome")]
[EditorBrowsable(EditorBrowsableState.Never)]
bool SaveAndPublish(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves and Publishes a single <see cref="IContent"/> object
/// </summary>
/// <param name="content">The <see cref="IContent"/> to save and publish</param>
/// <param name="userId">Optional Id of the User issueing the publishing</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise save events.</param>
/// <returns>True if publishing succeeded, otherwise False</returns>
Attempt<PublishStatus> SaveAndPublishWithStatus(IContent content, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Permanently deletes an <see cref="IContent"/> object.
/// </summary>
/// <remarks>
/// This method will also delete associated media files, child content and possibly associated domains.
/// </remarks>
/// <remarks>Please note that this method will completely remove the Content from the database</remarks>
/// <param name="content">The <see cref="IContent"/> to delete</param>
/// <param name="userId">Optional Id of the User deleting the Content</param>
void Delete(IContent content, int userId = 0);
/// <summary>
/// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current
/// to the new copy, which is returned. Recursively copies all children.
/// </summary>
/// <param name="content">The <see cref="IContent"/> to copy</param>
/// <param name="parentId">Id of the Content's new Parent</param>
/// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param>
/// <param name="userId">Optional Id of the User copying the Content</param>
/// <returns>The newly created <see cref="IContent"/> object</returns>
IContent Copy(IContent content, int parentId, bool relateToOriginal, int userId = 0);
/// <summary>
/// Copies an <see cref="IContent"/> object by creating a new Content object of the same type and copies all data from the current
/// to the new copy which is returned.
/// </summary>
/// <param name="content">The <see cref="IContent"/> to copy</param>
/// <param name="parentId">Id of the Content's new Parent</param>
/// <param name="relateToOriginal">Boolean indicating whether the copy should be related to the original</param>
/// <param name="recursive">A value indicating whether to recursively copy children.</param>
/// <param name="userId">Optional Id of the User copying the Content</param>
/// <returns>The newly created <see cref="IContent"/> object</returns>
IContent Copy(IContent content, int parentId, bool relateToOriginal, bool recursive, int userId = 0);
/// <summary>
/// Checks if the passed in <see cref="IContent"/> can be published based on the anscestors publish state.
/// </summary>
/// <param name="content"><see cref="IContent"/> to check if anscestors are published</param>
/// <returns>True if the Content can be published, otherwise False</returns>
bool IsPublishable(IContent content);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetAncestors(int id);
/// <summary>
/// Gets a collection of <see cref="IContent"/> objects, which are ancestors of the current content.
/// </summary>
/// <param name="content"><see cref="IContent"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IContent> GetAncestors(IContent content);
/// <summary>
/// Sorts a collection of <see cref="IContent"/> objects by updating the SortOrder according
/// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>.
/// </summary>
/// <remarks>
/// Using this method will ensure that the Published-state is maintained upon sorting
/// so the cache is updated accordingly - as needed.
/// </remarks>
/// <param name="items"></param>
/// <param name="userId"></param>
/// <param name="raiseEvents"></param>
/// <returns>True if sorting succeeded, otherwise False</returns>
bool Sort(IEnumerable<IContent> items, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Gets the parent of the current content as an <see cref="IContent"/> item.
/// </summary>
/// <param name="id">Id of the <see cref="IContent"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IContent"/> object</returns>
IContent GetParent(int id);
/// <summary>
/// Gets the parent of the current content as an <see cref="IContent"/> item.
/// </summary>
/// <param name="content"><see cref="IContent"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IContent"/> object</returns>
IContent GetParent(IContent content);
/// <summary>
/// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IContent"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parent">Parent <see cref="IContent"/> object for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContentWithIdentity(string name, IContent parent, string contentTypeAlias, int userId = 0);
/// <summary>
/// Creates and saves an <see cref="IContent"/> object using the alias of the <see cref="IContentType"/>
/// that this Content should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IContent"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Content object</param>
/// <param name="parentId">Id of Parent for the new Content</param>
/// <param name="contentTypeAlias">Alias of the <see cref="IContentType"/></param>
/// <param name="userId">Optional id of the user creating the content</param>
/// <returns><see cref="IContent"/></returns>
IContent CreateContentWithIdentity(string name, int parentId, string contentTypeAlias, int userId = 0);
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="SingleAnimationUsingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used to animate a Single property value along a set
/// of key frames.
/// </summary>
[ContentProperty("KeyFrames")]
public class SingleAnimationUsingKeyFrames : SingleAnimationBase, IKeyFrameAnimation, IAddChild
{
#region Data
private SingleKeyFrameCollection _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
private bool _areKeyTimesValid;
#endregion
#region Constructors
/// <Summary>
/// Creates a new KeyFrameSingleAnimation.
/// </Summary>
public SingleAnimationUsingKeyFrames()
: base()
{
_areKeyTimesValid = true;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this KeyFrameSingleAnimation.
/// </summary>
/// <returns>The copy</returns>
public new SingleAnimationUsingKeyFrames Clone()
{
return (SingleAnimationUsingKeyFrames)base.Clone();
}
/// <summary>
/// Returns a version of this class with all its base property values
/// set to the current animated values and removes the animations.
/// </summary>
/// <returns>
/// Since this class isn't animated, this method will always just return
/// this instance of the class.
/// </returns>
public new SingleAnimationUsingKeyFrames CloneCurrentValue()
{
return (SingleAnimationUsingKeyFrames)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
canFreeze &= Freezable.Freeze(_keyFrames, isChecking);
if (canFreeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return canFreeze;
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>.
/// </summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new SingleAnimationUsingKeyFrames();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
SingleAnimationUsingKeyFrames sourceAnimation = (SingleAnimationUsingKeyFrames) sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
SingleAnimationUsingKeyFrames sourceAnimation = (SingleAnimationUsingKeyFrames) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
SingleAnimationUsingKeyFrames sourceAnimation = (SingleAnimationUsingKeyFrames) source;
base.GetAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
SingleAnimationUsingKeyFrames sourceAnimation = (SingleAnimationUsingKeyFrames) source;
base.GetCurrentValueAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Helper used by the four Freezable clone methods to copy the resolved key times and
/// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core
/// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here.
/// </summary>
/// <param name="sourceAnimation"></param>
/// <param name="isCurrentValueClone"></param>
private void CopyCommon(SingleAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if ( _areKeyTimesValid
&& sourceAnimation._sortedResolvedKeyFrames != null)
{
// _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (SingleKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = (SingleKeyFrameCollection)sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
#endregion // Freezable
#region IAddChild interface
/// <summary>
/// Adds a child object to this KeyFrameAnimation.
/// </summary>
/// <param name="child">
/// The child object to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation only accepts a KeyFrame of the proper type as
/// a child.
/// </remarks>
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
/// <summary>
/// Implemented to allow KeyFrames to be direct children
/// of KeyFrameAnimations in markup.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
SingleKeyFrame keyFrame = child as SingleKeyFrame;
if (keyFrame != null)
{
KeyFrames.Add(keyFrame);
}
else
{
throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child");
}
}
/// <summary>
/// Adds a text string as a child of this KeyFrameAnimation.
/// </summary>
/// <param name="childText">
/// The text to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation does not accept text as a child, so this method will
/// raise an InvalididOperationException unless a derived class has
/// overridden the behavior to add text.
/// </remarks>
/// <exception cref="ArgumentNullException">The childText parameter is
/// null.</exception>
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
/// <summary>
/// This method performs the core functionality of the AddText()
/// method on the IAddChild interface. For a KeyFrameAnimation this means
/// throwing and InvalidOperationException because it doesn't
/// support adding text.
/// </summary>
/// <remarks>
/// This method is the only core implementation. It does not call
/// WritePreamble() or WritePostscript(). It also doesn't throw an
/// ArgumentNullException if the childText parameter is null. These tasks
/// are performed by the interface implementation. Therefore, it's OK
/// for a derived class to override this method and call the base
/// class implementation only if they determine that it's the right
/// course of action. The derived class can rely on KeyFrameAnimation's
/// implementation of IAddChild.AddChild or implement their own
/// following the Freezable pattern since that would be a public
/// method.
/// </remarks>
/// <param name="childText">A string representing the child text that
/// should be added. If this is a KeyFrameAnimation an exception will be
/// thrown.</param>
/// <exception cref="InvalidOperationException">Timelines have no way
/// of adding text.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren));
}
#endregion
#region SingleAnimationBase
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected sealed override Single GetCurrentValueCore(
Single defaultOriginValue,
Single defaultDestinationValue,
AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (_keyFrames == null)
{
return defaultDestinationValue;
}
// We resolved our KeyTimes when we froze, but also got notified
// of the frozen state and therefore invalidated ourselves.
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
TimeSpan currentTime = animationClock.CurrentTime.Value;
Int32 keyFrameCount = _sortedResolvedKeyFrames.Length;
Int32 maxKeyFrameIndex = keyFrameCount - 1;
Single currentIterationValue;
Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames.");
Int32 currentResolvedKeyFrameIndex = 0;
// Skip all the key frames with key times lower than the current time.
// currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex
// if we are past the last key frame.
while ( currentResolvedKeyFrameIndex < keyFrameCount
&& currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
// If there are multiple key frames at the same key time, be sure to go to the last one.
while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex
&& currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
if (currentResolvedKeyFrameIndex == keyFrameCount)
{
// Past the last key frame.
currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
// Exactly on a key frame.
currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
}
else
{
// Between two key frames.
Double currentSegmentProgress = 0.0;
Single fromValue;
if (currentResolvedKeyFrameIndex == 0)
{
// The current key frame is the first key frame so we have
// some special rules for determining the fromValue and an
// optimized method of calculating the currentSegmentProgress.
// If we're additive we want the base value to be a zero value
// so that if there isn't a key frame at time 0.0, we'll use
// the zero value for the time 0.0 value and then add that
// later to the base value.
if (IsAdditive)
{
fromValue = AnimatedTypeHelpers.GetZeroValueSingle(defaultOriginValue);
}
else
{
fromValue = defaultOriginValue;
}
// Current segment time divided by the segment duration.
// Note: the reason this works is that we know that we're in
// the first segment, so we can assume:
//
// currentTime.TotalMilliseconds = current segment time
// _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration
currentSegmentProgress = currentTime.TotalMilliseconds
/ _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
}
else
{
Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime;
TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
currentSegmentProgress = segmentCurrentTime.TotalMilliseconds
/ segmentDuration.TotalMilliseconds;
}
currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
}
// If we're cumulative, we need to multiply the final key frame
// value by the current repeat count and add this to the return
// value.
if (IsCumulative)
{
Double currentRepeat = (Double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
currentIterationValue = AnimatedTypeHelpers.AddSingle(
currentIterationValue,
AnimatedTypeHelpers.ScaleSingle(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat));
}
}
// If we're additive we need to add the base value to the return value.
if (IsAdditive)
{
return AnimatedTypeHelpers.AddSingle(defaultOriginValue, currentIterationValue);
}
return currentIterationValue;
}
/// <summary>
/// Provide a custom natural Duration when the Duration property is set to Automatic.
/// </summary>
/// <param name="clock">
/// The Clock whose natural duration is desired.
/// </param>
/// <returns>
/// If the last KeyFrame of this animation is a KeyTime, then this will
/// be used as the NaturalDuration; otherwise it will be one second.
/// </returns>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
#endregion
#region IKeyFrameAnimation
/// <summary>
/// Returns the SingleKeyFrameCollection used by this KeyFrameSingleAnimation.
/// </summary>
IList IKeyFrameAnimation.KeyFrames
{
get
{
return KeyFrames;
}
set
{
KeyFrames = (SingleKeyFrameCollection)value;
}
}
/// <summary>
/// Returns the SingleKeyFrameCollection used by this KeyFrameSingleAnimation.
/// </summary>
public SingleKeyFrameCollection KeyFrames
{
get
{
ReadPreamble();
// The reason we don't just set _keyFrames to the empty collection
// in the first place is that null tells us that the user has not
// asked for the collection yet. The first time they ask for the
// collection and we're unfrozen, policy dictates that we give
// them a new unfrozen collection. All subsequent times they will
// get whatever collection is present, whether frozen or unfrozen.
if (_keyFrames == null)
{
if (this.IsFrozen)
{
_keyFrames = SingleKeyFrameCollection.Empty;
}
else
{
WritePreamble();
_keyFrames = new SingleKeyFrameCollection();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (value != _keyFrames)
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
/// <summary>
/// Returns true if we should serialize the KeyFrames, property for this Animation.
/// </summary>
/// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
return _keyFrames != null
&& _keyFrames.Count > 0;
}
#endregion
#region Public Properties
/// <summary>
/// If this property is set to true, this animation will add its value
/// to the base value or the value of the previous animation in the
/// composition chain. Another way of saying this is that the units
/// specified in the animation are relative to the base value rather
/// than absolute units.
/// </summary>
/// <remarks>
/// In the case where the first key frame's resolved key time is not
/// 0.0 there is slightly different behavior between KeyFrameSingleAnimations
/// with IsAdditive set and without. Animations with the property set to false
/// will behave as if there is a key frame at time 0.0 with the value of the
/// base value. Animations with the property set to true will behave as if
/// there is a key frame at time 0.0 with a zero value appropriate to the type
/// of the animation. These behaviors provide the results most commonly expected
/// and can be overridden by simply adding a key frame at time 0.0 with the preferred value.
/// </remarks>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// If this property is set to true, the value of this animation will
/// accumulate over repeat cycles. For example, if this is a point
/// animation and your key frames describe something approximating and
/// arc, setting this property to true will result in an animation that
/// would appear to bounce the point across the screen.
/// </summary>
/// <remarks>
/// This property works along with the IsAdditive property. Setting
/// this value to true has no effect unless IsAdditive is also set
/// to true.
/// </remarks>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
#region Private Methods
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
private Single GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue");
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
private SingleKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame");
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
}
/// <summary>
/// Returns the largest time span specified key time from all of the key frames.
/// If there are not time span key times a time span of one second is returned
/// to match the default natural duration of the From/To/By animations.
/// </summary>
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool hasTimeSpanKeyTime = false;
TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero;
if (_keyFrames != null)
{
Int32 keyFrameCount = _keyFrames.Count;
for (int index = 0; index < keyFrameCount; index++)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
if (keyTime.Type == KeyTimeType.TimeSpan)
{
hasTimeSpanKeyTime = true;
if (keyTime.TimeSpan > largestTimeSpanKeyTime)
{
largestTimeSpanKeyTime = keyTime.TimeSpan;
}
}
}
}
if (hasTimeSpanKeyTime)
{
return largestTimeSpanKeyTime;
}
else
{
return TimeSpan.FromSeconds(1.0);
}
}
}
private void ResolveKeyTimes()
{
Debug.Assert(!_areKeyTimesValid, "KeyFrameSingleAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid.");
int keyFrameCount = 0;
if (_keyFrames != null)
{
keyFrameCount = _keyFrames.Count;
}
if (keyFrameCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
return;
}
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
int index = 0;
// Initialize the _originalKeyFrameIndex.
for ( ; index < keyFrameCount; index++)
{
_sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
}
// calculationDuration represents the time span we will use to resolve
// percent key times. This is defined as the value in the following
// precedence order:
// 1. The animation's duration, but only if it is a time span, not auto or forever.
// 2. The largest time span specified key time of all the key frames.
// 3. 1 second, to match the From/To/By animations.
TimeSpan calculationDuration = TimeSpan.Zero;
Duration duration = Duration;
if (duration.HasTimeSpan)
{
calculationDuration = duration.TimeSpan;
}
else
{
calculationDuration = LargestTimeSpanKeyTime;
}
int maxKeyFrameIndex = keyFrameCount - 1;
ArrayList unspecifiedBlocks = new ArrayList();
bool hasPacedKeyTimes = false;
//
// Pass 1: Resolve Percent and Time key times.
//
index = 0;
while (index < keyFrameCount)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Percent:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(
keyTime.Percent * calculationDuration.TotalMilliseconds);
index++;
break;
case KeyTimeType.TimeSpan:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
index++;
break;
case KeyTimeType.Paced:
case KeyTimeType.Uniform:
if (index == maxKeyFrameIndex)
{
// If the last key frame doesn't have a specific time
// associated with it its resolved key time will be
// set to the calculationDuration, which is the
// defined in the comments above where it is set.
// Reason: We only want extra time at the end of the
// key frames if the user specifically states that
// the last key frame ends before the animation ends.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
index++;
}
else if ( index == 0
&& keyTime.Type == KeyTimeType.Paced)
{
// Note: It's important that this block come after
// the previous if block because of rule precendence.
// If the first key frame in a multi-frame key frame
// collection is paced, we set its resolved key time
// to 0.0 for performance reasons. If we didn't, the
// resolved key time list would be dependent on the
// base value which can change every animation frame
// in many cases.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
index++;
}
else
{
if (keyTime.Type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
KeyTimeBlock block = new KeyTimeBlock();
block.BeginIndex = index;
// NOTE: We don't want to go all the way up to the
// last frame because if it is Uniform or Paced its
// resolved key time will be set to the calculation
// duration using the logic above.
//
// This is why the logic is:
// ((++index) < maxKeyFrameIndex)
// instead of:
// ((++index) < keyFrameCount)
while ((++index) < maxKeyFrameIndex)
{
KeyTimeType type = _keyFrames[index].KeyTime.Type;
if ( type == KeyTimeType.Percent
|| type == KeyTimeType.TimeSpan)
{
break;
}
else if (type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
}
Debug.Assert(index < keyFrameCount,
"The end index for a block of unspecified key frames is out of bounds.");
block.EndIndex = index;
unspecifiedBlocks.Add(block);
}
break;
}
}
//
// Pass 2: Resolve Uniform key times.
//
for (int j = 0; j < unspecifiedBlocks.Count; j++)
{
KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j];
TimeSpan blockBeginTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
}
// The number of segments is equal to the number of key
// frames we're working on plus 1. Think about the case
// where we're working on a single key frame. There's a
// segment before it and a segment after it.
//
// Time known Uniform Time known
// ^ ^ ^
// | | |
// | (segment 1) | (segment 2) |
Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
index = block.BeginIndex;
TimeSpan resolvedTime = blockBeginTime + uniformTimeStep;
while (index < block.EndIndex)
{
_sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
resolvedTime += uniformTimeStep;
index++;
}
}
//
// Pass 3: Resolve Paced key times.
//
if (hasPacedKeyTimes)
{
ResolvePacedKeyTimes();
}
//
// Sort resolved key frame entries.
//
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
return;
}
/// <summary>
/// This should only be called from ResolveKeyTimes and only at the
/// appropriate time.
/// </summary>
private void ResolvePacedKeyTimes()
{
Debug.Assert(_keyFrames != null && _keyFrames.Count > 2,
"Caller must guard against calling this method when there are insufficient keyframes.");
// If the first key frame is paced its key time has already
// been resolved, so we start at index 1.
int index = 1;
int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
{
//
// We've found a paced key frame so this is the
// beginning of a paced block.
//
// The first paced key frame in this block.
int firstPacedBlockKeyFrameIndex = index;
// List of segment lengths for this paced block.
List<Double> segmentLengths = new List<Double>();
// The resolved key time for the key frame before this
// block which we'll use as our starting point.
TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
// The total of the segment lengths of the paced key
// frames in this block.
Double totalLength = 0.0;
// The key value of the previous key frame which will be
// used to determine the segment length of this key frame.
Single prevKeyValue = _keyFrames[index - 1].Value;
do
{
Single currentKeyValue = _keyFrames[index].Value;
// Determine the segment length for this key frame and
// add to the total length.
totalLength += AnimatedTypeHelpers.GetSegmentLengthSingle(prevKeyValue, currentKeyValue);
// Temporarily store the distance into the total length
// that this key frame represents in the resolved
// key times array to be converted to a resolved key
// time outside of this loop.
segmentLengths.Add(totalLength);
// Prepare for the next iteration.
prevKeyValue = currentKeyValue;
index++;
}
while ( index < maxKeyFrameIndex
&& _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
// index is currently set to the index of the key frame
// after the last paced key frame. This will always
// be a valid index because we limit ourselves with
// maxKeyFrameIndex.
// We need to add the distance between the last paced key
// frame and the next key frame to get the total distance
// inside the key frame block.
totalLength += AnimatedTypeHelpers.GetSegmentLengthSingle(prevKeyValue, _keyFrames[index].Value);
// Calculate the time available in the resolved key time space.
TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
// Convert lengths in segmentLengths list to resolved
// key times for the paced key frames in this block.
for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
{
// The resolved key time for each key frame is:
//
// The key time of the key frame before this paced block
// + ((the percentage of the way through the total length)
// * the resolved key time space available for the block)
_sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(
(segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds);
}
}
else
{
index++;
}
}
while (index < maxKeyFrameIndex);
}
#endregion
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SkinnedModelProcessor.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using SkinnedModel;
#endregion
namespace SkinnedModelPipeline
{
/// <summary>
/// Custom processor extends the builtin framework ModelProcessor class,
/// adding animation support.
/// </summary>
[ContentProcessor]
public class SkinnedModelProcessor : ModelProcessor
{
/// <summary>
/// The main Process method converts an intermediate format content pipeline
/// NodeContent tree to a ModelContent object with embedded animation data.
/// </summary>
public override ModelContent Process(NodeContent input,
ContentProcessorContext context)
{
ValidateMesh(input, context, null);
// Find the skeleton.
BoneContent skeleton = MeshHelper.FindSkeleton(input);
if (skeleton == null)
throw new InvalidContentException("Input skeleton not found.");
// We don't want to have to worry about different parts of the model being
// in different local coordinate systems, so let's just bake everything.
FlattenTransforms(input, skeleton);
// Read the bind pose and skeleton hierarchy data.
IList<BoneContent> bones = MeshHelper.FlattenSkeleton(skeleton);
if (bones.Count > SkinnedEffect.MaxBones)
{
throw new InvalidContentException(string.Format(
"Skeleton has {0} bones, but the maximum supported is {1}.",
bones.Count, SkinnedEffect.MaxBones));
}
List<Matrix> bindPose = new List<Matrix>();
List<Matrix> inverseBindPose = new List<Matrix>();
List<int> skeletonHierarchy = new List<int>();
#region BaamStudios XnaMixamoImporter Change
List<string> boneNames = new List<string>();
#endregion
foreach (BoneContent bone in bones)
{
bindPose.Add(bone.Transform);
inverseBindPose.Add(Matrix.Invert(bone.AbsoluteTransform));
skeletonHierarchy.Add(bones.IndexOf(bone.Parent as BoneContent));
#region BaamStudios XnaMixamoImporter Change
boneNames.Add(bone.Name);
#endregion
}
// Convert animation data to our runtime format.
Dictionary<string, AnimationClip> animationClips;
animationClips = ProcessAnimations(skeleton.Animations, bones);
// Chain to the base ModelProcessor class so it can convert the model data.
ModelContent model = base.Process(input, context);
// Store our custom animation data in the Tag property of the model.
model.Tag = new SkinningData(animationClips, bindPose,
inverseBindPose, skeletonHierarchy
#region BaamStudios XnaMixamoImporter Change
, boneNames
#endregion
);
return model;
}
/// <summary>
/// Converts an intermediate format content pipeline AnimationContentDictionary
/// object to our runtime AnimationClip format.
/// </summary>
static Dictionary<string, AnimationClip> ProcessAnimations(
AnimationContentDictionary animations, IList<BoneContent> bones)
{
// Build up a table mapping bone names to indices.
Dictionary<string, int> boneMap = new Dictionary<string, int>();
for (int i = 0; i < bones.Count; i++)
{
string boneName = bones[i].Name;
if (!string.IsNullOrEmpty(boneName))
boneMap.Add(boneName, i);
}
// Convert each animation in turn.
Dictionary<string, AnimationClip> animationClips;
animationClips = new Dictionary<string, AnimationClip>();
foreach (KeyValuePair<string, AnimationContent> animation in animations)
{
AnimationClip processed = ProcessAnimation(animation.Value, boneMap);
animationClips.Add(animation.Key, processed);
}
#region BaamStudios XnaMixamoImporter Change
//if (animationClips.Count == 0)
//{
// throw new InvalidContentException(
// "Input file does not contain any animations.");
//}
#endregion
return animationClips;
}
/// <summary>
/// Converts an intermediate format content pipeline AnimationContent
/// object to our runtime AnimationClip format.
/// </summary>
static AnimationClip ProcessAnimation(AnimationContent animation,
Dictionary<string, int> boneMap)
{
List<Keyframe> keyframes = new List<Keyframe>();
// For each input animation channel.
foreach (KeyValuePair<string, AnimationChannel> channel in
animation.Channels)
{
// Look up what bone this channel is controlling.
int boneIndex;
if (!boneMap.TryGetValue(channel.Key, out boneIndex))
{
throw new InvalidContentException(string.Format(
"Found animation for bone '{0}', " +
"which is not part of the skeleton.", channel.Key));
}
// Convert the keyframe data.
foreach (AnimationKeyframe keyframe in channel.Value)
{
keyframes.Add(new Keyframe(boneIndex, keyframe.Time,
keyframe.Transform));
}
}
// Sort the merged keyframes by time.
keyframes.Sort(CompareKeyframeTimes);
if (keyframes.Count == 0)
throw new InvalidContentException("Animation has no keyframes.");
if (animation.Duration <= TimeSpan.Zero)
throw new InvalidContentException("Animation has a zero duration.");
return new AnimationClip(animation.Duration, keyframes);
}
/// <summary>
/// Comparison function for sorting keyframes into ascending time order.
/// </summary>
static int CompareKeyframeTimes(Keyframe a, Keyframe b)
{
return a.Time.CompareTo(b.Time);
}
/// <summary>
/// Makes sure this mesh contains the kind of data we know how to animate.
/// </summary>
static void ValidateMesh(NodeContent node, ContentProcessorContext context,
string parentBoneName)
{
MeshContent mesh = node as MeshContent;
if (mesh != null)
{
// Validate the mesh.
if (parentBoneName != null)
{
context.Logger.LogWarning(null, null,
"Mesh {0} is a child of bone {1}. SkinnedModelProcessor " +
"does not correctly handle meshes that are children of bones.",
mesh.Name, parentBoneName);
}
if (!MeshHasSkinning(mesh))
{
context.Logger.LogWarning(null, null,
"Mesh {0} has no skinning information, so it has been deleted.",
mesh.Name);
mesh.Parent.Children.Remove(mesh);
return;
}
}
else if (node is BoneContent)
{
// If this is a bone, remember that we are now looking inside it.
parentBoneName = node.Name;
}
// Recurse (iterating over a copy of the child collection,
// because validating children may delete some of them).
foreach (NodeContent child in new List<NodeContent>(node.Children))
ValidateMesh(child, context, parentBoneName);
}
/// <summary>
/// Checks whether a mesh contains skininng information.
/// </summary>
static bool MeshHasSkinning(MeshContent mesh)
{
foreach (GeometryContent geometry in mesh.Geometry)
{
if (!geometry.Vertices.Channels.Contains(VertexChannelNames.Weights()))
return false;
}
return true;
}
/// <summary>
/// Bakes unwanted transforms into the model geometry,
/// so everything ends up in the same coordinate system.
/// </summary>
static void FlattenTransforms(NodeContent node, BoneContent skeleton)
{
foreach (NodeContent child in node.Children)
{
// Don't process the skeleton, because that is special.
if (child == skeleton)
continue;
// Bake the local transform into the actual geometry.
MeshHelper.TransformScene(child, child.Transform);
// Having baked it, we can now set the local
// coordinate system back to identity.
child.Transform = Matrix.Identity;
// Recurse.
FlattenTransforms(child, skeleton);
}
}
/// <summary>
/// Force all the materials to use our skinned model effect.
/// </summary>
[DefaultValue(MaterialProcessorDefaultEffect.SkinnedEffect)]
public override MaterialProcessorDefaultEffect DefaultEffect
{
get { return MaterialProcessorDefaultEffect.SkinnedEffect; }
set { }
}
}
}
| |
//#define ProfileAstar
using UnityEngine;
using System.Text;
namespace Pathfinding {
[AddComponentMenu("Pathfinding/Pathfinding Debugger")]
[ExecuteInEditMode]
/** Debugger for the A* Pathfinding Project.
* This class can be used to profile different parts of the pathfinding system
* and the whole game as well to some extent.
*
* Clarification of the labels shown when enabled.
* All memory related things profiles <b>the whole game</b> not just the A* Pathfinding System.\n
* - Currently allocated: memory the GC (garbage collector) says the application has allocated right now.
* - Peak allocated: maximum measured value of the above.
* - Last collect peak: the last peak of 'currently allocated'.
* - Allocation rate: how much the 'currently allocated' value increases per second. This value is not as reliable as you can think
* it is often very random probably depending on how the GC thinks this application is using memory.
* - Collection frequency: how often the GC is called. Again, the GC might decide it is better with many small collections
* or with a few large collections. So you cannot really trust this variable much.
* - Last collect fps: FPS during the last garbage collection, the GC will lower the fps a lot.
*
* - FPS: current FPS (not updated every frame for readability)
* - Lowest FPS (last x): As the label says, the lowest fps of the last x frames.
*
* - Size: Size of the path pool.
* - Total created: Number of paths of that type which has been created. Pooled paths are not counted twice.
* If this value just keeps on growing and growing without an apparent stop, you are are either not pooling any paths
* or you have missed to pool some path somewhere in your code.
*
* \see pooling
*
* \todo Add field showing how many graph updates are being done right now
*/
[HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_astar_debugger.php")]
public class AstarDebugger : VersionedMonoBehaviour {
public int yOffset = 5;
public bool show = true;
public bool showInEditor = false;
public bool showFPS = false;
public bool showPathProfile = false;
public bool showMemProfile = false;
public bool showGraph = false;
public int graphBufferSize = 200;
/** Font to use.
* A monospaced font is the best
*/
public Font font = null;
public int fontSize = 12;
StringBuilder text = new StringBuilder();
string cachedText;
float lastUpdate = -999;
private GraphPoint[] graph;
struct GraphPoint {
public float fps, memory;
public bool collectEvent;
}
private float delayedDeltaTime = 1;
private float lastCollect = 0;
private float lastCollectNum = 0;
private float delta = 0;
private float lastDeltaTime = 0;
private int allocRate = 0;
private int lastAllocMemory = 0;
private float lastAllocSet = -9999;
private int allocMem = 0;
private int collectAlloc = 0;
private int peakAlloc = 0;
private int fpsDropCounterSize = 200;
private float[] fpsDrops;
private Rect boxRect;
private GUIStyle style;
private Camera cam;
float graphWidth = 100;
float graphHeight = 100;
float graphOffset = 50;
public void Start () {
useGUILayout = false;
fpsDrops = new float[fpsDropCounterSize];
cam = GetComponent<Camera>();
if (cam == null) {
cam = Camera.main;
}
graph = new GraphPoint[graphBufferSize];
if (Time.unscaledDeltaTime > 0) {
for (int i = 0; i < fpsDrops.Length; i++) {
fpsDrops[i] = 1F / Time.unscaledDeltaTime;
}
}
}
int maxVecPool = 0;
int maxNodePool = 0;
PathTypeDebug[] debugTypes = new PathTypeDebug[] {
new PathTypeDebug("ABPath", () => PathPool.GetSize(typeof(ABPath)), () => PathPool.GetTotalCreated(typeof(ABPath)))
};
struct PathTypeDebug {
string name;
System.Func<int> getSize;
System.Func<int> getTotalCreated;
public PathTypeDebug (string name, System.Func<int> getSize, System.Func<int> getTotalCreated) {
this.name = name;
this.getSize = getSize;
this.getTotalCreated = getTotalCreated;
}
public void Print (StringBuilder text) {
int totCreated = getTotalCreated();
if (totCreated > 0) {
text.Append("\n").Append((" " + name).PadRight(25)).Append(getSize()).Append("/").Append(totCreated);
}
}
}
public void LateUpdate () {
if (!show || (!Application.isPlaying && !showInEditor)) return;
if (Time.unscaledDeltaTime <= 0.0001f)
return;
int collCount = System.GC.CollectionCount(0);
if (lastCollectNum != collCount) {
lastCollectNum = collCount;
delta = Time.realtimeSinceStartup-lastCollect;
lastCollect = Time.realtimeSinceStartup;
lastDeltaTime = Time.unscaledDeltaTime;
collectAlloc = allocMem;
}
allocMem = (int)System.GC.GetTotalMemory(false);
bool collectEvent = allocMem < peakAlloc;
peakAlloc = !collectEvent ? allocMem : peakAlloc;
if (Time.realtimeSinceStartup - lastAllocSet > 0.3F || !Application.isPlaying) {
int diff = allocMem - lastAllocMemory;
lastAllocMemory = allocMem;
lastAllocSet = Time.realtimeSinceStartup;
delayedDeltaTime = Time.unscaledDeltaTime;
if (diff >= 0) {
allocRate = diff;
}
}
if (Application.isPlaying) {
fpsDrops[Time.frameCount % fpsDrops.Length] = Time.unscaledDeltaTime > 0.00001f ? 1F / Time.unscaledDeltaTime : 0;
int graphIndex = Time.frameCount % graph.Length;
graph[graphIndex].fps = Time.unscaledDeltaTime < 0.00001f ? 1F / Time.unscaledDeltaTime : 0;
graph[graphIndex].collectEvent = collectEvent;
graph[graphIndex].memory = allocMem;
}
if (Application.isPlaying && cam != null && showGraph) {
graphWidth = cam.pixelWidth*0.8f;
float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0;
for (int i = 0; i < graph.Length; i++) {
minMem = Mathf.Min(graph[i].memory, minMem);
maxMem = Mathf.Max(graph[i].memory, maxMem);
minFPS = Mathf.Min(graph[i].fps, minFPS);
maxFPS = Mathf.Max(graph[i].fps, maxFPS);
}
int currentGraphIndex = Time.frameCount % graph.Length;
Matrix4x4 m = Matrix4x4.TRS(new Vector3((cam.pixelWidth - graphWidth)/2f, graphOffset, 1), Quaternion.identity, new Vector3(graphWidth, graphHeight, 1));
for (int i = 0; i < graph.Length-1; i++) {
if (i == currentGraphIndex) continue;
DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, Mathf.InverseLerp(minMem, maxMem, graph[i].memory), Mathf.InverseLerp(minMem, maxMem, graph[i+1].memory), Color.blue);
DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, Mathf.InverseLerp(minFPS, maxFPS, graph[i].fps), Mathf.InverseLerp(minFPS, maxFPS, graph[i+1].fps), Color.green);
}
}
}
void DrawGraphLine (int index, Matrix4x4 m, float x1, float x2, float y1, float y2, Color color) {
Debug.DrawLine(cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x1, y1))), cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x2, y2))), color);
}
public void OnGUI () {
if (!show || (!Application.isPlaying && !showInEditor)) return;
if (style == null) {
style = new GUIStyle();
style.normal.textColor = Color.white;
style.padding = new RectOffset(5, 5, 5, 5);
}
if (Time.realtimeSinceStartup - lastUpdate > 0.5f || cachedText == null || !Application.isPlaying) {
lastUpdate = Time.realtimeSinceStartup;
boxRect = new Rect(5, yOffset, 310, 40);
text.Length = 0;
text.AppendLine("A* Pathfinding Project Debugger");
text.Append("A* Version: ").Append(AstarPath.Version.ToString());
if (showMemProfile) {
boxRect.height += 200;
text.AppendLine();
text.AppendLine();
text.Append("Currently allocated".PadRight(25));
text.Append((allocMem/1000000F).ToString("0.0 MB"));
text.AppendLine();
text.Append("Peak allocated".PadRight(25));
text.Append((peakAlloc/1000000F).ToString("0.0 MB")).AppendLine();
text.Append("Last collect peak".PadRight(25));
text.Append((collectAlloc/1000000F).ToString("0.0 MB")).AppendLine();
text.Append("Allocation rate".PadRight(25));
text.Append((allocRate/1000000F).ToString("0.0 MB")).AppendLine();
text.Append("Collection frequency".PadRight(25));
text.Append(delta.ToString("0.00"));
text.Append("s\n");
text.Append("Last collect fps".PadRight(25));
text.Append((1F/lastDeltaTime).ToString("0.0 fps"));
text.Append(" (");
text.Append(lastDeltaTime.ToString("0.000 s"));
text.Append(")");
}
if (showFPS) {
text.AppendLine();
text.AppendLine();
var delayedFPS = delayedDeltaTime > 0.00001f ? 1F/delayedDeltaTime : 0;
text.Append("FPS".PadRight(25)).Append(delayedFPS.ToString("0.0 fps"));
float minFps = Mathf.Infinity;
for (int i = 0; i < fpsDrops.Length; i++) if (fpsDrops[i] < minFps) minFps = fpsDrops[i];
text.AppendLine();
text.Append(("Lowest fps (last " + fpsDrops.Length + ")").PadRight(25)).Append(minFps.ToString("0.0"));
}
if (showPathProfile) {
AstarPath astar = AstarPath.active;
text.AppendLine();
if (astar == null) {
text.Append("\nNo AstarPath Object In The Scene");
} else {
if (Pathfinding.Util.ListPool<Vector3>.GetSize() > maxVecPool) maxVecPool = Pathfinding.Util.ListPool<Vector3>.GetSize();
if (Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize() > maxNodePool) maxNodePool = Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize();
text.Append("\nPool Sizes (size/total created)");
for (int i = 0; i < debugTypes.Length; i++) {
debugTypes[i].Print(text);
}
}
}
cachedText = text.ToString();
}
if (font != null) {
style.font = font;
style.fontSize = fontSize;
}
boxRect.height = style.CalcHeight(new GUIContent(cachedText), boxRect.width);
GUI.Box(boxRect, "");
GUI.Label(boxRect, cachedText, style);
if (showGraph) {
float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0;
for (int i = 0; i < graph.Length; i++) {
minMem = Mathf.Min(graph[i].memory, minMem);
maxMem = Mathf.Max(graph[i].memory, maxMem);
minFPS = Mathf.Min(graph[i].fps, minFPS);
maxFPS = Mathf.Max(graph[i].fps, maxFPS);
}
float line;
GUI.color = Color.blue;
// Round to nearest x.x MB
line = Mathf.RoundToInt(maxMem/(100.0f*1000));
GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB"));
line = Mathf.Round(minMem/(100.0f*1000));
GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB"));
GUI.color = Color.green;
// Round to nearest x.x MB
line = Mathf.Round(maxFPS);
GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS"));
line = Mathf.Round(minFPS);
GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS"));
}
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System.Linq;
using FluentAssertions;
using Glass.Mapper.Umb.Configuration;
using Glass.Mapper.Umb.Configuration.Attributes;
using NUnit.Framework;
using Glass.Mapper.Configuration.Attributes;
namespace Glass.Mapper.Umb.Tests.Configuration.Attributes
{
[TestFixture]
public class UmbracoPropertyAttributeFixture
{
[Test]
public void Does_UmbracoPropertyAttribute_Extend_FieldAttribute()
{
//Assign
var type = typeof(FieldAttribute);
//Act
//Assert
type.IsAssignableFrom(typeof(UmbracoPropertyAttribute)).Should().BeTrue();
}
[Test]
[TestCase("PropertyAlias")]
[TestCase("Setting")]
[TestCase("CodeFirst")]
[TestCase("PropertyName")]
[TestCase("PropertyType")]
[TestCase("ContentTab")]
[TestCase("PropertyDescription")]
[TestCase("PropertyIsMandatory")]
[TestCase("PropertyValidation")]
public void Does_UmbracoPropertyAttribute_Have_Properties(string propertyName)
{
//Assign
var properties = typeof(UmbracoPropertyAttribute).GetProperties();
//Act
//Assert
properties.Any(x => x.Name == propertyName).Should().BeTrue();
}
[Test]
public void Default_Constructor_Set_Setting_To_Default()
{
//Assign
var testUmbracoPropertyAttribute = new UmbracoPropertyAttribute();
//Act
//Assert
testUmbracoPropertyAttribute.Setting.ShouldBeEquivalentTo(UmbracoPropertySettings.Default);
}
[Test]
public void Constructor_Sets_PropertyAlias()
{
//Assign
var testPropertyAlias = "testPropertyAlias";
//Act
var testUmbracoPropertyAttribute = new UmbracoPropertyAttribute(testPropertyAlias);
//Assert
testUmbracoPropertyAttribute.PropertyAlias.ShouldBeEquivalentTo(testPropertyAlias);
}
[Test]
public void Constructor_Sets_PropertyIdAndPropertyType()
{
//Assign
var testPropertyId = "test";
var testContentTab = "General Properties";
var testCodeFirst = true;
//Act
var testUmbracoPropertyAttribute = new UmbracoPropertyAttribute("test", UmbracoPropertyType.NotSet);
//Assert
testUmbracoPropertyAttribute.CodeFirst.ShouldBeEquivalentTo(testCodeFirst);
testUmbracoPropertyAttribute.ContentTab.ShouldBeEquivalentTo(testContentTab);
testUmbracoPropertyAttribute.PropertyAlias.ShouldBeEquivalentTo(testPropertyId);
testUmbracoPropertyAttribute.PropertyType.ShouldBeEquivalentTo(UmbracoPropertyType.NotSet);
}
[Test]
public void Constructor_Sets_PropertyIdAndPropertyTypeAndContentTab()
{
//Assign
var testPropertyId = "test";
var testContentTab = "test";
var testCodeFirst = false;
//Act
var testUmbracoPropertyAttribute = new UmbracoPropertyAttribute("test", UmbracoPropertyType.NotSet, "test", false);
//Assert
testUmbracoPropertyAttribute.CodeFirst.ShouldBeEquivalentTo(testCodeFirst);
testUmbracoPropertyAttribute.ContentTab.ShouldBeEquivalentTo(testContentTab);
testUmbracoPropertyAttribute.PropertyAlias.ShouldBeEquivalentTo(testPropertyId);
testUmbracoPropertyAttribute.PropertyType.ShouldBeEquivalentTo(UmbracoPropertyType.NotSet);
}
#region Method - Configure
[Test]
public void Configure_SettingNotSet_SettingsReturnAsDefault()
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.Setting.ShouldBeEquivalentTo(UmbracoPropertySettings.Default);
}
[Test]
public void Configure_SettingSetToDontLoadLazily_SettingsReturnAsDontLoadLazily()
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");
attr.Setting = UmbracoPropertySettings.DontLoadLazily;
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.Setting.ShouldBeEquivalentTo(UmbracoPropertySettings.DontLoadLazily);
}
[Test]
[Sequential]
public void Configure_SettingCodeFirst_CodeFirstIsSetOnConfiguration(
[Values(true, false)] bool value,
[Values(true, false)] bool expected)
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");
attr.CodeFirst = value;
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.CodeFirst.ShouldBeEquivalentTo(expected);
}
[Test]
[Sequential]
public void Configure_SettingDataType_DataTypeIsSetOnConfiguration(
[Values(UmbracoPropertyType.TextString)] UmbracoPropertyType value,
[Values(UmbracoPropertyType.TextString)] UmbracoPropertyType expected)
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof (StubClass).GetProperty("DummyProperty");
attr.PropertyType = value;
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.PropertyType.ShouldBeEquivalentTo(expected);
}
[Test]
[Sequential]
public void Configure_SettingPropertyAlias_PropertyAliasIsSetOnConfiguration(
[Values("property alias")] string value,
[Values("property alias")] string expected)
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");
attr.PropertyAlias = value;
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.PropertyAlias.ShouldBeEquivalentTo(expected);
}
[Test]
[Sequential]
public void Configure_SettingContentTab_ContentTabIsSetOnConfiguration(
[Values("content tab")] string value,
[Values("content tab")] string expected)
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");
attr.ContentTab = value;
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.ContentTab.ShouldBeEquivalentTo(expected);
}
[Test]
[Sequential]
public void Configure_SettingPropertyName_PropertyNameIsSetOnConfiguration(
[Values("property name")] string value,
[Values("property name")] string expected)
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");
attr.PropertyName = value;
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.PropertyName.ShouldBeEquivalentTo(expected);
}
[Test]
[Sequential]
public void Configure_SettingPropertyDescription_PropertyDescriptionIsSetOnConfiguration(
[Values("property description")] string value,
[Values("property description")] string expected)
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");
attr.PropertyDescription = value;
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.PropertyDescription.ShouldBeEquivalentTo(expected);
}
[Test]
[Sequential]
public void Configure_SettingPropertyValidation_PropertyValidationIsSetOnConfiguration(
[Values("property validation")] string value,
[Values("property validation")] string expected)
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");
attr.PropertyValidation = value;
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.PropertyValidation.ShouldBeEquivalentTo(expected);
}
[Test]
[Sequential]
public void Configure_SettingPropertyMandatory_PropertyMandatoryIsSetOnConfiguration(
[Values(true)] bool value,
[Values(true)] bool expected)
{
//Assign
var attr = new UmbracoPropertyAttribute(string.Empty);
var propertyInfo = typeof(StubClass).GetProperty("DummyProperty");
attr.PropertyIsMandatory = value;
//Act
var result = attr.Configure(propertyInfo) as UmbracoPropertyConfiguration;
//Assert
result.Should().NotBeNull();
result.PropertyIsMandatory.ShouldBeEquivalentTo(expected);
}
#endregion
#region Stubs
public class StubClass
{
public string DummyProperty { get; set; }
}
#endregion
}
}
| |
/***************************************************************************/
/* Code taken here: https://github.com/khalidabuhakmeh/ConsoleTables */
/***************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleTables
{
public class ConsoleTable
{
public IList<object> Columns { get; set; }
public IList<object[]> Rows { get; protected set; }
public ConsoleTableOptions Options { get; protected set; }
public ConsoleTable(params string[] columns)
: this(new ConsoleTableOptions { Columns = new List<string>(columns) })
{
}
public ConsoleTable(ConsoleTableOptions options)
{
Options = options ?? throw new ArgumentNullException("options");
Rows = new List<object[]>();
Columns = new List<object>(options.Columns);
}
public ConsoleTable AddColumn(IEnumerable<string> names)
{
foreach (var name in names)
Columns.Add(name);
return this;
}
public ConsoleTable AddRow(params object[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
if (!Columns.Any())
throw new Exception("Please set the columns first");
if (Columns.Count != values.Length)
throw new Exception(
$"The number columns in the row ({Columns.Count}) does not match the values ({values.Length}");
Rows.Add(values);
return this;
}
public static ConsoleTable From<T>(IEnumerable<T> values)
{
var table = new ConsoleTable();
var columns = GetColumns<T>();
table.AddColumn(columns);
foreach (var propertyValues in values.Select(value => columns.Select(column => GetColumnValue<T>(value, column))))
table.AddRow(propertyValues.ToArray());
return table;
}
public override string ToString()
{
var builder = new StringBuilder();
// find the longest column by searching each row
var columnLengths = ColumnLengths();
// create the string format with padding
var format = Enumerable.Range(0, Columns.Count)
.Select(i => " | {" + i + ",-" + columnLengths[i] + "}")
.Aggregate((s, a) => s + a) + " |";
// find the longest formatted line
var maxRowLength = Math.Max(0, Rows.Any() ? Rows.Max(row => string.Format(format, row).Length) : 0);
var columnHeaders = string.Format(format, Columns.ToArray());
// longest line is greater of formatted columnHeader and longest row
var longestLine = Math.Max(maxRowLength, columnHeaders.Length);
// add each row
var results = Rows.Select(row => string.Format(format, row)).ToList();
// create the divider
var divider = " " + string.Join("", Enumerable.Repeat("-", longestLine - 1)) + " ";
builder.AppendLine(divider);
builder.AppendLine(columnHeaders);
foreach (var row in results)
{
builder.AppendLine(divider);
builder.AppendLine(row);
}
builder.AppendLine(divider);
if (Options.EnableCount)
{
builder.AppendLine("");
builder.AppendFormat(" Count: {0}", Rows.Count);
}
return builder.ToString();
}
public string ToMarkDownString()
{
var builder = new StringBuilder();
// find the longest column by searching each row
var columnLengths = ColumnLengths();
// create the string format with padding
var format = Format(columnLengths);
// find the longest formatted line
var columnHeaders = string.Format(format, Columns.ToArray());
// add each row
var results = Rows.Select(row => string.Format(format, row)).ToList();
// create the divider
var divider = Regex.Replace(columnHeaders, @"[^|]", "-");
builder.AppendLine(columnHeaders);
builder.AppendLine(divider);
results.ForEach(row => builder.AppendLine(row));
return builder.ToString();
}
public string ToStringAlternative()
{
var builder = new StringBuilder();
// find the longest column by searching each row
var columnLengths = ColumnLengths();
// create the string format with padding
var format = Format(columnLengths);
// find the longest formatted line
var columnHeaders = string.Format(format, Columns.ToArray());
// add each row
var results = Rows.Select(row => string.Format(format, row)).ToList();
// create the divider
var divider = Regex.Replace(columnHeaders, @"[^|]", "-");
var dividerPlus = divider.Replace("|", "+");
builder.AppendLine(dividerPlus);
builder.AppendLine(columnHeaders);
foreach (var row in results)
{
builder.AppendLine(dividerPlus);
builder.AppendLine(row);
}
builder.AppendLine(dividerPlus);
return builder.ToString();
}
private string Format(List<int> columnLengths)
{
var format = (Enumerable.Range(0, Columns.Count)
.Select(i => " | {" + i + ",-" + columnLengths[i] + "}")
.Aggregate((s, a) => s + a) + " |").Trim();
return format;
}
private List<int> ColumnLengths()
{
var columnLengths = Columns
.Select((t, i) => Rows.Select(x => x[i])
.Union(Columns)
.Where(x => x != null)
.Select(x => x.ToString().Length).Max())
.ToList();
return columnLengths;
}
public void Write(Format format = ConsoleTables.Format.Default)
{
switch (format)
{
case ConsoleTables.Format.Default:
Console.WriteLine(ToString());
break;
case ConsoleTables.Format.MarkDown:
Console.WriteLine(ToMarkDownString());
break;
case ConsoleTables.Format.Alternative:
Console.WriteLine(ToStringAlternative());
break;
default:
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
}
private static IEnumerable<string> GetColumns<T>()
{
return typeof(T).GetProperties().Select(x => x.Name).ToArray();
}
private static object GetColumnValue<T>(object target, string column)
{
return typeof(T).GetProperty(column).GetValue(target, null);
}
}
public class ConsoleTableOptions
{
public IEnumerable<string> Columns { get; set; } = new List<string>();
public bool EnableCount { get; set; } = true;
}
public enum Format
{
Default = 0,
MarkDown = 1,
Alternative = 2
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using aspnet45_mvc_webapi.Areas.HelpPage.ModelDescriptions;
using aspnet45_mvc_webapi.Areas.HelpPage.Models;
namespace aspnet45_mvc_webapi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.IO;
using System.Threading;
using Platform.IO;
using Platform.Text;
using Platform;
using Platform.VirtualFileSystem.Providers;
namespace Platform.VirtualFileSystem.Providers
{
public enum TransferState
{
NotStarted,
Preparing,
Comparing,
Transferring,
Copying,
Tidying,
Finished,
Stopped
}
public class StandardFileTransferService
: AbstractRunnableService, IFileTransferService
{
private readonly IFile source;
private readonly IFile destination;
private readonly FileTransferServiceType serviceType;
public virtual event FileTransferServiceEventHandler TransferStateChanged;
public virtual void OnTransferStateChanged(FileTransferServiceEventArgs eventArgs)
{
if (TransferStateChanged != null)
{
TransferStateChanged(this, eventArgs);
}
}
public virtual INode OperatingNode
{
get
{
return this.source;
}
}
public virtual INode TargetNode
{
get
{
return this.destination;
}
}
public virtual string HashAlgorithmName { get; set; }
public StandardFileTransferService(IFile source, IFile destination)
: this(source, new FileTransferServiceType(destination, true))
{
}
public StandardFileTransferService(IFile source, FileTransferServiceType serviceType)
{
this.serviceType = serviceType;
this.source = source;
this.destination = this.serviceType.Destination;
this.HashAlgorithmName = serviceType.HashAlgorithmName;
this.progress = new TransferProgress(this);
}
public override IMeter Progress
{
get
{
return this.progress;
}
}
private readonly TransferProgress progress;
private sealed class TransferProgress
: AbstractMeter
{
private readonly StandardFileTransferService service;
public TransferProgress(StandardFileTransferService service)
{
this.service = service;
}
public override object Owner
{
get
{
return this.service;
}
}
public override object MaximumValue
{
get
{
return this.service.GetBytesToTransfer();
}
}
public override object MinimumValue
{
get
{
return 0;
}
}
public override object CurrentValue
{
get
{
return this.service.GetBytesTransferred();
}
}
public override string Units
{
get
{
return "bytes";
}
}
public override string ToString()
{
switch (this.service.transferState)
{
case TransferState.Finished:
return String.Format("Finished {0}/{1} bytes ({2:0}%)", CurrentValue, MaximumValue, Convert.ToDouble(CurrentValue) / Convert.ToDouble(MaximumValue) * 100.0);
case TransferState.Transferring:
return String.Format("Transferring {0}/{1} bytes ({2:0.##}%)", CurrentValue, MaximumValue, Convert.ToDouble(CurrentValue) / Convert.ToDouble(MaximumValue) * 100.0);
default:
return Enum.GetName(typeof(TransferState), this.service.transferState);
}
}
public void RaiseValueChanged(object oldValue, object newValue)
{
OnValueChanged(oldValue, newValue);
}
public void RaiseMajorChange()
{
OnMajorChange();
}
private bool pumpRegistered = false;
public void RaiseStateChanged()
{
if (this.service.transferState == TransferState.Transferring)
{
lock (this)
{
if (!this.pumpRegistered && this.service.copier != null)
{
this.service.copier.Progress.ValueChanged += PumpProgress_ValueChanged;
this.service.copier.Progress.MajorChange += new EventHandler(PumpProgress_MajorChange);
this.pumpRegistered = true;
}
}
}
}
private void PumpProgress_ValueChanged(object sender, MeterEventArgs eventArgs)
{
OnValueChanged((long)eventArgs.OldValue + this.service.offset, (long)eventArgs.NewValue + this.service.offset);
}
private void PumpProgress_MajorChange(object sender, EventArgs e)
{
OnMajorChange();
}
}
protected static TaskState ToTaskState(TransferState transferState)
{
switch (transferState)
{
case TransferState.NotStarted:
return TaskState.NotStarted;
case TransferState.Preparing:
case TransferState.Comparing:
case TransferState.Transferring:
case TransferState.Copying:
case TransferState.Tidying:
return TaskState.Running;
case TransferState.Finished:
return TaskState.Finished;
case TransferState.Stopped:
return TaskState.Stopped;
default:
return TaskState.Unknown;
}
}
public TransferState TransferState
{
get
{
return this.transferState;
}
}
private TransferState transferState = TransferState.NotStarted;
private void SetTransferState(TransferState value)
{
lock (this)
{
var oldValue = this.transferState;
if (this.transferState != value)
{
this.transferState = value;
OnTransferStateChanged(new FileTransferServiceEventArgs((TransferState)oldValue, this.transferState));
SetTaskState(ToTaskState(this.transferState));
Monitor.PulseAll(this);
this.progress.RaiseStateChanged();
}
}
}
private StreamCopier copier;
private long bytesTransferred = 0L;
private long GetBytesTransferred()
{
if (this.copier != null)
{
return Convert.ToInt64(this.copier.Progress.CurrentValue) + this.offset;
}
else
{
return this.bytesTransferred + this.offset;
}
}
private long GetBytesToTransfer()
{
if (this.copier != null)
{
return Convert.ToInt64(this.copier.Progress.MaximumValue) + this.offset;
}
else
{
return this.source.Length ?? 0;
}
}
private long offset = 0;
public override void DoRun()
{
IFile destinationTemp;
Stream destinationTempStream;
string sourceHash;
try
{
lock (this)
{
SetTransferState(TransferState.Preparing);
}
Action<IFile> transferAttributes = delegate(IFile dest)
{
using (dest.Attributes.AquireUpdateContext())
{
foreach (string s in this.serviceType.AttributesToTransfer)
{
dest.Attributes[s] = this.source.Attributes[s];
}
}
};
Stream sourceStream = null;
for (var i = 0; i < 4; i++)
{
try
{
sourceStream = this.OperatingNode.GetContent().GetInputStream(FileMode.Open, FileShare.Read);
break;
}
catch (NodeNotFoundException)
{
throw;
}
catch (Exception)
{
if (i == 3)
{
throw;
}
}
ProcessTaskStateRequest();
}
using (sourceStream)
{
var sourceHashingService = (IHashingService)this.OperatingNode.GetService(new StreamHashingServiceType(sourceStream, this.HashAlgorithmName));
// Compute the hash of the source file
SetTransferState(TransferState.Comparing);
ProcessTaskStateRequest();
sourceHash = sourceHashingService.ComputeHash().TextValue;
// Try to open the destination file
ProcessTaskStateRequest();
var destinationHashingService = (IHashingService)this.TargetNode.GetService(new FileHashingServiceType(this.HashAlgorithmName));
string destinationHash;
try
{
destinationHash = destinationHashingService.ComputeHash().TextValue;
}
catch (DirectoryNodeNotFoundException)
{
this.TargetNode.ParentDirectory.Create(true);
try
{
destinationHash = destinationHashingService.ComputeHash().TextValue;
}
catch (NodeNotFoundException)
{
destinationHash = null;
}
}
catch (NodeNotFoundException)
{
destinationHash = null;
}
ProcessTaskStateRequest();
// Source and destination are identical
if (sourceHash == destinationHash)
{
SetTransferState(TransferState.Transferring);
this.progress.RaiseValueChanged(0, GetBytesToTransfer());
SetTransferState(TransferState.Tidying);
// Transfer attributes
try
{
transferAttributes((IFile) this.TargetNode);
}
catch (FileNotFoundException)
{
}
// Done
SetTransferState(TransferState.Finished);
ProcessTaskStateRequest();
return;
}
// Get a temp file for the destination based on the source's hash
destinationTemp = ((ITempIdentityFileService)this.destination.GetService(new TempIdentityFileServiceType(sourceHash))).GetTempFile();
// Get the stream for the destination temp file
try
{
if (!destinationTemp.ParentDirectory.Exists)
{
destinationTemp.ParentDirectory.Create(true);
}
}
catch (IOException)
{
}
using (destinationTempStream = destinationTemp.GetContent().OpenStream(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
Action finishUp = delegate
{
SetTransferState(TransferState.Tidying);
destinationTempStream.Close();
for (int i = 0; i < 4; i++)
{
try
{
// Save hash value
StandardFileHashingService.SaveHashToCache((IFile) destinationTemp, this.HashAlgorithmName,
sourceHash, (IFile) this.TargetNode);
try
{
// Transfer attributes
transferAttributes(destinationTemp);
}
catch (FileNotFoundException e)
{
Console.WriteLine(e);
}
// Move destination temp to destination
destinationTemp.MoveTo(this.TargetNode, true);
break;
}
catch (Exception)
{
if (i == 3)
{
throw;
}
}
ProcessTaskStateRequest();
}
// Done
SetTransferState(TransferState.Finished);
ProcessTaskStateRequest();
};
// Get the hash for the destination temp file
var destinationTempHashingService = (IHashingService) destinationTemp.GetService(new StreamHashingServiceType(destinationTempStream));
// If the destination temp and the source aren't the same
// then complete the destination temp
string destinationTempHash;
if (destinationTempStream.Length >= sourceStream.Length)
{
// Destination is longer than source but starts source (unlikely)
destinationTempHash = destinationTempHashingService.ComputeHash(0, sourceStream.Length).TextValue;
if (destinationTempHash == sourceHash)
{
if (destinationTempStream.Length != sourceStream.Length)
{
destinationTempStream.SetLength(sourceStream.Length);
}
finishUp();
return;
}
destinationTempStream.SetLength(0);
}
if (destinationTempStream.Length > 0)
{
destinationTempHash = destinationTempHashingService.ComputeHash().TextValue;
// Destination shorter than the source but is a partial copy of source
sourceHash = sourceHashingService.ComputeHash(0, destinationTempStream.Length).TextValue;
if (sourceHash == destinationTempHash)
{
this.offset = destinationTempStream.Length;
}
else
{
this.offset = 0;
destinationTempStream.SetLength(0);
}
}
else
{
this.offset = 0;
}
this.progress.RaiseValueChanged(0, this.offset);
// Transfer over the remaining part needed (or everything if offset is 0)
this.offset = destinationTempStream.Length;
Stream sourcePartialStream = new PartialStream(sourceStream, destinationTempStream.Length);
Stream destinationTempPartialStream = new PartialStream(destinationTempStream, destinationTempStream.Length);
this.copier =
new StreamCopier(new BufferedStream(sourcePartialStream, this.serviceType.BufferSize), destinationTempPartialStream,
false, false, this.serviceType.ChunkSize);
this.copier.TaskStateChanged += delegate(object sender, TaskEventArgs eventArgs)
{
if (eventArgs.TaskState == TaskState.Running
|| eventArgs.TaskState == TaskState.Paused
|| eventArgs.TaskState == TaskState.Stopped)
{
SetTaskState(eventArgs.TaskState);
}
};
SetTransferState(TransferState.Transferring);
ProcessTaskStateRequest();
this.copier.Run();
if (this.copier.TaskState == TaskState.Stopped)
{
throw new StopRequestedException();
}
finishUp();
}
}
}
catch (StopRequestedException)
{
}
finally
{
if (this.TransferState != TransferState.Finished)
{
SetTransferState(TransferState.Stopped);
}
}
}
private void Pump_TaskStateChanged(object sender, TaskEventArgs eventArgs)
{
if (eventArgs.TaskState == TaskState.Running || eventArgs.TaskState == TaskState.Paused)
{
SetTaskState(eventArgs.TaskState);
}
}
public override bool RequestTaskState(TaskState taskState, TimeSpan timeout)
{
if (this.copier != null && this.copier.TaskState != TaskState.NotStarted
&& this.copier.TaskState != TaskState.Finished && this.copier.TaskState != TaskState.Stopped)
{
this.copier.RequestTaskState(taskState, timeout);
}
return base.RequestTaskState(taskState, timeout);
}
}
}
| |
namespace SqlStreamStore.HAL.DevServer
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using MidFunc = System.Func<
Microsoft.AspNetCore.Http.HttpContext,
System.Func<System.Threading.Tasks.Task>,
System.Threading.Tasks.Task
>;
internal static class SqlStreamStoreBrowserExtensions
{
public static IApplicationBuilder UseSqlStreamStoreBrowser(
this IApplicationBuilder builder)
{
var httpClient = new HttpClient();
return builder
.UseWebSockets()
.Use(ForwardWebsockets(httpClient))
.Use(ForwardAcceptHtml(httpClient))
.Use(ForwardStaticFiles(httpClient));
}
private static MidFunc ForwardWebsockets(HttpClient httpClient) => (context, next)
=> context.WebSockets.IsWebSocketRequest
? ForwardWebsocketToClientDevServer(context)
: context.Request.Path.StartsWithSegments(new PathString("/sockjs-node"))
? ForwardToClientDevServer(httpClient, context)
: next();
private static MidFunc ForwardStaticFiles(HttpClient httpClient) => (context, next)
=> context.Request.Path.StartsWithSegments(new PathString("/static"))
|| context.Request.Path.StartsWithSegments("/__webpack_dev_server__")
? ForwardToClientDevServer(
httpClient,
context)
: next();
private static MidFunc ForwardAcceptHtml(HttpClient httpClient) => (context, next)
=> GetAcceptHeaders(context.Request)
.Any(header => header == "text/html")
? ForwardToClientDevServer(
httpClient,
context,
context.Request.PathBase.ToUriComponent())
: next();
private static Task ForwardToClientDevServer(
HttpClient httpClient,
HttpContext context)
=> ForwardToClientDevServer(httpClient, context, context.Request.Path);
private static async Task ForwardToClientDevServer(
HttpClient httpClient,
HttpContext context,
PathString path)
{
using(var request = BuildRequest(context, path))
using(var response = await httpClient.SendAsync(request))
using(var stream = await response.Content.ReadAsStreamAsync())
{
context.Response.StatusCode = (int) response.StatusCode;
var headers = from header in response.Headers.Concat(
response.Content?.Headers
?? Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>())
where !"transfer-encoding".Equals(header.Key, StringComparison.InvariantCultureIgnoreCase)
select header;
foreach(var header in headers)
{
context.Response.Headers.Add(header.Key, new StringValues(header.Value.ToArray()));
}
await stream.CopyToAsync(context.Response.Body, 8196, context.RequestAborted);
await context.Response.Body.FlushAsync(context.RequestAborted);
}
}
private static HttpRequestMessage BuildRequest(HttpContext context, PathString path)
{
var request = new HttpRequestMessage(
new HttpMethod(context.Request.Method),
new UriBuilder
{
Port = 3000,
Path = path.ToUriComponent(),
Query = context.Request.QueryString.ToUriComponent()
}.Uri);
foreach(var (key, value) in context.Request.Headers)
{
var values = value.ToArray();
request.Headers.TryAddWithoutValidation(key, values);
request.Content?.Headers.TryAddWithoutValidation(key, values);
}
return request;
}
private static string[] GetAcceptHeaders(HttpRequest contextRequest)
=> Array.ConvertAll(
contextRequest.Headers.GetCommaSeparatedValues("Accept"),
value => MediaTypeWithQualityHeaderValue.TryParse(value, out var header)
? header.MediaType
: null);
private static async Task ForwardWebsocketToClientDevServer(HttpContext context)
{
var socket = await context.WebSockets.AcceptWebSocketAsync();
using(var forwarder = new WebsocketForwarder(socket))
{
await forwarder.SendAndReceive(context.RequestAborted);
}
}
private class WebsocketForwarder : IDisposable
{
private readonly WebSocket _socket;
private readonly ClientWebSocket _client;
public WebsocketForwarder(WebSocket socket)
{
_socket = socket;
_client = new ClientWebSocket();
}
public async Task SendAndReceive(CancellationToken ct)
{
await _client.ConnectAsync(new UriBuilder
{
Port = 3000
}.Uri,
ct);
await Task.WhenAll(Send(ct), Receive(ct));
}
private async Task Send(CancellationToken ct)
{
var receiveBuffer = new byte[4096];
while(_socket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(receiveBuffer);
var result = await _socket.ReceiveAsync(
buffer,
ct);
if(result.MessageType == WebSocketMessageType.Close)
{
await _client.CloseAsync(
result.CloseStatus ?? WebSocketCloseStatus.Empty,
result.CloseStatusDescription,
ct);
return;
}
await _client.SendAsync(buffer, result.MessageType, result.EndOfMessage, ct);
}
}
private async Task Receive(CancellationToken ct)
{
var sendBuffer = new byte[4096];
while(_socket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(sendBuffer);
var result = await _client.ReceiveAsync(
buffer,
ct);
if(result.MessageType == WebSocketMessageType.Close)
{
await _socket.CloseAsync(
result.CloseStatus ?? WebSocketCloseStatus.Empty,
result.CloseStatusDescription,
ct);
return;
}
await _socket.SendAsync(buffer, result.MessageType, result.EndOfMessage, ct);
}
}
public void Dispose() => _client?.Dispose();
}
}
}
| |
/*
* 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.
*/
// $Id: FactoryFinder.java 670431 2008-06-23 01:40:03Z mrglavas $
using System;
using java = biz.ritter.javapi;
namespace biz.ritter.javapix.xml.parsers
{
/**
* This class is duplicated for each JAXP subpackage so keep it in
* sync. It is package private.
*
* This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to run on JDK version 1.1 and later including
* JVMs that perform early linking like the Microsoft JVM in IE 5. Note
* however that it must be compiled on a JDK version 1.2 or later system
* since it calls Thread#getContextClassLoader(). The code also runs both
* as part of an unbundled jar file and when bundled as part of the JDK.
*/
internal sealed class FactoryFinder
{
/**
* <p>Debug flag to trace loading process.</p>
*/
private static bool debug = false;
/**
* <p>Cache properties for performance.</p>
*/
private static java.util.Properties cacheProps = new java.util.Properties ();
/**
* <p>First time requires initialization overhead.</p>
*/
private static bool firstTime = true;
/**
* Default columns per line.
*/
private const int DEFAULT_LINE_LENGTH = 80;
// Define system property "jaxp.debug" to get output
static FactoryFinder ()
{
// Use try/catch block to support applets, which throws
// SecurityException out of this code.
try {
String val = SecuritySupport.getSystemProperty ("jaxp.debug");
// Allow simply setting the prop to turn on debug
debug = val != null && (! "false".equals (val));
} catch (java.lang.SecurityException se) {
debug = false;
}
}
private FactoryFinder ()
{
}
private static void dPrint (String msg)
{
if (debug) {
java.lang.SystemJ.err.println ("JAXP: " + msg);
}
}
/**
* Create an instance of a class using the specified ClassLoader and
* optionally fall back to the current ClassLoader if not found.
*
* @param className Name of the concrete class corresponding to the
* service provider
*
* @param cl ClassLoader to use to load the class, null means to use
* the bootstrap ClassLoader
*
* @param doFallback true if the current ClassLoader should be tried as
* a fallback if the class is not found using cl
*/
internal static Object newInstance (String className, java.lang.ClassLoader cl,
bool doFallback)
//throws ConfigurationError
{
// assert(className != null);
try {
java.lang.Class providerClass;
if (cl == null) {
// If classloader is null Use the bootstrap ClassLoader.
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = java.lang.Class.forName (className);
} else {
try {
providerClass = cl.loadClass (className);
} catch (java.lang.ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
cl = typeof(FactoryFinder).getClass ().getClassLoader ();
if (cl != null) {
providerClass = cl.loadClass (className);
} else {
providerClass = java.lang.Class.forName (className);
}
} else {
throw x;
}
}
}
Object instance = providerClass.newInstance ();
if (debug)
dPrint ("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (java.lang.ClassNotFoundException x) {
throw new ConfigurationError (
"Provider " + className + " not found", x);
} catch (java.lang.Exception x) {
throw new ConfigurationError (
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
/**
* Finds the implementation Class object in the specified order. Main
* entry point.
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* Package private so this code can be shared.
*/
internal static Object find (String factoryId, String fallbackClassName)
// throws ConfigurationError
{
// Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
java.lang.ClassLoader classLoader = SecuritySupport.getContextClassLoader ();
if (classLoader == null) {
// if we have no Context ClassLoader
// so use the current ClassLoader
classLoader = typeof(FactoryFinder).getClass ().getClassLoader ();
}
if (debug)
dPrint ("find factoryId =" + factoryId);
// Use the system property first
try {
String systemProp = SecuritySupport.getSystemProperty (factoryId);
if (systemProp != null && systemProp.length () > 0) {
if (debug)
dPrint ("found system property, value=" + systemProp);
return newInstance (systemProp, classLoader, true);
}
} catch (java.lang.SecurityException se) {
//if first option fails due to any reason we should try next option in the
//look up algorithm.
}
// try to read from $java.home/lib/jaxp.properties
try {
String javah = SecuritySupport.getSystemProperty ("java.home");
String configFile = javah + java.io.File.separator +
"lib" + java.io.File.separator + "jaxp.properties";
String factoryClassName = null;
if (firstTime) {
lock (cacheProps) {
if (firstTime) {
java.io.File f = new java.io.File (configFile);
firstTime = false;
if (SecuritySupport.doesFileExist (f)) {
if (debug)
dPrint ("Read properties file " + f);
//cacheProps.load( new FileInputStream(f));
cacheProps.load (SecuritySupport.getFileInputStream (f));
}
}
}
}
factoryClassName = cacheProps.getProperty (factoryId);
if (factoryClassName != null) {
if (debug)
dPrint ("found in $java.home/jaxp.properties, value=" + factoryClassName);
return newInstance (factoryClassName, classLoader, true);
}
} catch (java.lang.Exception ex) {
if (debug)
ex.printStackTrace ();
}
// Try Jar Service Provider Mechanism
Object provider = findJarServiceProvider (factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
throw new ConfigurationError (
"Provider for " + factoryId + " cannot be found", null);
}
if (debug)
dPrint ("loaded from fallback value: " + fallbackClassName);
return newInstance (fallbackClassName, classLoader, true);
}
/*
* Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null
*/
private static Object findJarServiceProvider (String factoryId)
//throws ConfigurationError
{
String serviceId = "META-INF/services/" + factoryId;
java.io.InputStream isJ = null;
// First try the Context ClassLoader
java.lang.ClassLoader cl = SecuritySupport.getContextClassLoader ();
if (cl != null) {
isJ = SecuritySupport.getResourceAsStream (cl, serviceId);
// If no provider found then try the current ClassLoader
if (isJ == null) {
cl = typeof(FactoryFinder).getClass ().getClassLoader ();
isJ = SecuritySupport.getResourceAsStream (cl, serviceId);
}
} else {
// No Context ClassLoader, try the current
// ClassLoader
cl = typeof(FactoryFinder).getClass ().getClassLoader ();
isJ = SecuritySupport.getResourceAsStream (cl, serviceId);
}
if (isJ == null) {
// No provider found
return null;
}
if (debug)
dPrint ("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
java.io.BufferedReader rd;
try {
rd = new java.io.BufferedReader (new java.io.InputStreamReader (isJ, "UTF-8"), DEFAULT_LINE_LENGTH);
} catch (java.io.UnsupportedEncodingException e) {
rd = new java.io.BufferedReader (new java.io.InputStreamReader (isJ), DEFAULT_LINE_LENGTH);
}
String factoryClassName = null;
try {
// XXX Does not handle all possible input as specified by the
// Jar Service Provider specification
factoryClassName = rd.readLine ();
} catch (java.io.IOException x) {
// No provider found
return null;
} finally {
try {
// try to close the reader.
rd.close ();
}
// Ignore the exception.
catch (java.io.IOException exc) {
}
}
if (factoryClassName != null &&
! "".equals (factoryClassName)) {
if (debug)
dPrint ("found in resource, value="
+ factoryClassName);
// Note: here we do not want to fall back to the current
// ClassLoader because we want to avoid the case where the
// resource file was found using one ClassLoader and the
// provider class was instantiated using a different one.
return newInstance (factoryClassName, cl, false);
}
// No provider found
return null;
}
internal class ConfigurationError : java.lang.Error
{
private java.lang.Exception exception;
/**
* Construct a new instance with the specified detail string and
* exception.
*/
internal ConfigurationError (String msg, java.lang.Exception x) :
base(msg)
{
this.exception = x;
}
internal java.lang.Exception getException ()
{
return exception;
}
}
}
}
| |
// 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;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Text;
using System.Runtime.Serialization;
using System.Globalization;
namespace System.Xml
{
public delegate void OnXmlDictionaryReaderClose(XmlDictionaryReader reader);
public abstract class XmlDictionaryReader : XmlReader
{
internal const int MaxInitialArrayLength = 65535;
public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader)
{
if (reader == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(reader));
XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
if (dictionaryReader == null)
{
dictionaryReader = new XmlWrappedReader(reader, null);
}
return dictionaryReader;
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer));
return CreateBinaryReader(buffer, 0, buffer.Length, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(buffer, offset, count, null, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(buffer, offset, count, dictionary, quotas, null);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
{
return CreateBinaryReader(buffer, offset, count, dictionary, quotas, session, onClose: null);
}
public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose)
{
XmlBinaryReader reader = new XmlBinaryReader();
reader.SetInput(buffer, offset, count, dictionary, quotas, session, onClose);
return reader;
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(stream, null, quotas);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas)
{
return CreateBinaryReader(stream, dictionary, quotas, null);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session)
{
return CreateBinaryReader(stream, dictionary, quotas, session, onClose: null);
}
public static XmlDictionaryReader CreateBinaryReader(Stream stream,
IXmlDictionary dictionary,
XmlDictionaryReaderQuotas quotas,
XmlBinaryReaderSession session,
OnXmlDictionaryReaderClose onClose)
{
XmlBinaryReader reader = new XmlBinaryReader();
reader.SetInput(stream, dictionary, quotas, session, onClose);
return reader;
}
public static XmlDictionaryReader CreateTextReader(byte[] buffer, XmlDictionaryReaderQuotas quotas)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer));
return CreateTextReader(buffer, 0, buffer.Length, quotas);
}
public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, XmlDictionaryReaderQuotas quotas)
{
return CreateTextReader(buffer, offset, count, null, quotas, null);
}
public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count,
Encoding encoding,
XmlDictionaryReaderQuotas quotas,
OnXmlDictionaryReaderClose onClose)
{
XmlUTF8TextReader reader = new XmlUTF8TextReader();
reader.SetInput(buffer, offset, count, encoding, quotas, onClose);
return reader;
}
public static XmlDictionaryReader CreateTextReader(Stream stream, XmlDictionaryReaderQuotas quotas)
{
return CreateTextReader(stream, null, quotas, null);
}
public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding encoding,
XmlDictionaryReaderQuotas quotas,
OnXmlDictionaryReaderClose onClose)
{
XmlUTF8TextReader reader = new XmlUTF8TextReader();
reader.SetInput(stream, encoding, quotas, onClose);
return reader;
}
public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas)
{
if (encoding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(encoding));
return CreateMtomReader(stream, new Encoding[1] { encoding }, quotas);
}
public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(stream, encodings, null, quotas);
}
public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(stream, encodings, contentType, quotas, int.MaxValue, null);
}
public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType,
XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding);
}
public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas)
{
if (encoding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(encoding));
return CreateMtomReader(buffer, offset, count, new Encoding[1] { encoding }, quotas);
}
public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(buffer, offset, count, encodings, null, quotas);
}
public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas)
{
return CreateMtomReader(buffer, offset, count, encodings, contentType, quotas, int.MaxValue, null);
}
public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType,
XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding);
}
public virtual bool CanCanonicalize
{
get
{
return false;
}
}
public virtual XmlDictionaryReaderQuotas Quotas
{
get
{
return XmlDictionaryReaderQuotas.Max;
}
}
public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void EndCanonicalization()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual void MoveToStartElement()
{
if (!IsStartElement())
XmlExceptionHelper.ThrowStartElementExpected(this);
}
public virtual void MoveToStartElement(string name)
{
if (!IsStartElement(name))
XmlExceptionHelper.ThrowStartElementExpected(this, name);
}
public virtual void MoveToStartElement(string localName, string namespaceUri)
{
if (!IsStartElement(localName, namespaceUri))
XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri);
}
public virtual void MoveToStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (!IsStartElement(localName, namespaceUri))
XmlExceptionHelper.ThrowStartElementExpected(this, localName, namespaceUri);
}
public virtual bool IsLocalName(string localName)
{
return this.LocalName == localName;
}
public virtual bool IsLocalName(XmlDictionaryString localName)
{
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localName));
return IsLocalName(localName.Value);
}
public virtual bool IsNamespaceUri(string namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
return this.NamespaceURI == namespaceUri;
}
public virtual bool IsNamespaceUri(XmlDictionaryString namespaceUri)
{
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
return IsNamespaceUri(namespaceUri.Value);
}
public virtual void ReadFullStartElement()
{
MoveToStartElement();
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this);
Read();
}
public virtual void ReadFullStartElement(string name)
{
MoveToStartElement(name);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, name);
Read();
}
public virtual void ReadFullStartElement(string localName, string namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri);
Read();
}
public virtual void ReadFullStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
if (IsEmptyElement)
XmlExceptionHelper.ThrowFullStartElementExpected(this, localName, namespaceUri);
Read();
}
public virtual void ReadStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
MoveToStartElement(localName, namespaceUri);
Read();
}
public virtual bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return IsStartElement(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public virtual int IndexOfLocalName(string[] localNames, string namespaceUri)
{
if (localNames == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localNames));
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
if (this.NamespaceURI == namespaceUri)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
string value = localNames[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i));
if (localName == value)
{
return i;
}
}
}
return -1;
}
public virtual int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString namespaceUri)
{
if (localNames == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(localNames));
if (namespaceUri == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri));
if (this.NamespaceURI == namespaceUri.Value)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
XmlDictionaryString value = localNames[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "localNames[{0}]", i));
if (localName == value.Value)
{
return i;
}
}
}
return -1;
}
public virtual string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return GetAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri));
}
public virtual bool TryGetBase64ContentLength(out int length)
{
length = 0;
return false;
}
public virtual int ReadValueAsBase64(byte[] buffer, int offset, int count)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
public virtual byte[] ReadContentAsBase64()
{
return ReadContentAsBase64(Quotas.MaxArrayLength, MaxInitialArrayLength);
}
internal byte[] ReadContentAsBase64(int maxByteArrayContentLength, int maxInitialCount)
{
int length;
if (TryGetBase64ContentLength(out length))
{
if (length <= maxInitialCount)
{
byte[] buffer = new byte[length];
int read = 0;
while (read < length)
{
int actual = ReadContentAsBase64(buffer, read, length - read);
if (actual == 0)
XmlExceptionHelper.ThrowBase64DataExpected(this);
read += actual;
}
return buffer;
}
}
return ReadContentAsBytes(true, maxByteArrayContentLength);
}
public override string ReadContentAsString()
{
return ReadContentAsString(Quotas.MaxStringContentLength);
}
protected string ReadContentAsString(int maxStringContentLength)
{
StringBuilder sb = null;
string result = string.Empty;
bool done = false;
while (true)
{
switch (this.NodeType)
{
case XmlNodeType.Attribute:
result = this.Value;
break;
case XmlNodeType.Text:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.CDATA:
// merge text content
string value = this.Value;
if (result.Length == 0)
{
result = value;
}
else
{
if (sb == null)
sb = new StringBuilder(result);
sb.Append(value);
}
break;
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.EndEntity:
// skip comments, pis and end entity nodes
break;
case XmlNodeType.EntityReference:
if (this.CanResolveEntity)
{
this.ResolveEntity();
break;
}
goto default;
case XmlNodeType.Element:
case XmlNodeType.EndElement:
default:
done = true;
break;
}
if (done)
break;
if (this.AttributeCount != 0)
ReadAttributeValue();
else
Read();
}
if (sb != null)
result = sb.ToString();
return result;
}
public override string ReadString()
{
return ReadString(Quotas.MaxStringContentLength);
}
protected string ReadString(int maxStringContentLength)
{
if (this.ReadState != ReadState.Interactive)
return string.Empty;
if (this.NodeType != XmlNodeType.Element)
MoveToElement();
if (this.NodeType == XmlNodeType.Element)
{
if (this.IsEmptyElement)
return string.Empty;
if (!Read())
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlInvalidOperation));
if (this.NodeType == XmlNodeType.EndElement)
return string.Empty;
}
StringBuilder sb = null;
string result = string.Empty;
while (IsTextNode(this.NodeType))
{
string value = this.Value;
if (result.Length == 0)
{
result = value;
}
else
{
if (sb == null)
sb = new StringBuilder(result);
if (sb.Length > maxStringContentLength - value.Length)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
sb.Append(value);
}
if (!Read())
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlInvalidOperation));
}
if (sb != null)
result = sb.ToString();
if (result.Length > maxStringContentLength)
XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, maxStringContentLength);
return result;
}
public virtual byte[] ReadContentAsBinHex()
{
return ReadContentAsBinHex(Quotas.MaxArrayLength);
}
protected byte[] ReadContentAsBinHex(int maxByteArrayContentLength)
{
return ReadContentAsBytes(false, maxByteArrayContentLength);
}
private byte[] ReadContentAsBytes(bool base64, int maxByteArrayContentLength)
{
byte[][] buffers = new byte[32][];
byte[] buffer;
// Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
int count = 384;
int bufferCount = 0;
int totalRead = 0;
while (true)
{
buffer = new byte[count];
buffers[bufferCount++] = buffer;
int read = 0;
while (read < buffer.Length)
{
int actual;
if (base64)
actual = ReadContentAsBase64(buffer, read, buffer.Length - read);
else
actual = ReadContentAsBinHex(buffer, read, buffer.Length - read);
if (actual == 0)
break;
read += actual;
}
totalRead += read;
if (read < buffer.Length)
break;
count = count * 2;
}
buffer = new byte[totalRead];
int offset = 0;
for (int i = 0; i < bufferCount - 1; i++)
{
Buffer.BlockCopy(buffers[i], 0, buffer, offset, buffers[i].Length);
offset += buffers[i].Length;
}
Buffer.BlockCopy(buffers[bufferCount - 1], 0, buffer, offset, totalRead - offset);
return buffer;
}
protected bool IsTextNode(XmlNodeType nodeType)
{
return nodeType == XmlNodeType.Text ||
nodeType == XmlNodeType.Whitespace ||
nodeType == XmlNodeType.SignificantWhitespace ||
nodeType == XmlNodeType.CDATA ||
nodeType == XmlNodeType.Attribute;
}
public virtual int ReadContentAsChars(char[] chars, int offset, int count)
{
int read = 0;
while (true)
{
XmlNodeType nodeType = this.NodeType;
if (nodeType == XmlNodeType.Element || nodeType == XmlNodeType.EndElement)
break;
if (IsTextNode(nodeType))
{
read = ReadValueChunk(chars, offset, count);
if (read > 0)
break;
if (nodeType == XmlNodeType.Attribute /* || inAttributeText */)
break;
if (!Read())
break;
}
else
{
if (!Read())
break;
}
}
return read;
}
public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
{
if (type == typeof(Guid[]))
{
string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver);
Guid[] guids = new Guid[values.Length];
for (int i = 0; i < values.Length; i++)
guids[i] = XmlConverter.ToGuid(values[i]);
return guids;
}
if (type == typeof(UniqueId[]))
{
string[] values = (string[])ReadContentAs(typeof(string[]), namespaceResolver);
UniqueId[] uniqueIds = new UniqueId[values.Length];
for (int i = 0; i < values.Length; i++)
uniqueIds[i] = XmlConverter.ToUniqueId(values[i]);
return uniqueIds;
}
return base.ReadContentAs(type, namespaceResolver);
}
public virtual string ReadContentAsString(string[] strings, out int index)
{
if (strings == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(strings));
string s = ReadContentAsString();
index = -1;
for (int i = 0; i < strings.Length; i++)
{
string value = strings[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i));
if (value == s)
{
index = i;
return value;
}
}
return s;
}
public virtual string ReadContentAsString(XmlDictionaryString[] strings, out int index)
{
if (strings == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(strings));
string s = ReadContentAsString();
index = -1;
for (int i = 0; i < strings.Length; i++)
{
XmlDictionaryString value = strings[i];
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(string.Format(CultureInfo.InvariantCulture, "strings[{0}]", i));
if (value.Value == s)
{
index = i;
return value.Value;
}
}
return s;
}
public override decimal ReadContentAsDecimal()
{
return XmlConverter.ToDecimal(ReadContentAsString());
}
public override float ReadContentAsFloat()
{
return XmlConverter.ToSingle(ReadContentAsString());
}
public virtual UniqueId ReadContentAsUniqueId()
{
return XmlConverter.ToUniqueId(ReadContentAsString());
}
public virtual Guid ReadContentAsGuid()
{
return XmlConverter.ToGuid(ReadContentAsString());
}
public virtual TimeSpan ReadContentAsTimeSpan()
{
return XmlConverter.ToTimeSpan(ReadContentAsString());
}
public virtual void ReadContentAsQualifiedName(out string localName, out string namespaceUri)
{
string prefix;
XmlConverter.ToQualifiedName(ReadContentAsString(), out prefix, out localName);
namespaceUri = LookupNamespace(prefix);
if (namespaceUri == null)
XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix);
}
/* string, bool, int, long, float, double, decimal, DateTime, base64, binhex, uniqueID, object, list*/
public override string ReadElementContentAsString()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
string value;
if (isEmptyElement)
{
Read();
value = string.Empty;
}
else
{
ReadStartElement();
value = ReadContentAsString();
ReadEndElement();
}
return value;
}
public override bool ReadElementContentAsBoolean()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
bool value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToBoolean(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsBoolean();
ReadEndElement();
}
return value;
}
public override int ReadElementContentAsInt()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
int value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToInt32(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsInt();
ReadEndElement();
}
return value;
}
public override long ReadElementContentAsLong()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
long value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToInt64(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsLong();
ReadEndElement();
}
return value;
}
public override float ReadElementContentAsFloat()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
float value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToSingle(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsFloat();
ReadEndElement();
}
return value;
}
public override double ReadElementContentAsDouble()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
double value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToDouble(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsDouble();
ReadEndElement();
}
return value;
}
public override decimal ReadElementContentAsDecimal()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
decimal value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToDecimal(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsDecimal();
ReadEndElement();
}
return value;
}
public override DateTime ReadElementContentAsDateTime()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
DateTime value;
if (isEmptyElement)
{
Read();
try
{
value = DateTime.Parse(string.Empty, NumberFormatInfo.InvariantInfo);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "DateTime", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsDateTime();
ReadEndElement();
}
return value;
}
public virtual UniqueId ReadElementContentAsUniqueId()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
UniqueId value;
if (isEmptyElement)
{
Read();
try
{
value = new UniqueId(string.Empty);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "UniqueId", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsUniqueId();
ReadEndElement();
}
return value;
}
public virtual Guid ReadElementContentAsGuid()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
Guid value;
if (isEmptyElement)
{
Read();
try
{
value = new Guid(string.Empty);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(string.Empty, "Guid", exception));
}
}
else
{
ReadStartElement();
value = ReadContentAsGuid();
ReadEndElement();
}
return value;
}
public virtual TimeSpan ReadElementContentAsTimeSpan()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
TimeSpan value;
if (isEmptyElement)
{
Read();
value = XmlConverter.ToTimeSpan(string.Empty);
}
else
{
ReadStartElement();
value = ReadContentAsTimeSpan();
ReadEndElement();
}
return value;
}
public virtual byte[] ReadElementContentAsBase64()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
Read();
buffer = Array.Empty<byte>();
}
else
{
ReadStartElement();
buffer = ReadContentAsBase64();
ReadEndElement();
}
return buffer;
}
public virtual byte[] ReadElementContentAsBinHex()
{
bool isEmptyElement = IsStartElement() && IsEmptyElement;
byte[] buffer;
if (isEmptyElement)
{
Read();
buffer = Array.Empty<byte>();
}
else
{
ReadStartElement();
buffer = ReadContentAsBinHex();
ReadEndElement();
}
return buffer;
}
public virtual void GetNonAtomizedNames(out string localName, out string namespaceUri)
{
localName = LocalName;
namespaceUri = NamespaceURI;
}
public virtual bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName)
{
localName = null;
return false;
}
public virtual bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString namespaceUri)
{
namespaceUri = null;
return false;
}
public virtual bool TryGetValueAsDictionaryString(out XmlDictionaryString value)
{
value = null;
return false;
}
private void CheckArray(Array array, int offset, int count)
{
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
public virtual bool IsStartArray(out Type type)
{
type = null;
return false;
}
public virtual bool TryGetArrayLength(out int count)
{
count = 0;
return false;
}
// Boolean
public virtual bool[] ReadBooleanArray(string localName, string namespaceUri)
{
return BooleanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual bool[] ReadBooleanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return BooleanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, bool[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsBoolean();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int16
public virtual short[] ReadInt16Array(string localName, string namespaceUri)
{
return Int16ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual short[] ReadInt16Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int16ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, short[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
int i = ReadElementContentAsInt();
if (i < short.MinValue || i > short.MaxValue)
XmlExceptionHelper.ThrowConversionOverflow(this, i.ToString(NumberFormatInfo.CurrentInfo), "Int16");
array[offset + actual] = (short)i;
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int32
public virtual int[] ReadInt32Array(string localName, string namespaceUri)
{
return Int32ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int[] ReadInt32Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int32ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, int[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsInt();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Int64
public virtual long[] ReadInt64Array(string localName, string namespaceUri)
{
return Int64ArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual long[] ReadInt64Array(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return Int64ArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, long[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsLong();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Single
public virtual float[] ReadSingleArray(string localName, string namespaceUri)
{
return SingleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual float[] ReadSingleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return SingleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, float[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsFloat();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Double
public virtual double[] ReadDoubleArray(string localName, string namespaceUri)
{
return DoubleArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual double[] ReadDoubleArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DoubleArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, double[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDouble();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Decimal
public virtual decimal[] ReadDecimalArray(string localName, string namespaceUri)
{
return DecimalArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual decimal[] ReadDecimalArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DecimalArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, decimal[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDecimal();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// DateTime
public virtual DateTime[] ReadDateTimeArray(string localName, string namespaceUri)
{
return DateTimeArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual DateTime[] ReadDateTimeArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsDateTime();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// Guid
public virtual Guid[] ReadGuidArray(string localName, string namespaceUri)
{
return GuidArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual Guid[] ReadGuidArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return GuidArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, Guid[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsGuid();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
// TimeSpan
public virtual TimeSpan[] ReadTimeSpanArray(string localName, string namespaceUri)
{
return TimeSpanArrayHelperWithString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual TimeSpan[] ReadTimeSpanArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
return TimeSpanArrayHelperWithDictionaryString.Instance.ReadArray(this, localName, namespaceUri, Quotas.MaxArrayLength);
}
public virtual int ReadArray(string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
CheckArray(array, offset, count);
int actual = 0;
while (actual < count && IsStartElement(localName, namespaceUri))
{
array[offset + actual] = ReadElementContentAsTimeSpan();
actual++;
}
return actual;
}
public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
return ReadArray(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count);
}
private class XmlWrappedReader : XmlDictionaryReader, IXmlLineInfo
{
private XmlReader _reader;
private XmlNamespaceManager _nsMgr;
public XmlWrappedReader(XmlReader reader, XmlNamespaceManager nsMgr)
{
_reader = reader;
_nsMgr = nsMgr;
}
public override int AttributeCount
{
get
{
return _reader.AttributeCount;
}
}
public override string BaseURI
{
get
{
return _reader.BaseURI;
}
}
public override bool CanReadBinaryContent
{
get { return _reader.CanReadBinaryContent; }
}
public override bool CanReadValueChunk
{
get { return _reader.CanReadValueChunk; }
}
public override void Close()
{
_reader.Dispose();
_nsMgr = null;
}
public override int Depth
{
get
{
return _reader.Depth;
}
}
public override bool EOF
{
get
{
return _reader.EOF;
}
}
public override string GetAttribute(int index)
{
return _reader.GetAttribute(index);
}
public override string GetAttribute(string name)
{
return _reader.GetAttribute(name);
}
public override string GetAttribute(string name, string namespaceUri)
{
return _reader.GetAttribute(name, namespaceUri);
}
public override bool HasValue
{
get
{
return _reader.HasValue;
}
}
public override bool IsDefault
{
get
{
return _reader.IsDefault;
}
}
public override bool IsEmptyElement
{
get
{
return _reader.IsEmptyElement;
}
}
public override bool IsStartElement(string name)
{
return _reader.IsStartElement(name);
}
public override bool IsStartElement(string localName, string namespaceUri)
{
return _reader.IsStartElement(localName, namespaceUri);
}
public override string LocalName
{
get
{
return _reader.LocalName;
}
}
public override string LookupNamespace(string namespaceUri)
{
return _reader.LookupNamespace(namespaceUri);
}
public override void MoveToAttribute(int index)
{
_reader.MoveToAttribute(index);
}
public override bool MoveToAttribute(string name)
{
return _reader.MoveToAttribute(name);
}
public override bool MoveToAttribute(string name, string namespaceUri)
{
return _reader.MoveToAttribute(name, namespaceUri);
}
public override bool MoveToElement()
{
return _reader.MoveToElement();
}
public override bool MoveToFirstAttribute()
{
return _reader.MoveToFirstAttribute();
}
public override bool MoveToNextAttribute()
{
return _reader.MoveToNextAttribute();
}
public override string Name
{
get
{
return _reader.Name;
}
}
public override string NamespaceURI
{
get
{
return _reader.NamespaceURI;
}
}
public override XmlNameTable NameTable
{
get
{
return _reader.NameTable;
}
}
public override XmlNodeType NodeType
{
get
{
return _reader.NodeType;
}
}
public override string Prefix
{
get
{
return _reader.Prefix;
}
}
public override bool Read()
{
return _reader.Read();
}
public override bool ReadAttributeValue()
{
return _reader.ReadAttributeValue();
}
public override string ReadInnerXml()
{
return _reader.ReadInnerXml();
}
public override string ReadOuterXml()
{
return _reader.ReadOuterXml();
}
public override void ReadStartElement(string name)
{
_reader.ReadStartElement(name);
}
public override void ReadStartElement(string localName, string namespaceUri)
{
_reader.ReadStartElement(localName, namespaceUri);
}
public override void ReadEndElement()
{
_reader.ReadEndElement();
}
public override ReadState ReadState
{
get
{
return _reader.ReadState;
}
}
public override void ResolveEntity()
{
_reader.ResolveEntity();
}
public override string this[int index]
{
get
{
return _reader[index];
}
}
public override string this[string name]
{
get
{
return _reader[name];
}
}
public override string this[string name, string namespaceUri]
{
get
{
return _reader[name, namespaceUri];
}
}
public override string Value
{
get
{
return _reader.Value;
}
}
public override string XmlLang
{
get
{
return _reader.XmlLang;
}
}
public override XmlSpace XmlSpace
{
get
{
return _reader.XmlSpace;
}
}
public override int ReadElementContentAsBase64(byte[] buffer, int offset, int count)
{
return _reader.ReadElementContentAsBase64(buffer, offset, count);
}
public override int ReadContentAsBase64(byte[] buffer, int offset, int count)
{
return _reader.ReadContentAsBase64(buffer, offset, count);
}
public override int ReadElementContentAsBinHex(byte[] buffer, int offset, int count)
{
return _reader.ReadElementContentAsBinHex(buffer, offset, count);
}
public override int ReadContentAsBinHex(byte[] buffer, int offset, int count)
{
return _reader.ReadContentAsBinHex(buffer, offset, count);
}
public override int ReadValueChunk(char[] chars, int offset, int count)
{
return _reader.ReadValueChunk(chars, offset, count);
}
public override Type ValueType
{
get
{
return _reader.ValueType;
}
}
public override bool ReadContentAsBoolean()
{
try
{
return _reader.ReadContentAsBoolean();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Boolean", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Boolean", exception));
}
}
public override DateTime ReadContentAsDateTime()
{
return _reader.ReadContentAsDateTime();
}
public override decimal ReadContentAsDecimal()
{
try
{
return (decimal)_reader.ReadContentAs(typeof(decimal), null);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Decimal", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Decimal", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Decimal", exception));
}
}
public override double ReadContentAsDouble()
{
try
{
return _reader.ReadContentAsDouble();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Double", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Double", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Double", exception));
}
}
public override int ReadContentAsInt()
{
try
{
return _reader.ReadContentAsInt();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int32", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int32", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int32", exception));
}
}
public override long ReadContentAsLong()
{
try
{
return _reader.ReadContentAsLong();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int64", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int64", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Int64", exception));
}
}
public override float ReadContentAsFloat()
{
try
{
return _reader.ReadContentAsFloat();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Single", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Single", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("Single", exception));
}
}
public override string ReadContentAsString()
{
try
{
return _reader.ReadContentAsString();
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("String", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException("String", exception));
}
}
public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver)
{
return _reader.ReadContentAs(type, namespaceResolver);
}
public bool HasLineInfo()
{
IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
if (lineInfo == null)
return false;
return lineInfo.HasLineInfo();
}
public int LineNumber
{
get
{
IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
if (lineInfo == null)
return 1;
return lineInfo.LineNumber;
}
}
public int LinePosition
{
get
{
IXmlLineInfo lineInfo = _reader as IXmlLineInfo;
if (lineInfo == null)
return 1;
return lineInfo.LinePosition;
}
}
}
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BitSharper.Store;
using NUnit.Framework;
namespace BitSharper.Test
{
[TestFixture]
public class WalletTest
{
private static readonly NetworkParameters _params = NetworkParameters.UnitTests();
private Address _myAddress;
private Wallet _wallet;
private IBlockStore _blockStore;
[SetUp]
public void SetUp()
{
var myKey = new EcKey();
_myAddress = myKey.ToAddress(_params);
_wallet = new Wallet(_params);
_wallet.AddKey(myKey);
_blockStore = new MemoryBlockStore(_params);
}
[TearDown]
public void TearDown()
{
_blockStore.Dispose();
}
[Test]
public void BasicSpending()
{
// We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change.
var v1 = Utils.ToNanoCoins(1, 0);
var t1 = TestUtils.CreateFakeTx(_params, v1, _myAddress);
_wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(v1, _wallet.GetBalance());
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All));
var k2 = new EcKey();
var v2 = Utils.ToNanoCoins(0, 50);
var t2 = _wallet.CreateSend(k2.ToAddress(_params), v2);
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All));
// Do some basic sanity checks.
Assert.AreEqual(1, t2.Inputs.Count);
Assert.AreEqual(_myAddress, t2.Inputs[0].ScriptSig.FromAddress);
// We have NOT proven that the signature is correct!
_wallet.ConfirmSend(t2);
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Pending));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Spent));
Assert.AreEqual(2, _wallet.GetPoolSize(Wallet.Pool.All));
}
[Test]
public void SideChain()
{
// The wallet receives a coin on the main chain, then on a side chain. Only main chain counts towards balance.
var v1 = Utils.ToNanoCoins(1, 0);
var t1 = TestUtils.CreateFakeTx(_params, v1, _myAddress);
_wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(v1, _wallet.GetBalance());
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All));
var v2 = Utils.ToNanoCoins(0, 50);
var t2 = TestUtils.CreateFakeTx(_params, v2, _myAddress);
_wallet.Receive(t2, null, BlockChain.NewBlockType.SideChain);
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Inactive));
Assert.AreEqual(2, _wallet.GetPoolSize(Wallet.Pool.All));
Assert.AreEqual(v1, _wallet.GetBalance());
}
[Test]
public void Listener()
{
var fakeTx = TestUtils.CreateFakeTx(_params, Utils.ToNanoCoins(1, 0), _myAddress);
var didRun = false;
_wallet.CoinsReceived +=
(sender, e) =>
{
Assert.IsTrue(e.PrevBalance.Equals(0));
Assert.IsTrue(e.NewBalance.Equals(Utils.ToNanoCoins(1, 0)));
Assert.AreEqual(e.Tx, fakeTx);
Assert.AreEqual(sender, _wallet);
didRun = true;
};
_wallet.Receive(fakeTx, null, BlockChain.NewBlockType.BestChain);
Assert.IsTrue(didRun);
}
[Test]
public void Balance()
{
// Receive 5 coins then half a coin.
var v1 = Utils.ToNanoCoins(5, 0);
var v2 = Utils.ToNanoCoins(0, 50);
var t1 = TestUtils.CreateFakeTx(_params, v1, _myAddress);
var t2 = TestUtils.CreateFakeTx(_params, v2, _myAddress);
var b1 = TestUtils.CreateFakeBlock(_params, _blockStore, t1).StoredBlock;
var b2 = TestUtils.CreateFakeBlock(_params, _blockStore, t2).StoredBlock;
var expected = Utils.ToNanoCoins(5, 50);
_wallet.Receive(t1, b1, BlockChain.NewBlockType.BestChain);
_wallet.Receive(t2, b2, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(expected, _wallet.GetBalance());
// Now spend one coin.
var v3 = Utils.ToNanoCoins(1, 0);
var spend = _wallet.CreateSend(new EcKey().ToAddress(_params), v3);
_wallet.ConfirmSend(spend);
// Available and estimated balances should not be the same. We don't check the exact available balance here
// because it depends on the coin selection algorithm.
Assert.AreEqual(Utils.ToNanoCoins(4, 50), _wallet.GetBalance(Wallet.BalanceType.Estimated));
Assert.IsFalse(_wallet.GetBalance(Wallet.BalanceType.Available).Equals(
_wallet.GetBalance(Wallet.BalanceType.Estimated)));
// Now confirm the transaction by including it into a block.
var b3 = TestUtils.CreateFakeBlock(_params, _blockStore, spend).StoredBlock;
_wallet.Receive(spend, b3, BlockChain.NewBlockType.BestChain);
// Change is confirmed. We started with 5.50 so we should have 4.50 left.
var v4 = Utils.ToNanoCoins(4, 50);
Assert.AreEqual(v4, _wallet.GetBalance(Wallet.BalanceType.Available));
}
// Intuitively you'd expect to be able to create a transaction with identical inputs and outputs and get an
// identical result to the official client. However the signatures are not deterministic - signing the same data
// with the same key twice gives two different outputs. So we cannot prove bit-for-bit compatibility in this test
// suite.
[Test]
public void BlockChainCatchup()
{
var tx1 = TestUtils.CreateFakeTx(_params, Utils.ToNanoCoins(1, 0), _myAddress);
var b1 = TestUtils.CreateFakeBlock(_params, _blockStore, tx1).StoredBlock;
_wallet.Receive(tx1, b1, BlockChain.NewBlockType.BestChain);
// Send 0.10 to somebody else.
var send1 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 10), _myAddress);
// Pretend it makes it into the block chain, our wallet state is cleared but we still have the keys, and we
// want to get back to our previous state. We can do this by just not confirming the transaction as
// createSend is stateless.
var b2 = TestUtils.CreateFakeBlock(_params, _blockStore, send1).StoredBlock;
_wallet.Receive(send1, b2, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(Utils.BitcoinValueToFriendlyString(_wallet.GetBalance()), "0.90");
// And we do it again after the catch-up.
var send2 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 10), _myAddress);
// What we'd really like to do is prove the official client would accept it .... no such luck unfortunately.
_wallet.ConfirmSend(send2);
var b3 = TestUtils.CreateFakeBlock(_params, _blockStore, send2).StoredBlock;
_wallet.Receive(send2, b3, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(Utils.BitcoinValueToFriendlyString(_wallet.GetBalance()), "0.80");
}
[Test]
public void Balances()
{
var nanos = Utils.ToNanoCoins(1, 0);
var tx1 = TestUtils.CreateFakeTx(_params, nanos, _myAddress);
_wallet.Receive(tx1, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(nanos, tx1.GetValueSentToMe(_wallet, true));
// Send 0.10 to somebody else.
var send1 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 10), _myAddress);
// Re-serialize.
var send2 = new Transaction(_params, send1.BitcoinSerialize());
Assert.AreEqual(nanos, send2.GetValueSentFromMe(_wallet));
}
[Test]
public void Transactions()
{
// This test covers a bug in which Transaction.getValueSentFromMe was calculating incorrectly.
var tx = TestUtils.CreateFakeTx(_params, Utils.ToNanoCoins(1, 0), _myAddress);
// Now add another output (ie, change) that goes to some other address.
var someOtherGuy = new EcKey().ToAddress(_params);
var output = new TransactionOutput(_params, tx, Utils.ToNanoCoins(0, 5), someOtherGuy);
tx.AddOutput(output);
// Note that tx is no longer valid: it spends more than it imports. However checking transactions balance
// correctly isn't possible in SPV mode because value is a property of outputs not inputs. Without all
// transactions you can't check they add up.
_wallet.Receive(tx, null, BlockChain.NewBlockType.BestChain);
// Now the other guy creates a transaction which spends that change.
var tx2 = new Transaction(_params);
tx2.AddInput(output);
tx2.AddOutput(new TransactionOutput(_params, tx2, Utils.ToNanoCoins(0, 5), _myAddress));
// tx2 doesn't send any coins from us, even though the output is in the wallet.
Assert.AreEqual(Utils.ToNanoCoins(0, 0), tx2.GetValueSentFromMe(_wallet));
}
[Test]
public void Bounce()
{
// This test covers bug 64 (False double spends). Check that if we create a spend and it's immediately sent
// back to us, this isn't considered as a double spend.
var coin1 = Utils.ToNanoCoins(1, 0);
var coinHalf = Utils.ToNanoCoins(0, 50);
// Start by giving us 1 coin.
var inbound1 = TestUtils.CreateFakeTx(_params, coin1, _myAddress);
_wallet.Receive(inbound1, null, BlockChain.NewBlockType.BestChain);
// Send half to some other guy. Sending only half then waiting for a confirm is important to ensure the tx is
// in the unspent pool, not pending or spent.
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.Unspent));
Assert.AreEqual(1, _wallet.GetPoolSize(Wallet.Pool.All));
var someOtherGuy = new EcKey().ToAddress(_params);
var outbound1 = _wallet.CreateSend(someOtherGuy, coinHalf);
_wallet.ConfirmSend(outbound1);
_wallet.Receive(outbound1, null, BlockChain.NewBlockType.BestChain);
// That other guy gives us the coins right back.
var inbound2 = new Transaction(_params);
inbound2.AddOutput(new TransactionOutput(_params, inbound2, coinHalf, _myAddress));
inbound2.AddInput(outbound1.Outputs[0]);
_wallet.Receive(inbound2, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(coin1, _wallet.GetBalance());
}
[Test]
public void FinneyAttack()
{
// A Finney attack is where a miner includes a transaction spending coins to themselves but does not
// broadcast it. When they find a solved block, they hold it back temporarily whilst they buy something with
// those same coins. After purchasing, they broadcast the block thus reversing the transaction. It can be
// done by any miner for products that can be bought at a chosen time and very quickly (as every second you
// withhold your block means somebody else might find it first, invalidating your work).
//
// Test that we handle ourselves performing the attack correctly: a double spend on the chain moves
// transactions from pending to dead.
//
// Note that the other way around, where a pending transaction sending us coins becomes dead,
// isn't tested because today BitCoinJ only learns about such transactions when they appear in the chain.
Transaction eventDead = null;
Transaction eventReplacement = null;
_wallet.DeadTransaction +=
(sender, e) =>
{
eventDead = e.DeadTx;
eventReplacement = e.ReplacementTx;
};
// Receive 1 BTC.
var nanos = Utils.ToNanoCoins(1, 0);
var t1 = TestUtils.CreateFakeTx(_params, nanos, _myAddress);
_wallet.Receive(t1, null, BlockChain.NewBlockType.BestChain);
// Create a send to a merchant.
var send1 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 50));
// Create a double spend.
var send2 = _wallet.CreateSend(new EcKey().ToAddress(_params), Utils.ToNanoCoins(0, 50));
// Broadcast send1.
_wallet.ConfirmSend(send1);
// Receive a block that overrides it.
_wallet.Receive(send2, null, BlockChain.NewBlockType.BestChain);
Assert.AreEqual(send1, eventDead);
Assert.AreEqual(send2, eventReplacement);
}
}
}
| |
/*
* CP1254.cs - Turkish (Windows) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-5350.ucm".
namespace I18N.MidEast
{
using System;
using I18N.Common;
public class CP1254 : ByteEncoding
{
public CP1254()
: base(1254, ToChars, "Turkish (Windows)",
"iso-8859-9", "windows-1254", "windows-1254",
true, true, true, true, 1254)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u007F', '\u20AC', '\u0081', '\u201A', '\u0192',
'\u201E', '\u2026', '\u2020', '\u2021', '\u02C6', '\u2030',
'\u0160', '\u2039', '\u0152', '\u008D', '\u008E', '\u008F',
'\u0090', '\u2018', '\u2019', '\u201C', '\u201D', '\u2022',
'\u2013', '\u2014', '\u02DC', '\u2122', '\u0161', '\u203A',
'\u0153', '\u009D', '\u009E', '\u0178', '\u00A0', '\u00A1',
'\u00A2', '\u00A3', '\u00A4', '\u00A5', '\u00A6', '\u00A7',
'\u00A8', '\u00A9', '\u00AA', '\u00AB', '\u00AC', '\u00AD',
'\u00AE', '\u00AF', '\u00B0', '\u00B1', '\u00B2', '\u00B3',
'\u00B4', '\u00B5', '\u00B6', '\u00B7', '\u00B8', '\u00B9',
'\u00BA', '\u00BB', '\u00BC', '\u00BD', '\u00BE', '\u00BF',
'\u00C0', '\u00C1', '\u00C2', '\u00C3', '\u00C4', '\u00C5',
'\u00C6', '\u00C7', '\u00C8', '\u00C9', '\u00CA', '\u00CB',
'\u00CC', '\u00CD', '\u00CE', '\u00CF', '\u011E', '\u00D1',
'\u00D2', '\u00D3', '\u00D4', '\u00D5', '\u00D6', '\u00D7',
'\u00D8', '\u00D9', '\u00DA', '\u00DB', '\u00DC', '\u0130',
'\u015E', '\u00DF', '\u00E0', '\u00E1', '\u00E2', '\u00E3',
'\u00E4', '\u00E5', '\u00E6', '\u00E7', '\u00E8', '\u00E9',
'\u00EA', '\u00EB', '\u00EC', '\u00ED', '\u00EE', '\u00EF',
'\u011F', '\u00F1', '\u00F2', '\u00F3', '\u00F4', '\u00F5',
'\u00F6', '\u00F7', '\u00F8', '\u00F9', '\u00FA', '\u00FB',
'\u00FC', '\u0131', '\u015F', '\u00FF',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x0081:
case 0x008D:
case 0x008E:
case 0x008F:
case 0x0090:
case 0x009D:
case 0x009E:
case 0x00A0:
case 0x00A1:
case 0x00A2:
case 0x00A3:
case 0x00A4:
case 0x00A5:
case 0x00A6:
case 0x00A7:
case 0x00A8:
case 0x00A9:
case 0x00AA:
case 0x00AB:
case 0x00AC:
case 0x00AD:
case 0x00AE:
case 0x00AF:
case 0x00B0:
case 0x00B1:
case 0x00B2:
case 0x00B3:
case 0x00B4:
case 0x00B5:
case 0x00B6:
case 0x00B7:
case 0x00B8:
case 0x00B9:
case 0x00BA:
case 0x00BB:
case 0x00BC:
case 0x00BD:
case 0x00BE:
case 0x00BF:
case 0x00C0:
case 0x00C1:
case 0x00C2:
case 0x00C3:
case 0x00C4:
case 0x00C5:
case 0x00C6:
case 0x00C7:
case 0x00C8:
case 0x00C9:
case 0x00CA:
case 0x00CB:
case 0x00CC:
case 0x00CD:
case 0x00CE:
case 0x00CF:
case 0x00D1:
case 0x00D2:
case 0x00D3:
case 0x00D4:
case 0x00D5:
case 0x00D6:
case 0x00D7:
case 0x00D8:
case 0x00D9:
case 0x00DA:
case 0x00DB:
case 0x00DC:
case 0x00DF:
case 0x00E0:
case 0x00E1:
case 0x00E2:
case 0x00E3:
case 0x00E4:
case 0x00E5:
case 0x00E6:
case 0x00E7:
case 0x00E8:
case 0x00E9:
case 0x00EA:
case 0x00EB:
case 0x00EC:
case 0x00ED:
case 0x00EE:
case 0x00EF:
case 0x00F1:
case 0x00F2:
case 0x00F3:
case 0x00F4:
case 0x00F5:
case 0x00F6:
case 0x00F7:
case 0x00F8:
case 0x00F9:
case 0x00FA:
case 0x00FB:
case 0x00FC:
case 0x00FF:
break;
case 0x011E: ch = 0xD0; break;
case 0x011F: ch = 0xF0; break;
case 0x0130: ch = 0xDD; break;
case 0x0131: ch = 0xFD; break;
case 0x0152: ch = 0x8C; break;
case 0x0153: ch = 0x9C; break;
case 0x015E: ch = 0xDE; break;
case 0x015F: ch = 0xFE; break;
case 0x0160: ch = 0x8A; break;
case 0x0161: ch = 0x9A; break;
case 0x0178: ch = 0x9F; break;
case 0x0192: ch = 0x83; break;
case 0x02C6: ch = 0x88; break;
case 0x02DC: ch = 0x98; break;
case 0x2013: ch = 0x96; break;
case 0x2014: ch = 0x97; break;
case 0x2018: ch = 0x91; break;
case 0x2019: ch = 0x92; break;
case 0x201A: ch = 0x82; break;
case 0x201C: ch = 0x93; break;
case 0x201D: ch = 0x94; break;
case 0x201E: ch = 0x84; break;
case 0x2020: ch = 0x86; break;
case 0x2021: ch = 0x87; break;
case 0x2022: ch = 0x95; break;
case 0x2026: ch = 0x85; break;
case 0x2030: ch = 0x89; break;
case 0x2039: ch = 0x8B; break;
case 0x203A: ch = 0x9B; break;
case 0x20AC: ch = 0x80; break;
case 0x2122: ch = 0x99; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 128) switch(ch)
{
case 0x0081:
case 0x008D:
case 0x008E:
case 0x008F:
case 0x0090:
case 0x009D:
case 0x009E:
case 0x00A0:
case 0x00A1:
case 0x00A2:
case 0x00A3:
case 0x00A4:
case 0x00A5:
case 0x00A6:
case 0x00A7:
case 0x00A8:
case 0x00A9:
case 0x00AA:
case 0x00AB:
case 0x00AC:
case 0x00AD:
case 0x00AE:
case 0x00AF:
case 0x00B0:
case 0x00B1:
case 0x00B2:
case 0x00B3:
case 0x00B4:
case 0x00B5:
case 0x00B6:
case 0x00B7:
case 0x00B8:
case 0x00B9:
case 0x00BA:
case 0x00BB:
case 0x00BC:
case 0x00BD:
case 0x00BE:
case 0x00BF:
case 0x00C0:
case 0x00C1:
case 0x00C2:
case 0x00C3:
case 0x00C4:
case 0x00C5:
case 0x00C6:
case 0x00C7:
case 0x00C8:
case 0x00C9:
case 0x00CA:
case 0x00CB:
case 0x00CC:
case 0x00CD:
case 0x00CE:
case 0x00CF:
case 0x00D1:
case 0x00D2:
case 0x00D3:
case 0x00D4:
case 0x00D5:
case 0x00D6:
case 0x00D7:
case 0x00D8:
case 0x00D9:
case 0x00DA:
case 0x00DB:
case 0x00DC:
case 0x00DF:
case 0x00E0:
case 0x00E1:
case 0x00E2:
case 0x00E3:
case 0x00E4:
case 0x00E5:
case 0x00E6:
case 0x00E7:
case 0x00E8:
case 0x00E9:
case 0x00EA:
case 0x00EB:
case 0x00EC:
case 0x00ED:
case 0x00EE:
case 0x00EF:
case 0x00F1:
case 0x00F2:
case 0x00F3:
case 0x00F4:
case 0x00F5:
case 0x00F6:
case 0x00F7:
case 0x00F8:
case 0x00F9:
case 0x00FA:
case 0x00FB:
case 0x00FC:
case 0x00FF:
break;
case 0x011E: ch = 0xD0; break;
case 0x011F: ch = 0xF0; break;
case 0x0130: ch = 0xDD; break;
case 0x0131: ch = 0xFD; break;
case 0x0152: ch = 0x8C; break;
case 0x0153: ch = 0x9C; break;
case 0x015E: ch = 0xDE; break;
case 0x015F: ch = 0xFE; break;
case 0x0160: ch = 0x8A; break;
case 0x0161: ch = 0x9A; break;
case 0x0178: ch = 0x9F; break;
case 0x0192: ch = 0x83; break;
case 0x02C6: ch = 0x88; break;
case 0x02DC: ch = 0x98; break;
case 0x2013: ch = 0x96; break;
case 0x2014: ch = 0x97; break;
case 0x2018: ch = 0x91; break;
case 0x2019: ch = 0x92; break;
case 0x201A: ch = 0x82; break;
case 0x201C: ch = 0x93; break;
case 0x201D: ch = 0x94; break;
case 0x201E: ch = 0x84; break;
case 0x2020: ch = 0x86; break;
case 0x2021: ch = 0x87; break;
case 0x2022: ch = 0x95; break;
case 0x2026: ch = 0x85; break;
case 0x2030: ch = 0x89; break;
case 0x2039: ch = 0x8B; break;
case 0x203A: ch = 0x9B; break;
case 0x20AC: ch = 0x80; break;
case 0x2122: ch = 0x99; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP1254
public class ENCwindows_1254 : CP1254
{
public ENCwindows_1254() : base() {}
}; // class ENCwindows_1254
}; // namespace I18N.MidEast
| |
// 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.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.HttpOverrides
{
public class CertificateForwardingTests
{
[Fact]
public void VerifySettingNullHeaderOptionThrows()
{
var services = new ServiceCollection()
.AddOptions()
.AddCertificateForwarding(o => o.CertificateHeader = null);
var options = services.BuildServiceProvider().GetRequiredService<IOptions<CertificateForwardingOptions>>();
Assert.Throws<OptionsValidationException>(() => options.Value);
}
[Fact]
public void VerifySettingEmptyHeaderOptionThrows()
{
var services = new ServiceCollection()
.AddOptions()
.AddCertificateForwarding(o => o.CertificateHeader = "");
var options = services.BuildServiceProvider().GetRequiredService<IOptions<CertificateForwardingOptions>>();
Assert.Throws<OptionsValidationException>(() => options.Value);
}
[Fact]
public async Task VerifyHeaderIsUsedIfNoCertificateAlreadySet()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddCertificateForwarding(options => { });
})
.Configure(app =>
{
app.Use(async (context, next) =>
{
Assert.Null(context.Connection.ClientCertificate);
await next(context);
});
app.UseCertificateForwarding();
app.Use(async (context, next) =>
{
Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku);
await next(context);
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var context = await server.SendAsync(c =>
{
c.Request.Headers["X-Client-Cert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData);
});
}
[Fact]
public async Task VerifyHeaderOverridesCertificateEvenAlreadySet()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddCertificateForwarding(options => { });
})
.Configure(app =>
{
app.Use(async (context, next) =>
{
Assert.Null(context.Connection.ClientCertificate);
context.Connection.ClientCertificate = Certificates.SelfSignedNotYetValid;
await next(context);
});
app.UseCertificateForwarding();
app.Use(async (context, next) =>
{
Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku);
await next(context);
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var context = await server.SendAsync(c =>
{
c.Request.Headers["X-Client-Cert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData);
});
}
[Fact]
public async Task VerifySettingTheAzureHeaderOnTheForwarderOptionsWorks()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddCertificateForwarding(options => options.CertificateHeader = "X-ARR-ClientCert");
})
.Configure(app =>
{
app.Use(async (context, next) =>
{
Assert.Null(context.Connection.ClientCertificate);
await next(context);
});
app.UseCertificateForwarding();
app.Use(async (context, next) =>
{
Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku);
await next(context);
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var context = await server.SendAsync(c =>
{
c.Request.Headers["X-ARR-ClientCert"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData);
});
}
[Fact]
public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddCertificateForwarding(options => options.CertificateHeader = "some-random-header");
})
.Configure(app =>
{
app.Use(async (context, next) =>
{
Assert.Null(context.Connection.ClientCertificate);
await next(context);
});
app.UseCertificateForwarding();
app.Use(async (context, next) =>
{
Assert.Null(context.Connection.ClientCertificate);
await next(context);
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var context = await server.SendAsync(c =>
{
c.Request.Headers["not-the-right-header"] = Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData);
});
}
[Fact]
public async Task VerifyArrHeaderEncodedCertFailsOnBadEncoding()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddCertificateForwarding(options => { });
})
.Configure(app =>
{
app.Use(async (context, next) =>
{
Assert.Null(context.Connection.ClientCertificate);
await next(context);
});
app.UseCertificateForwarding();
app.Use(async (context, next) =>
{
Assert.Null(context.Connection.ClientCertificate);
await next(context);
});
});
}).Build();
await host.StartAsync();
var server = host.GetTestServer();
var context = await server.SendAsync(c =>
{
c.Request.Headers["X-Client-Cert"] = "OOPS" + Convert.ToBase64String(Certificates.SelfSignedValidWithNoEku.RawData);
});
}
private static class Certificates
{
public static X509Certificate2 SelfSignedValidWithClientEku { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("validSelfSignedClientEkuCertificate.cer"));
public static X509Certificate2 SelfSignedValidWithNoEku { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("validSelfSignedNoEkuCertificate.cer"));
public static X509Certificate2 SelfSignedValidWithServerEku { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("validSelfSignedServerEkuCertificate.cer"));
public static X509Certificate2 SelfSignedNotYetValid { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("selfSignedNoEkuCertificateNotValidYet.cer"));
public static X509Certificate2 SelfSignedExpired { get; private set; } =
new X509Certificate2(GetFullyQualifiedFilePath("selfSignedNoEkuCertificateExpired.cer"));
private static string GetFullyQualifiedFilePath(string filename)
{
var filePath = Path.Combine(AppContext.BaseDirectory, filename);
if (!File.Exists(filePath))
{
throw new FileNotFoundException(filePath);
}
return filePath;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MvcMusicStore.Areas.HelpPage.ModelDescriptions;
using MvcMusicStore.Areas.HelpPage.Models;
namespace MvcMusicStore.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//
// System.Data.Common.DbTable.cs
//
// Author:
// Tim Coleman ([email protected])
//
// Copyright (C) Tim Coleman, 2003
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0 || TARGET_JVM
using System.ComponentModel;
namespace System.Data.Common {
public abstract class DbTable : DataTable
{
#region Constructors
[MonoTODO]
protected DbTable (DbProviderFactory providerFactory)
{
}
#endregion // Constructors
#region Properties
[MonoTODO]
public ConflictOptions ConflictDetection {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
[MonoTODO]
public DbConnection Connection {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
[MonoTODO]
public DbCommand DeleteCommand {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
[MonoTODO]
public DbCommand InsertCommand {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
[MonoTODO]
public DbProviderFactory ProviderFactory {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public bool ReturnProviderSpecificTypes {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
[MonoTODO]
public DbCommand SelectCommand {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
[MonoTODO]
public override ISite Site {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
[MonoTODO]
public DataTableMapping TableMapping {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public int UpdateBatchSize {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
[MonoTODO]
public DbCommand UpdateCommand {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
#endregion // Properties
#region Methods
[MonoTODO]
public DataRelation AddChildTable (string relationName, DbTable childTable, string parentColumnName, string childColumnName)
{
throw new NotImplementedException ();
}
[MonoTODO]
public DataRelation AddChildTable (string relationName, DbTable childTable, string[] parentColumnNames, string[] childColumnNames)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override void BeginInit ()
{
throw new NotImplementedException ();
}
[MonoTODO]
protected virtual DbCommandBuilder CreateCommandBuilder (DbConnection connection)
{
throw new NotImplementedException ();
}
[MonoTODO]
protected override void Dispose (bool disposing)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override void EndInit ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public int Fill (object[] parameterValues)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int Fill (FillOptions options, object[] parameterValues)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int Fill (FillOptions options, DbTransaction transaction, object[] parameterValues)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int FillPage (int startRecord, int maxRecords, object[] parameterValues)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int FillPage (int startRecord, int maxRecords, FillOptions options, object[] parameterValues)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int FillPage (int startRecord, int maxRecords, FillOptions options, DbTransaction transaction, object[] parameterValues)
{
throw new NotImplementedException ();
}
[MonoTODO]
protected virtual string GenerateQuery (DbCommandBuilder cmdBuilder)
{
throw new NotImplementedException ();
}
[MonoTODO]
protected virtual string GenerateQueryForHierarchy (DbCommandBuilder builder, DataTable[] tableList)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int Update ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public int Update (UpdateOptions updateOptions)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int Update (UpdateOptions updateOptions, DbTransaction transaction)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int UpdateRows (DataRow[] dataRows)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int UpdateRows (DataRow[] dataRows, UpdateOptions updateOptions)
{
throw new NotImplementedException ();
}
[MonoTODO]
public int UpdateRows (DataRow[] dataRows, UpdateOptions updateOptions, DbTransaction transaction)
{
throw new NotImplementedException ();
}
#endregion // Methods
}
}
#endif
| |
// 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.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using IServiceProvider = System.IServiceProvider;
using Microsoft.PythonTools.Uwp.Interpreter;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Flavor;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools;
using System.Threading.Tasks;
namespace Microsoft.PythonTools.Uwp.Project {
[Guid("27BB1268-135A-4409-914F-7AA64AD8195D")]
partial class PythonUwpProject :
FlavoredProjectBase,
IOleCommandTarget,
IVsProjectFlavorCfgProvider,
IVsProject,
IVsFilterAddProjectItemDlg {
private PythonUwpPackage _package;
internal IVsProject _innerProject;
internal IVsProject3 _innerProject3;
private IVsProjectFlavorCfgProvider _innerVsProjectFlavorCfgProvider;
private static Guid PythonProjectGuid = new Guid(PythonConstants.ProjectFactoryGuid);
private IOleCommandTarget _menuService;
private FileSystemWatcher _sitePackageWatcher;
private readonly TaskScheduler _scheduler;
private readonly TaskFactory _factory;
public PythonUwpProject() {
_scheduler = TaskScheduler.FromCurrentSynchronizationContext();
_factory = new TaskFactory(_scheduler);
}
internal PythonUwpPackage Package {
get { return _package; }
set {
Debug.Assert(_package == null);
if (_package != null) {
throw new InvalidOperationException("PythonUwpProject.Package must only be set once");
}
_package = value;
}
}
#region IVsAggregatableProject
/// <summary>
/// Do the initialization here (such as loading flavor specific
/// information from the project)
/// </summary>
protected override void InitializeForOuter(string fileName, string location, string name, uint flags, ref Guid guidProject, out bool cancel) {
var pythonProject = this.GetProject().GetPythonProject();
var msbuildProject = pythonProject.GetMSBuildProjectInstance();
msbuildProject.Build("CreatePythonUwpIoTPythonEnv", null);
var sitePackagesDir = Path.Combine(
pythonProject.ProjectDirectory,
PythonUwpConstants.InterpreterRelativePath,
PythonUwpConstants.InterpreterLibPath,
PythonUwpConstants.InterpreterSitePackagesPath);
try {
var sitePackageDirInfo = new DirectoryInfo(sitePackagesDir);
if (sitePackageDirInfo.Exists) {
_sitePackageWatcher = new FileSystemWatcher {
IncludeSubdirectories = true,
Path = sitePackagesDir,
};
_sitePackageWatcher.Created += SitePackageWatcher_Changed;
_sitePackageWatcher.Changed += SitePackageWatcher_Changed;
_sitePackageWatcher.Deleted += SitePackageWatcher_Changed;
_sitePackageWatcher.Renamed += SitePackageWatcher_Changed;
_sitePackageWatcher.EnableRaisingEvents = true;
}
} catch (PathTooLongException) {
}
base.InitializeForOuter(fileName, location, name, flags, ref guidProject, out cancel);
}
#endregion
private void SitePackageWatcher_Changed(object sender, System.IO.FileSystemEventArgs e) {
// Run on the UI thread
_factory.StartNew(() => {
var bps = this._innerProject as IVsBuildPropertyStorage;
if (bps != null) {
bps.SetPropertyValue("SitePackageChangedTime", null, (uint)_PersistStorageType.PST_PROJECT_FILE, DateTime.Now.ToString());
}
});
}
protected override void Close() {
base.Close();
if (_sitePackageWatcher != null) {
_sitePackageWatcher.Dispose();
_sitePackageWatcher = null;
}
}
protected override int QueryStatusCommand(uint itemid, ref Guid pguidCmdGroup, uint cCmds, VisualStudio.OLE.Interop.OLECMD[] prgCmds, IntPtr pCmdText) {
if (pguidCmdGroup == GuidList.guidOfficeSharePointCmdSet) {
for (int i = 0; i < prgCmds.Length; i++) {
// Report it as supported so that it's not routed any
// further, but disable it and make it invisible.
prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_INVISIBLE);
}
return VSConstants.S_OK;
}
return base.QueryStatusCommand(itemid, ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
protected override void SetInnerProject(IntPtr innerIUnknown) {
var inner = Marshal.GetObjectForIUnknown(innerIUnknown);
// The reason why we keep a reference to those is that doing a QI after being
// aggregated would do the AddRef on the outer object.
_innerVsProjectFlavorCfgProvider = inner as IVsProjectFlavorCfgProvider;
_innerProject = inner as IVsProject;
_innerProject3 = inner as IVsProject3;
_innerVsHierarchy = inner as IVsHierarchy;
// Ensure we have a service provider as this is required for menu items to work
if (this.serviceProvider == null) {
this.serviceProvider = (IServiceProvider)Package;
}
// Now let the base implementation set the inner object
base.SetInnerProject(innerIUnknown);
// Get access to the menu service used by FlavoredProjectBase. We
// need to forward IOleCommandTarget functions to this object, since
// we override the FlavoredProjectBase implementation with no way to
// call it directory.
// (This must run after we called base.SetInnerProject)
_menuService = (IOleCommandTarget)((IServiceProvider)this).GetService(typeof(IMenuCommandService));
if (_menuService == null) {
throw new InvalidOperationException("Cannot initialize Uwp project");
}
}
protected override int GetProperty(uint itemId, int propId, out object property) {
switch ((__VSHPROPID2)propId) {
case __VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList:
{
var res = base.GetProperty(itemId, propId, out property);
if (ErrorHandler.Succeeded(res)) {
var guids = GetGuidsFromList(property as string);
guids.RemoveAll(g => CfgSpecificPropertyPagesToRemove.Contains(g));
guids.AddRange(CfgSpecificPropertyPagesToAdd);
property = MakeListFromGuids(guids);
}
return res;
}
case __VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList:
{
var res = base.GetProperty(itemId, propId, out property);
if (ErrorHandler.Succeeded(res)) {
var guids = GetGuidsFromList(property as string);
guids.RemoveAll(g => PropertyPagesToRemove.Contains(g));
guids.AddRange(PropertyPagesToAdd);
property = MakeListFromGuids(guids);
}
return res;
}
}
switch ((__VSHPROPID6)propId) {
case __VSHPROPID6.VSHPROPID_Subcaption:
{
var bps = this._innerProject as IVsBuildPropertyStorage;
string descriptor = null;
if (bps != null) {
var res = bps.GetPropertyValue("TargetOsAndVersion", null, (uint)_PersistStorageType.PST_PROJECT_FILE, out descriptor);
property = descriptor;
return res;
}
break;
}
}
return base.GetProperty(itemId, propId, out property);
}
private static Guid[] PropertyPagesToAdd = new Guid[0];
private static Guid[] CfgSpecificPropertyPagesToAdd = new Guid[] {
new Guid(GuidList.guidUwpPropertyPageString)
};
private static HashSet<Guid> PropertyPagesToRemove = new HashSet<Guid> {
new Guid("{8C0201FE-8ECA-403C-92A3-1BC55F031979}"), // typeof(DeployPropertyPageComClass)
new Guid("{ED3B544C-26D8-4348-877B-A1F7BD505ED9}"), // typeof(DatabaseDeployPropertyPageComClass)
new Guid("{909D16B3-C8E8-43D1-A2B8-26EA0D4B6B57}"), // Microsoft.VisualStudio.Web.Application.WebPropertyPage
new Guid("{379354F2-BBB3-4BA9-AA71-FBE7B0E5EA94}"), // Microsoft.VisualStudio.Web.Application.SilverlightLinksPage
new Guid("{A553AD0B-2F9E-4BCE-95B3-9A1F7074BC27}"), // Package/Publish Web
new Guid("{9AB2347D-948D-4CD2-8DBE-F15F0EF78ED3}"), // Package/Publish SQL
new Guid(PythonConstants.DebugPropertyPageGuid),
new Guid(PythonConstants.GeneralPropertyPageGuid),
new Guid(PythonConstants.PublishPropertyPageGuid)
};
internal static HashSet<Guid> CfgSpecificPropertyPagesToRemove = new HashSet<Guid>(new Guid[] { Guid.Empty });
private static List<Guid> GetGuidsFromList(string guidList) {
if (string.IsNullOrEmpty(guidList)) {
return new List<Guid>();
}
Guid value;
return guidList.Split(';')
.Select(str => Guid.TryParse(str, out value) ? (Guid?)value : null)
.Where(g => g.HasValue)
.Select(g => g.Value)
.ToList();
}
private static string MakeListFromGuids(IEnumerable<Guid> guidList) {
return string.Join(";", guidList.Select(g => g.ToString("B")));
}
internal string RemovePropertyPagesFromList(string propertyPagesList, string[] pagesToRemove) {
if (pagesToRemove == null || !pagesToRemove.Any()) {
return propertyPagesList;
}
var guidsToRemove = new HashSet<Guid>(
pagesToRemove.Select(str => { Guid guid; return Guid.TryParse(str, out guid) ? guid : Guid.Empty; })
);
guidsToRemove.Add(Guid.Empty);
return string.Join(
";",
propertyPagesList.Split(';')
.Where(str => !string.IsNullOrEmpty(str))
.Select(str => { Guid guid; return Guid.TryParse(str, out guid) ? guid : Guid.Empty; })
.Except(guidsToRemove)
.Select(guid => guid.ToString("B"))
);
}
int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
return _menuService.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) {
return _menuService.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
#region IVsProjectFlavorCfgProvider Members
public int CreateProjectFlavorCfg(IVsCfg pBaseProjectCfg, out IVsProjectFlavorCfg ppFlavorCfg) {
// We're flavored with a Windows Store Application project and our normal
// project... But we don't want the web application project to
// influence our config as that alters our debug launch story. We
// control that w/ the web project which is actually just letting
// the base Python project handle it. So we keep the base Python
// project config here.
IVsProjectFlavorCfg uwpCfg;
ErrorHandler.ThrowOnFailure(
_innerVsProjectFlavorCfgProvider.CreateProjectFlavorCfg(
pBaseProjectCfg,
out uwpCfg
)
);
ppFlavorCfg = new PythonUwpProjectConfig(pBaseProjectCfg, uwpCfg);
return VSConstants.S_OK;
}
#endregion
#region IVsProject Members
int IVsProject.AddItem(uint itemidLoc, VSADDITEMOPERATION dwAddItemOperation, string pszItemName, uint cFilesToOpen, string[] rgpszFilesToOpen, IntPtr hwndDlgOwner, VSADDRESULT[] pResult) {
return _innerProject.AddItem(itemidLoc, dwAddItemOperation, pszItemName, cFilesToOpen, rgpszFilesToOpen, hwndDlgOwner, pResult);
}
int IVsProject.GenerateUniqueItemName(uint itemidLoc, string pszExt, string pszSuggestedRoot, out string pbstrItemName) {
return _innerProject.GenerateUniqueItemName(itemidLoc, pszExt, pszSuggestedRoot, out pbstrItemName);
}
int IVsProject.GetItemContext(uint itemid, out VisualStudio.OLE.Interop.IServiceProvider ppSP) {
return _innerProject.GetItemContext(itemid, out ppSP);
}
int IVsProject.GetMkDocument(uint itemid, out string pbstrMkDocument) {
return _innerProject.GetMkDocument(itemid, out pbstrMkDocument);
}
int IVsProject.IsDocumentInProject(string pszMkDocument, out int pfFound, VSDOCUMENTPRIORITY[] pdwPriority, out uint pitemid) {
return _innerProject.IsDocumentInProject(pszMkDocument, out pfFound, pdwPriority, out pitemid);
}
int IVsProject.OpenItem(uint itemid, ref Guid rguidLogicalView, IntPtr punkDocDataExisting, out IVsWindowFrame ppWindowFrame) {
return _innerProject.OpenItem(itemid, rguidLogicalView, punkDocDataExisting, out ppWindowFrame);
}
#endregion
#region IVsFilterAddProjectItemDlg Members
int IVsFilterAddProjectItemDlg.FilterListItemByLocalizedName(ref Guid rguidProjectItemTemplates, string pszLocalizedName, out int pfFilter) {
pfFilter = 0;
return VSConstants.S_OK;
}
int IVsFilterAddProjectItemDlg.FilterListItemByTemplateFile(ref Guid rguidProjectItemTemplates, string pszTemplateFile, out int pfFilter) {
pfFilter = 0;
return VSConstants.S_OK;
}
int IVsFilterAddProjectItemDlg.FilterTreeItemByLocalizedName(ref Guid rguidProjectItemTemplates, string pszLocalizedName, out int pfFilter) {
pfFilter = 0;
return VSConstants.S_OK;
}
int IVsFilterAddProjectItemDlg.FilterTreeItemByTemplateDir(ref Guid rguidProjectItemTemplates, string pszTemplateDir, out int pfFilter) {
// https://pytools.codeplex.com/workitem/1313
// ASP.NET will filter some things out, including .css files, which we don't want it to do.
// So we shut that down by not forwarding this to any inner projects, which is fine, because
// Python projects don't implement this interface either.
pfFilter = 0;
return VSConstants.S_OK;
}
#endregion
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <[email protected]>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
public enum TexReferenceType
{
Object = 0,
Instance
}
public enum MipType
{
Auto,
MipLevel,
MipBias,
Derivative
}
[Serializable]
[NodeAttributes( "Texture Sample", "Textures", "Samples a chosen texture a returns its color", KeyCode.T, true, 0, int.MaxValue, typeof( Texture ), typeof( Texture2D ), typeof( Texture3D ), typeof( Cubemap ), typeof( ProceduralTexture ) )]
public sealed class SamplerNode : TexturePropertyNode
{
private const string MipModeStr = "Mip Mode";
private const string DefaultTextureUseSematicsStr = "Use Semantics";
private const string DefaultTextureIsNormalMapsStr = "Is Normal Map";
private const string NormalScaleStr = "Scale";
private float InstanceIconWidth = 19;
private float InstanceIconHeight = 19;
private readonly Color ReferenceHeaderColor = new Color( 2.67f, 1.0f, 0.5f, 1.0f );
[SerializeField]
private int m_textureCoordSet = 0;
[SerializeField]
private string m_normalMapUnpackMode;
[SerializeField]
private bool m_autoUnpackNormals = false;
[SerializeField]
private bool m_useSemantics;
[SerializeField]
private string m_samplerType;
[SerializeField]
private MipType m_mipMode = MipType.Auto;
[SerializeField]
private TexReferenceType m_referenceType = TexReferenceType.Object;
[SerializeField]
private int m_referenceArrayId = -1;
[SerializeField]
private int m_referenceNodeId = -1;
private SamplerNode m_referenceSampler = null;
[SerializeField]
private GUIStyle m_referenceStyle = null;
[SerializeField]
private GUIStyle m_referenceIconStyle = null;
[SerializeField]
private GUIContent m_referenceContent = null;
[SerializeField]
private float m_referenceWidth = -1;
private string m_previousAdditionalText = string.Empty;
private bool m_forceSamplerUpdate = false;
private bool m_forceInputTypeCheck = false;
private int m_cachedUvsId = -1;
private int m_cachedUnpackId = -1;
private int m_cachedLodId = -1;
private InputPort m_texPort;
private InputPort m_uvPort;
private InputPort m_lodPort;
private InputPort m_ddxPort;
private InputPort m_ddyPort;
private InputPort m_normalPort;
private OutputPort m_colorPort;
public SamplerNode() : base() { }
public SamplerNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { }
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_defaultTextureValue = TexturePropertyValues.white;
AddInputPort( WirePortDataType.SAMPLER2D, false, "Tex" );
m_inputPorts[ 0 ].CreatePortRestrictions( WirePortDataType.SAMPLER1D, WirePortDataType.SAMPLER2D, WirePortDataType.SAMPLER3D, WirePortDataType.SAMPLERCUBE, WirePortDataType.OBJECT );
AddInputPort( WirePortDataType.FLOAT2, false, "UV" );
AddInputPort( WirePortDataType.FLOAT, false, "Level" );
AddInputPort( WirePortDataType.FLOAT2, false, "DDX" );
AddInputPort( WirePortDataType.FLOAT2, false, "DDY" );
AddInputPort( WirePortDataType.FLOAT, false, NormalScaleStr );
m_texPort = m_inputPorts[ 0 ];
m_uvPort = m_inputPorts[ 1 ];
m_lodPort = m_inputPorts[ 2 ];
m_ddxPort = m_inputPorts[ 3 ];
m_ddyPort = m_inputPorts[ 4 ];
m_normalPort = m_inputPorts[ 5 ];
m_lodPort.Visible = false;
m_lodPort.FloatInternalData = 1.0f;
m_ddxPort.Visible = false;
m_ddyPort.Visible = false;
m_normalPort.Visible = m_autoUnpackNormals;
m_normalPort.FloatInternalData = 1.0f;
//Remove output port (sampler)
m_outputPortsDict.Remove( m_outputPorts[ 0 ].PortId );
m_outputPorts.RemoveAt( 0 );
AddOutputColorPorts( "RGBA" );
m_colorPort = m_outputPorts[ 0 ];
m_currentParameterType = PropertyType.Property;
// m_useCustomPrefix = true;
m_customPrefix = "Texture Sample ";
m_referenceContent = new GUIContent( string.Empty );
m_freeType = false;
m_useSemantics = true;
m_drawPicker = false;
ConfigTextureData( TextureType.Texture2D );
m_selectedLocation = PreviewLocation.TopCenter;
m_previewShaderGUID = "7b4e86a89b70ae64993bf422eb406422";
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if ( m_cachedUvsId == -1 )
m_cachedUvsId = Shader.PropertyToID( "_CustomUVs" );
if ( m_cachedSamplerId == -1 )
m_cachedSamplerId = Shader.PropertyToID( "_Sampler" );
if ( m_cachedUnpackId == -1 )
m_cachedUnpackId = Shader.PropertyToID( "_Unpack" );
if ( m_cachedLodId == -1 )
m_cachedLodId = Shader.PropertyToID( "_LodType" );
PreviewMaterial.SetFloat( m_cachedLodId, ( m_mipMode == MipType.MipLevel ? 1 : ( m_mipMode == MipType.MipBias ? 2 : 0 ) ) );
PreviewMaterial.SetFloat( m_cachedUnpackId, m_autoUnpackNormals ? 1 : 0 );
if ( SoftValidReference )
{
PreviewMaterial.SetTexture( m_cachedSamplerId, m_referenceSampler.TextureProperty.Value );
}
else if ( TextureProperty != null )
{
PreviewMaterial.SetTexture( m_cachedSamplerId, TextureProperty.Value );
}
PreviewMaterial.SetFloat( m_cachedUvsId, ( m_uvPort.IsConnected ? 1 : 0 ) );
}
protected override void OnUniqueIDAssigned()
{
base.OnUniqueIDAssigned();
if ( m_referenceType == TexReferenceType.Object )
{
UIUtils.RegisterSamplerNode( this );
UIUtils.RegisterPropertyNode( this );
}
m_textureProperty = this;
}
public void ConfigSampler()
{
switch ( m_currentType )
{
case TextureType.Texture1D:
m_samplerType = "tex1D";
break;
case TextureType.Texture2D:
m_samplerType = "tex2D";
break;
case TextureType.Texture3D:
m_samplerType = "tex3D";
break;
case TextureType.Cube:
m_samplerType = "texCUBE";
break;
}
}
public override void DrawSubProperties()
{
ShowDefaults();
DrawSamplerOptions();
EditorGUI.BeginChangeCheck();
m_defaultValue = EditorGUILayoutObjectField( Constants.DefaultValueLabel, m_defaultValue, m_textureType, false ) as Texture;
if ( EditorGUI.EndChangeCheck() )
{
CheckTextureImporter( true );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
public override void DrawMaterialProperties()
{
ShowDefaults();
DrawSamplerOptions();
EditorGUI.BeginChangeCheck();
m_materialValue = EditorGUILayoutObjectField( Constants.MaterialValueLabel, m_materialValue, m_textureType, false ) as Texture;
if ( EditorGUI.EndChangeCheck() )
{
CheckTextureImporter( true );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
new void ShowDefaults()
{
m_textureCoordSet = EditorGUILayoutIntPopup( Constants.AvailableUVSetsLabel, m_textureCoordSet, Constants.AvailableUVSetsStr, Constants.AvailableUVSets );
m_defaultTextureValue = (TexturePropertyValues)EditorGUILayoutEnumPopup( DefaultTextureStr, m_defaultTextureValue );
AutoCastType newAutoCast = (AutoCastType)EditorGUILayoutEnumPopup( AutoCastModeStr, m_autocastMode );
if ( newAutoCast != m_autocastMode )
{
m_autocastMode = newAutoCast;
if ( m_autocastMode != AutoCastType.Auto )
{
ConfigTextureData( m_currentType );
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
}
public override void AdditionalCheck()
{
m_autoUnpackNormals = m_isNormalMap;
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
if ( portId == m_texPort.PortId )
{
m_textureProperty = m_texPort.GetOutputNode( 0 ) as TexturePropertyNode;
if ( m_textureProperty == null )
{
m_textureProperty = this;
}
else
{
if ( m_autocastMode == AutoCastType.Auto )
{
m_currentType = m_textureProperty.CurrentType;
}
AutoUnpackNormals = m_textureProperty.IsNormalMap;
if ( m_textureProperty is VirtualTexturePropertyNode )
{
AutoUnpackNormals = ( m_textureProperty as VirtualTexturePropertyNode ).Channel == VirtualChannel.Normal;
}
UIUtils.UnregisterPropertyNode( this );
UIUtils.UnregisterTexturePropertyNode( this );
}
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
public override void OnInputPortDisconnected( int portId )
{
base.OnInputPortDisconnected( portId );
if ( portId == m_texPort.PortId )
{
m_textureProperty = this;
if ( m_referenceType == TexReferenceType.Object )
{
UIUtils.RegisterPropertyNode( this );
UIUtils.RegisterTexturePropertyNode( this );
}
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
private void ForceInputPortsChange()
{
m_texPort.ChangeType( WirePortDataType.SAMPLER2D, false );
m_normalPort.ChangeType( WirePortDataType.FLOAT, false );
switch ( m_currentType )
{
case TextureType.Texture2D:
m_uvPort.ChangeType( WirePortDataType.FLOAT2, false );
m_ddxPort.ChangeType( WirePortDataType.FLOAT2, false );
m_ddyPort.ChangeType( WirePortDataType.FLOAT2, false );
break;
case TextureType.Texture3D:
case TextureType.Cube:
m_uvPort.ChangeType( WirePortDataType.FLOAT3, false );
m_ddxPort.ChangeType( WirePortDataType.FLOAT3, false );
m_ddyPort.ChangeType( WirePortDataType.FLOAT3, false );
break;
}
}
public override void ConfigureInputPorts()
{
m_normalPort.Visible = AutoUnpackNormals;
switch ( m_mipMode )
{
case MipType.Auto:
m_lodPort.Visible = false;
m_ddxPort.Visible = false;
m_ddyPort.Visible = false;
break;
case MipType.MipLevel:
m_lodPort.Name = "Level";
m_lodPort.Visible = true;
m_ddxPort.Visible = false;
m_ddyPort.Visible = false;
break;
case MipType.MipBias:
m_lodPort.Name = "Bias";
m_lodPort.Visible = true;
m_ddxPort.Visible = false;
m_ddyPort.Visible = false;
break;
case MipType.Derivative:
m_lodPort.Visible = false;
m_ddxPort.Visible = true;
m_ddyPort.Visible = true;
break;
}
switch ( m_currentType )
{
case TextureType.Texture2D:
m_uvPort.ChangeType( WirePortDataType.FLOAT2, false );
m_ddxPort.ChangeType( WirePortDataType.FLOAT2, false );
m_ddyPort.ChangeType( WirePortDataType.FLOAT2, false );
break;
case TextureType.Texture3D:
case TextureType.Cube:
m_uvPort.ChangeType( WirePortDataType.FLOAT3, false );
m_ddxPort.ChangeType( WirePortDataType.FLOAT3, false );
m_ddyPort.ChangeType( WirePortDataType.FLOAT3, false );
break;
}
m_sizeIsDirty = true;
}
public override void ConfigureOutputPorts()
{
m_outputPorts[ m_colorPort.PortId + 4 ].Visible = !AutoUnpackNormals;
if ( !AutoUnpackNormals )
{
m_colorPort.ChangeProperties( "RGBA", WirePortDataType.FLOAT4, false );
m_outputPorts[ m_colorPort.PortId + 1 ].ChangeProperties( "R", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 2 ].ChangeProperties( "G", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 3 ].ChangeProperties( "B", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 4 ].ChangeProperties( "A", WirePortDataType.FLOAT, false );
}
else
{
m_colorPort.ChangeProperties( "XYZ", WirePortDataType.FLOAT3, false );
m_outputPorts[ m_colorPort.PortId + 1 ].ChangeProperties( "X", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 2 ].ChangeProperties( "Y", WirePortDataType.FLOAT, false );
m_outputPorts[ m_colorPort.PortId + 3 ].ChangeProperties( "Z", WirePortDataType.FLOAT, false );
}
m_sizeIsDirty = true;
}
public override void OnObjectDropped( UnityEngine.Object obj )
{
base.OnObjectDropped( obj );
ConfigFromObject( obj );
}
public override void SetupFromCastObject( UnityEngine.Object obj )
{
base.SetupFromCastObject( obj );
ConfigFromObject( obj );
}
void UpdateHeaderColor()
{
m_headerColorModifier = ( m_referenceType == TexReferenceType.Object ) ? Color.white : ReferenceHeaderColor;
}
public void DrawSamplerOptions()
{
MipType newMipMode = (MipType)EditorGUILayoutEnumPopup( MipModeStr, m_mipMode );
if ( newMipMode != m_mipMode )
{
m_mipMode = newMipMode;
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
EditorGUI.BeginChangeCheck();
m_autoUnpackNormals = EditorGUILayoutToggle( "Normal Map", m_autoUnpackNormals );
if ( m_autoUnpackNormals && !m_normalPort.IsConnected )
{
m_normalPort.FloatInternalData = EditorGUILayoutFloatField( NormalScaleStr, m_normalPort.FloatInternalData );
}
if ( EditorGUI.EndChangeCheck() )
{
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
}
public override void DrawMainPropertyBlock()
{
EditorGUI.BeginChangeCheck();
m_referenceType = ( TexReferenceType ) EditorGUILayoutPopup( Constants.ReferenceTypeStr, (int)m_referenceType , Constants.ReferenceArrayLabels );
if ( EditorGUI.EndChangeCheck() )
{
if ( m_referenceType == TexReferenceType.Object )
{
UIUtils.RegisterSamplerNode( this );
UIUtils.RegisterPropertyNode( this );
if ( !m_texPort.IsConnected )
UIUtils.RegisterTexturePropertyNode( this );
SetTitleText( m_propertyInspectorName );
SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
m_referenceArrayId = -1;
m_referenceNodeId = -1;
m_referenceSampler = null;
}
else
{
UIUtils.UnregisterSamplerNode( this );
UIUtils.UnregisterPropertyNode( this );
if ( !m_texPort.IsConnected )
UIUtils.UnregisterTexturePropertyNode( this );
}
UpdateHeaderColor();
}
if ( m_referenceType == TexReferenceType.Object )
{
EditorGUI.BeginChangeCheck();
if ( m_texPort.IsConnected )
{
m_drawAttributes = false;
m_textureCoordSet = EditorGUILayoutIntPopup( Constants.AvailableUVSetsLabel, m_textureCoordSet, Constants.AvailableUVSetsStr, Constants.AvailableUVSets );
DrawSamplerOptions();
} else
{
m_drawAttributes = true;
base.DrawMainPropertyBlock();
}
if ( EditorGUI.EndChangeCheck() )
{
OnPropertyNameChanged();
}
}
else
{
m_drawAttributes = true;
string[] arr = UIUtils.SamplerNodeArr();
bool guiEnabledBuffer = GUI.enabled;
if ( arr != null && arr.Length > 0 )
{
GUI.enabled = true;
}
else
{
m_referenceArrayId = -1;
GUI.enabled = false;
}
EditorGUI.BeginChangeCheck();
m_referenceArrayId = EditorGUILayoutPopup( Constants.AvailableReferenceStr, m_referenceArrayId, arr );
if ( EditorGUI.EndChangeCheck() )
{
m_referenceSampler = UIUtils.GetSamplerNode( m_referenceArrayId );
if ( m_referenceSampler != null )
{
m_referenceNodeId = m_referenceSampler.UniqueId;
}
else
{
m_referenceArrayId = -1;
m_referenceNodeId = -1;
}
}
GUI.enabled = guiEnabledBuffer;
DrawSamplerOptions();
}
}
public override void OnPropertyNameChanged()
{
base.OnPropertyNameChanged();
UIUtils.UpdateSamplerDataNode( UniqueId, PropertyInspectorName );
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( m_forceInputTypeCheck )
{
m_forceInputTypeCheck = false;
ForceInputPortsChange();
}
EditorGUI.BeginChangeCheck();
if ( m_forceSamplerUpdate )
{
m_forceSamplerUpdate = false;
if ( UIUtils.CurrentShaderVersion() > 22 )
{
m_referenceSampler = UIUtils.GetNode( m_referenceNodeId ) as SamplerNode;
m_referenceArrayId = UIUtils.GetSamplerNodeRegisterId( m_referenceNodeId );
}
else
{
m_referenceSampler = UIUtils.GetSamplerNode( m_referenceArrayId );
if ( m_referenceSampler != null )
{
m_referenceNodeId = m_referenceSampler.UniqueId;
}
}
}
if ( EditorGUI.EndChangeCheck() )
{
OnPropertyNameChanged();
}
CheckReference();
if ( m_isVisible )
{
if ( SoftValidReference )
{
m_drawPicker = false;
DrawTexturePropertyPreview( drawInfo, true );
}
else
if ( m_texPort.IsConnected )
{
m_drawPicker = false;
DrawTexturePropertyPreview( drawInfo, false );
}
else
{
SetTitleText( m_propertyInspectorName );
//small optimization, string format on every frame is killer
string tempVal = GetPropertyValStr();
if ( !m_previousAdditionalText.Equals( tempVal ) )
{
m_previousAdditionalText = tempVal;
m_additionalContent.text = string.Concat( "Value( ", tempVal, " )" );
//m_additionalContent.text = string.Format( Constants.PropertyValueLabel, tempVal );
m_sizeIsDirty = true;
}
//SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) );
m_drawPicker = true;
}
}
}
void CheckReference()
{
if ( m_referenceType != TexReferenceType.Instance )
{
return;
}
if ( m_referenceArrayId > -1 )
{
ParentNode newNode = UIUtils.GetSamplerNode( m_referenceArrayId );
if ( newNode == null || newNode.UniqueId != m_referenceNodeId )
{
m_referenceSampler = null;
int count = UIUtils.GetSamplerNodeAmount();
for ( int i = 0; i < count; i++ )
{
ParentNode node = UIUtils.GetSamplerNode( i );
if ( node.UniqueId == m_referenceNodeId )
{
m_referenceSampler = node as SamplerNode;
m_referenceArrayId = i;
break;
}
}
}
}
if ( m_referenceSampler == null && m_referenceNodeId > -1 )
{
m_referenceNodeId = -1;
m_referenceArrayId = -1;
}
}
public void SetTitleTextDelay( string newText )
{
if ( !newText.Equals( m_content.text ) )
{
m_content.text = newText;
BeginDelayedDirtyProperty();
}
}
public void SetAdditonalTitleTextDelay( string newText )
{
if ( !newText.Equals( m_additionalContent.text ) )
{
m_additionalContent.text = newText;
BeginDelayedDirtyProperty();
}
}
private void DrawTexturePropertyPreview( DrawInfo drawInfo, bool instance )
{
Rect newPos = m_previewRect;
TexturePropertyNode texProp = null;
if ( instance )
texProp = m_referenceSampler.TextureProperty;
else
texProp = TextureProperty;
if ( texProp == null )
texProp = this;
float previewSizeX = PreviewSizeX;
float previewSizeY = PreviewSizeY;
newPos.width = previewSizeX * drawInfo.InvertedZoom;
newPos.height = previewSizeY * drawInfo.InvertedZoom;
SetTitleText( texProp.PropertyInspectorName + ( instance ? Constants.InstancePostfixStr : " (Input)" ) );
SetAdditonalTitleText( texProp.AdditonalTitleContent.text );
if ( m_referenceStyle == null )
{
m_referenceStyle = UIUtils.GetCustomStyle( CustomStyle.SamplerTextureRef );
}
if ( m_referenceIconStyle == null || m_referenceIconStyle.normal == null )
{
m_referenceIconStyle = UIUtils.GetCustomStyle( CustomStyle.SamplerTextureIcon );
if ( m_referenceIconStyle != null && m_referenceIconStyle.normal != null && m_referenceIconStyle.normal.background != null)
{
InstanceIconWidth = m_referenceIconStyle.normal.background.width;
InstanceIconHeight = m_referenceIconStyle.normal.background.height;
}
}
Rect iconPos = m_globalPosition;
iconPos.width = InstanceIconWidth * drawInfo.InvertedZoom;
iconPos.height = InstanceIconHeight * drawInfo.InvertedZoom;
iconPos.y += 10 * drawInfo.InvertedZoom;
iconPos.x += m_globalPosition.width - iconPos.width - 5 * drawInfo.InvertedZoom;
if ( GUI.Button( newPos, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SamplerTextureRef )/* m_referenceStyle */) ||
GUI.Button( iconPos, string.Empty, m_referenceIconStyle )
)
{
UIUtils.FocusOnNode( texProp, 1, true );
}
if ( texProp.Value != null )
{
DrawPreview( drawInfo, m_previewRect );
GUI.Box( newPos, string.Empty, UIUtils.GetCustomStyle( CustomStyle.SamplerFrame ) );
//UIUtils.GetCustomStyle( CustomStyle.SamplerButton ).fontSize = ( int )Mathf.Round( 9 * drawInfo.InvertedZoom );
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar )
{
if ( dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
{
UIUtils.ShowMessage( m_nodeAttribs.Name + " cannot be used on Master Node Tessellation port" );
return "(-1)";
}
OnPropertyNameChanged();
ConfigSampler();
string portProperty = string.Empty;
if ( m_texPort.IsConnected )
portProperty = m_texPort.GenerateShaderForOutput( ref dataCollector, m_texPort.DataType, ignoreLocalVar );
if ( m_autoUnpackNormals )
{
bool isScaledNormal = false;
if ( m_normalPort.IsConnected )
{
isScaledNormal = true;
}
else
{
if ( m_normalPort.FloatInternalData != 1 )
{
isScaledNormal = true;
}
}
if ( isScaledNormal )
{
string scaleValue = m_normalPort.GeneratePortInstructions( ref dataCollector );
dataCollector.AddToIncludes( UniqueId, Constants.UnityStandardUtilsLibFuncs );
m_normalMapUnpackMode = "UnpackScaleNormal( {0} ," + scaleValue + " )";
}
else
{
m_normalMapUnpackMode = "UnpackNormal( {0} )";
}
}
if ( !m_texPort.IsConnected )
base.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalVar );
string valueName = SetFetchedData( ref dataCollector, ignoreLocalVar, outputId, portProperty );
if ( TextureProperty is VirtualTexturePropertyNode )
{
return valueName;
}
else
{
return GetOutputColorItem( 0, outputId, valueName );
}
}
public string SampleVirtualTexture( VirtualTexturePropertyNode node, string coord )
{
string sampler = string.Empty;
switch ( node.Channel )
{
default:
case VirtualChannel.Albedo:
case VirtualChannel.Base:
sampler = "VTSampleAlbedo( " + coord + " )";
break;
case VirtualChannel.Normal:
case VirtualChannel.Height:
case VirtualChannel.Occlusion:
case VirtualChannel.Displacement:
sampler = "VTSampleNormal( " + coord + " )";
break;
case VirtualChannel.Specular:
case VirtualChannel.SpecMet:
case VirtualChannel.Material:
sampler = "VTSampleSpecular( " + coord + " )";
break;
}
return sampler;
}
public string SetFetchedData( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar, int outputId, string portProperty = null )
{
m_precisionString = UIUtils.PrecisionWirePortToCgType( UIUtils.GetFinalPrecision( m_currentPrecisionType ), m_colorPort.DataType );
string propertyName = CurrentPropertyReference;
if ( !string.IsNullOrEmpty( portProperty ) )
{
propertyName = portProperty;
}
string mipType = "";
if ( m_lodPort.IsConnected )
{
switch ( m_mipMode )
{
case MipType.Auto:
break;
case MipType.MipLevel:
mipType = "lod";
break;
case MipType.MipBias:
mipType = "bias";
break;
case MipType.Derivative:
break;
}
}
if ( ignoreLocalVar )
{
if ( TextureProperty is VirtualTexturePropertyNode )
Debug.Log( "TODO" );
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
{
mipType = "lod";
}
string samplerValue = m_samplerType + mipType + "( " + propertyName + ", " + GetUVCoords( ref dataCollector, ignoreLocalVar, portProperty ) + " )";
AddNormalMapTag( ref samplerValue );
return samplerValue;
}
VirtualTexturePropertyNode vtex = ( TextureProperty as VirtualTexturePropertyNode );
if ( vtex != null )
{
string atPathname = AssetDatabase.GUIDToAssetPath( Constants.ATSharedLibGUID );
if ( string.IsNullOrEmpty( atPathname ) )
{
UIUtils.ShowMessage( "Could not find Amplify Texture on your project folder. Please install it and re-compile the shader.", MessageSeverity.Error );
}
else
{
//Need to see if the asset really exists because AssetDatabase.GUIDToAssetPath() can return a valid path if
// the asset was previously imported and deleted after that
UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>( atPathname );
if ( obj == null )
{
UIUtils.ShowMessage( "Could not find Amplify Texture on your project folder. Please install it and re-compile the shader.", MessageSeverity.Error );
}
else
{
if ( m_isTextureFetched )
return m_textureFetchedValue;
//string remapPortR = ".r";
//string remapPortG = ".g";
//string remapPortB = ".b";
//string remapPortA = ".a";
//if ( vtex.Channel == VirtualChannel.Occlusion )
//{
// remapPortR = ".r"; remapPortG = ".r"; remapPortB = ".r"; remapPortA = ".r";
//}
//else if ( vtex.Channel == VirtualChannel.SpecMet && ( ContainerGraph.CurrentStandardSurface != null && ContainerGraph.CurrentStandardSurface.CurrentLightingModel == StandardShaderLightModel.Standard ) )
//{
// remapPortR = ".r"; remapPortG = ".r"; remapPortB = ".r";
//}
//else if ( vtex.Channel == VirtualChannel.Height || vtex.Channel == VirtualChannel.Displacement )
//{
// remapPortR = ".b"; remapPortG = ".b"; remapPortB = ".b"; remapPortA = ".b";
//}
dataCollector.AddToPragmas( UniqueId, IOUtils.VirtualTexturePragmaHeader );
dataCollector.AddToIncludes( UniqueId, atPathname );
string lodBias = m_mipMode == MipType.MipLevel ? "Lod" : m_mipMode == MipType.MipBias ? "Bias" : "";
int virtualCoordId = dataCollector.GetVirtualCoordinatesId( UniqueId, GetVirtualUVCoords( ref dataCollector, ignoreLocalVar, portProperty ), lodBias );
string virtualSampler = SampleVirtualTexture( vtex, Constants.VirtualCoordNameStr + virtualCoordId );
string virtualVariable = dataCollector.AddVirtualLocalVariable( UniqueId, "virtualNode" + OutputId, virtualSampler );
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
dataCollector.AddToVertexLocalVariables( UniqueId, "float4 " + virtualVariable + " = " + virtualSampler + ";" );
else
dataCollector.AddToLocalVariables( UniqueId, "float4 " + virtualVariable + " = " + virtualSampler + ";" );
AddNormalMapTag( ref virtualVariable );
switch ( vtex.Channel )
{
default:
case VirtualChannel.Albedo:
case VirtualChannel.Base:
case VirtualChannel.Normal:
case VirtualChannel.Specular:
case VirtualChannel.SpecMet:
case VirtualChannel.Material:
virtualVariable = GetOutputColorItem( 0, outputId, virtualVariable );
break;
case VirtualChannel.Displacement:
case VirtualChannel.Height:
{
if ( outputId > 0 )
virtualVariable += ".b";
else
{
dataCollector.AddLocalVariable( UniqueId, "float4 virtual_cast_" + OutputId + " = " + virtualVariable + ".b;" );
virtualVariable = "virtual_cast_" + OutputId;
}
//virtualVariable = UIUtils.CastPortType( dataCollector.PortCategory, m_currentPrecisionType, new NodeCastInfo( UniqueId, outputId ), virtualVariable, WirePortDataType.FLOAT, WirePortDataType.FLOAT4, virtualVariable );
}
break;
case VirtualChannel.Occlusion:
{
if( outputId > 0)
virtualVariable += ".r";
else
{
dataCollector.AddLocalVariable( UniqueId, "float4 virtual_cast_" + OutputId + " = " + virtualVariable + ".r;" );
virtualVariable = "virtual_cast_" + OutputId;
}
}
break;
}
//for ( int i = 0; i < m_outputPorts.Count; i++ )
//{
// if ( m_outputPorts[ i ].IsConnected )
// {
// //TODO: make the sampler not generate local variables at all times
// m_textureFetchedValue = "virtualNode" + OutputId;
// m_isTextureFetched = true;
// //dataCollector.AddToLocalVariables( m_uniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + virtualSampler + ";" );
// if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
// dataCollector.AddToVertexLocalVariables( UniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + virtualSampler + ";" );
// else
// dataCollector.AddToLocalVariables( UniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + virtualSampler + ";" );
// m_colorPort.SetLocalValue( m_textureFetchedValue );
// m_outputPorts[ m_colorPort.PortId + 1 ].SetLocalValue( m_textureFetchedValue + remapPortR );
// m_outputPorts[ m_colorPort.PortId + 2 ].SetLocalValue( m_textureFetchedValue + remapPortG );
// m_outputPorts[ m_colorPort.PortId + 3 ].SetLocalValue( m_textureFetchedValue + remapPortB );
// m_outputPorts[ m_colorPort.PortId + 4 ].SetLocalValue( m_textureFetchedValue + remapPortA );
// return m_textureFetchedValue;
// }
//}
return virtualVariable;
}
}
}
if ( m_isTextureFetched )
return m_textureFetchedValue;
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
{
mipType = "lod";
}
string samplerOp = m_samplerType + mipType + "( " + propertyName + ", " + GetUVCoords( ref dataCollector, ignoreLocalVar, portProperty ) + " )";
AddNormalMapTag( ref samplerOp );
int connectedPorts = 0;
for ( int i = 0; i < m_outputPorts.Count; i++ )
{
if ( m_outputPorts[ i ].IsConnected )
{
connectedPorts += 1;
if ( connectedPorts > 1 || m_outputPorts[ i ].ConnectionCount > 1 )
{
// Create common local var and mark as fetched
m_textureFetchedValue = m_samplerType + "Node" + OutputId;
m_isTextureFetched = true;
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
dataCollector.AddToVertexLocalVariables( UniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + samplerOp + ";" );
else
dataCollector.AddToLocalVariables( UniqueId, m_precisionString + " " + m_textureFetchedValue + " = " + samplerOp + ";" );
m_colorPort.SetLocalValue( m_textureFetchedValue );
m_outputPorts[ m_colorPort.PortId + 1 ].SetLocalValue( m_textureFetchedValue + ".r" );
m_outputPorts[ m_colorPort.PortId + 2 ].SetLocalValue( m_textureFetchedValue + ".g" );
m_outputPorts[ m_colorPort.PortId + 3 ].SetLocalValue( m_textureFetchedValue + ".b" );
m_outputPorts[ m_colorPort.PortId + 4 ].SetLocalValue( m_textureFetchedValue + ".a" );
return m_textureFetchedValue;
}
}
}
return samplerOp;
}
private void AddNormalMapTag( ref string value )
{
if ( m_autoUnpackNormals )
{
value = string.Format( m_normalMapUnpackMode, value );
}
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
string textureName = GetCurrentParam( ref nodeParams );
m_defaultValue = AssetDatabase.LoadAssetAtPath<Texture>( textureName );
m_useSemantics = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
m_textureCoordSet = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
m_isNormalMap = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
m_defaultTextureValue = ( TexturePropertyValues ) Enum.Parse( typeof( TexturePropertyValues ), GetCurrentParam( ref nodeParams ) );
m_autocastMode = ( AutoCastType ) Enum.Parse( typeof( AutoCastType ), GetCurrentParam( ref nodeParams ) );
m_autoUnpackNormals = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
if ( UIUtils.CurrentShaderVersion() > 12 )
{
m_referenceType = ( TexReferenceType ) Enum.Parse( typeof( TexReferenceType ), GetCurrentParam( ref nodeParams ) );
if ( UIUtils.CurrentShaderVersion() > 22 )
{
m_referenceNodeId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
else
{
m_referenceArrayId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
if ( m_referenceType == TexReferenceType.Instance )
{
UIUtils.UnregisterSamplerNode( this );
UIUtils.UnregisterPropertyNode( this );
m_forceSamplerUpdate = true;
}
UpdateHeaderColor();
}
if ( UIUtils.CurrentShaderVersion() > 2406 )
m_mipMode = ( MipType ) Enum.Parse( typeof( MipType ), GetCurrentParam( ref nodeParams ) );
if ( UIUtils.CurrentShaderVersion() > 3201 )
m_currentType = ( TextureType ) Enum.Parse( typeof( TextureType ), GetCurrentParam( ref nodeParams ) );
if ( m_defaultValue == null )
{
ConfigureInputPorts();
ConfigureOutputPorts();
ResizeNodeToPreview();
}
else
{
ConfigFromObject( m_defaultValue );
}
m_forceInputTypeCheck = true;
}
public override void ReadAdditionalData( ref string[] nodeParams ) { }
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, ( m_defaultValue != null ) ? AssetDatabase.GetAssetPath( m_defaultValue ) : Constants.NoStringValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_useSemantics.ToString() );
IOUtils.AddFieldValueToString( ref nodeInfo, m_textureCoordSet.ToString() );
IOUtils.AddFieldValueToString( ref nodeInfo, m_isNormalMap.ToString() );
IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultTextureValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_autocastMode );
IOUtils.AddFieldValueToString( ref nodeInfo, m_autoUnpackNormals );
IOUtils.AddFieldValueToString( ref nodeInfo, m_referenceType );
IOUtils.AddFieldValueToString( ref nodeInfo, ( ( m_referenceSampler != null ) ? m_referenceSampler.UniqueId : -1 ) );
IOUtils.AddFieldValueToString( ref nodeInfo, m_mipMode );
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentType );
}
public override void WriteAdditionalToString( ref string nodeInfo, ref string connectionsInfo ) { }
public string GetVirtualUVCoords( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar, string portProperty )
{
string bias = "";
if ( m_mipMode == MipType.MipBias || m_mipMode == MipType.MipLevel )
{
string lodLevel = m_lodPort.GeneratePortInstructions( ref dataCollector );
bias += ", " + lodLevel;
}
if ( m_uvPort.IsConnected )
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
return uvs + bias;
}
else
{
string uvCoord = string.Empty;
if ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation )
{
uvCoord = Constants.VertexShaderInputStr + ".texcoord";
if ( m_textureCoordSet > 0 )
{
uvCoord += m_textureCoordSet.ToString();
}
}
else
{
string propertyName = CurrentPropertyReference;
if ( !string.IsNullOrEmpty( portProperty ) )
{
propertyName = portProperty;
}
string uvChannelName = IOUtils.GetUVChannelName( propertyName, m_textureCoordSet );
string dummyPropUV = "_texcoord" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" );
string dummyUV = "uv" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ) + dummyPropUV;
dataCollector.AddToProperties( UniqueId, "[HideInInspector] " + dummyPropUV + "( \"\", 2D ) = \"white\" {}", 100 );
dataCollector.AddToInput( UniqueId, "float2 " + dummyUV, true );
string attr = GetPropertyValue();
if ( attr.IndexOf( "[NoScaleOffset]" ) > -1 )
{
dataCollector.AddToLocalVariables( UniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV );
}
else
{
dataCollector.AddToUniforms( UniqueId, "uniform float4 " + propertyName + "_ST;" );
dataCollector.AddToLocalVariables( UniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw" );
}
uvCoord = uvChannelName;
}
return uvCoord + bias;
}
}
public string GetUVCoords( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar, string portProperty )
{
bool isVertex = ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation );
if ( m_uvPort.IsConnected )
{
if ( ( m_mipMode == MipType.MipLevel || m_mipMode == MipType.MipBias ) && m_lodPort.IsConnected )
{
string lodLevel = m_lodPort.GeneratePortInstructions( ref dataCollector );
if ( m_currentType != TextureType.Texture2D )
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", " + lodLevel + ")";
}
else
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", 0, " + lodLevel + ")";
}
}
else if ( m_mipMode == MipType.Derivative )
{
if ( m_currentType != TextureType.Texture2D )
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
return uvs + ", " + ddx + ", " + ddy;
}
else
{
string uvs = m_uvPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
return uvs + ", " + ddx + ", " + ddy;
}
}
else
{
if ( m_currentType != TextureType.Texture2D )
return m_uvPort.GenerateShaderForOutput( ref dataCollector, isVertex ? WirePortDataType.FLOAT4 : WirePortDataType.FLOAT3, ignoreLocalVar, true );
else
return m_uvPort.GenerateShaderForOutput( ref dataCollector, isVertex ? WirePortDataType.FLOAT4 : WirePortDataType.FLOAT2, ignoreLocalVar, true );
}
}
else
{
string vertexCoords = Constants.VertexShaderInputStr + ".texcoord";
if ( m_textureCoordSet > 0 )
{
vertexCoords += m_textureCoordSet.ToString();
}
string propertyName = CurrentPropertyReference;
if ( !string.IsNullOrEmpty( portProperty ) )
{
propertyName = portProperty;
}
string uvChannelName = IOUtils.GetUVChannelName( propertyName, m_textureCoordSet );
string dummyPropUV = "_texcoord" + ( m_textureCoordSet > 0 ? (m_textureCoordSet + 1).ToString() : "" );
string dummyUV = "uv" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ) + dummyPropUV;
//dataCollector.AddToUniforms( UniqueId, "uniform float4 " + propertyName + "_ST;");
dataCollector.AddToProperties( UniqueId, "[HideInInspector] "+ dummyPropUV + "( \"\", 2D ) = \"white\" {}", 100 );
dataCollector.AddToInput( UniqueId, "float2 " + dummyUV, true );
if ( isVertex )
{
dataCollector.AddToUniforms( UniqueId, "uniform float4 " + propertyName + "_ST;" );
string lodLevel = "0";
if( m_mipMode == MipType.MipLevel || m_mipMode == MipType.MipBias )
lodLevel = m_lodPort.GeneratePortInstructions( ref dataCollector );
dataCollector.AddToVertexLocalVariables( UniqueId, "float4 " + uvChannelName + " = float4(" + vertexCoords + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw, 0 ," + lodLevel + ");" );
return uvChannelName;
}
else
{
string attr = GetPropertyValue();
if ( attr.IndexOf( "[NoScaleOffset]" ) > -1 )
{
dataCollector.AddToLocalVariables( UniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV );
}
else
{
dataCollector.AddToUniforms( UniqueId, "uniform float4 " + propertyName + "_ST;" );
dataCollector.AddToLocalVariables( UniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw" );
}
}
string uvCoord = uvChannelName;
if ( ( m_mipMode == MipType.MipLevel || m_mipMode == MipType.MipBias ) && m_lodPort.IsConnected )
{
string lodLevel = m_lodPort.GeneratePortInstructions( ref dataCollector );
if ( m_currentType != TextureType.Texture2D )
{
string uvs = string.Format( "float3({0},0.0)", uvCoord ); ;
return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", " + lodLevel + ")";
}
else
{
string uvs = uvCoord;
return UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, WirePortDataType.FLOAT4 ) + "( " + uvs + ", 0, " + lodLevel + ")";
}
}
else if ( m_mipMode == MipType.Derivative )
{
if ( m_currentType != TextureType.Texture2D )
{
string uvs = string.Format( "float3({0},0.0)", uvCoord );
string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT3, ignoreLocalVar, true );
return uvs + ", " + ddx + ", " + ddy;
}
else
{
string uvs = uvCoord;
string ddx = m_ddxPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
string ddy = m_ddyPort.GenerateShaderForOutput( ref dataCollector, WirePortDataType.FLOAT2, ignoreLocalVar, true );
return uvs + ", " + ddx + ", " + ddy;
}
}
else
{
if ( m_currentType != TextureType.Texture2D )
{
return string.Format( "float3({0},0.0)", uvCoord );
}
else
{
return uvCoord;
}
}
}
}
public override int VersionConvertInputPortId( int portId )
{
int newPort = portId;
//change normal scale port to last
if ( UIUtils.CurrentShaderVersion() < 2407 )
{
if ( portId == 1 )
newPort = 4;
}
if ( UIUtils.CurrentShaderVersion() < 2408 )
{
newPort = newPort + 1;
}
return newPort;
}
public override void Destroy()
{
base.Destroy();
m_defaultValue = null;
m_materialValue = null;
m_referenceSampler = null;
m_referenceStyle = null;
m_referenceContent = null;
m_texPort = null;
m_uvPort = null;
m_lodPort = null;
m_ddxPort = null;
m_ddyPort = null;
m_normalPort = null;
m_colorPort = null;
if ( m_referenceType == TexReferenceType.Object )
{
UIUtils.UnregisterSamplerNode( this );
UIUtils.UnregisterPropertyNode( this );
}
}
public override string GetPropertyValStr()
{
return m_materialMode ? ( m_materialValue != null ? m_materialValue.name : IOUtils.NO_TEXTURES ) : ( m_defaultValue != null ? m_defaultValue.name : IOUtils.NO_TEXTURES );
}
public TexturePropertyNode TextureProperty
{
get
{
if ( m_referenceSampler != null )
{
m_textureProperty = m_referenceSampler as TexturePropertyNode;
}
else if ( m_texPort.IsConnected )
{
m_textureProperty = m_texPort.GetOutputNode( 0 ) as TexturePropertyNode;
}
return m_textureProperty;
}
}
public override string GetPropertyValue()
{
if ( SoftValidReference )
{
return m_referenceSampler.TextureProperty.GetPropertyValue();
}
else
if ( m_texPort.IsConnected && TextureProperty != null )
{
return TextureProperty.GetPropertyValue();
}
switch ( m_currentType )
{
case TextureType.Texture2D:
{
return PropertyAttributes + GetTexture2DPropertyValue();
}
case TextureType.Texture3D:
{
return PropertyAttributes + GetTexture3DPropertyValue();
}
case TextureType.Cube:
{
return PropertyAttributes + GetCubePropertyValue();
}
}
return string.Empty;
}
public override string GetUniformValue()
{
if ( SoftValidReference )
{
return m_referenceSampler.TextureProperty.GetUniformValue();
}
else if ( m_texPort.IsConnected && TextureProperty != null )
{
return TextureProperty.GetUniformValue();
}
return base.GetUniformValue();
}
public override bool GetUniformData( out string dataType, out string dataName )
{
if ( SoftValidReference )
{
return m_referenceSampler.TextureProperty.GetUniformData( out dataType, out dataName);
}
else if ( m_texPort.IsConnected && TextureProperty != null )
{
return TextureProperty.GetUniformData( out dataType, out dataName );
}
return base.GetUniformData( out dataType, out dataName );
}
public string UVCoordsName { get { return Constants.InputVarStr + "." + IOUtils.GetUVChannelName( CurrentPropertyReference, m_textureCoordSet ); } }
public override string CurrentPropertyReference
{
get
{
string propertyName = string.Empty;
if ( m_referenceType == TexReferenceType.Instance && m_referenceArrayId > -1 )
{
SamplerNode node = UIUtils.GetSamplerNode( m_referenceArrayId );
propertyName = ( node != null ) ? node.TextureProperty.PropertyName : PropertyName;
}
else if ( m_texPort.IsConnected && TextureProperty != null )
{
propertyName = TextureProperty.PropertyName;
}
else
{
propertyName = PropertyName;
}
return propertyName;
}
}
public bool SoftValidReference
{
get
{
if ( m_referenceType == TexReferenceType.Instance && m_referenceArrayId > -1 )
{
m_referenceSampler = UIUtils.GetSamplerNode( m_referenceArrayId );
m_texPort.Locked = true;
if ( m_referenceContent == null )
m_referenceContent = new GUIContent();
if ( m_referenceSampler != null )
{
m_referenceContent.image = m_referenceSampler.Value;
if ( m_referenceWidth != m_referenceSampler.Position.width )
{
m_referenceWidth = m_referenceSampler.Position.width;
m_sizeIsDirty = true;
}
}
else
{
m_referenceArrayId = -1;
m_referenceWidth = -1;
}
return m_referenceSampler != null;
}
m_texPort.Locked = false;
return false;
}
}
public bool AutoUnpackNormals
{
get { return m_autoUnpackNormals; }
set
{
m_autoUnpackNormals = value;
m_defaultTextureValue = value ? TexturePropertyValues.bump : TexturePropertyValues.white;
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.IdentityModel
{
using System;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Security.Cryptography;
using System.Xml;
/// <summary>
/// Wraps a reader pointing to a enveloped signed XML and provides
/// a reader that can be used to read the content without having to
/// process the signature. The Signature is automatically validated
/// when the last element of the envelope is read.
/// </summary>
public sealed class EnvelopedSignatureReader : DelegatingXmlDictionaryReader
{
bool _automaticallyReadSignature;
DictionaryManager _dictionaryManager;
int _elementCount;
bool _resolveIntrinsicSigningKeys;
bool _requireSignature;
SigningCredentials _signingCredentials;
SecurityTokenResolver _signingTokenResolver;
SignedXml _signedXml;
SecurityTokenSerializer _tokenSerializer;
WrappedReader _wrappedReader;
bool _disposed;
/// <summary>
/// Initializes an instance of <see cref="EnvelopedSignatureReader"/>
/// </summary>
/// <param name="reader">Reader pointing to the enveloped signed XML.</param>
/// <param name="securityTokenSerializer">Token Serializer to resolve the signing token.</param>
public EnvelopedSignatureReader(XmlReader reader, SecurityTokenSerializer securityTokenSerializer)
: this(reader, securityTokenSerializer, null)
{
}
/// <summary>
/// Initializes an instance of <see cref="EnvelopedSignatureReader"/>
/// </summary>
/// <param name="reader">Reader pointing to the enveloped signed XML.</param>
/// <param name="securityTokenSerializer">Token Serializer to deserialize the KeyInfo of the Signature.</param>
/// <param name="signingTokenResolver">Token Resolver to resolve the signing token.</param>
/// <exception cref="ArgumentNullException">One of the input parameter is null.</exception>
public EnvelopedSignatureReader(XmlReader reader, SecurityTokenSerializer securityTokenSerializer, SecurityTokenResolver signingTokenResolver)
: this(reader, securityTokenSerializer, signingTokenResolver, true, true, true)
{
}
/// <summary>
/// Initializes an instance of <see cref="EnvelopedSignatureReader"/>
/// </summary>
/// <param name="reader">Reader pointing to the enveloped signed XML.</param>
/// <param name="securityTokenSerializer">Token Serializer to deserialize the KeyInfo of the Signature.</param>
/// <param name="signingTokenResolver">Token Resolver to resolve the signing token.</param>
/// <param name="requireSignature">The value indicates whether the signature is optional.</param>
/// <param name="automaticallyReadSignature">This value indicates if the Signature should be read
/// when the Signature element is encountered or allow the caller to read the Signature manually.</param>
/// <param name="resolveIntrinsicSigningKeys">A value indicating if intrinsic signing keys should be resolved.</param>
public EnvelopedSignatureReader(XmlReader reader, SecurityTokenSerializer securityTokenSerializer, SecurityTokenResolver signingTokenResolver, bool requireSignature, bool automaticallyReadSignature, bool resolveIntrinsicSigningKeys)
{
if (reader == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
}
if (securityTokenSerializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenSerializer");
}
_automaticallyReadSignature = automaticallyReadSignature;
_dictionaryManager = new DictionaryManager();
_tokenSerializer = securityTokenSerializer;
_requireSignature = requireSignature;
_signingTokenResolver = signingTokenResolver ?? EmptySecurityTokenResolver.Instance;
_resolveIntrinsicSigningKeys = resolveIntrinsicSigningKeys;
XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(reader);
_wrappedReader = new WrappedReader(dictionaryReader);
base.InitializeInnerReader(_wrappedReader);
}
void OnEndOfRootElement()
{
if (null == _signedXml)
{
if (_requireSignature)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new CryptographicException(SR.GetString(SR.ID3089)));
}
}
else
{
ResolveSigningCredentials();
_signedXml.StartSignatureVerification(_signingCredentials.SigningKey);
_wrappedReader.XmlTokens.SetElementExclusion(XD.XmlSignatureDictionary.Signature.Value, XD.XmlSignatureDictionary.Namespace.Value);
WifSignedInfo signedInfo = _signedXml.Signature.SignedInfo as WifSignedInfo;
_signedXml.EnsureDigestValidity(signedInfo[0].ExtractReferredId(), _wrappedReader);
_signedXml.CompleteSignatureVerification();
}
}
/// <summary>
/// Returns the SigningCredentials used in the signature after the
/// envelope is consumed and when the signature is validated.
/// </summary>
public SigningCredentials SigningCredentials
{
get
{
return _signingCredentials;
}
}
/// <summary>
/// Gets a XmlBuffer of the envelope that was enveloped signed.
/// The buffer is available after the XML has been read and
/// signature validated.
/// </summary>
internal XmlTokenStream XmlTokens
{
get
{
return _wrappedReader.XmlTokens.Trim();
}
}
/// <summary>
/// Overrides the base Read method. Checks if the end of the envelope is reached and
/// validates the signature if requireSignature is enabled. If the reader gets
/// positioned on a Signature element the whole signature is read in if automaticallyReadSignature
/// is enabled.
/// </summary>
/// <returns>true if the next node was read successfully; false if there are no more nodes</returns>
public override bool Read()
{
if ((base.NodeType == XmlNodeType.Element) && (!base.IsEmptyElement))
{
_elementCount++;
}
if (base.NodeType == XmlNodeType.EndElement)
{
_elementCount--;
if (_elementCount == 0)
{
OnEndOfRootElement();
}
}
bool result = base.Read();
if (_automaticallyReadSignature
&& (_signedXml == null)
&& result
&& base.InnerReader.IsLocalName(XD.XmlSignatureDictionary.Signature)
&& base.InnerReader.IsNamespaceUri(XD.XmlSignatureDictionary.Namespace))
{
ReadSignature();
}
return result;
}
void ReadSignature()
{
_signedXml = new SignedXml(new WifSignedInfo(_dictionaryManager), _dictionaryManager, _tokenSerializer);
_signedXml.TransformFactory = ExtendedTransformFactory.Instance;
_signedXml.ReadFrom(_wrappedReader);
if (_signedXml.Signature.SignedInfo.ReferenceCount != 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.GetString(SR.ID3057)));
}
}
void ResolveSigningCredentials()
{
if (_signedXml.Signature == null || _signedXml.Signature.KeyIdentifier == null || _signedXml.Signature.KeyIdentifier.Count == 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID3276)));
}
SecurityKey signingKey = null;
if (!_signingTokenResolver.TryResolveSecurityKey(_signedXml.Signature.KeyIdentifier[0], out signingKey))
{
if (_resolveIntrinsicSigningKeys && _signedXml.Signature.KeyIdentifier.CanCreateKey)
{
signingKey = _signedXml.Signature.KeyIdentifier.CreateKey();
}
else
{
//
// we cannot find the signing key to verify the signature
//
EncryptedKeyIdentifierClause encryptedKeyClause;
if (_signedXml.Signature.KeyIdentifier.TryFind<EncryptedKeyIdentifierClause>(out encryptedKeyClause))
{
//
// System.IdentityModel.Tokens.EncryptedKeyIdentifierClause.ToString() does not print out
// very good information except the cipher data in this case. We have worked around that
// by using the token serializer to serialize the key identifier clause again.
//
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SignatureVerificationFailedException(
SR.GetString(SR.ID4036, XmlUtil.SerializeSecurityKeyIdentifier(_signedXml.Signature.KeyIdentifier, _tokenSerializer))));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SignatureVerificationFailedException(SR.GetString(SR.ID4037, _signedXml.Signature.KeyIdentifier.ToString())));
}
}
}
WifSignedInfo signedInfo = _signedXml.Signature.SignedInfo as WifSignedInfo;
_signingCredentials = new SigningCredentials(signingKey, _signedXml.Signature.SignedInfo.SignatureMethod, signedInfo[0].DigestMethod, _signedXml.Signature.KeyIdentifier);
}
/// <summary>
/// Reads the signature if the reader is currently positioned at a Signature element.
/// </summary>
/// <returns>true if the signature was successfully read else false.</returns>
/// <remarks>Does not move the reader when returning false.</remarks>
public bool TryReadSignature()
{
if (IsStartElement(XD.XmlSignatureDictionary.Signature, XD.XmlSignatureDictionary.Namespace))
{
ReadSignature();
return true;
}
return false;
}
#region IDisposable Members
/// <summary>
/// Releases the unmanaged resources used by the System.IdentityModel.Protocols.XmlSignature.EnvelopedSignatureReader and optionally
/// releases the managed resources.
/// </summary>
/// <param name="disposing">
/// True to release both managed and unmanaged resources; false to release only unmanaged resources.
/// </param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (_disposed)
{
return;
}
if (disposing)
{
//
// Free all of our managed resources
//
if (_wrappedReader != null)
{
_wrappedReader.Close();
_wrappedReader = null;
}
}
// Free native resources, if any.
_disposed = true;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace StudentSystem.Api.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Compute.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Models;
using System.Collections.Generic;
using System;
using Newtonsoft.Json.Linq;
using ResourceManager.Fluent.Core;
/// <summary>
/// The implementation for DiskVolumeEncryptionStatus for Linux virtual machine.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uTGludXhEaXNrVm9sdW1lRW5jcnlwdGlvbk1vbml0b3JJbXBs
internal partial class LinuxDiskVolumeEncryptionMonitorImpl :
IDiskVolumeEncryptionMonitor
{
private string rgName;
private string vmName;
private IComputeManager computeManager;
private VirtualMachineExtensionInner encryptionExtension;
/// <summary>
/// Creates LinuxDiskVolumeEncryptionMonitorImpl.
/// </summary>
/// <param name="virtualMachineId">Resource id of Linux virtual machine to retrieve encryption status from.</param>
/// <param name="computeManager">Compute manager.</param>
///GENMHASH:A42CB27228CC0FEEF184DFCCC4F8DCB2:0C2BFB2332C823A9307222D73EFBAF83
internal LinuxDiskVolumeEncryptionMonitorImpl(string virtualMachineId, IComputeManager computeManager)
{
this.rgName = ResourceUtils.GroupFromResourceId(virtualMachineId);
this.vmName = ResourceUtils.NameFromResourceId(virtualMachineId);
this.computeManager = computeManager;
}
///GENMHASH:4002186478A1CB0B59732EBFB18DEB3A:FF7924BFEF46CE7F250D6F5B1A727744
public IDiskVolumeEncryptionMonitor Refresh()
{
return ResourceManager.Fluent.Core.Extensions.Synchronize(() => RefreshAsync());
}
/// <return>The instance view status collection associated with the encryption extension.</return>
///GENMHASH:DF6D090576A3266E52582EE3F48781B1:FE003BD6635A94757D4D94620D2271C0
private IList<Models.InstanceViewStatus> InstanceViewStatuses()
{
if (!HasEncryptionExtension())
{
return new List<InstanceViewStatus>();
}
VirtualMachineExtensionInstanceView instanceView = this.encryptionExtension.InstanceView;
if (instanceView == null
|| instanceView.Statuses == null)
{
return new List<InstanceViewStatus>();
}
return instanceView.Statuses;
}
/// <summary>
/// Retrieve the extension with latest state. If the extension could not be found then
/// an empty observable will be returned.
/// </summary>
/// <param name="extension">The extension name.</param>
/// <return>An observable that emits the retrieved extension.</return>
///GENMHASH:8B810B2C467EB2B9F131F38236BA630F:FA32EDB4C3CE589CF08191999C2005C5
private async Task<Models.VirtualMachineExtensionInner> RetrieveExtensionWithInstanceViewAsync(VirtualMachineExtensionInner extension, CancellationToken cancellationToken = default(CancellationToken))
{
return await this.computeManager
.Inner
.VirtualMachineExtensions
.GetAsync(rgName, vmName, extension.Name, "instanceView", cancellationToken);
}
///GENMHASH:CFF730CD005B7D5386D59ADCF7C33D0C:80F0D0455B27E848B9196C7D1768B4DB
public EncryptionStatus DataDiskStatus()
{
if (!HasEncryptionExtension())
{
return EncryptionStatus.NotEncrypted;
}
string subStatusJson = InstanceViewFirstSubStatus();
if (subStatusJson == null)
{
return EncryptionStatus.Unknown;
}
if (subStatusJson == null)
{
return EncryptionStatus.Unknown;
}
JObject jObject = JObject.Parse(subStatusJson);
if (jObject["data"] == null)
{
return EncryptionStatus.Unknown;
}
return EncryptionStatus.Parse((string)jObject["data"]);
}
/// <return>
/// The first sub-status from instance view sub-status collection associated with the
/// encryption extension.
/// </return>
///GENMHASH:41E2F45F0E1CC7217B8CEF67918CFBD9:327967FA4D7F005F7016223268CC352F
private string InstanceViewFirstSubStatus()
{
if (!HasEncryptionExtension())
{
return null;
}
VirtualMachineExtensionInstanceView instanceView = this.encryptionExtension.InstanceView;
if (instanceView == null
|| instanceView.Substatuses == null)
{
return null;
}
IList<InstanceViewStatus> instanceViewSubStatuses = instanceView.Substatuses;
if (instanceViewSubStatuses.Count == 0)
{
return null;
}
return instanceViewSubStatuses[0].Message;
}
///GENMHASH:1BAF4F1B601F89251ABCFE6CC4867026:14DA61D401D0341BDBDB99994BA6DA1F
public OperatingSystemTypes OSType()
{
return OperatingSystemTypes.Linux;
}
///GENMHASH:D1037603B1F11C451DD830F07021E503:1E738399F355D89FDD840DEFB7CAE473
public EncryptionStatus OSDiskStatus()
{
if (!HasEncryptionExtension())
{
return EncryptionStatus.NotEncrypted;
}
if (!HasEncryptionExtension())
{
return EncryptionStatus.NotEncrypted;
}
string subStatusJson = InstanceViewFirstSubStatus();
if (subStatusJson == null)
{
return EncryptionStatus.Unknown;
}
JObject jObject = JObject.Parse(subStatusJson);
if (jObject["os"] == null)
{
return EncryptionStatus.Unknown;
}
return EncryptionStatus.Parse((string)jObject["os"]);
}
///GENMHASH:5A2D79502EDA81E37A36694062AEDC65:1983032392C8C2C0E86D7F672D2737DF
public async Task<Microsoft.Azure.Management.Compute.Fluent.IDiskVolumeEncryptionMonitor> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken))
{
// Refreshes the cached encryption extension installed in the Linux virtual machine.
VirtualMachineExtensionInner virtualMachineExtensionInner = await RetrieveEncryptExtensionWithInstanceViewAsync(cancellationToken);
if (virtualMachineExtensionInner != null)
{
this.encryptionExtension = virtualMachineExtensionInner;
}
return this;
}
/// <summary>
/// Retrieves the latest state of encryption extension in the virtual machine.
/// </summary>
/// <return>The retrieved extension.</return>
///GENMHASH:0D7229D8D998BA64BC9507355D492994:3CAE38CC4AFCD502C95C2524E812168D
private async Task<Models.VirtualMachineExtensionInner> RetrieveEncryptExtensionWithInstanceViewAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (encryptionExtension != null)
{
// If there is already a cached extension simply retrieve it again with instance view.
//
return await RetrieveExtensionWithInstanceViewAsync(encryptionExtension, cancellationToken);
}
else
{
// Extension is not cached already so retrieve name from the virtual machine and
// then get the extension with instance view.
//
return await RetrieveEncryptExtensionWithInstanceViewFromVMAsync(cancellationToken);
}
}
/// <summary>
/// Retrieve the encryption extension from the virtual machine and then retrieve it again with instance view expanded.
/// If the virtual machine does not exists then an error observable will be returned, if the extension could not be
/// located then an empty observable will be returned.
/// </summary>
/// <return>The retrieved extension.</return>
///GENMHASH:F5645D5F0FF252C17769B3B4778AD204:9A94E8179A8202B9101EC72C66DB254C
private async Task<Models.VirtualMachineExtensionInner> RetrieveEncryptExtensionWithInstanceViewFromVMAsync(CancellationToken cancellationToken = default(CancellationToken))
{
VirtualMachineInner virtualMachine = await this.computeManager
.Inner
.VirtualMachines
.GetAsync(rgName, vmName, cancellationToken: cancellationToken);
if (virtualMachine == null)
{
new Exception($"VM with name '{vmName}' not found (resource group '{rgName}')");
}
if (virtualMachine.Resources != null)
{
foreach (var extension in virtualMachine.Resources)
{
if (extension.Publisher.Equals("Microsoft.Azure.Security", StringComparison.OrdinalIgnoreCase)
&& extension.VirtualMachineExtensionType.Equals("AzureDiskEncryptionForLinux", StringComparison.OrdinalIgnoreCase))
{
return await RetrieveExtensionWithInstanceViewAsync(extension, cancellationToken);
}
}
}
return await Task.FromResult<Models.VirtualMachineExtensionInner>(null);
}
///GENMHASH:6BC2D312A9C6A52A192D8C5304AB76C7:8D5351CEBDDEA6C608931050B58B3338
public string ProgressMessage()
{
if (!HasEncryptionExtension())
{
return null;
}
IList<InstanceViewStatus> statuses = InstanceViewStatuses();
if (statuses.Count == 0)
{
return null;
}
return statuses[0].Message;
}
///GENMHASH:71BDA0CA4CE6BBBC011C764A218FEA88:5B97ED6BFAA87368F39F4CEFC342885A
private bool HasEncryptionExtension()
{
return this.encryptionExtension != null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Versions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interactive;
using static Microsoft.CodeAnalysis.Utilities.ForegroundThreadDataKind;
namespace Microsoft.VisualStudio.LanguageServices.Setup
{
[Guid(Guids.RoslynPackageIdString)]
[PackageRegistration(UseManagedResourcesOnly = true)]
[ProvideMenuResource("Menus.ctmenu", version: 13)]
internal class RoslynPackage : Package
{
private LibraryManager _libraryManager;
private uint _libraryManagerCookie;
private VisualStudioWorkspace _workspace;
private WorkspaceFailureOutputPane _outputPane;
private IComponentModel _componentModel;
private RuleSetEventHandler _ruleSetEventHandler;
private IDisposable _solutionEventMonitor;
protected override void Initialize()
{
base.Initialize();
// Assume that we are being initialized on the UI thread at this point.
ForegroundThreadAffinitizedObject.CurrentForegroundThreadData = ForegroundThreadData.CreateDefault(defaultKind: ForcedByPackageInitialize);
Debug.Assert(ForegroundThreadAffinitizedObject.CurrentForegroundThreadData.Kind != Unknown);
FatalError.Handler = FailFast.OnFatalException;
FatalError.NonFatalHandler = WatsonReporter.Report;
// We also must set the FailFast handler for the compiler layer as well
var compilerAssembly = typeof(Compilation).Assembly;
var compilerFatalError = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true);
var property = compilerFatalError.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public);
var compilerFailFast = compilerAssembly.GetType(typeof(FailFast).FullName, throwOnError: true);
var method = compilerFailFast.GetMethod(nameof(FailFast.OnFatalException), BindingFlags.Static | BindingFlags.NonPublic);
property.SetValue(null, Delegate.CreateDelegate(property.PropertyType, method));
InitializePortableShim(compilerAssembly);
RegisterFindResultsLibraryManager();
var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel));
_workspace = componentModel.GetService<VisualStudioWorkspace>();
var telemetrySetupExtensions = componentModel.GetExtensions<IRoslynTelemetrySetup>();
foreach (var telemetrySetup in telemetrySetupExtensions)
{
telemetrySetup.Initialize(this);
}
// set workspace output pane
_outputPane = new WorkspaceFailureOutputPane(this, _workspace);
InitializeColors();
// load some services that have to be loaded in UI thread
LoadComponentsInUIContext();
_solutionEventMonitor = new SolutionEventMonitor(_workspace);
}
private static void InitializePortableShim(Assembly compilerAssembly)
{
// We eagerly force all of the types to be loaded within the PortableShim because there are scenarios
// in which loading types can trigger the current AppDomain's AssemblyResolve or TypeResolve events.
// If handlers of those events do anything that would cause PortableShim to be accessed recursively,
// bad things can happen. In particular, this fixes the scenario described in TFS bug #1185842.
//
// Note that the fix below is written to be as defensive as possible to do no harm if it impacts other
// scenarios.
// Initialize the PortableShim linked into the Workspaces layer.
Roslyn.Utilities.PortableShim.Initialize();
// Initialize the PortableShim linked into the Compilers layer via reflection.
var compilerPortableShim = compilerAssembly.GetType("Roslyn.Utilities.PortableShim", throwOnError: false);
var initializeMethod = compilerPortableShim?.GetMethod(nameof(Roslyn.Utilities.PortableShim.Initialize), BindingFlags.Static | BindingFlags.NonPublic);
initializeMethod?.Invoke(null, null);
}
private void InitializeColors()
{
// Use VS color keys in order to support theming.
CodeAnalysisColors.SystemCaptionTextColorKey = EnvironmentColors.SystemWindowTextColorKey;
CodeAnalysisColors.SystemCaptionTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.CheckBoxTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey;
CodeAnalysisColors.RenameErrorTextBrushKey = VSCodeAnalysisColors.RenameErrorTextBrushKey;
CodeAnalysisColors.RenameResolvableConflictTextBrushKey = VSCodeAnalysisColors.RenameResolvableConflictTextBrushKey;
CodeAnalysisColors.BackgroundBrushKey = VsBrushes.CommandBarGradientBeginKey;
CodeAnalysisColors.ButtonStyleKey = VsResourceKeys.ButtonStyleKey;
CodeAnalysisColors.AccentBarColorKey = EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey;
}
private void LoadComponentsInUIContext()
{
if (KnownUIContexts.SolutionExistsAndFullyLoadedContext.IsActive)
{
// if we are already in the right UI context, load it right away
LoadComponents();
}
else
{
// load them when it is a right context.
KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged += OnSolutionExistsAndFullyLoadedContext;
}
}
private void OnSolutionExistsAndFullyLoadedContext(object sender, UIContextChangedEventArgs e)
{
if (e.Activated)
{
// unsubscribe from it
KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged -= OnSolutionExistsAndFullyLoadedContext;
// load components
LoadComponents();
}
}
private void LoadComponents()
{
// we need to load it as early as possible since we can have errors from
// package from each language very early
this.ComponentModel.GetService<VisualStudioDiagnosticListTable>();
this.ComponentModel.GetService<VisualStudioTodoListTable>();
this.ComponentModel.GetService<VisualStudioDiagnosticListTableCommandHandler>().Initialize(this);
this.ComponentModel.GetService<HACK_ThemeColorFixer>();
this.ComponentModel.GetExtensions<IReferencedSymbolsPresenter>();
this.ComponentModel.GetExtensions<INavigableItemsPresenter>();
this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>();
this.ComponentModel.GetService<VirtualMemoryNotificationListener>();
// The misc files workspace needs to be loaded on the UI thread. This way it will have
// the appropriate task scheduler to report events on.
this.ComponentModel.GetService<MiscellaneousFilesWorkspace>();
LoadAnalyzerNodeComponents();
Task.Run(() => LoadComponentsBackground());
}
private void LoadComponentsBackground()
{
// Perf: Initialize the command handlers.
var commandHandlerServiceFactory = this.ComponentModel.GetService<ICommandHandlerServiceFactory>();
commandHandlerServiceFactory.Initialize(ContentTypeNames.RoslynContentType);
LoadInteractiveMenus();
this.ComponentModel.GetService<MiscellaneousTodoListTable>();
this.ComponentModel.GetService<MiscellaneousDiagnosticListTable>();
}
private void LoadInteractiveMenus()
{
var menuCommandService = (OleMenuCommandService)GetService(typeof(IMenuCommandService));
var monitorSelectionService = (IVsMonitorSelection)this.GetService(typeof(SVsShellMonitorSelection));
new CSharpResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel)
.InitializeResetInteractiveFromProjectCommand();
new VisualBasicResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel)
.InitializeResetInteractiveFromProjectCommand();
}
internal IComponentModel ComponentModel
{
get
{
if (_componentModel == null)
{
_componentModel = (IComponentModel)GetService(typeof(SComponentModel));
}
return _componentModel;
}
}
protected override void Dispose(bool disposing)
{
UnregisterFindResultsLibraryManager();
DisposeVisualStudioDocumentTrackingService();
UnregisterAnalyzerTracker();
UnregisterRuleSetEventHandler();
ReportSessionWideTelemetry();
if (_solutionEventMonitor != null)
{
_solutionEventMonitor.Dispose();
_solutionEventMonitor = null;
}
base.Dispose(disposing);
}
private void ReportSessionWideTelemetry()
{
PersistedVersionStampLogger.LogSummary();
LinkedFileDiffMergingLogger.ReportTelemetry();
}
private void RegisterFindResultsLibraryManager()
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
_libraryManager = new LibraryManager(this);
if (ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(_libraryManager, out _libraryManagerCookie)))
{
_libraryManagerCookie = 0;
}
((IServiceContainer)this).AddService(typeof(LibraryManager), _libraryManager, promote: true);
}
}
private void UnregisterFindResultsLibraryManager()
{
if (_libraryManagerCookie != 0)
{
var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (objectManager != null)
{
objectManager.UnregisterLibrary(_libraryManagerCookie);
_libraryManagerCookie = 0;
}
((IServiceContainer)this).RemoveService(typeof(LibraryManager), promote: true);
_libraryManager = null;
}
}
private void DisposeVisualStudioDocumentTrackingService()
{
if (_workspace != null)
{
var documentTrackingService = _workspace.Services.GetService<IDocumentTrackingService>() as VisualStudioDocumentTrackingService;
documentTrackingService.Dispose();
}
}
private void LoadAnalyzerNodeComponents()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this);
_ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>();
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Register();
}
}
private void UnregisterAnalyzerTracker()
{
this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister();
}
private void UnregisterRuleSetEventHandler()
{
if (_ruleSetEventHandler != null)
{
_ruleSetEventHandler.Unregister();
_ruleSetEventHandler = null;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using OpenADK.Library;
using OpenADK.Library.us.Common;
using OpenADK.Library.us.Food;
using OpenADK.Library.us.Programs;
using OpenADK.Library.us.Student;
using OpenADK.Library.Tools.Cfg;
using OpenADK.Library.Tools.Mapping;
using OpenADK.Library.Tools.XPath;
using NUnit.Framework;
using Library.UnitTesting.Framework;
namespace Library.Nunit.US.Tools.Mapping
{
/// <summary>
/// Summary description for MappingTests.
/// </summary>
[TestFixture]
public abstract class MappingTests : BaseMappingsTest
{
private SifVersion fVersion;
private String fFileName;
private AgentConfig fCfg;
protected MappingTests( SifVersion testedVersion, String configFileName )
{
fVersion = testedVersion;
fFileName = configFileName;
}
[SetUp]
public override void setUp()
{
base.setUp();
Adk.SifVersion = fVersion;
fCfg = new AgentConfig();
fCfg.Read( fFileName, false );
}
/**
* Asserts default value field mapping behavior
*
* @
*/
[Test]
public void testFieldMapping010()
{
StudentPersonal sp = new StudentPersonal();
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
IDictionary map = buildIDictionaryForStudentPersonalTest();
// Add a "default" to the middle name rule and assert that it gets
// created
ObjectMapping om = mappings.GetObjectMapping( "StudentPersonal", false );
FieldMapping middleNameRule = om.GetRule( 3 );
middleNameRule.DefaultValue = "Jerry";
map.Remove( "MIDDLE_NAME" );
StringMapAdaptor adaptor = new StringMapAdaptor( map );
mappings.MapOutbound( adaptor, sp );
SifWriter writer = new SifWriter( Console.Out );
writer.Write( sp );
writer.Flush();
// For the purposes of this test, all we care about is the Ethnicity
// mapping.
// It should have the default outbound value we specified, which is "7"
Assertion.AssertEquals( "Middle Name should be Jerry", "Jerry", sp
.Name.MiddleName );
// Now, remap the student back into application fields
IDictionary restoredData = new Hashtable();
adaptor.Dictionary = restoredData;
mappings.MapInbound( sp, adaptor );
Assertion.AssertEquals( "Middle Name should be Jerry", "Jerry",
restoredData["MIDDLE_NAME"] );
sp.Name.LastName = null;
// Now, remap the student back into application fields
restoredData = new Hashtable();
adaptor.Dictionary = restoredData;
mappings.MapInbound( sp, adaptor );
Object lastName = restoredData["LAST_NAME"];
Console.WriteLine( sp.ToXml() );
Assertion.AssertNull( "Last Name should be null", lastName );
}
/**
* Assert that defaults work even with valueset mapping
*
* @
*/
[Test]
public void testFieldMapping020()
{
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
IDictionary map = buildIDictionaryForStudentPersonalTest();
// Find the Ethnicity rule
ObjectMapping om = mappings.GetObjectMapping( "StudentPersonal", false );
FieldMapping inboundEthnicityRule = null;
FieldMapping outboundEthnicityRule = null;
for ( int a = 0; a < om.RuleCount; a++ )
{
FieldMapping fm = om.GetRule( a );
if ( fm.FieldName.Equals( "ETHNICITY" ) )
{
if ( fm.Filter.Direction == MappingDirection.Inbound )
{
inboundEthnicityRule = fm;
}
else
{
outboundEthnicityRule = fm;
}
}
}
// Put a value into the map that won't match the valueset
map[ "ETHNICITY" ] = "abcdefg" ;
StudentPersonal sp = new StudentPersonal();
MapOutbound( sp, mappings, map );
// There's no default value defined, so we expect that what get's put in
// is what we get out
Assertion.AssertEquals( "Outbound Ethnicity", "abcdefg", sp.Demographics.RaceList.ItemAt( 0 ).Code );
// Now, remap the student back into application fields
IDictionary restoredData = new Hashtable();
StringMapAdaptor adaptor = new StringMapAdaptor( restoredData );
mappings.MapInbound( sp, adaptor );
// The value "abcdefg" does not have a match in the value set
// It should be passed back through
Assertion.AssertEquals( "Inbound Ethnicity", "abcdefg", restoredData["ETHNICITY"] );
inboundEthnicityRule.DefaultValue = "11111";
outboundEthnicityRule.DefaultValue = "99999";
sp = new StudentPersonal();
MapOutbound( sp, mappings, map );
// It should have the default value we specified, which is "99999"
Assertion.AssertEquals( "Outbound Ethnicity", "99999", sp.Demographics.RaceList.ItemAt( 0 ).Code );
// Now, remap the student back into application fields
restoredData = new Hashtable();
adaptor.Dictionary = restoredData;
mappings.MapInbound( sp, adaptor );
// The value "9999" does not have a match in the value set
// we want it to take on the default value, which is "111111"
Assertion.AssertEquals( "Inbound Ethnicity", "11111", restoredData["ETHNICITY"] );
// Now, do the mapping again, this time with the Ethnicity value
// completely missing
sp = new StudentPersonal();
map.Remove( "ETHNICITY" );
MapOutbound( sp, mappings, map );
// Ethnicity should be set to "99999" in this case because we didn't set
// the "ifNull" behavior and the
// default behavior is "NULL_DEFAULT"
Assertion.AssertEquals( "Outbound Ethnicity", "99999", sp.Demographics
.RaceList.ItemAt( 0 ).Code );
// Now, do the mapping again, this time with the NULL_DEFALT behavior.
// The result should be the same
outboundEthnicityRule.NullBehavior = MappingBehavior.IfNullDefault;
sp = new StudentPersonal();
MapOutbound( sp, mappings, map );
// Ethnicity should be set to "99999" in this case because we set the
// ifnull behavior to "NULL_DEFAULT"
Assertion.AssertEquals( "Outbound Ethnicity", "99999", sp.Demographics.RaceList.ItemAt( 0 ).Code );
outboundEthnicityRule.NullBehavior = MappingBehavior.IfNullSuppress;
sp = new StudentPersonal();
MapOutbound( sp, mappings, map );
// Ethnicity should be null in this case because we told it to suppress
// set the "ifNull" behavior
Assertion.AssertNull( "Ethnicity should not be set", sp.Demographics.RaceList );
}
/**
* Asserts default value field mapping behavior
*
* @
*/
[Test]
public void testStudentContactMapping010()
{
StudentContact sc = new StudentContact();
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
IFieldAdaptor adaptor = createStudentContactFields();
mappings.MapOutbound( adaptor, sc );
SifWriter writer = new SifWriter( Console.Out );
writer.Write( sc );
writer.Flush();
Assertion.AssertEquals( "Testing Pickup Rights", "Yes", sc.ContactFlags.PickupRights );
}
/**
* @param sp
* @param mappings
* @param map
* @throws AdkMappingException
*/
private void MapOutbound( StudentPersonal sp, Mappings mappings, IDictionary map )
{
StringMapAdaptor adaptor = new StringMapAdaptor( map );
mappings.MapOutbound( adaptor, sp );
SifWriter writer = new SifWriter( Console.Out );
writer.Write( sp );
writer.Flush();
writer.Close();
}
[Test]
public void testValueSetMapping010()
{
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
ValueSet vs = mappings.GetValueSet( "Ethnicity", false );
// Normal Translation
Assertion.AssertEquals( "Translate", "A", vs.Translate( "1" ) );
Assertion.AssertEquals( "TranslateReverse", "1", vs.TranslateReverse( "A" ) );
// Default Values
Assertion.AssertEquals( "Translate", "ZZZ", vs.Translate( "foo", "ZZZ" ) );
Assertion.AssertEquals( "TranslateReverse", "AAA", vs.TranslateReverse( "foo",
"AAA" ) );
// Test Null behavior
Assertion.AssertNull( "TranslateNull", vs.Translate( null ) );
Assertion.AssertNull( "TranslateReverseNull", vs.TranslateReverse( null ) );
// No Match (this time should return what we pass in)
Assertion.AssertEquals( "TranslateNoMatch", "QQQQ", vs.Translate( "QQQQ" ) );
Assertion.AssertEquals( "TranslateReverseNoMath", "QQQQ", vs
.TranslateReverse( "QQQQ" ) );
// //////////////////////////////////
//
// Add an app default
//
// //////////////////////////////////
vs.SetAppDefault( "6", false );
// Normal Translation
Assertion.AssertEquals( "Translate", "A", vs.Translate( "1" ) );
Assertion.AssertEquals( "TranslateReverse", "1", vs.TranslateReverse( "A" ) );
// Default Values
Assertion.AssertEquals( "Translate", "ZZZ", vs.Translate( "foo", "ZZZ" ) );
Assertion.AssertEquals( "TranslateReverse", "AAA", vs.TranslateReverse( "foo",
"AAA" ) );
// Test Null behavior
Assertion.AssertNull( "TranslateNull", vs.Translate( null ) );
Assertion.AssertNull( "TranslateReverseNull", vs.TranslateReverse( null ) );
// No Match (this time should return a default for app value)
Assertion.AssertEquals( "TranslateNoMatch", "QQQQ", vs.Translate( "QQQQ" ) );
Assertion.AssertEquals( "TranslateReverseNoMath", "6", vs.TranslateReverse( "QQQQ" ) );
// ////////////////////////////////
//
// Add a SIF default
//
// //////////////////////////////////
vs.SetSifDefault( "H", false );
// Normal Translation
Assertion.AssertEquals( "Translate", "A", vs.Translate( "1" ) );
Assertion.AssertEquals( "TranslateReverse", "1", vs.TranslateReverse( "A" ) );
// Default Values
Assertion.AssertEquals( "Translate", "ZZZ", vs.Translate( "foo", "ZZZ" ) );
Assertion.AssertEquals( "TranslateReverse", "AAA", vs.TranslateReverse( "foo",
"AAA" ) );
// Test Null behavior
Assertion.AssertNull( "TranslateNull", vs.Translate( null ) );
Assertion.AssertNull( "TranslateReverseNull", vs.TranslateReverse( null ) );
// No Match (this time should return a default for app value and sif
// value)
Assertion.AssertEquals( "TranslateNoMatch", "H", vs.Translate( "QQQQ" ) );
Assertion.AssertEquals( "TranslateReverseNoMath", "6", vs.TranslateReverse( "QQQQ" ) );
// //////////////////////////////////
//
// Change the App and SIF Value and set it to render if null
//
// //////////////////////////////////
vs.SetSifDefault( "C", true );
vs.SetAppDefault( "7", true );
// Normal Translation
Assertion.AssertEquals( "Translate", "A", vs.Translate( "1" ) );
Assertion.AssertEquals( "TranslateReverse", "1", vs.TranslateReverse( "A" ) );
// Default Values
Assertion.AssertEquals( "Translate", "ZZZ", vs.Translate( "foo", "ZZZ" ) );
Assertion.AssertEquals( "TranslateReverse", "AAA", vs.TranslateReverse( "foo",
"AAA" ) );
// Test Null behavior
Assertion.AssertEquals( "TranslateNullReturnsDefault", "C", vs.Translate( null ) );
Assertion.AssertEquals( "TranslateReverseNullReturnsDefault", "7", vs
.TranslateReverse( null ) );
// No Match (this time should return a default for app value and sif
// value)
Assertion.AssertEquals( "TranslateNoMatch", "C", vs.Translate( "QQQQ" ) );
Assertion.AssertEquals( "TranslateReverseNoMath", "7", vs.TranslateReverse( "QQQQ" ) );
}
/**
* This test creates a StudentPersonal object and then builds it out using
* outbound mappings.
*
* Then, it uses the mappings again to rebuild a new Hashtable. The
* Hashtables are then compared to ensure that the resulting data is
* identical
*
* @
*/
[Test]
public void testStudentMappingAdk15Mappings()
{
StudentPersonal sp = new StudentPersonal();
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
IDictionary map = buildIDictionaryForStudentPersonalTest();
StringMapAdaptor adaptor = new StringMapAdaptor( map );
mappings.MapOutbound( adaptor, sp );
SifWriter writer = new SifWriter( Console.Out );
writer.Write( sp );
writer.Flush();
// Assert that the StudentPersonal object was mapped correctly
assertStudentPersonal( sp );
// Now, map the student personal back to a hashmap and assert it
IDictionary restoredData = new Hashtable();
adaptor.Dictionary = restoredData;
mappings.MapInbound( sp, adaptor );
assertMapsAreEqual( map, restoredData, "ALT_PHONE_TYPE" );
}
/**
* This test creates a StudentPlacement object and then builds it out using
* outbound mappings.
*
* Then, it uses the mappings again to rebuild a new Hashtable. The
* hashtables are then compared.
*
* @
*/
[Test]
public void testStudentPlacementMapping()
{
StudentPlacement sp = new StudentPlacement();
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
IDictionary map = buildIDictionaryForStudentPlacementTest();
StringMapAdaptor sma = new StringMapAdaptor( map );
mappings.MapOutbound( sma, sp );
sp = (StudentPlacement) AdkObjectParseHelper.WriteParseAndReturn( sp, fVersion );
// Assert that the StudentPlacement object was mapped correctly
assertStudentPlacement( sp );
// Now, map the StudentPlacement back to a hashmap and assert it
IDictionary restoredData = new Hashtable();
sma = new StringMapAdaptor( restoredData );
mappings.MapInbound( sp, sma );
assertMapsAreEqual( map, restoredData );
}
/**
* This test creates a StudentMeal object and then builds it out using
* outbound mappings.
*
* Then, it uses the mappings again to rebuild a new Hashtable. The
* hashtables are then compared.
*
* @
*/
[Test]
public void testStudentMealMappings()
{
StudentMeal sm = new StudentMeal();
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
IDictionary map = new Hashtable();
map.Add( "Balance", "10.55" );
StringMapAdaptor sma = new StringMapAdaptor( map );
mappings.MapOutbound( sma, sm );
sm = (StudentMeal) AdkObjectParseHelper.WriteParseAndReturn( sm, fVersion );
// Assert that the object was mapped correctly
FSAmounts amounts = sm.Amounts;
Assertion.AssertNotNull( amounts );
FSAmount amount = amounts.ItemAt( 0 );
Assertion.Assert( amount.Value.HasValue );
Assertion.AssertEquals( 10.55, amount.Value.Value );
// Now, map the object back to a hashmap and assert it
IDictionary restoredData = new Hashtable();
sma = new StringMapAdaptor( restoredData );
mappings.MapInbound( sm, sma );
assertMapsAreEqual( map, restoredData );
}
/**
* This test creates a SectionInfo object and then builds it out using
* outbound mappings.
*
* Then, it uses the mappings again to rebuild a new Hashtable. The
* hashtables are then compared.
*
* @
*/
[Test]
public void testSectionInfoMappings()
{
SectionInfo si = new SectionInfo();
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
IDictionary map = new Hashtable();
map.Add( "STAFF_REFID", "123456789ABCDEF" );
StringMapAdaptor sma = new StringMapAdaptor( map );
mappings.MapOutbound( sma, si );
si = (SectionInfo) AdkObjectParseHelper.WriteParseAndReturn( si, fVersion );
// Assert that the object was mapped correctly
ScheduleInfoList sil = si.ScheduleInfoList;
Assertion.AssertNotNull( sil );
ScheduleInfo schedule = sil.ItemAt( 0 );
Assertion.AssertNotNull( schedule );
TeacherList tl = schedule.TeacherList;
Assertion.AssertNotNull( tl );
StaffPersonalRefId refId = tl.ItemAt( 0 );
Assertion.AssertNotNull( refId );
Assertion.AssertEquals( "123456789ABCDEF", refId.Value );
// Now, map the object back to a hashmap and assert it
IDictionary restoredData = new Hashtable();
sma = new StringMapAdaptor( restoredData );
mappings.MapInbound( si, sma );
assertMapsAreEqual( map, restoredData );
}
protected abstract IDictionary buildIDictionaryForStudentPlacementTest();
protected abstract void assertStudentPlacement( StudentPlacement sp );
private void assertByXPath( SifXPathContext context, String xPath,
String assertedValue )
{
Element e = (Element) context.GetValue( xPath );
Assertion.AssertNotNull( "Field is null for path " + xPath, e );
SifSimpleType value = e.SifValue;
Assertion.AssertNotNull( "Value is null for path " + xPath, value );
Assertion.AssertEquals( xPath, assertedValue, value.ToString() );
}
protected StringMapAdaptor createStudentContactFields()
{
IDictionary values = new Hashtable();
values.Add( "APRN.SOCSECNUM", "123456789" );
values.Add( "APRN.SCHOOLNUM", "999" );
values.Add( "APRN.SCHOOLNUM2", "999" );
values.Add( "APRN.EMAILADDR", null );
values.Add( "APRN.LASTNAME", "DOE" );
values.Add( "APRN.FIRSTNAME", "JOHN" );
values.Add( "APRN.MIDDLENAME", null );
values.Add( "APRN.WRKADDR", null );
values.Add( "APRN.WRKCITY", null );
values.Add( "APRN.WRKSTATE", null );
values.Add( "APRN.WRKCOUNTRY", null );
values.Add( "APRN.WRKZIP", "54494" );
values.Add( "APRN.ADDRESS", null );
values.Add( "APRN.CITY", null );
values.Add( "APRN.STATE", null );
values.Add( "APRN.COUNTRY", null );
values.Add( "APRN.ZIPCODE", null );
values.Add( "APRN.TELEPHONE", "8014504555" );
values.Add( "APRN.ALTTEL", "8014505555" );
values.Add( "APRN.WRKTEL", null );
values.Add( "APRN.WRKEXTN", null );
values.Add( "APRN.RELATION", "01" );
values.Add( "APRN.PICKUPRIGHTS", "Yes" );
StringMapAdaptor sma = new StringMapAdaptor( values );
return sma;
}
[Test]
public void StudentMapping()
{
StudentPersonal sp = new StudentPersonal();
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
IDictionary map = buildIDictionaryForStudentPersonalTest();
StringMapAdaptor sma = new StringMapAdaptor( map );
mappings.MapOutbound( sma, sp );
SifWriter writer = new SifWriter( Console.Out );
writer.Write( sp );
writer.Flush();
// Assert that the StudentPersonal object was mapped correctly
assertStudentPersonal( sp );
// Now, map the student personal back to a hashmap and assert it
IDictionary restoredData = new HybridDictionary();
StringMapAdaptor restorer = new StringMapAdaptor( restoredData );
mappings.MapInbound( sp, restorer );
assertDictionariesAreEqual( restoredData, map );
}
[Test]
public void StudentPlacementMapping()
{
StudentPlacement sp = new StudentPlacement();
Mappings mappings = fCfg.Mappings.GetMappings( "Default" );
IDictionary map = buildIDictionaryForStudentPlacementTest();
StringMapAdaptor sma = new StringMapAdaptor( map );
mappings.MapOutbound( sma, sp );
SifWriter writer = new SifWriter( Console.Out );
writer.Write( sp );
writer.Flush();
// Assert that the StudentPersonal object was mapped correctly
assertStudentParticipation( sp );
// Now, map the student personal back to a hashmap and assert it
IDictionary restoredData = new HybridDictionary();
StringMapAdaptor restorer = new StringMapAdaptor( restoredData );
mappings.MapInbound( sp, restorer );
assertDictionariesAreEqual( map, restoredData );
}
private IDictionary buildIDictionaryForStudentPersonalTest()
{
IDictionary data = new Hashtable();
data.Add( "STUDENT_NUM", "998" );
data.Add( "LAST_NAME", "Johnson" );
data.Add( "MIDDLE_NAME", "George" );
data.Add( "FIRST_NAME", "Betty" );
data.Add( "BIRTHDATE", "19900101" );
data.Add( "ETHNICITY", "4" );
data.Add( "HOME_PHONE", "202-358-6687" );
data.Add( "CELL_PHONE", "202-502-4856" );
data.Add( "ALT_PHONE", "201-668-1245" );
data.Add( "ALT_PHONE_TYPE", "TE" );
data.Add( "ACTUALGRADYEAR", "2007" );
data.Add( "ORIGINALGRADYEAR", "2005" );
data.Add( "PROJECTEDGRADYEAR", "2007" );
data.Add( "ADDR1", "321 Oak St" );
data.Add( "ADDR2", "APT 11" );
data.Add( "CITY", "Metropolis" );
data.Add( "STATE", "IL" );
data.Add( "COUNTRY", "US" );
data.Add( "ZIPCODE", "321546" );
return data;
}
private void assertStudentParticipation( StudentPlacement sp )
{
Assert.AreEqual( "0000000000000000", sp.RefId, "RefID" );
Assert.AreEqual("0000000000000000", sp.StudentPersonalRefId, "StudentPersonalRefid");
Assert.AreEqual("Local", sp.Service.CodeType, "Code Type");
Assert.AreEqual("Related Service", sp.Service.Type, "Type");
Assert.AreEqual("ZZZ99987", sp.Service.TextValue, "Service");
}
private void assertStudentPersonal( StudentPersonal sp )
{
DateTime birthDate = new DateTime( 1990, 1, 1 );
Assertion.AssertEquals( "First Name", "Betty", sp.Name.FirstName );
Assertion.AssertEquals( "Middle Name", "George", sp.Name.MiddleName );
Assertion.AssertEquals( "Last Name", "Johnson", sp.Name.LastName );
Assertion.AssertEquals( "Student Number", "998", sp.OtherIdList.ItemAt( 0 ).TextValue );
Assertion.AssertEquals( "Birthdate", birthDate, sp.Demographics.BirthDate.Value );
Assertion.AssertEquals( "Ethnicity", "H", sp.Demographics.RaceList.ItemAt( 0 ).Code );
PhoneNumberList pnl = sp.PhoneNumberList;
Assertion.AssertNotNull( "PhoneNumberList", pnl );
PhoneNumber homePhone = pnl[PhoneNumberType.SIF1x_HOME_PHONE];
Assertion.AssertNotNull( "Home Phone is null", homePhone );
Assertion.AssertEquals( "Home Phone", "202-358-6687", homePhone
.Number );
PhoneNumber cellPhone = pnl
[PhoneNumberType.SIF1x_PERSONAL_CELL];
Assertion.AssertNotNull( "cellPhone Phone is null", cellPhone );
Assertion.AssertEquals( "Cell Phone", "202-502-4856", cellPhone.Number );
SifXPathContext xpathContext = SifXPathContext.NewSIFContext( sp, SifVersion.SIF20r1 );
assertByXPath( xpathContext, "AddressList/Address/Street/Line1",
"321 Oak St" );
assertByXPath( xpathContext, "AddressList/Address/Street/Line1",
"321 Oak St" );
assertByXPath( xpathContext, "AddressList/Address/Street/Line2",
"APT 11" );
assertByXPath( xpathContext, "AddressList/Address/City", "Metropolis" );
assertByXPath( xpathContext, "AddressList/Address/StateProvince", "IL" );
assertByXPath( xpathContext, "AddressList/Address/Country", "US" );
assertByXPath( xpathContext, "AddressList/Address/PostalCode", "321546" );
/*
* These assertions are currently commented out because the Adk does not
* currently support Repeatable elements that have wildcard attributes
*
* PhoneNumber number = sp.PhoneNumber( PhoneNumberType.PHONE );
* Assertion.AssertNotNull( "Alternate Phone Element is null", number );
* Assertion.AssertEquals( "Alternate Phone", "201-668-1245",
* number.ToString() );
*/
Assertion.AssertEquals( "OriginalGradYear", 2005, sp.OnTimeGraduationYear.Value );
Assertion.AssertEquals( "Projected", 2007, sp.ProjectedGraduationYear.Value );
Assertion.AssertNotNull( "Actual Grad Year", sp.GraduationDate.Value );
Assertion.AssertEquals( "OriginalGradYear", 2007, sp.GraduationDate.Year );
}
private void assertDictionariesAreEqual( IDictionary map1, IDictionary map2 )
{
foreach ( Object key in map1.Keys )
{
Assert.AreEqual( map1[key], map2[key], key.ToString() );
}
}
}
}
| |
// <copyright file="RiakMapReduceQuery.cs" company="Basho Technologies, Inc.">
// Copyright 2011 - OJ Reeves & Jeremiah Peschka
// Copyright 2014 - Basho Technologies, Inc.
//
// This file is provided 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.
// </copyright>
namespace RiakClient.Models.MapReduce
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Extensions;
using Fluent;
using Inputs;
using KeyFilters;
using Languages;
using Messages;
using Newtonsoft.Json;
using Phases;
/// <summary>
/// A fluent builder class for Riak MapReduce queries.
/// </summary>
public class RiakMapReduceQuery
{
private readonly List<RiakPhase> phases = new List<RiakPhase>();
private readonly string contentType = RiakConstants.ContentTypes.ApplicationJson;
private readonly int? timeout = null;
private string query;
private RiakPhaseInput inputs;
/// <summary>
/// Initializes a new instance of the <see cref="RiakMapReduceQuery"/> class.
/// </summary>
/// <remarks>
/// This overload defaults the content-type to "application/json", with the default timeout.
/// </remarks>
#pragma warning disable 618
public RiakMapReduceQuery()
: this(RiakConstants.ContentTypes.ApplicationJson, null)
#pragma warning restore 618
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RiakMapReduceQuery"/> class.
/// </summary>
/// <param name="timeout">The timeout period for the query, in milliseconds.</param>
/// <remarks>
/// This overload defaults the content-type to "application/json".
/// </remarks>
public RiakMapReduceQuery(int? timeout = null)
{
this.contentType = RiakConstants.ContentTypes.ApplicationJson;
this.timeout = timeout;
}
// TODO: Remove this overload - contentType is always json.
/// <summary>
/// Initializes a new instance of the <see cref="RiakMapReduceQuery"/> class.
/// </summary>
/// <param name="contentType">The query's return content-type.</param>
/// <param name="timeout">The timeout period for the query, in milliseconds.</param>
/// <exception cref="ArgumentException">The value of 'contentType' cannot be null, empty, or whitespace.</exception>
[Obsolete("This overload will be removed in the next version, please use the RiakMapReduceQuery() " +
"or RiakMapReduceQuery(int? timeout) overloads instead.")]
public RiakMapReduceQuery(string contentType, int? timeout = null)
{
if (string.IsNullOrWhiteSpace(contentType))
{
throw new ArgumentException("The value of 'contentType' cannot be null, empty, or whitespace.");
}
this.contentType = contentType;
this.timeout = timeout;
}
/// <summary>
/// The content-type of the mapreduce query.
/// </summary>
public string ContentType
{
get { return contentType; }
}
/// <summary>
/// The optional timeout for the mapreduce query.
/// </summary>
public int? Timeout
{
get { return timeout; }
}
/// <summary>
/// Add a bucket to the list of inputs.
/// </summary>
/// <param name="bucket">The Bucket to add to the list of inputs.</param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
public RiakMapReduceQuery Inputs(string bucket)
{
inputs = new RiakBucketInput(bucket);
return this;
}
/// <summary>
/// Add a bucket to the list of inputs.
/// </summary>
/// <param name="bucketType">The bucket type containing the bucket to use as input.</param>
/// <param name="bucket">The BucketType/Bucket to add to the list of inputs.</param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
public RiakMapReduceQuery Inputs(string bucketType, string bucket)
{
inputs = new RiakBucketInput(bucketType, bucket);
return this;
}
/// <summary>
/// Add a bucket-based legacy search input to the list of inputs.
/// </summary>
/// <param name="riakBucketSearchInput">The <see cref="RiakBucketSearchInput"/> to add to the list of inputs.</param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
[Obsolete("Using Legacy Search as input for MapReduce is deprecated. Please move to Riak 2.0 Search, and use the RiakSearchInput class instead.")]
public RiakMapReduceQuery Inputs(RiakBucketSearchInput riakBucketSearchInput)
{
inputs = riakBucketSearchInput;
return this;
}
/// <summary>
/// Add an index-based search input to the list of inputs.
/// </summary>
/// <param name="riakSearchInput">The <see cref="RiakSearchInput"/> to add to the list of inputs.</param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
/// <remarks>Riak 2.0+ only.</remarks>
public RiakMapReduceQuery Inputs(RiakSearchInput riakSearchInput)
{
inputs = riakSearchInput;
return this;
}
/// <summary>
/// Add a collection of <see cref="RiakObjectId"/>'s to the list of inputs.
/// </summary>
/// <param name="riakBucketKeyInputs">The <see cref="RiakBucketKeyInput"/> to add to the list of inputs.</param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
public RiakMapReduceQuery Inputs(RiakBucketKeyInput riakBucketKeyInputs)
{
inputs = riakBucketKeyInputs;
return this;
}
/// <summary>
/// Add a collection of <see cref="RiakObjectId"/> / KeyData sets to the list of inputs.
/// </summary>
/// <param name="riakBucketKeyKeyDataInputs">The <see cref="RiakBucketKeyKeyDataInput"/> to add to the list of inputs.</param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
public RiakMapReduceQuery Inputs(RiakBucketKeyKeyDataInput riakBucketKeyKeyDataInputs)
{
inputs = riakBucketKeyKeyDataInputs;
return this;
}
/// <summary>
/// Add an Erlang Module/Function/Arg combo to the list of inputs.
/// </summary>
/// <param name="riakModFunArgsInput">The <see cref="RiakModuleFunctionArgInput"/> to add to the list of inputs.</param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
public RiakMapReduceQuery Inputs(RiakModuleFunctionArgInput riakModFunArgsInput)
{
inputs = riakModFunArgsInput;
return this;
}
/// <summary>
/// Add a secondary index query to the list of inputs.
/// </summary>
/// <param name="riakIndexPhaseInput">The <see cref="RiakIndexInput"/> to add to the list of inputs.</param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
public RiakMapReduceQuery Inputs(RiakIndexInput riakIndexPhaseInput)
{
inputs = riakIndexPhaseInput;
return this;
}
/// <summary>
/// Add an Erlang map phase to the list of phases.
/// </summary>
/// <param name="setup">
/// An <see cref="Action{T}"/> that accepts a <see cref="RiakFluentActionPhaseJavascript"/>,
/// and configures the map phase with it.
/// </param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
/// <remarks>
/// Configure the phase with a lambda similar to:
/// <code>.MapErlang(m => m.ModFun("riak_kv_mapreduce", "map_object_value"))</code>
/// The above code will run the "riak_kv_mapreduce:map_object_value" Erlang function on each input in the phase..
/// </remarks>
public RiakMapReduceQuery MapErlang(Action<RiakFluentActionPhaseErlang> setup)
{
var phase = new RiakMapPhase<RiakPhaseLanguageErlang>();
var fluent = new RiakFluentActionPhaseErlang(phase);
setup(fluent);
phases.Add(phase);
return this;
}
/// <summary>
/// Add a JavaScript map phase to the list of phases.
/// </summary>
/// <param name="setup">
/// An <see cref="Action{T}"/> that accepts a <see cref="RiakFluentActionPhaseJavascript"/>,
/// and configures the map phase with it.
/// </param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
/// <remarks>
/// Configure the phase with a lambda similar to:
/// <code>.MapJs(m => m.Source(@"function(o) {return [ 1 ];}"))</code>
/// The above code will run a custom JavaScript function that returns "[1]" for each input in the phase.
/// </remarks>
public RiakMapReduceQuery MapJs(Action<RiakFluentActionPhaseJavascript> setup)
{
var phase = new RiakMapPhase<RiakPhaseLanguageJavascript>();
var fluent = new RiakFluentActionPhaseJavascript(phase);
setup(fluent);
phases.Add(phase);
return this;
}
/// <summary>
/// Add an Erlang reduce phase to the list of phases.
/// </summary>
/// <param name="setup">
/// An <see cref="Action{T}"/> that accepts a <see cref="RiakFluentActionPhaseErlang"/>,
/// and configures the reduce phase with it.
/// </param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
/// <remarks>
/// Configure the phase with a lambda similar to:
/// <code>.ReduceErlang(r => r.ModFun("riak_kv_mapreduce", "reduce_set_union")</code>
/// The code above will run the "riak_kv_mapreduce:reduce_set_union" Erlang function on the phase inputs.
/// </remarks>
public RiakMapReduceQuery ReduceErlang(Action<RiakFluentActionPhaseErlang> setup)
{
var phase = new RiakReducePhase<RiakPhaseLanguageErlang>();
var fluent = new RiakFluentActionPhaseErlang(phase);
setup(fluent);
phases.Add(phase);
return this;
}
/// <summary>
/// Add a JavaScript reduce phase to the list of phases.
/// </summary>
/// <param name="setup">
/// An <see cref="Action{T}"/> that accepts a <see cref="RiakFluentActionPhaseJavascript"/>,
/// and configures the reduce phase with it.
/// </param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
/// <remarks>
/// Configure the phase with a lambda similar to:
/// <code>.ReduceJs(r => r.Name(@"Riak.reduceSum");</code>
/// The code above will run the built-in JavaScript function "Riak.reduceSum" on the phase inputs.
/// </remarks>
public RiakMapReduceQuery ReduceJs(Action<RiakFluentActionPhaseJavascript> setup)
{
var phase = new RiakReducePhase<RiakPhaseLanguageJavascript>();
var fluent = new RiakFluentActionPhaseJavascript(phase);
setup(fluent);
phases.Add(phase);
return this;
}
#pragma warning disable 618
/// <summary>
/// Add a link phase to the list of phases.
/// </summary>
/// <param name="setup">
/// An <see cref="Action{T}"/> that accepts a <see cref="RiakFluentLinkPhase"/>,
/// and configures the link phase with it.
/// </param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
/// <remarks>
/// Configure the phase with a lambda similar to:
/// <code>.Link(l => l.Tag("friends");</code>
/// The code above will walk links with a tag of "friends".
/// </remarks>
[Obsolete("Linkwalking is a deprecated feature of Riak and will eventually be removed.")]
public RiakMapReduceQuery Link(Action<RiakFluentLinkPhase> setup)
{
var phase = new RiakLinkPhase();
var fluent = new RiakFluentLinkPhase(phase);
setup(fluent);
phases.Add(phase);
return this;
}
/// <summary>
/// Add a key filter input to the inputs.
/// </summary>
/// <param name="setup">
/// An <see cref="Action{T}"/> that accepts a <see cref="RiakFluentKeyFilter"/>,
/// and configures the input filter with it.
/// </param>
/// <returns>A reference to this updated instance, for fluent chaining.</returns>
/// <remarks>
/// Configure the phase with a lambda similar to:
/// <code>new RiakMapReduceQuery().Inputs("Bucketname").Filter(f => f.StartsWith("time"));</code>
/// The example above will filter out all keys that don't start with the string "time".
/// Please see the <see cref="Fluent.RiakFluentKeyFilter"/> for
/// more built-in filters.
/// </remarks>
[Obsolete("Key Filters are a deprecated feature of Riak and will eventually be removed.")]
public RiakMapReduceQuery Filter(Action<RiakFluentKeyFilter> setup)
{
var filters = new List<IRiakKeyFilterToken>();
var fluent = new RiakFluentKeyFilter(filters);
setup(fluent);
inputs.Filters.AddRange(filters);
return this;
}
#pragma warning restore 618
/// <summary>
/// Compile the mapreduce query.
/// </summary>
public void Compile()
{
Debug.Assert(inputs != null, "Compile inputs must not be null");
if (!string.IsNullOrWhiteSpace(query))
{
return;
}
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.WriteStartObject();
if (inputs != null)
{
inputs.WriteJson(writer);
}
writer.WritePropertyName("query");
writer.WriteStartArray();
phases.ForEach(p => writer.WriteRawValue(p.ToJsonString()));
writer.WriteEndArray();
if (timeout.HasValue)
{
writer.WriteProperty<int>("timeout", timeout.Value);
}
writer.WriteEndObject();
}
}
query = sb.ToString();
}
internal RpbMapRedReq ToMessage()
{
Compile();
var message = new RpbMapRedReq
{
request = query.ToRiakString(),
content_type = contentType.ToRiakString()
};
return message;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Globalization;
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>
/// This data structure implements IDictionary first using a linked list
/// (ListDictionary) and then switching over to use Hashtable when large. This is recommended
/// for cases where the number of elements in a dictionary is unknown and might be small.
///
/// It also has a single boolean parameter to allow case-sensitivity that is not affected by
/// ambient culture and has been optimized for looking up case-insensitive symbols
/// </para>
/// </devdoc>
public class HybridDictionary : IDictionary
{
// These numbers have been carefully tested to be optimal. Please don't change them
// without doing thorough performance testing.
private const int CutoverPoint = 9;
private const int InitialHashtableSize = 13;
private const int FixedSizeCutoverPoint = 6;
// Instance variables. This keeps the HybridDictionary very light-weight when empty
private ListDictionary _list;
private Hashtable _hashtable;
private readonly bool _caseInsensitive;
public HybridDictionary()
{
}
public HybridDictionary(int initialSize) : this(initialSize, false)
{
}
public HybridDictionary(bool caseInsensitive)
{
_caseInsensitive = caseInsensitive;
}
public HybridDictionary(int initialSize, bool caseInsensitive)
{
_caseInsensitive = caseInsensitive;
if (initialSize >= FixedSizeCutoverPoint)
{
if (caseInsensitive)
{
_hashtable = new Hashtable(initialSize, StringComparer.OrdinalIgnoreCase);
}
else
{
_hashtable = new Hashtable(initialSize);
}
}
}
public object this[object key]
{
get
{
// Hashtable supports multiple read, one writer thread safety.
// Although we never made the same guarantee for HybridDictionary,
// it is still nice to do the same thing here since we have recommended
// HybridDictionary as replacement for Hashtable.
ListDictionary cachedList = _list;
if (_hashtable != null)
{
return _hashtable[key];
}
else if (cachedList != null)
{
return cachedList[key];
}
else
{
// cachedList can be null in too cases:
// (1) The dictionary is empty, we will return null in this case
// (2) There is writer which is doing ChangeOver. However in that case
// we should see the change to hashtable as well.
// So it should work just fine.
if (key == null)
{
throw new ArgumentNullException("key", SR.ArgumentNull_Key);
}
return null;
}
}
set
{
if (_hashtable != null)
{
_hashtable[key] = value;
}
else if (_list != null)
{
if (_list.Count >= CutoverPoint - 1)
{
ChangeOver();
_hashtable[key] = value;
}
else
{
_list[key] = value;
}
}
else
{
_list = new ListDictionary(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null);
_list[key] = value;
}
}
}
private ListDictionary List
{
get
{
if (_list == null)
{
_list = new ListDictionary(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null);
}
return _list;
}
}
private void ChangeOver()
{
IDictionaryEnumerator en = _list.GetEnumerator();
Hashtable newTable;
if (_caseInsensitive)
{
newTable = new Hashtable(InitialHashtableSize, StringComparer.OrdinalIgnoreCase);
}
else
{
newTable = new Hashtable(InitialHashtableSize);
}
while (en.MoveNext())
{
newTable.Add(en.Key, en.Value);
}
// Keep the order of writing to hashtable and list.
// We assume we will see the change in hashtable if list is set to null in
// this method in another reader thread.
_hashtable = newTable;
_list = null;
}
public int Count
{
get
{
ListDictionary cachedList = _list;
if (_hashtable != null)
{
return _hashtable.Count;
}
else if (cachedList != null)
{
return cachedList.Count;
}
else
{
return 0;
}
}
}
public ICollection Keys
{
get
{
if (_hashtable != null)
{
return _hashtable.Keys;
}
else
{
return List.Keys;
}
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool IsFixedSize
{
get
{
return false;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot
{
get
{
return this;
}
}
public ICollection Values
{
get
{
if (_hashtable != null)
{
return _hashtable.Values;
}
else
{
return List.Values;
}
}
}
public void Add(object key, object value)
{
if (_hashtable != null)
{
_hashtable.Add(key, value);
}
else
{
if (_list == null)
{
_list = new ListDictionary(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null);
_list.Add(key, value);
}
else
{
if (_list.Count + 1 >= CutoverPoint)
{
ChangeOver();
_hashtable.Add(key, value);
}
else
{
_list.Add(key, value);
}
}
}
}
public void Clear()
{
if (_hashtable != null)
{
Hashtable cachedHashtable = _hashtable;
_hashtable = null;
cachedHashtable.Clear();
}
if (_list != null)
{
ListDictionary cachedList = _list;
_list = null;
cachedList.Clear();
}
}
public bool Contains(object key)
{
ListDictionary cachedList = _list;
if (_hashtable != null)
{
return _hashtable.Contains(key);
}
else if (cachedList != null)
{
return cachedList.Contains(key);
}
else
{
if (key == null)
{
throw new ArgumentNullException("key", SR.ArgumentNull_Key);
}
return false;
}
}
public void CopyTo(Array array, int index)
{
if (_hashtable != null)
{
_hashtable.CopyTo(array, index);
}
else
{
List.CopyTo(array, index);
}
}
public IDictionaryEnumerator GetEnumerator()
{
if (_hashtable != null)
{
return _hashtable.GetEnumerator();
}
if (_list == null)
{
_list = new ListDictionary(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null);
}
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
if (_hashtable != null)
{
return _hashtable.GetEnumerator();
}
if (_list == null)
{
_list = new ListDictionary(_caseInsensitive ? StringComparer.OrdinalIgnoreCase : null);
}
return _list.GetEnumerator();
}
public void Remove(object key)
{
if (_hashtable != null)
{
_hashtable.Remove(key);
}
else if (_list != null)
{
_list.Remove(key);
}
else
{
if (key == null)
{
throw new ArgumentNullException("key", SR.ArgumentNull_Key);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Subscription
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SubscriptionDefinitionsOperations.
/// </summary>
public static partial class SubscriptionDefinitionsOperationsExtensions
{
/// <summary>
/// Create an Azure subscription definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionDefinitionName'>
/// The name of the Azure subscription definition.
/// </param>
/// <param name='body'>
/// The subscription definition creation.
/// </param>
public static SubscriptionDefinition Create(this ISubscriptionDefinitionsOperations operations, string subscriptionDefinitionName, SubscriptionDefinition body)
{
return operations.CreateAsync(subscriptionDefinitionName, body).GetAwaiter().GetResult();
}
/// <summary>
/// Create an Azure subscription definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionDefinitionName'>
/// The name of the Azure subscription definition.
/// </param>
/// <param name='body'>
/// The subscription definition creation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SubscriptionDefinition> CreateAsync(this ISubscriptionDefinitionsOperations operations, string subscriptionDefinitionName, SubscriptionDefinition body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(subscriptionDefinitionName, body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get an Azure subscription definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionDefinitionName'>
/// The name of the Azure subscription definition.
/// </param>
public static SubscriptionDefinition Get(this ISubscriptionDefinitionsOperations operations, string subscriptionDefinitionName)
{
return operations.GetAsync(subscriptionDefinitionName).GetAwaiter().GetResult();
}
/// <summary>
/// Get an Azure subscription definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionDefinitionName'>
/// The name of the Azure subscription definition.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SubscriptionDefinition> GetAsync(this ISubscriptionDefinitionsOperations operations, string subscriptionDefinitionName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(subscriptionDefinitionName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List an Azure subscription definition by subscriptionId.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<SubscriptionDefinition> List(this ISubscriptionDefinitionsOperations operations)
{
return operations.ListAsync().GetAwaiter().GetResult();
}
/// <summary>
/// List an Azure subscription definition by subscriptionId.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SubscriptionDefinition>> ListAsync(this ISubscriptionDefinitionsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieves the status of the subscription definition PUT operation. The URI
/// of this API is returned in the Location field of the response header.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='operationId'>
/// The operation ID, which can be found from the Location field in the
/// generate recommendation response header.
/// </param>
public static SubscriptionDefinition GetOperationStatus(this ISubscriptionDefinitionsOperations operations, System.Guid operationId)
{
return operations.GetOperationStatusAsync(operationId).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves the status of the subscription definition PUT operation. The URI
/// of this API is returned in the Location field of the response header.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='operationId'>
/// The operation ID, which can be found from the Location field in the
/// generate recommendation response header.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SubscriptionDefinition> GetOperationStatusAsync(this ISubscriptionDefinitionsOperations operations, System.Guid operationId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOperationStatusWithHttpMessagesAsync(operationId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create an Azure subscription definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionDefinitionName'>
/// The name of the Azure subscription definition.
/// </param>
/// <param name='body'>
/// The subscription definition creation.
/// </param>
public static SubscriptionDefinition BeginCreate(this ISubscriptionDefinitionsOperations operations, string subscriptionDefinitionName, SubscriptionDefinition body)
{
return operations.BeginCreateAsync(subscriptionDefinitionName, body).GetAwaiter().GetResult();
}
/// <summary>
/// Create an Azure subscription definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='subscriptionDefinitionName'>
/// The name of the Azure subscription definition.
/// </param>
/// <param name='body'>
/// The subscription definition creation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SubscriptionDefinition> BeginCreateAsync(this ISubscriptionDefinitionsOperations operations, string subscriptionDefinitionName, SubscriptionDefinition body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(subscriptionDefinitionName, body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List an Azure subscription definition by subscriptionId.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SubscriptionDefinition> ListNext(this ISubscriptionDefinitionsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// List an Azure subscription definition by subscriptionId.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SubscriptionDefinition>> ListNextAsync(this ISubscriptionDefinitionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Microsoft.Extensions.PlatformAbstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Extensions.DependencyModel
{
public class DependencyContextWriter
{
public void Write(DependencyContext context, Stream stream)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
using (var writer = new StreamWriter(stream))
{
using (var jsonWriter = new JsonTextWriter(writer) { Formatting = Formatting.Indented })
{
Write(context).WriteTo(jsonWriter);
}
}
}
private JObject Write(DependencyContext context)
{
var contextObject = new JObject(
new JProperty(DependencyContextStrings.RuntimeTargetPropertyName, WriteRuntimeTargetInfo(context)),
new JProperty(DependencyContextStrings.CompilationOptionsPropertName, WriteCompilationOptions(context.CompilationOptions)),
new JProperty(DependencyContextStrings.TargetsPropertyName, WriteTargets(context)),
new JProperty(DependencyContextStrings.LibrariesPropertyName, WriteLibraries(context))
);
if (context.RuntimeGraph.Any())
{
contextObject.Add(new JProperty(DependencyContextStrings.RuntimesPropertyName, WriteRuntimeGraph(context)));
}
return contextObject;
}
private JObject WriteRuntimeTargetInfo(DependencyContext context)
{
return new JObject(
new JProperty(DependencyContextStrings.RuntimeTargetNamePropertyName,
context.Target.IsPortable ?
context.Target.Framework :
context.Target.Framework + DependencyContextStrings.VersionSeperator + context.Target.Runtime
),
new JProperty(DependencyContextStrings.RuntimeTargetSignaturePropertyName,
context.Target.RuntimeSignature
)
);
}
private JObject WriteRuntimeGraph(DependencyContext context)
{
return new JObject(
context.RuntimeGraph.Select(g => new JProperty(g.Runtime, new JArray(g.Fallbacks)))
);
}
private JObject WriteCompilationOptions(CompilationOptions compilationOptions)
{
var o = new JObject();
if (compilationOptions.Defines?.Any() == true)
{
o[DependencyContextStrings.DefinesPropertyName] = new JArray(compilationOptions.Defines);
}
AddPropertyIfNotNull(o, DependencyContextStrings.LanguageVersionPropertyName, compilationOptions.LanguageVersion);
AddPropertyIfNotNull(o, DependencyContextStrings.PlatformPropertyName, compilationOptions.Platform);
AddPropertyIfNotNull(o, DependencyContextStrings.AllowUnsafePropertyName, compilationOptions.AllowUnsafe);
AddPropertyIfNotNull(o, DependencyContextStrings.WarningsAsErrorsPropertyName, compilationOptions.WarningsAsErrors);
AddPropertyIfNotNull(o, DependencyContextStrings.OptimizePropertyName, compilationOptions.Optimize);
AddPropertyIfNotNull(o, DependencyContextStrings.KeyFilePropertyName, compilationOptions.KeyFile);
AddPropertyIfNotNull(o, DependencyContextStrings.DelaySignPropertyName, compilationOptions.DelaySign);
AddPropertyIfNotNull(o, DependencyContextStrings.PublicSignPropertyName, compilationOptions.PublicSign);
AddPropertyIfNotNull(o, DependencyContextStrings.EmitEntryPointPropertyName, compilationOptions.EmitEntryPoint);
AddPropertyIfNotNull(o, DependencyContextStrings.GenerateXmlDocumentationPropertyName, compilationOptions.GenerateXmlDocumentation);
AddPropertyIfNotNull(o, DependencyContextStrings.DebugTypePropertyName, compilationOptions.DebugType);
return o;
}
private void AddPropertyIfNotNull<T>(JObject o, string name, T value)
{
if (value != null)
{
o.Add(new JProperty(name, value));
}
}
private JObject WriteTargets(DependencyContext context)
{
if (context.Target.IsPortable)
{
return new JObject(
new JProperty(context.Target.Framework, WritePortableTarget(context.RuntimeLibraries, context.CompileLibraries))
);
}
return new JObject(
new JProperty(context.Target.Framework, WriteTarget(context.CompileLibraries)),
new JProperty(context.Target.Framework + DependencyContextStrings.VersionSeperator + context.Target.Runtime,
WriteTarget(context.RuntimeLibraries))
);
}
private JObject WriteTarget(IReadOnlyList<Library> libraries)
{
return new JObject(
libraries.Select(library =>
new JProperty(library.Name + DependencyContextStrings.VersionSeperator + library.Version, WriteTargetLibrary(library))));
}
private JObject WritePortableTarget(IReadOnlyList<RuntimeLibrary> runtimeLibraries, IReadOnlyList<CompilationLibrary> compilationLibraries)
{
var runtimeLookup = runtimeLibraries.ToDictionary(l => l.Name);
var compileLookup = compilationLibraries.ToDictionary(l => l.Name);
var targetObject = new JObject();
foreach (var packageName in runtimeLookup.Keys.Concat(compileLookup.Keys).Distinct())
{
RuntimeLibrary runtimeLibrary;
runtimeLookup.TryGetValue(packageName, out runtimeLibrary);
CompilationLibrary compilationLibrary;
compileLookup.TryGetValue(packageName, out compilationLibrary);
if (compilationLibrary != null && runtimeLibrary != null)
{
Debug.Assert(compilationLibrary.Serviceable == runtimeLibrary.Serviceable);
Debug.Assert(compilationLibrary.Version == runtimeLibrary.Version);
Debug.Assert(compilationLibrary.Hash == runtimeLibrary.Hash);
Debug.Assert(compilationLibrary.Type == runtimeLibrary.Type);
}
var library = (Library)compilationLibrary ?? (Library)runtimeLibrary;
targetObject.Add(
new JProperty(library.Name + DependencyContextStrings.VersionSeperator + library.Version,
WritePortableTargetLibrary(runtimeLibrary, compilationLibrary)
)
);
}
return targetObject;
}
private void AddCompilationAssemblies(JObject libraryObject, IEnumerable<string> compilationAssemblies)
{
if (!compilationAssemblies.Any())
{
return;
}
libraryObject.Add(new JProperty(DependencyContextStrings.CompileTimeAssembliesKey,
WriteAssetList(compilationAssemblies))
);
}
private void AddAssets(JObject libraryObject, string key, RuntimeAssetGroup group)
{
if (group == null || !group.AssetPaths.Any())
{
return;
}
libraryObject.Add(new JProperty(key,
WriteAssetList(group.AssetPaths))
);
}
private void AddDependencies(JObject libraryObject, IEnumerable<Dependency> dependencies)
{
if (!dependencies.Any())
{
return;
}
libraryObject.AddFirst(
new JProperty(DependencyContextStrings.DependenciesPropertyName,
new JObject(
dependencies.Select(dependency => new JProperty(dependency.Name, dependency.Version))))
);
}
private void AddResourceAssemblies(JObject libraryObject, IEnumerable<ResourceAssembly> resourceAssemblies)
{
if (!resourceAssemblies.Any())
{
return;
}
libraryObject.Add(DependencyContextStrings.ResourceAssembliesPropertyName,
new JObject(resourceAssemblies.Select(a =>
new JProperty(NormalizePath(a.Path), new JObject(new JProperty(DependencyContextStrings.LocalePropertyName, a.Locale))))
)
);
}
private JObject WriteTargetLibrary(Library library)
{
var runtimeLibrary = library as RuntimeLibrary;
if (runtimeLibrary != null)
{
var libraryObject = new JObject();
AddDependencies(libraryObject, runtimeLibrary.Dependencies);
// Add runtime-agnostic assets
AddAssets(libraryObject, DependencyContextStrings.RuntimeAssembliesKey, runtimeLibrary.RuntimeAssemblyGroups.GetDefaultGroup());
AddAssets(libraryObject, DependencyContextStrings.NativeLibrariesKey, runtimeLibrary.NativeLibraryGroups.GetDefaultGroup());
AddResourceAssemblies(libraryObject, runtimeLibrary.ResourceAssemblies);
return libraryObject;
}
var compilationLibrary = library as CompilationLibrary;
if (compilationLibrary != null)
{
var libraryObject = new JObject();
AddDependencies(libraryObject, compilationLibrary.Dependencies);
AddCompilationAssemblies(libraryObject, compilationLibrary.Assemblies);
return libraryObject;
}
throw new NotSupportedException();
}
private JObject WritePortableTargetLibrary(RuntimeLibrary runtimeLibrary, CompilationLibrary compilationLibrary)
{
var libraryObject = new JObject();
var dependencies = new HashSet<Dependency>();
if (runtimeLibrary != null)
{
// Add runtime-agnostic assets
AddAssets(libraryObject, DependencyContextStrings.RuntimeAssembliesKey, runtimeLibrary.RuntimeAssemblyGroups.GetDefaultGroup());
AddAssets(libraryObject, DependencyContextStrings.NativeLibrariesKey, runtimeLibrary.NativeLibraryGroups.GetDefaultGroup());
AddResourceAssemblies(libraryObject, runtimeLibrary.ResourceAssemblies);
// Add runtime-specific assets
var runtimeTargets = new JObject();
AddRuntimeSpecificAssetGroups(runtimeTargets, DependencyContextStrings.RuntimeAssetType, runtimeLibrary.RuntimeAssemblyGroups);
AddRuntimeSpecificAssetGroups(runtimeTargets, DependencyContextStrings.NativeAssetType, runtimeLibrary.NativeLibraryGroups);
if (runtimeTargets.Count > 0)
{
libraryObject.Add(DependencyContextStrings.RuntimeTargetsPropertyName, runtimeTargets);
}
dependencies.UnionWith(runtimeLibrary.Dependencies);
}
if (compilationLibrary != null)
{
AddCompilationAssemblies(libraryObject, compilationLibrary.Assemblies);
dependencies.UnionWith(compilationLibrary.Dependencies);
}
AddDependencies(libraryObject, dependencies);
return libraryObject;
}
private void AddRuntimeSpecificAssetGroups(JObject runtimeTargets, string assetType, IEnumerable<RuntimeAssetGroup> assetGroups)
{
foreach (var group in assetGroups.Where(g => !string.IsNullOrEmpty(g.Runtime)))
{
if (group.AssetPaths.Any())
{
AddRuntimeSpecificAssets(runtimeTargets, group.AssetPaths, group.Runtime, assetType);
}
else
{
// Add a placeholder item
// We need to generate a pseudo-path because there could be multiple different asset groups with placeholders
// Only the last path segment matters, the rest is basically just a GUID.
var pseudoPathFolder = assetType == DependencyContextStrings.RuntimeAssetType ?
"lib" :
"native";
runtimeTargets[$"runtime/{group.Runtime}/{pseudoPathFolder}/_._"] = new JObject(
new JProperty(DependencyContextStrings.RidPropertyName, group.Runtime),
new JProperty(DependencyContextStrings.AssetTypePropertyName, assetType));
}
}
}
private void AddRuntimeSpecificAssets(JObject target, IEnumerable<string> assets, string runtime, string assetType)
{
foreach (var asset in assets)
{
target.Add(new JProperty(NormalizePath(asset),
new JObject(
new JProperty(DependencyContextStrings.RidPropertyName, runtime),
new JProperty(DependencyContextStrings.AssetTypePropertyName, assetType)
)
));
}
}
private JObject WriteAssetList(IEnumerable<string> assetPaths)
{
return new JObject(assetPaths.Select(assembly => new JProperty(NormalizePath(assembly), new JObject())));
}
private JObject WriteLibraries(DependencyContext context)
{
var allLibraries =
context.RuntimeLibraries.Cast<Library>().Concat(context.CompileLibraries)
.GroupBy(library => library.Name + DependencyContextStrings.VersionSeperator + library.Version);
return new JObject(allLibraries.Select(libraries => new JProperty(libraries.Key, WriteLibrary(libraries.First()))));
}
private JObject WriteLibrary(Library library)
{
return new JObject(
new JProperty(DependencyContextStrings.TypePropertyName, library.Type),
new JProperty(DependencyContextStrings.ServiceablePropertyName, library.Serviceable),
new JProperty(DependencyContextStrings.Sha512PropertyName, library.Hash)
);
}
private string NormalizePath(string path)
{
return path.Replace('\\', '/');
}
}
}
| |
//
// X509CertificateCollectionTest.cs: Unit tests for X509CertificationCollection
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2004 Novell (http://www.novell.com)
//
using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using NUnit.Framework;
namespace MonoTests.System.Security.Cryptography.X509Certificates {
[TestFixture]
public class X509CertificateCollectionTest : Assertion {
private static byte[] cert_a = { 0x30,0x82,0x01,0xFF,0x30,0x82,0x01,0x6C,0x02,0x05,0x02,0x72,0x00,0x06,0xE8,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x02,0x05,0x00,0x30,0x5F,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x0A,0x13,0x17,0x52,0x53,0x41,0x20,0x44,0x61,0x74,0x61,0x20,0x53,0x65,0x63,0x75,0x72,0x69,0x74,0x79,0x2C,0x20,0x49,0x6E,0x63,0x2E,0x31,0x2E,0x30,0x2C,0x06,0x03,0x55,0x04,0x0B,0x13,0x25,0x53,0x65,0x63,0x75,0x72,0x65,0x20,0x53,0x65,0x72,0x76,
0x65,0x72,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x1E,0x17,0x0D,0x39,0x36,0x30,0x33,0x31,0x32,0x31,0x38,0x33,0x38,0x34,0x37,0x5A,0x17,0x0D,0x39,0x37,0x30,0x33,0x31,0x32,0x31,0x38,0x33,0x38,0x34,0x36,0x5A,0x30,0x61,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x13,0x30,0x11,0x06,0x03,0x55,0x04,0x08,0x13,0x0A,0x43,0x61,0x6C,0x69,0x66,0x6F,0x72,0x6E,0x69,0x61,0x31,0x14,0x30,0x12,0x06,0x03,
0x55,0x04,0x0A,0x13,0x0B,0x43,0x6F,0x6D,0x6D,0x65,0x72,0x63,0x65,0x4E,0x65,0x74,0x31,0x27,0x30,0x25,0x06,0x03,0x55,0x04,0x0B,0x13,0x1E,0x53,0x65,0x72,0x76,0x65,0x72,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6F,0x6E,0x20,0x41,0x75,0x74,0x68,0x6F,0x72,0x69,0x74,0x79,0x30,0x70,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x5F,0x00,0x30,0x5C,0x02,0x55,0x2D,0x58,0xE9,0xBF,0xF0,0x31,0xCD,0x79,0x06,0x50,0x5A,0xD5,0x9E,0x0E,0x2C,0xE6,0xC2,0xF7,0xF9,
0xD2,0xCE,0x55,0x64,0x85,0xB1,0x90,0x9A,0x92,0xB3,0x36,0xC1,0xBC,0xEA,0xC8,0x23,0xB7,0xAB,0x3A,0xA7,0x64,0x63,0x77,0x5F,0x84,0x22,0x8E,0xE5,0xB6,0x45,0xDD,0x46,0xAE,0x0A,0xDD,0x00,0xC2,0x1F,0xBA,0xD9,0xAD,0xC0,0x75,0x62,0xF8,0x95,0x82,0xA2,0x80,0xB1,0x82,0x69,0xFA,0xE1,0xAF,0x7F,0xBC,0x7D,0xE2,0x7C,0x76,0xD5,0xBC,0x2A,0x80,0xFB,0x02,0x03,0x01,0x00,0x01,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x02,0x05,0x00,0x03,0x7E,0x00,0x54,0x20,0x67,0x12,0xBB,0x66,0x14,0xC3,0x26,0x6B,0x7F,
0xDA,0x4A,0x25,0x4D,0x8B,0xE0,0xFD,0x1E,0x53,0x6D,0xAC,0xA2,0xD0,0x89,0xB8,0x2E,0x90,0xA0,0x27,0x43,0xA4,0xEE,0x4A,0x26,0x86,0x40,0xFF,0xB8,0x72,0x8D,0x1E,0xE7,0xB7,0x77,0xDC,0x7D,0xD8,0x3F,0x3A,0x6E,0x55,0x10,0xA6,0x1D,0xB5,0x58,0xF2,0xF9,0x0F,0x2E,0xB4,0x10,0x55,0x48,0xDC,0x13,0x5F,0x0D,0x08,0x26,0x88,0xC9,0xAF,0x66,0xF2,0x2C,0x9C,0x6F,0x3D,0xC3,0x2B,0x69,0x28,0x89,0x40,0x6F,0x8F,0x35,0x3B,0x9E,0xF6,0x8E,0xF1,0x11,0x17,0xFB,0x0C,0x98,0x95,0xA1,0xC2,0xBA,0x89,0x48,0xEB,0xB4,0x06,0x6A,0x22,0x54,
0xD7,0xBA,0x18,0x3A,0x48,0xA6,0xCB,0xC2,0xFD,0x20,0x57,0xBC,0x63,0x1C };
private static byte[] cert_b = { 0x30,0x82,0x01,0xDF,0x30,0x82,0x01,0x48,0x02,0x01,0x00,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x30,0x39,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x0D,0x30,0x0B,0x06,0x03,0x55,0x04,0x0A,0x14,0x04,0x41,0x54,0x26,0x54,0x31,0x1B,0x30,0x19,0x06,0x03,0x55,0x04,0x0B,0x14,0x12,0x44,0x69,0x72,0x65,0x63,0x74,0x6F,0x72,0x79,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x30,0x1E,0x17,0x0D,0x39,0x36,0x30,0x31,0x31,0x38,0x32,0x31,0x30,0x33,0x35,0x32,
0x5A,0x17,0x0D,0x30,0x31,0x30,0x31,0x31,0x36,0x32,0x31,0x30,0x33,0x35,0x32,0x5A,0x30,0x39,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x0D,0x30,0x0B,0x06,0x03,0x55,0x04,0x0A,0x14,0x04,0x41,0x54,0x26,0x54,0x31,0x1B,0x30,0x19,0x06,0x03,0x55,0x04,0x0B,0x14,0x12,0x44,0x69,0x72,0x65,0x63,0x74,0x6F,0x72,0x79,0x20,0x53,0x65,0x72,0x76,0x69,0x63,0x65,0x73,0x30,0x81,0x9D,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x81,0x8B,0x00,0x30,0x81,0x87,
0x02,0x81,0x81,0x00,0x87,0x64,0x72,0x89,0x0B,0x20,0x8F,0x87,0x27,0xAC,0xC6,0x22,0xFE,0x00,0x40,0x69,0x48,0xAF,0xC6,0x86,0xCD,0x23,0x33,0xE3,0x11,0xC5,0x31,0x1A,0x1F,0x7E,0x9E,0x92,0x13,0xB6,0xA2,0xAC,0xE3,0xB0,0x1F,0x2A,0x07,0x6C,0xB6,0xD4,0xDE,0x4B,0xFA,0xF1,0xA2,0xA0,0x7D,0xCE,0x4B,0xBE,0xBE,0x26,0x48,0x09,0x8C,0x85,0x11,0xDE,0xCB,0x22,0xE7,0xC2,0xEE,0x44,0x51,0xFE,0x67,0xD5,0x5B,0x5A,0xE0,0x16,0x37,0x54,0x04,0xB8,0x3B,0x32,0x12,0x94,0x83,0x9E,0xB1,0x4D,0x80,0x6C,0xA4,0xA9,0x76,0xAC,0xB8,0xA4,
0x97,0xF7,0xAB,0x0B,0x6C,0xA5,0x43,0xBA,0x6E,0x4F,0xC5,0x4E,0x00,0x30,0x16,0x3C,0x3F,0x99,0x14,0xDA,0xA2,0x20,0x08,0x8B,0xBA,0xED,0x76,0xAC,0x97,0x00,0xD5,0x6D,0x02,0x01,0x0F,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x04,0x05,0x00,0x03,0x81,0x81,0x00,0x38,0x50,0x1D,0x0A,0xD3,0x1B,0xBB,0xA2,0x9F,0x6C,0x8D,0x10,0xAA,0x42,0x1B,0x05,0x8D,0xE4,0x25,0xAB,0xFB,0x55,0xAE,0x6D,0xBA,0x53,0x67,0x15,0x07,0x9A,0xEC,0x55,0x9F,0x72,0x89,0x5F,0x24,0xB0,0xDB,0xCA,0x64,0xBD,0x64,0xAA,0xC2,0x8C,
0xD9,0x3D,0xA2,0x45,0xB7,0xC6,0x92,0x71,0x51,0xEF,0xED,0xE1,0x51,0x54,0x97,0x56,0x35,0xA1,0xCE,0xE4,0x44,0xC4,0x47,0x66,0xFF,0x91,0xDA,0x88,0x9C,0x23,0xC2,0xB3,0xD4,0x62,0x4A,0xBC,0x94,0x55,0x9C,0x80,0x8E,0xB3,0xDD,0x4F,0x1A,0xED,0x12,0x5A,0xB5,0x2E,0xBC,0xF8,0x4B,0xCE,0xC6,0xD4,0x70,0xB3,0xB3,0x22,0xF8,0x5E,0x5C,0x36,0x7A,0xA6,0xB8,0x39,0x73,0x46,0x43,0x5C,0x9B,0x9A,0xBD,0x1E,0x7E,0xA7,0x04,0xCF,0x25,0x36 };
private static byte[] cert_c = { 0x30,0x82,0x03,0x4E,0x30,0x82,0x02,0xB7,0xA0,0x03,0x02,0x01,0x02,0x02,0x20,0x03,0x53,0xD7,0x8B,0xDB,0x3E,0x16,0x15,0x80,0x55,0xC4,0x05,0x40,0x02,0x73,0x4D,0x0C,0x20,0xF8,0x0D,0x88,0x00,0x5F,0x65,0x7A,0xAC,0xBA,0x86,0xBD,0x1C,0xD7,0xE4,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x30,0x49,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x18,0x30,0x16,0x06,0x03,0x55,0x04,0x0A,0x13,0x0F,0x43,0x43,0x41,0x20,0x2D,0x20,0x55,0x6E,0x69,0x71,0x75,0x65,0x20,
0x49,0x44,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x03,0x13,0x17,0x42,0x72,0x61,0x6E,0x64,0x20,0x4E,0x61,0x6D,0x65,0x3A,0x50,0x72,0x6F,0x64,0x75,0x63,0x74,0x20,0x54,0x79,0x70,0x65,0x30,0x1E,0x17,0x0D,0x39,0x36,0x30,0x38,0x30,0x37,0x30,0x30,0x30,0x30,0x30,0x30,0x5A,0x17,0x0D,0x39,0x36,0x30,0x38,0x33,0x31,0x32,0x33,0x35,0x39,0x35,0x39,0x5A,0x30,0x6E,0x31,0x0B,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x10,0x30,0x0E,0x06,0x03,0x55,0x04,0x0A,0x13,0x07,0x42,0x72,0x61,0x6E,0x64,0x49,
0x44,0x31,0x26,0x30,0x24,0x06,0x03,0x55,0x04,0x0B,0x13,0x1D,0x49,0x73,0x73,0x75,0x69,0x6E,0x67,0x20,0x46,0x69,0x6E,0x61,0x6E,0x63,0x69,0x61,0x6C,0x20,0x49,0x6E,0x73,0x74,0x69,0x74,0x75,0x74,0x69,0x6F,0x6E,0x31,0x25,0x30,0x23,0x06,0x03,0x55,0x04,0x03,0x13,0x1C,0x30,0x2B,0x57,0x4B,0x4A,0x78,0x2B,0x77,0x59,0x45,0x5A,0x61,0x62,0x53,0x53,0x50,0x56,0x58,0x39,0x6B,0x4C,0x73,0x6E,0x78,0x39,0x32,0x73,0x3D,0x30,0x5C,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x01,0x05,0x00,0x03,0x4B,0x00,
0x30,0x48,0x02,0x41,0x00,0xAC,0xC4,0x0E,0x05,0x25,0xBC,0xEA,0xEF,0x0C,0x22,0x7F,0xC4,0x0C,0x4A,0x69,0x31,0x00,0xF9,0x3F,0xE9,0xE1,0x6C,0x54,0x97,0x77,0x4E,0x18,0xC6,0x4A,0x95,0xE0,0xD4,0x58,0x29,0x5C,0x17,0x5D,0x1D,0x1E,0x56,0xBC,0x49,0x3D,0xE0,0xF9,0x9F,0xBB,0x01,0xF9,0x86,0xB6,0xA6,0x95,0xDD,0xE1,0x04,0x32,0x01,0x52,0x4E,0x8F,0x86,0x30,0xF7,0x02,0x03,0x01,0x00,0x01,0xA3,0x82,0x01,0x44,0x30,0x82,0x01,0x40,0x30,0x5C,0x06,0x03,0x55,0x1D,0x23,0x04,0x55,0x30,0x53,0x81,0x4B,0x84,0x49,0x31,0x0B,0x30,
0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x18,0x30,0x16,0x06,0x03,0x55,0x04,0x0A,0x13,0x0F,0x43,0x43,0x41,0x20,0x2D,0x20,0x55,0x6E,0x69,0x71,0x75,0x65,0x20,0x49,0x44,0x31,0x20,0x30,0x1E,0x06,0x03,0x55,0x04,0x03,0x13,0x17,0x42,0x72,0x61,0x6E,0x64,0x20,0x4E,0x61,0x6D,0x65,0x3A,0x50,0x72,0x6F,0x64,0x75,0x63,0x74,0x20,0x54,0x79,0x70,0x65,0x82,0x04,0x32,0x06,0xAC,0x10,0x30,0x0E,0x06,0x03,0x55,0x1D,0x0F,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,0x07,0x80,0x30,0x2E,0x06,0x03,0x55,0x1D,0x10,0x01,
0x01,0xFF,0x04,0x24,0x30,0x22,0x80,0x0F,0x31,0x39,0x39,0x36,0x30,0x38,0x30,0x37,0x30,0x37,0x34,0x39,0x30,0x30,0x5A,0x81,0x0F,0x31,0x39,0x39,0x36,0x30,0x39,0x30,0x37,0x30,0x37,0x34,0x39,0x30,0x30,0x5A,0x30,0x18,0x06,0x03,0x55,0x1D,0x20,0x04,0x11,0x30,0x0F,0x30,0x0D,0x06,0x0B,0x60,0x86,0x48,0x01,0x86,0xF8,0x45,0x01,0x07,0x01,0x01,0x30,0x0C,0x06,0x03,0x55,0x1D,0x13,0x01,0x01,0xFF,0x04,0x02,0x30,0x00,0x30,0x14,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xF8,0x45,0x02,0x03,0x01,0x01,0xFF,0x04,0x04,0x03,0x02,
0x07,0x80,0x30,0x62,0x06,0x09,0x60,0x86,0x48,0x01,0x86,0xF8,0x45,0x02,0x07,0x01,0x01,0xFF,0x04,0x52,0x30,0x50,0x04,0x14,0x33,0x39,0x38,0x32,0x33,0x39,0x38,0x37,0x32,0x33,0x37,0x38,0x39,0x31,0x33,0x34,0x39,0x37,0x38,0x32,0x30,0x09,0x06,0x05,0x2B,0x0D,0x03,0x02,0x1A,0x05,0x00,0x16,0x0F,0x74,0x65,0x72,0x73,0x65,0x20,0x73,0x74,0x61,0x74,0x65,0x6D,0x65,0x6E,0x74,0x1D,0x00,0x16,0x1A,0x67,0x65,0x74,0x73,0x65,0x74,0x2D,0x63,0x65,0x6E,0x74,0x65,0x72,0x40,0x76,0x65,0x72,0x69,0x73,0x69,0x67,0x6E,0x2E,0x63,
0x6F,0x6D,0x30,0x0D,0x06,0x09,0x2A,0x86,0x48,0x86,0xF7,0x0D,0x01,0x01,0x05,0x05,0x00,0x03,0x81,0x81,0x00,0x1D,0x6C,0x90,0xF2,0x02,0x10,0xD5,0xA0,0x7B,0xEB,0x07,0x14,0x1D,0xAE,0x2C,0xD5,0xB1,0x4C,0x23,0x30,0xB2,0x31,0x7F,0x96,0x3C,0xD1,0x41,0x11,0xEA,0x08,0x0D,0x80,0x5F,0x46,0x66,0x9D,0x0A,0xF2,0x91,0xE8,0x7C,0xCE,0xC0,0xAD,0xE6,0x96,0x19,0x9C,0x26,0xC3,0x4E,0xEB,0x6F,0xF4,0x4A,0x69,0x4C,0xFE,0x4C,0x76,0xB3,0x51,0xCA,0x44,0x03,0xFC,0xD4,0xF4,0xF9,0x32,0x2A,0xAE,0x03,0x1B,0x5F,0xA6,0xBF,0x16,0x61,
0xA0,0x07,0x86,0x85,0xA7,0xD6,0x0D,0xEF,0x88,0x9B,0x2A,0xBA,0xB8,0xD4,0x5C,0x94,0x7C,0x63,0xE1,0xE0,0x69,0xEB,0x3D,0x2F,0xC1,0x71,0x56,0x47,0x55,0x4B,0xB8,0xFD,0xCD,0xD6,0xC7,0x6F,0xA7,0x47,0xE9,0x43,0x91,0x2E,0xCF,0x93,0xA4,0x05,0x18,0xC5,0x98 };
private static X509Certificate x509a;
private static X509Certificate x509b;
private static X509Certificate x509c;
private static X509Certificate[] range;
[TestFixtureSetUp]
public void CreateCertificates ()
{
x509a = new X509Certificate (cert_a);
x509b = new X509Certificate (cert_b);
x509c = new X509Certificate (cert_c);
range = new X509Certificate [2];
range [0] = x509a;
range [1] = x509b;
}
[Test]
public void Constructor ()
{
X509CertificateCollection c = new X509CertificateCollection ();
AssertEquals ("Count", 0, c.Count);
}
[Test]
public void Constructor_CertificateArray ()
{
X509CertificateCollection c = new X509CertificateCollection (range);
AssertEquals ("Count", 2, c.Count);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Constructor_CertificateArray_Null ()
{
X509Certificate[] array = null;
new X509CertificateCollection (array);
}
[Test]
public void Constructor_CertificateCollection ()
{
X509CertificateCollection coll = new X509CertificateCollection (range);
X509CertificateCollection c = new X509CertificateCollection (coll);
AssertEquals ("Count", 2, c.Count);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Constructor_CertificateCollection_Null ()
{
X509CertificateCollection coll = null;
new X509CertificateCollection (coll);
}
[Test]
public void Add ()
{
X509CertificateCollection c = new X509CertificateCollection ();
AssertEquals ("Add a", 0, c.Add (x509a));
AssertEquals ("1", 1, c.Count);
AssertEquals ("Add a(dup)", 1, c.Add (x509a));
AssertEquals ("2", 2, c.Count);
AssertEquals ("Add b", 2, c.Add (x509b));
AssertEquals ("3", 3, c.Count);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Add_Null ()
{
X509CertificateCollection c = new X509CertificateCollection ();
c.Add (null);
}
[Test]
public void AddRange_Array ()
{
X509CertificateCollection c = new X509CertificateCollection ();
c.AddRange (range);
AssertEquals ("Range(a+b)", 2, c.Count);
c.AddRange (range);
AssertEquals ("Duplicate(a+b)", 4, c.Count);
c.Add (x509c);
AssertEquals ("New(c)", 5, c.Count);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void AddRange_ArrayNull ()
{
X509Certificate[] array = null;
X509CertificateCollection c = new X509CertificateCollection ();
c.AddRange (array);
}
[Test]
public void AddRange_Collection ()
{
X509CertificateCollection coll = new X509CertificateCollection (range);
X509CertificateCollection c = new X509CertificateCollection ();
c.AddRange (c);
AssertEquals ("Self(none)", 0, c.Count);
c.AddRange (coll);
AssertEquals ("Range(a+b)", 2, c.Count);
c.AddRange (coll);
AssertEquals ("Duplicate(a+b)", 4, c.Count);
c.Add (x509c);
AssertEquals ("New(c)", 5, c.Count);
// This leads to an infinite loop until the runtime throws an OutOfMemoryException
//c.AddRange (c);
//AssertEquals ("Self(double)", 10, c.Count);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void AddRange_CollectionNull ()
{
X509CertificateCollection coll = null;
X509CertificateCollection c = new X509CertificateCollection ();
c.AddRange (coll);
}
[Test]
public void Contains ()
{
X509CertificateCollection c = new X509CertificateCollection ();
Assert ("Empty-A", !c.Contains (x509a));
Assert ("Empty-Null", !c.Contains (null));
c.Add (x509a);
Assert ("A-A", c.Contains (x509a));
Assert ("A-B", !c.Contains (x509b));
// works by value not by object reference
X509Certificate x = new X509Certificate (cert_a);
Assert ("A-x", c.Contains (x));
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void CopyTo_Null ()
{
X509CertificateCollection c = new X509CertificateCollection ();
c.CopyTo (null, 0);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void CopyTo_TooSmall ()
{
X509Certificate[] array = new X509Certificate [1];
X509CertificateCollection c = new X509CertificateCollection ();
c.AddRange (range);
c.CopyTo (array, 0);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void CopyTo_IndexNegative ()
{
X509Certificate[] array = new X509Certificate [1];
X509CertificateCollection c = new X509CertificateCollection ();
c.CopyTo (array, -1);
}
[Test]
public void CopyTo ()
{
X509Certificate[] array = new X509Certificate [1];
X509CertificateCollection c = new X509CertificateCollection ();
c.Add (x509a);
c.CopyTo (array, 0);
Assert ("CopyTo", x509a.Equals (array [0]));
}
[Test]
public void IndexOf ()
{
X509CertificateCollection c = new X509CertificateCollection ();
AssertEquals ("Empty-A", -1, c.IndexOf (x509a));
AssertEquals ("Empty-Null", -1, c.IndexOf (null));
c.Add (x509a);
AssertEquals ("A-A", 0, c.IndexOf (x509a));
AssertEquals ("A-B", -1, c.IndexOf (x509b));
// works by object reference (not value)
X509Certificate x = new X509Certificate (cert_a);
Assert ("!ReferenceEquals", !Object.ReferenceEquals (x509a, x));
#if NET_2_0
AssertEquals ("A-x", 0, c.IndexOf (x));
#else
AssertEquals ("A-x", -1, c.IndexOf (x));
#endif
}
[Test]
public void Insert ()
{
X509CertificateCollection c = new X509CertificateCollection ();
c.Add (x509a);
AssertEquals ("a=0", 0, c.IndexOf (x509a));
c.Add (x509c);
AssertEquals ("c=1", 1, c.IndexOf (x509c));
c.Insert (1, x509b);
AssertEquals ("1", 1, c.IndexOf (x509b));
AssertEquals ("2", 2, c.IndexOf (x509c));
}
[Test]
public void Remove ()
{
X509CertificateCollection c = new X509CertificateCollection ();
c.Add (x509a);
AssertEquals ("Count==1", 1, c.Count);
c.Remove (x509a);
AssertEquals ("Remove,Count==0", 0, c.Count);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Remove_Unexisting ()
{
X509CertificateCollection c = new X509CertificateCollection ();
// non existing
c.Remove (x509a);
}
[Test]
#if !NET_2_0
[ExpectedException (typeof (ArgumentException))]
#endif
public void Remove_ByValue ()
{
X509CertificateCollection c = new X509CertificateCollection ();
X509Certificate x = null;
try {
// don't fail in this block
c.Add (x509a);
AssertEquals ("Read,Count==1", 1, c.Count);
// works by object reference (not by value)
x = new X509Certificate (cert_a);
Assert ("!ReferenceEquals", !Object.ReferenceEquals (x509a, x));
}
catch {}
// fail here! (well for 1.x)
c.Remove (x);
AssertEquals ("Remove-by-value,Count==0", 0, c.Count);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Remove_Null ()
{
X509CertificateCollection c = new X509CertificateCollection ();
// non existing
c.Remove (null);
}
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
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.
********************************************************************************************/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.Project.Automation
{
/// <summary>
/// Contains ProjectItem objects
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[ComVisible(true)]
public class OAProjectItems : OANavigableProjectItems
{
#region ctor
public OAProjectItems(OAProject project, HierarchyNode nodeWithItems)
: base(project, nodeWithItems)
{
}
#endregion
#region EnvDTE.ProjectItems
/// <summary>
/// Creates a new project item from an existing item template file and adds it to the project.
/// </summary>
/// <param name="fileName">The full path and file name of the template project file.</param>
/// <param name="name">The file name to use for the new project item.</param>
/// <returns>A ProjectItem object. </returns>
public override EnvDTE.ProjectItem AddFromTemplate(string fileName, string name)
{
if(this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed)
{
throw new InvalidOperationException();
}
return UIThread.DoOnUIThread(delegate()
{
ProjectNode proj = this.Project.Project;
EnvDTE.ProjectItem itemAdded = null;
using (AutomationScope scope = new AutomationScope(this.Project.Project.Site))
{
string fixedFileName = fileName;
if (!File.Exists(fileName))
{
string tempFileName = GetTemplateNoZip(fileName);
if (File.Exists(tempFileName))
{
fixedFileName = tempFileName;
}
}
// Determine the operation based on the extension of the filename.
// We should run the wizard only if the extension is vstemplate
// otherwise it's a clone operation
VSADDITEMOPERATION op;
if(Utilities.IsTemplateFile(fixedFileName))
{
op = VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD;
}
else
{
op = VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE;
}
VSADDRESULT[] result = new VSADDRESULT[1];
// It is not a very good idea to throw since the AddItem might return Cancel or Abort.
// The problem is that up in the call stack the wizard code does not check whether it has received a ProjectItem or not and will crash.
// The other problem is that we cannot get add wizard dialog back if a cancel or abort was returned because we throw and that code will never be executed. Typical catch 22.
ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, name, 0, new string[1] { fixedFileName }, IntPtr.Zero, result));
string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems);
string templateFilePath = System.IO.Path.Combine(fileDirectory, name);
itemAdded = this.EvaluateAddResult(result[0], templateFilePath);
}
return itemAdded;
});
}
/// <summary>
/// Adds a folder to the collection of ProjectItems with the given name.
///
/// The kind must be null, empty string, or the string value of vsProjectItemKindPhysicalFolder.
/// Virtual folders are not supported by this implementation.
/// </summary>
/// <param name="name">The name of the new folder to add</param>
/// <param name="kind">A string representing a Guid of the folder kind.</param>
/// <returns>A ProjectItem representing the newly added folder.</returns>
public override ProjectItem AddFolder(string name, string kind)
{
if(this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed)
{
throw new InvalidOperationException();
}
return UIThread.DoOnUIThread(delegate()
{
//Verify name is not null or empty
Utilities.ValidateFileName(this.Project.Project.Site, name);
//Verify that kind is null, empty, or a physical folder
if (!(string.IsNullOrEmpty(kind) || kind.Equals(EnvDTE.Constants.vsProjectItemKindPhysicalFolder)))
{
throw new ArgumentException("Parameter specification for AddFolder was not meet", "kind");
}
for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling)
{
if (child.Caption.Equals(name, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Folder already exists with the name '{0}'", name));
}
}
ProjectNode proj = this.Project.Project;
HierarchyNode newFolder = null;
using (AutomationScope scope = new AutomationScope(this.Project.Project.Site))
{
//In the case that we are adding a folder to a folder, we need to build up
//the path to the project node.
name = Path.Combine(this.NodeWithItems.VirtualNodeName, name);
newFolder = proj.CreateFolderNodes(name);
}
return newFolder.GetAutomationObject() as ProjectItem;
});
}
/// <summary>
/// Copies a source file and adds it to the project.
/// </summary>
/// <param name="filePath">The path and file name of the project item to be added.</param>
/// <returns>A ProjectItem object. </returns>
public override EnvDTE.ProjectItem AddFromFileCopy(string filePath)
{
return this.AddItem(filePath, VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE);
}
/// <summary>
/// Adds a project item from a file that is installed in a project directory structure.
/// </summary>
/// <param name="fileName">The file name of the item to add as a project item. </param>
/// <returns>A ProjectItem object. </returns>
public override EnvDTE.ProjectItem AddFromFile(string fileName)
{
// TODO: VSADDITEMOP_LINKTOFILE
return this.AddItem(fileName, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE);
}
#endregion
#region helper methods
/// <summary>
/// Adds an item to the project.
/// </summary>
/// <param name="path">The full path of the item to add.</param>
/// <param name="op">The <paramref name="VSADDITEMOPERATION"/> to use when adding the item.</param>
/// <returns>A ProjectItem object. </returns>
protected virtual EnvDTE.ProjectItem AddItem(string path, VSADDITEMOPERATION op)
{
if(this.Project == null || this.Project.Project == null || this.Project.Project.Site == null || this.Project.Project.IsClosed)
{
throw new InvalidOperationException();
}
return UIThread.DoOnUIThread(delegate()
{
ProjectNode proj = this.Project.Project;
EnvDTE.ProjectItem itemAdded = null;
using (AutomationScope scope = new AutomationScope(this.Project.Project.Site))
{
VSADDRESULT[] result = new VSADDRESULT[1];
ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, path, 0, new string[1] { path }, IntPtr.Zero, result));
string fileName = System.IO.Path.GetFileName(path);
string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems);
string filePathInProject = System.IO.Path.Combine(fileDirectory, fileName);
itemAdded = this.EvaluateAddResult(result[0], filePathInProject);
}
return itemAdded;
});
}
/// <summary>
/// Evaluates the result of an add operation.
/// </summary>
/// <param name="result">The <paramref name="VSADDRESULT"/> returned by the Add methods</param>
/// <param name="path">The full path of the item added.</param>
/// <returns>A ProjectItem object.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
protected virtual EnvDTE.ProjectItem EvaluateAddResult(VSADDRESULT result, string path)
{
return UIThread.DoOnUIThread(delegate()
{
if (result == VSADDRESULT.ADDRESULT_Success)
{
HierarchyNode nodeAdded = this.NodeWithItems.FindChild(path);
Debug.Assert(nodeAdded != null, "We should have been able to find the new element in the hierarchy");
if (nodeAdded != null)
{
EnvDTE.ProjectItem item = null;
if (nodeAdded is FileNode)
{
item = new OAFileItem(this.Project, nodeAdded as FileNode);
}
else if (nodeAdded is NestedProjectNode)
{
item = new OANestedProjectItem(this.Project, nodeAdded as NestedProjectNode);
}
else
{
item = new OAProjectItem<HierarchyNode>(this.Project, nodeAdded);
}
this.Items.Add(item);
return item;
}
}
return null;
});
}
/// <summary>
/// Removes .zip extensions from the components of a path.
/// </summary>
private static string GetTemplateNoZip(string fileName)
{
char[] separators = { '\\' };
string[] components = fileName.Split(separators);
for (int i = 0; i < components.Length; i++)
{
string component = components[i];
if (Path.GetExtension(component).Equals(".zip", StringComparison.InvariantCultureIgnoreCase))
{
component = Path.GetFileNameWithoutExtension(component);
components[i] = component;
}
}
// if first element is a drive, we need to combine the first and second.
// Path.Combine does not add a directory separator between the drive and the
// first directory.
if (components.Length > 1)
{
if (Path.IsPathRooted(components[0]))
{
components[0] = string.Format("{0}{1}{2}", components[0], Path.DirectorySeparatorChar, components[1]);
components[1] = string.Empty; // Path.Combine drops empty strings.
}
}
return Path.Combine(components);
}
#endregion
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace Microsoft.Zing
{
/// <exclude/>
/// <summary>
/// Base class for all Zing methods. Represents an invocation of the method.
/// </summary>
/// <remarks>
/// Subclasses of ZingMethod are always nested within a subclass of ZingClass.
/// </remarks>
[CLSCompliant(false)]
public abstract class ZingMethod
{
// this property should be overridden in the generated code for instance methods
public virtual Pointer This
{
get { return new Pointer(0); }
set { }
}
public abstract string ProgramCounter { get; }
public string MethodName
{
get
{
string name = this.GetType().ToString();
return name.Replace("Microsoft.Zing.Application+", "").Replace('+', '.');
}
}
// <summary>Constructor</summary>
protected ZingMethod()
{
}
public abstract ushort NextBlock { get; set; }
public abstract UndoableStorage Locals { get; }
public abstract UndoableStorage Inputs { get; }
public abstract UndoableStorage Outputs { get; }
public abstract int CompareTo(object obj);
public abstract void WriteString(StateImpl state, BinaryWriter bw);
public abstract void WriteOutputsString(StateImpl state, BinaryWriter bw);
public abstract void Dispatch(Process process);
public virtual ulong GetRunnableJoinStatements(Process process)
{
return ulong.MaxValue;
}
public virtual bool IsAtomicEntryBlock()
{
return false;
}
// This field is set when the select statement actually begins execution and is
// examined in the join statement "tester" blocks. This just avoids having to
// calculate the runnable flags multiple times.
private ulong savedRunnableJoinStatements;
protected ulong SavedRunnableJoinStatements
{
get { return savedRunnableJoinStatements; }
set { savedRunnableJoinStatements = value; }
}
public bool IsRunnable(Process process)
{
return GetRunnableJoinStatements(process) != 0;
}
public virtual bool ValidEndState { get { return true; } }
public virtual ZingSourceContext Context { get { return null; } }
public virtual ZingAttribute ContextAttribute { get { return null; } }
public ZingMethod Caller
{
get { return caller; }
set { caller = value; }
}
private ZingMethod caller;
public int CurrentException
{
get { return currentException; }
set { currentException = value; }
}
private int currentException;
private int savedAtomicityLevel;
public int SavedAtomicityLevel
{
get { return savedAtomicityLevel; }
set { savedAtomicityLevel = value; }
}
// This is overridden by methods that return bool so that they can be used as
// predicates in wait-style join conditions.
public virtual bool BooleanReturnValue
{
get
{
throw new NotImplementedException();
}
}
// Returns true if the exception can be handled in this stack frame
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
public abstract bool RaiseZingException(int exception);
public abstract StateImpl StateImpl { get; set; }
public abstract ZingMethod Clone(StateImpl myState, Process myProcess, bool shallowCopy);
public object DoCheckIn()
{
//Console.WriteLine("checking in stack frame {0}", stackFrameId);
object othersULE = DoCheckInOthers();
if (othersULE != null || Locals.IsDirty || Outputs.IsDirty || Inputs.IsDirty)
{
// something has changed
ZingMethodULE ule = new ZingMethodULE();
ule.localsULE = Locals.DoCheckIn();
ule.inputsULE = Inputs.DoCheckIn();
ule.outputsULE = Outputs.DoCheckIn();
ule.othersULE = othersULE;
return ule;
}
return null;
}
internal void DoRevert()
{
Locals.DoRevert();
Inputs.DoRevert();
Outputs.DoRevert();
DoRevertOthers();
}
internal void DoRollback(object[] uleList)
{
int n = uleList.Length;
object[] lc_ules = new object[n];
object[] in_ules = new object[n];
object[] out_ules = new object[n];
object[] oth_ules = new object[n];
int i;
for (i = 0; i < n; i++)
{
if (uleList[i] == null)
{
lc_ules[i] = null;
in_ules[i] = null;
out_ules[i] = null;
oth_ules[i] = null;
}
else
{
ZingMethodULE ule = (ZingMethodULE)uleList[i];
lc_ules[i] = ule.localsULE;
in_ules[i] = ule.inputsULE;
out_ules[i] = ule.outputsULE;
oth_ules[i] = ule.othersULE;
}
}
Locals.DoRollback(lc_ules);
Inputs.DoRollback(in_ules);
Outputs.DoRollback(out_ules);
DoRollbackOthers(oth_ules);
}
private class ZingMethodULE
{
public object localsULE;
public object inputsULE;
public object outputsULE;
public object othersULE;
internal ZingMethodULE()
{
}
}
public abstract object DoCheckInOthers();
public abstract void DoRevertOthers();
public abstract void DoRollbackOthers(object[] uleList);
// Note: The emitted code generates a derived class for each method
// defined on a Zing class. The generated classes will contain nested
// classes named "Locals", "Inputs", and "Outputs". The generated code
// will refer to these classes and their members in a strongly-typed
// way.
public bool ContainsVariable(string name)
{
return Utils.ContainsVariable(this, "locals", name) ||
Utils.ContainsVariable(this, "inputs", name) ||
Utils.ContainsVariable(this, "outputs", name);
}
public object LookupValueByName(string name)
{
if (Utils.ContainsVariable(this, "locals", name))
return Utils.LookupValueByName(this, "locals", name);
else if (Utils.ContainsVariable(this, "inputs", name))
return Utils.LookupValueByName(this, "inputs", name);
else
return Utils.LookupValueByName(this, "outputs", name);
}
abstract public void TraverseFields(FieldTraverser ft);
}
}
| |
#region Foreign-License
/*
Copyright (c) 1997 Sun Microsystems, Inc.
Copyright (c) 2012 Sky Morey
See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#endregion
using System;
using System.Text;
using System.IO;
namespace Tcl.Lang
{
/// <summary> The Channel class provides functionality that will
/// be needed for any type of Tcl channel. It performs
/// generic reads, writes, without specifying how a
/// given channel is actually created. Each new channel
/// type will need to extend the abstract Channel class
/// and override any methods it needs to provide a
/// specific implementation for.
/// </summary>
public abstract class Channel
{
private void InitBlock()
{
buffering = TclIO.BUFF_FULL;
inputTranslation = TclIO.TRANS_AUTO;
outputTranslation = TclIO.TRANS_PLATFORM;
}
/// <summary> This method should be overridden in the subclass to provide
/// a channel specific InputStream object.
/// </summary>
protected internal abstract Stream InputStream
{
get;
}
/// <summary> This method should be overridden in the subclass to provide
/// a channel specific OutputStream object.
/// </summary>
protected internal abstract Stream OutputStream
{
get;
}
/// <summary> Gets the chanName that is the key for the chanTable hashtable.</summary>
/// <returns> channelId
/// </returns>
/// <summary> Sets the chanName that is the key for the chanTable hashtable.</summary>
/// <param name="chan">the unique channelId
/// </param>
public string ChanName
{
get
{
return chanName;
}
set
{
chanName = value;
}
}
/// <summary> Return a string that describes the channel type.
///
/// This is the equivilent of the Tcl_ChannelTypE.typeName field.
/// </summary>
public abstract string ChanType
{
get;
}
/// <summary> Return number of references to this Channel.</summary>
public int RefCount
{
get
{
return refCount;
}
}
public bool ReadOnly
{
get
{
return ((mode & TclIO.RDONLY) != 0);
}
}
public bool WriteOnly
{
get
{
return ((mode & TclIO.WRONLY) != 0);
}
}
public bool ReadWrite
{
get
{
return ((mode & TclIO.RDWR) != 0);
}
}
/// <summary> Query blocking mode.</summary>
/// <summary> Set blocking mode.
///
/// </summary>
/// <param name="blocking">new blocking mode
/// </param>
public bool Blocking
{
get
{
return blocking;
}
set
{
blocking = value;
if (input != null)
input.Blocking = blocking;
if (output != null)
output.Blocking = blocking;
}
}
/// <summary> Query buffering mode.</summary>
/// <summary> Set buffering mode
///
/// </summary>
/// <param name="buffering">One of TclIO.BUFF_FULL, TclIO.BUFF_LINE,
/// or TclIO.BUFF_NONE
/// </param>
public int Buffering
{
get
{
return buffering;
}
set
{
if (value < TclIO.BUFF_FULL || value > TclIO.BUFF_NONE)
throw new TclRuntimeError("invalid buffering mode in Channel.setBuffering()");
buffering = value;
if (input != null)
input.Buffering = buffering;
if (output != null)
output.Buffering = buffering;
}
}
/// <summary> Query buffer size</summary>
/// <summary> Tcl_SetChannelBufferSize -> setBufferSize
///
/// </summary>
/// <param name="size">new buffer size
/// </param>
public int BufferSize
{
get
{
return bufferSize;
}
set
{
// If the buffer size is smaller than 10 bytes or larger than 1 Meg
// do not accept the requested size and leave the current buffer size.
if ((value < 10) || (value > (1024 * 1024)))
{
return;
}
bufferSize = value;
if (input != null)
input.BufferSize = bufferSize;
if (output != null)
output.BufferSize = bufferSize;
}
}
public int NumBufferedInputBytes
{
get
{
if (input != null)
return input.NumBufferedBytes;
else
return 0;
}
}
public int NumBufferedOutputBytes
{
get
{
if (output != null)
return output.NumBufferedBytes;
else
return 0;
}
}
/// <summary> Returns true if a background flush is waiting to happen.</summary>
public bool BgFlushScheduled
{
get
{
// FIXME: Need to query output here
return false;
}
}
/// <summary> Query encoding
///
/// </summary>
/// <returns> Name of Channel's Java encoding (null if no encoding)
/// </returns>
/// <summary> Set new Java encoding</summary>
internal System.Text.Encoding Encoding
{
get
{
return encoding;
}
set
{
encoding = value;
if ((System.Object)encoding == null)
bytesPerChar = 1;
else
bytesPerChar = EncodingCmd.getBytesPerChar(encoding);
if (input != null)
input.Encoding = encoding;
if (output != null)
output.Encoding = encoding;
// FIXME: Pass bytesPerChar to input and output
}
}
/// <summary> Query input translation
/// Set new input translation</summary>
public int InputTranslation
{
get
{
return inputTranslation;
}
set
{
inputTranslation = value;
if (input != null)
input.Translation = inputTranslation;
}
}
/// <summary> Query output translation
/// Set new output translation</summary>
public int OutputTranslation
{
get
{
return outputTranslation;
}
set
{
outputTranslation = value;
if (output != null)
output.Translation = outputTranslation;
}
}
/// <summary> Query input eof character</summary>
/// <summary> Set new input eof character</summary>
internal char InputEofChar
{
get
{
return inputEofChar;
}
set
{
// Store as a byte, not a unicode character
inputEofChar = (char)(value & 0xFF);
if (input != null)
input.EofChar = inputEofChar;
}
}
/// <summary> Query output eof character</summary>
/// <summary> Set new output eof character</summary>
internal char OutputEofChar
{
get
{
return outputEofChar;
}
set
{
// Store as a byte, not a unicode character
outputEofChar = (char)(value & 0xFF);
if (output != null)
output.EofChar = outputEofChar;
}
}
/// <summary> The read, write, append and create flags are set here. The
/// variables used to set the flags are found in the class TclIO.
/// </summary>
protected internal int mode;
/// <summary> This is a unique name that sub-classes need to set. It is used
/// as the key in the hashtable of registered channels (in interp).
/// </summary>
private string chanName;
/// <summary> How many interpreters hold references to this IO channel?</summary>
protected internal int refCount = 0;
/// <summary> Tcl input and output objecs. These are like a mix between
/// a Java Stream and a Reader.
/// </summary>
protected internal TclInputStream input = null;
protected internal TclOutputStream output = null;
/// <summary> Set to false when channel is in non-blocking mode.</summary>
protected internal bool blocking = true;
/// <summary> Buffering (full,line, or none)</summary>
protected internal int buffering;
/// <summary> Buffer size, in bytes, allocated for channel to store input or output</summary>
protected internal int bufferSize = 4096;
/// <summary> Name of Java encoding for this Channel.
/// A null value means use no encoding (binary).
/// </summary>
// FIXME: Check to see if this field is updated after a call
// to "encoding system $enc" for new Channel objects!
protected internal System.Text.Encoding encoding;
protected internal int bytesPerChar;
/// <summary> Translation mode for end-of-line character</summary>
protected internal int inputTranslation;
protected internal int outputTranslation;
/// <summary> If nonzero, use this as a signal of EOF on input.</summary>
protected internal char inputEofChar = (char)(0);
/// <summary> If nonzero, append this to a writeable channel on close.</summary>
protected internal char outputEofChar = (char)(0);
internal Channel()
{
InitBlock();
Encoding = EncodingCmd.systemJavaEncoding;
}
/// <summary> Tcl_ReadChars -> read
///
/// Read data from the Channel into the given TclObject.
///
/// </summary>
/// <param name="interp"> is used for TclExceptions.
/// </param>
/// <param name="tobj"> the object data will be added to.
/// </param>
/// <param name="readType"> specifies if the read should read the entire
/// buffer (TclIO.READ_ALL), the next line
/// (TclIO.READ_LINE), of a specified number
/// of bytes (TclIO.READ_N_BYTES).
/// </param>
/// <param name="numBytes"> the number of bytes/chars to read. Used only
/// when the readType is TclIO.READ_N_BYTES.
/// </param>
/// <returns> the number of bytes read.
/// Returns -1 on EOF or on error.
/// </returns>
/// <exception cref=""> TclException is thrown if read occurs on WRONLY channel.
/// </exception>
/// <exception cref=""> IOException is thrown when an IO error occurs that was not
/// correctly tested for. Most cases should be caught.
/// </exception>
internal int read(Interp interp, TclObject tobj, int readType, int numBytes)
{
TclObject dataObj;
checkRead(interp);
initInput();
switch (readType)
{
case TclIO.READ_ALL:
{
return input.doReadChars(tobj, -1);
}
case TclIO.READ_LINE:
{
return input.getsObj(tobj);
}
case TclIO.READ_N_BYTES:
{
return input.doReadChars(tobj, numBytes);
}
default:
{
throw new TclRuntimeError("Channel.read: Invalid read mode.");
}
}
}
/// <summary> Tcl_WriteObj -> write
///
/// Write data to the Channel
///
/// </summary>
/// <param name="interp">is used for TclExceptions.
/// </param>
/// <param name="outData">the TclObject that holds the data to write.
/// </param>
public virtual void Write(Interp interp, TclObject outData)
{
checkWrite(interp);
initOutput();
// FIXME: Is it possible for a write to happen with a null output?
if (output != null)
{
output.writeObj(outData);
}
}
/// <summary> Tcl_WriteChars -> write
///
/// Write string data to the Channel.
///
/// </summary>
/// <param name="interp">is used for TclExceptions.
/// </param>
/// <param name="outStr">the String object to write.
/// </param>
public void Write(Interp interp, string outStr)
{
Write(interp, TclString.NewInstance(outStr));
}
/// <summary> Close the Channel. The channel is only closed, it is
/// the responsibility of the "closer" to remove the channel from
/// the channel table.
/// </summary>
internal virtual void Close()
{
IOException ex = null;
if (input != null)
{
try
{
input.close();
}
catch (IOException e)
{
ex = e;
}
input = null;
}
if (output != null)
{
try
{
output.close();
}
catch (IOException e)
{
ex = e;
}
output = null;
}
if (ex != null)
throw ex;
}
/// <summary> Flush the Channel.
///
/// </summary>
/// <exception cref=""> TclException is thrown when attempting to flush a
/// read only channel.
/// </exception>
/// <exception cref=""> IOEcception is thrown for all other flush errors.
/// </exception>
public void Flush(Interp interp)
{
checkWrite(interp);
if (output != null)
{
output.flush();
}
}
/// <summary> Move the current file pointer. If seek is not supported on the
/// given channel then -1 will be returned. A subclass should
/// override this method if it supports the seek operation.
///
/// </summary>
/// <param name="interp">currrent interpreter.
/// </param>
/// <param name="offset">The number of bytes to move the file pointer.
/// </param>
/// <param name="mode">where to begin incrementing the file pointer; beginning,
/// current, end.
/// </param>
public virtual void seek(Interp interp, long offset, int mode)
{
throw new TclPosixException(interp, TclPosixException.EINVAL, true, "error during seek on \"" + ChanName + "\"");
}
/// <summary> Return the current file pointer. If tell is not supported on the
/// given channel then -1 will be returned. A subclass should override
/// this method if it supports the tell operation.
/// </summary>
public virtual long tell()
{
return (long)(-1);
}
/// <summary> Setup the TclInputStream on the first call to read</summary>
protected internal void initInput()
{
if (input != null)
return;
input = new TclInputStream(InputStream);
input.Encoding = encoding;
input.Translation = inputTranslation;
input.EofChar = inputEofChar;
input.Buffering = buffering;
input.BufferSize = bufferSize;
input.Blocking = blocking;
}
/// <summary> Setup the TclOutputStream on the first call to write</summary>
protected internal void initOutput()
{
if (output != null)
return;
output = new TclOutputStream(OutputStream);
output.Encoding = encoding;
output.Translation = outputTranslation;
output.EofChar = outputEofChar;
output.Buffering = buffering;
output.BufferSize = bufferSize;
output.Blocking = blocking;
}
/// <summary> Returns true if the last read reached the EOF.</summary>
public bool eof()
{
if (input != null)
return input.eof();
else
return false;
}
// Helper methods to check read/write permission and raise a
// TclException if reading is not allowed.
protected internal void checkRead(Interp interp)
{
if (!ReadOnly && !ReadWrite)
{
throw new TclException(interp, "channel \"" + ChanName + "\" wasn't opened for reading");
}
}
protected internal void checkWrite(Interp interp)
{
if (!WriteOnly && !ReadWrite)
{
throw new TclException(interp, "channel \"" + ChanName + "\" wasn't opened for writing");
}
}
/// <summary> Tcl_InputBlocked -> isBlocked
///
/// Returns true if input is blocked on this channel, false otherwise.
///
/// </summary>
public bool isBlocked(Interp interp)
{
checkRead(interp);
if (input != null)
return input.Blocked;
else
return false;
}
/// <summary> Channel is in CRLF eol input translation mode and the last
/// byte seen was a CR.
/// </summary>
public bool inputSawCR()
{
if (input != null)
return input.sawCR();
return false;
}
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure
{
/// <summary>
/// This is the main client class for interacting with the Azure SQL
/// Database REST APIs.
/// </summary>
public static partial class ServerOperationsExtensions
{
/// <summary>
/// Changes the administrative password of an existing Azure SQL
/// Database Server for a given subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that will have
/// the administrator password changed.
/// </param>
/// <param name='parameters'>
/// Required. The necessary parameters for modifying the adminstrator
/// password for a server.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse ChangeAdministratorPassword(this IServerOperations operations, string serverName, ServerChangeAdministratorPasswordParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).ChangeAdministratorPasswordAsync(serverName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Changes the administrative password of an existing Azure SQL
/// Database Server for a given subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that will have
/// the administrator password changed.
/// </param>
/// <param name='parameters'>
/// Required. The necessary parameters for modifying the adminstrator
/// password for a server.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> ChangeAdministratorPasswordAsync(this IServerOperations operations, string serverName, ServerChangeAdministratorPasswordParameters parameters)
{
return operations.ChangeAdministratorPasswordAsync(serverName, parameters, CancellationToken.None);
}
/// <summary>
/// Provisions a new SQL Database server in a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='parameters'>
/// Required. The parameters needed to provision a server.
/// </param>
/// <returns>
/// The response returned from the Create Server operation. This
/// contains all the information returned from the service when a
/// server is created.
/// </returns>
public static ServerCreateResponse Create(this IServerOperations operations, ServerCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).CreateAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Provisions a new SQL Database server in a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='parameters'>
/// Required. The parameters needed to provision a server.
/// </param>
/// <returns>
/// The response returned from the Create Server operation. This
/// contains all the information returned from the service when a
/// server is created.
/// </returns>
public static Task<ServerCreateResponse> CreateAsync(this IServerOperations operations, ServerCreateParameters parameters)
{
return operations.CreateAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Deletes the specified Azure SQL Database Server from a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to be deleted.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Delete(this IServerOperations operations, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).DeleteAsync(serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Azure SQL Database Server from a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to be deleted.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> DeleteAsync(this IServerOperations operations, string serverName)
{
return operations.DeleteAsync(serverName, CancellationToken.None);
}
/// <summary>
/// Returns all SQL Database Servers that are provisioned for a
/// subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <returns>
/// The response structure for the Server List operation. Contains a
/// list of all the servers in a subscription.
/// </returns>
public static ServerListResponse List(this IServerOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns all SQL Database Servers that are provisioned for a
/// subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <returns>
/// The response structure for the Server List operation. Contains a
/// list of all the servers in a subscription.
/// </returns>
public static Task<ServerListResponse> ListAsync(this IServerOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
}
}
| |
//=============================================================================
// System : Sandcastle Help File Builder Utilities
// File : ConvertFromSandcastleGui.cs
// Author : Eric Woodruff ([email protected])
// Updated : 06/20/2010
// Note : Copyright 2008-2010, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a class used to convert project files created by Stephan
// Smetsers Sandcastle GUI to the MSBuild format project files used by SHFB.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.8.0.0 07/23/2008 EFW Created the code
//=============================================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.XPath;
using SandcastleBuilder.Utils.Design;
namespace SandcastleBuilder.Utils.Conversion
{
/// <summary>
/// This class is used to convert Stephan Smetsers Sandcastle GUI project
/// files to the MSBuild format project files used by the help file builder.
/// </summary>
public class ConvertFromSandcastleGui : ConvertToMSBuildFormat
{
#region Properties
//=====================================================================
/// <summary>
/// An XML reader isn't used by this converter
/// </summary>
protected internal override XmlTextReader Reader
{
get { return null; }
}
#endregion
#region Constructor
//=====================================================================
/// <summary>
/// Constructor
/// </summary>
/// <param name="oldProjectFile">The old project filename</param>
/// <param name="folder">The folder in which to place the new project
/// and its related files. This cannot be the same folder as the
/// old project file.</param>
public ConvertFromSandcastleGui(string oldProjectFile, string folder) :
base(oldProjectFile, folder)
{
}
#endregion
#region Conversion methods
//=====================================================================
/// <summary>
/// This is used to perform the actual conversion
/// </summary>
/// <returns>The new project filename on success. An exception is
/// thrown if the conversion fails.</returns>
public override string ConvertProject()
{
SandcastleProject project = base.Project;
FileItem fileItem;
List<string> syntaxFilters = new List<string> { "CSharp", "VisualBasic", "CPlusPlus" };
string option, lastProperty = null, value;
int pos;
try
{
project.HelpTitle = project.HtmlHelpName =
Path.GetFileNameWithoutExtension(base.OldProjectFile);
using(StreamReader sr = new StreamReader(base.OldProjectFile))
while(!sr.EndOfStream)
{
option = sr.ReadLine();
if(String.IsNullOrEmpty(option))
continue;
pos = option.IndexOf('=');
if(pos == -1)
continue;
lastProperty = option.Substring(0, pos).Trim().ToLower(
CultureInfo.InvariantCulture);
value = option.Substring(pos + 1).Trim();
switch(lastProperty)
{
case "copyright":
project.CopyrightText = value;
break;
case "productname":
project.HelpTitle = value;
break;
case "assemblydir":
project.DocumentationSources.Add(Path.Combine(
value, "*.*"), null, null, false);
break;
case "docdir":
this.ConvertAdditionalContent(value);
break;
case "logo":
fileItem = project.AddFileToProject(value,
Path.Combine(base.ProjectFolder,
Path.GetFileName(value)));
// Since the logo is copied by the
// Post-Transform component, set the build
// action to None so that it isn't added
// to the help file as content.
fileItem.BuildAction = BuildAction.None;
break;
case "msdnlinks":
if(String.Compare(value, "false", StringComparison.OrdinalIgnoreCase) == 0)
{
project.HtmlSdkLinkType = project.WebsiteSdkLinkType = HtmlSdkLinkType.None;
project.MSHelp2SdkLinkType = MSHelp2SdkLinkType.Index;
project.MSHelpViewerSdkLinkType = MSHelpViewerSdkLinkType.Id;
}
break;
case "outputtype":
if(value.IndexOf("website",
StringComparison.OrdinalIgnoreCase) != -1)
project.HelpFileFormat = HelpFileFormat.HtmlHelp1 |
HelpFileFormat.Website;
break;
case "friendlyfilenames":
if(String.Compare(value, "true",
StringComparison.OrdinalIgnoreCase) == 0)
project.NamingMethod = NamingMethod.MemberName;
break;
case "template":
project.PresentationStyle =
PresentationStyleTypeConverter.FirstMatching(value);
break;
case "internals":
if(String.Compare(value, "true",
StringComparison.OrdinalIgnoreCase) == 0)
project.DocumentPrivates =
project.DocumentInternals = true;
break;
case "cssyntaxdeclaration":
if(String.Compare(value, "false",
StringComparison.OrdinalIgnoreCase) == 0)
syntaxFilters.Remove("CSharp");
break;
case "vbsyntaxdeclaration":
if(String.Compare(value, "false",
StringComparison.OrdinalIgnoreCase) == 0)
syntaxFilters.Remove("VisualBasic");
break;
case "cppsyntaxdeclaration":
if(String.Compare(value, "false",
StringComparison.OrdinalIgnoreCase) == 0)
syntaxFilters.Remove("CPlusPlus");
break;
case "javascriptsyntaxdeclaration":
if(String.Compare(value, "true",
StringComparison.OrdinalIgnoreCase) == 0)
syntaxFilters.Add("JavaScript");
break;
default: // Ignored
break;
}
}
// Set the syntax filters
project.SyntaxFilters = String.Join(", ", syntaxFilters.ToArray());
base.CreateFolderItems();
project.SaveProject(project.Filename);
}
catch(Exception ex)
{
throw new BuilderException("CVT0005", String.Format(
CultureInfo.CurrentCulture, "Error reading project " +
"from '{0}' (last property = {1}):\r\n{2}",
base.OldProjectFile, lastProperty, ex.Message), ex);
}
return project.Filename;
}
#endregion
#region Helper methods
//=====================================================================
/// <summary>
/// Add additional content to the project
/// </summary>
/// <param name="folder">The folder containing the content</param>
private void ConvertAdditionalContent(string folder)
{
string fileSpec, source, dest, destFile;
int pos;
fileSpec = base.FullPath(Path.Combine(folder, "*.*"));
source = Path.GetDirectoryName(fileSpec);
dest = base.ProjectFolder;
pos = source.LastIndexOf('\\');
if(pos != -1)
dest = Path.Combine(dest, source.Substring(pos + 1));
foreach(string file in ExpandWildcard(fileSpec, true))
{
// Remove the base path but keep any subfolders
destFile = file.Substring(source.Length + 1);
destFile = Path.Combine(dest, destFile);
base.Project.AddFileToProject(file, destFile);
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexInput = Lucene.Net.Store.IndexInput;
using BitVector = Lucene.Net.Util.BitVector;
namespace Lucene.Net.Index
{
public class SegmentTermDocs : TermDocs
{
protected internal SegmentReader parent;
protected internal IndexInput freqStream;
protected internal int count;
protected internal int df;
protected internal BitVector deletedDocs;
internal int doc = 0;
internal int freq;
private int skipInterval;
private int maxSkipLevels;
private DefaultSkipListReader skipListReader;
private long freqBasePointer;
private long proxBasePointer;
private long skipPointer;
private bool haveSkipped;
protected internal bool currentFieldStoresPayloads;
protected internal bool currentFieldOmitTermFreqAndPositions;
public /*protected internal*/ SegmentTermDocs(SegmentReader parent)
{
this.parent = parent;
this.freqStream = (IndexInput) parent.core.freqStream.Clone();
lock (parent)
{
this.deletedDocs = parent.deletedDocs;
}
this.skipInterval = parent.core.GetTermsReader().GetSkipInterval();
this.maxSkipLevels = parent.core.GetTermsReader().GetMaxSkipLevels();
}
public virtual void Seek(Term term)
{
TermInfo ti = parent.core.GetTermsReader().Get(term);
Seek(ti, term);
}
public virtual void Seek(TermEnum termEnum)
{
TermInfo ti;
Term term;
// use comparison of fieldinfos to verify that termEnum belongs to the same segment as this SegmentTermDocs
if (termEnum is SegmentTermEnum && ((SegmentTermEnum) termEnum).fieldInfos == parent.core.fieldInfos)
{
// optimized case
SegmentTermEnum segmentTermEnum = ((SegmentTermEnum) termEnum);
term = segmentTermEnum.Term();
ti = segmentTermEnum.TermInfo();
}
else
{
// punt case
term = termEnum.Term();
ti = parent.core.GetTermsReader().Get(term);
}
Seek(ti, term);
}
internal virtual void Seek(TermInfo ti, Term term)
{
count = 0;
FieldInfo fi = parent.core.fieldInfos.FieldInfo(term.field);
currentFieldOmitTermFreqAndPositions = (fi != null)?fi.omitTermFreqAndPositions:false;
currentFieldStoresPayloads = (fi != null)?fi.storePayloads:false;
if (ti == null)
{
df = 0;
}
else
{
df = ti.docFreq;
doc = 0;
freqBasePointer = ti.freqPointer;
proxBasePointer = ti.proxPointer;
skipPointer = freqBasePointer + ti.skipOffset;
freqStream.Seek(freqBasePointer);
haveSkipped = false;
}
}
public virtual void Close()
{
freqStream.Close();
if (skipListReader != null)
skipListReader.Close();
}
public int Doc()
{
return doc;
}
public int Freq()
{
return freq;
}
protected internal virtual void SkippingDoc()
{
}
public virtual bool Next()
{
while (true)
{
if (count == df)
return false;
int docCode = freqStream.ReadVInt();
if (currentFieldOmitTermFreqAndPositions)
{
doc += docCode;
freq = 1;
}
else
{
doc += SupportClass.Number.URShift(docCode, 1); // shift off low bit
if ((docCode & 1) != 0)
// if low bit is set
freq = 1;
// freq is one
else
freq = freqStream.ReadVInt(); // else read freq
}
count++;
if (deletedDocs == null || !deletedDocs.Get(doc))
break;
SkippingDoc();
}
return true;
}
/// <summary>Optimized implementation. </summary>
public virtual int Read(int[] docs, int[] freqs)
{
int length = docs.Length;
if (currentFieldOmitTermFreqAndPositions)
{
return ReadNoTf(docs, freqs, length);
}
else
{
int i = 0;
while (i < length && count < df)
{
// manually inlined call to next() for speed
int docCode = freqStream.ReadVInt();
doc += SupportClass.Number.URShift(docCode, 1); // shift off low bit
if ((docCode & 1) != 0)
// if low bit is set
freq = 1;
// freq is one
else
freq = freqStream.ReadVInt(); // else read freq
count++;
if (deletedDocs == null || !deletedDocs.Get(doc))
{
docs[i] = doc;
freqs[i] = freq;
++i;
}
}
return i;
}
}
private int ReadNoTf(int[] docs, int[] freqs, int length)
{
int i = 0;
while (i < length && count < df)
{
// manually inlined call to next() for speed
doc += freqStream.ReadVInt();
count++;
if (deletedDocs == null || !deletedDocs.Get(doc))
{
docs[i] = doc;
// Hardware freq to 1 when term freqs were not
// stored in the index
freqs[i] = 1;
++i;
}
}
return i;
}
/// <summary>Overridden by SegmentTermPositions to skip in prox stream. </summary>
protected internal virtual void SkipProx(long proxPointer, int payloadLength)
{
}
/// <summary>Optimized implementation. </summary>
public virtual bool SkipTo(int target)
{
if (df >= skipInterval)
{
// optimized case
if (skipListReader == null)
skipListReader = new DefaultSkipListReader((IndexInput) freqStream.Clone(), maxSkipLevels, skipInterval); // lazily clone
if (!haveSkipped)
{
// lazily initialize skip stream
skipListReader.Init(skipPointer, freqBasePointer, proxBasePointer, df, currentFieldStoresPayloads);
haveSkipped = true;
}
int newCount = skipListReader.SkipTo(target);
if (newCount > count)
{
freqStream.Seek(skipListReader.GetFreqPointer());
SkipProx(skipListReader.GetProxPointer(), skipListReader.GetPayloadLength());
doc = skipListReader.GetDoc();
count = newCount;
}
}
// done skipping, now just scan
do
{
if (!Next())
return false;
}
while (target > doc);
return true;
}
public IndexInput freqStream_ForNUnit
{
get { return freqStream; }
set { freqStream = value; }
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Dicom.IO {
#region Endian
public struct Endian {
public static readonly Endian Little = new Endian(false);
public static readonly Endian Big = new Endian(true);
public static readonly Endian LocalMachine = BitConverter.IsLittleEndian ? Little : Big;
public static readonly Endian Network = Big;
private bool _isBigEndian;
private Endian(bool isBigEndian) {
_isBigEndian = isBigEndian;
}
public override bool Equals(object obj) {
if (obj == null)
return false;
if (obj is Endian)
return this == (Endian)obj;
return false;
}
public override int GetHashCode() {
return _isBigEndian.GetHashCode();
}
public override string ToString() {
if (_isBigEndian)
return "Big Endian";
return "Little Endian";
}
public static bool operator ==(Endian e1, Endian e2) {
if ((object)e1 == null && (object)e2 == null)
return true;
if ((object)e1 == null || (object)e2 == null)
return false;
return e1._isBigEndian == e2._isBigEndian;
}
public static bool operator !=(Endian e1, Endian e2) {
return !(e1 == e2);
}
public static void SwapBytes(int bytesToSwap, byte[] bytes) {
if (bytesToSwap == 1)
return;
if (bytesToSwap == 2) { SwapBytes2(bytes); return; }
if (bytesToSwap == 4) { SwapBytes4(bytes); return; }
//if (bytesToSwap == 8) { Swap8(); return; }
unchecked {
int l = bytes.Length - (bytes.Length % bytesToSwap);
for (int i = 0; i < l; i += bytesToSwap) {
Array.Reverse(bytes, i, bytesToSwap);
}
}
}
public static void SwapBytes2(byte[] bytes) {
unchecked {
byte b;
int l = bytes.Length - (bytes.Length % 2);
for (int i = 0; i < l; i += 2) {
b = bytes[i + 1];
bytes[i + 1] = bytes[i];
bytes[i] = b;
}
}
}
public static void SwapBytes4(byte[] bytes) {
unchecked {
byte b;
int l = bytes.Length - (bytes.Length % 4);
for (int i = 0; i < l; i += 4) {
b = bytes[i + 3];
bytes[i + 3] = bytes[i];
bytes[i] = b;
b = bytes[i + 2];
bytes[i + 2] = bytes[i + 1];
bytes[i + 1] = b;
}
}
}
public static void SwapBytes8(byte[] bytes) {
SwapBytes(8, bytes);
}
public static short Swap(short value) {
return (short)Swap((ushort)value);
}
public static ushort Swap(ushort value) {
return unchecked((ushort)((value >> 8) | (value << 8)));
}
public static int Swap(int value) {
return (int)Swap((uint)value);
}
public static uint Swap(uint value) {
return unchecked(
((value & 0x000000ffU) << 24) |
((value & 0x0000ff00U) << 8) |
((value & 0x00ff0000U) >> 8) |
((value & 0xff000000U) >> 24));
}
public static long Swap(long value) {
return (long)Swap((ulong)value);
}
public static ulong Swap(ulong value) {
return unchecked(
((value & 0x00000000000000ffU) << 56) |
((value & 0x000000000000ff00U) << 40) |
((value & 0x0000000000ff0000U) << 24) |
((value & 0x00000000ff000000U) << 8) |
((value & 0x000000ff00000000U) >> 8) |
((value & 0x0000ff0000000000U) >> 24) |
((value & 0x00ff000000000000U) >> 40) |
((value & 0xff00000000000000U) >> 56));
}
public static float Swap(float value) {
byte[] b = BitConverter.GetBytes(value);
Array.Reverse(b);
return BitConverter.ToSingle(b, 0);
}
public static double Swap(double value) {
byte[] b = BitConverter.GetBytes(value);
Array.Reverse(b);
return BitConverter.ToDouble(b, 0);
}
public static void Swap(short[] values) {
Parallel.For(0, values.Length, (i) => {
values[i] = Swap(values[i]);
});
}
public static void Swap(ushort[] values) {
Parallel.For(0, values.Length, (i) => {
values[i] = Swap(values[i]);
});
}
public static void Swap(int[] values) {
Parallel.For(0, values.Length, (i) => {
values[i] = Swap(values[i]);
});
}
public static void Swap(uint[] values) {
Parallel.For(0, values.Length, (i) => {
values[i] = Swap(values[i]);
});
}
public static void Swap<T>(T[] values) {
if (typeof(T) == typeof(short))
Swap(values as short[]);
else if (typeof(T) == typeof(ushort))
Swap(values as ushort[]);
else if (typeof(T) == typeof(int))
Swap(values as int[]);
else if (typeof(T) == typeof(uint))
Swap(values as uint[]);
else
throw new InvalidOperationException("Attempted to byte swap non-specialized type: " + typeof(T).Name);
}
}
#endregion
#region EndianBinaryReader
public class EndianBinaryReader : BinaryReader {
#region Private Members
private bool SwapBytes = false;
private byte[] InternalBuffer = new byte[8];
#endregion
#region Public Constructors
public EndianBinaryReader(Stream input) : base(input) {
}
public EndianBinaryReader(Stream input, Encoding encoding) : base(input, encoding) {
}
public EndianBinaryReader(Stream input, Endian endian) : base(input) {
Endian = endian;
}
public EndianBinaryReader(Stream input, Encoding encoding, Endian endian) : base(input, encoding) {
Endian = endian;
}
public static BinaryReader Create(Stream input, Endian endian) {
if (input == null)
throw new ArgumentNullException("input");
if (endian == null)
throw new ArgumentNullException("endian");
if (BitConverter.IsLittleEndian) {
if (Endian.Little == endian) {
return new BinaryReader(input);
} else {
return new EndianBinaryReader(input, endian);
}
} else {
if (Endian.Big == endian) {
return new BinaryReader(input);
} else {
return new EndianBinaryReader(input, endian);
}
}
}
public static BinaryReader Create(Stream input, Encoding encoding, Endian endian) {
if (encoding == null)
return Create(input, endian);
if (input == null)
throw new ArgumentNullException("input");
if (endian == null)
throw new ArgumentNullException("endian");
if (BitConverter.IsLittleEndian) {
if (Endian.Little == endian) {
return new BinaryReader(input, encoding);
}
else {
return new EndianBinaryReader(input, encoding, endian);
}
}
else {
if (Endian.Big == endian) {
return new BinaryReader(input, encoding);
}
else {
return new EndianBinaryReader(input, encoding, endian);
}
}
}
#endregion
#region Public Properties
public Endian Endian {
get {
if (BitConverter.IsLittleEndian) {
return SwapBytes ? Endian.Big : Endian.Little;
} else {
return SwapBytes ? Endian.Little : Endian.Big;
}
}
set {
if (BitConverter.IsLittleEndian) {
SwapBytes = (Endian.Big == value);
} else {
SwapBytes = (Endian.Little == value);
}
}
}
public bool UseInternalBuffer {
get {
return (InternalBuffer != null);
}
set {
if (value && (InternalBuffer == null)) {
InternalBuffer = new byte[8];
} else {
InternalBuffer = null;
}
}
}
#endregion
#region Private Methods
private byte[] ReadBytesInternal(int count) {
byte[] Buffer = null;
if (InternalBuffer != null) {
base.Read(InternalBuffer, 0, count);
Buffer = InternalBuffer;
} else {
Buffer = base.ReadBytes(count);
}
if (SwapBytes) {
Array.Reverse(Buffer, 0, count);
}
return Buffer;
}
#endregion
#region BinaryReader Overrides
public override short ReadInt16() {
if (SwapBytes) {
return Endian.Swap(base.ReadInt16());
}
return base.ReadInt16();
}
public override int ReadInt32() {
if (SwapBytes) {
return Endian.Swap(base.ReadInt32());
}
return base.ReadInt32();
}
public override long ReadInt64() {
if (SwapBytes) {
return Endian.Swap(base.ReadInt64());
}
return base.ReadInt64();
}
public override float ReadSingle() {
if (SwapBytes) {
byte[] b = ReadBytesInternal(4);
return BitConverter.ToSingle(b, 0);
}
return base.ReadSingle();
}
public override double ReadDouble() {
if (SwapBytes) {
byte[] b = ReadBytesInternal(8);
return BitConverter.ToDouble(b, 0);
}
return base.ReadDouble();
}
public override ushort ReadUInt16() {
if (SwapBytes) {
return Endian.Swap(base.ReadUInt16());
}
return base.ReadUInt16();
}
public override uint ReadUInt32() {
if (SwapBytes) {
return Endian.Swap(base.ReadUInt32());
}
return base.ReadUInt32();
}
public override ulong ReadUInt64() {
if (SwapBytes) {
return Endian.Swap(base.ReadUInt64());
}
return base.ReadUInt64();
}
#endregion
}
#endregion
#region EndianBinaryWriter
public class EndianBinaryWriter : BinaryWriter {
#region Private Members
private bool SwapBytes = false;
#endregion
#region Public Constructors
public EndianBinaryWriter(Stream output) : base(output) {
}
public EndianBinaryWriter(Stream output, Encoding encoding) : base(output, encoding) {
}
public EndianBinaryWriter(Stream output, Endian endian) : base(output) {
Endian = endian;
}
public EndianBinaryWriter(Stream output, Encoding encoding, Endian endian) : base(output, encoding) {
Endian = endian;
}
public static BinaryWriter Create(Stream output, Endian endian) {
if (output == null)
throw new ArgumentNullException("output");
if (endian == null)
throw new ArgumentNullException("endian");
if (BitConverter.IsLittleEndian) {
if (Endian.Little == endian) {
return new BinaryWriter(output);
} else {
return new EndianBinaryWriter(output, endian);
}
} else {
if (Endian.Big == endian) {
return new BinaryWriter(output);
} else {
return new EndianBinaryWriter(output, endian);
}
}
}
public static BinaryWriter Create(Stream output, Encoding encoding, Endian endian) {
if (encoding == null)
return Create(output, endian);
if (output == null)
throw new ArgumentNullException("output");
if (endian == null)
throw new ArgumentNullException("endian");
if (BitConverter.IsLittleEndian) {
if (Endian.Little == endian) {
return new BinaryWriter(output, encoding);
}
else {
return new EndianBinaryWriter(output, encoding, endian);
}
}
else {
if (Endian.Big == endian) {
return new BinaryWriter(output, encoding);
}
else {
return new EndianBinaryWriter(output, encoding, endian);
}
}
}
#endregion
#region Public Properties
public Endian Endian {
get {
if (BitConverter.IsLittleEndian) {
return SwapBytes ? Endian.Big : Endian.Little;
} else {
return SwapBytes ? Endian.Little : Endian.Big;
}
}
set {
if (BitConverter.IsLittleEndian) {
SwapBytes = (Endian.Big == value);
} else {
SwapBytes = (Endian.Little == value);
}
}
}
#endregion
#region Private Methods
private void WriteInternal(byte[] Buffer) {
if (SwapBytes) {
Array.Reverse(Buffer);
}
base.Write(Buffer);
}
#endregion
#region BinaryWriter Overrides
public override void Write(double value) {
if (SwapBytes) {
byte[] b = BitConverter.GetBytes(value);
WriteInternal(b);
} else {
base.Write(value);
}
}
public override void Write(float value) {
if (SwapBytes) {
byte[] b = BitConverter.GetBytes(value);
WriteInternal(b);
} else {
base.Write(value);
}
}
public override void Write(int value) {
if (SwapBytes) {
byte[] b = BitConverter.GetBytes(value);
WriteInternal(b);
} else {
base.Write(value);
}
}
public override void Write(long value) {
if (SwapBytes) {
byte[] b = BitConverter.GetBytes(value);
WriteInternal(b);
} else {
base.Write(value);
}
}
public override void Write(short value) {
if (SwapBytes) {
byte[] b = BitConverter.GetBytes(value);
WriteInternal(b);
} else {
base.Write(value);
}
}
public override void Write(uint value) {
if (SwapBytes) {
byte[] b = BitConverter.GetBytes(value);
WriteInternal(b);
} else {
base.Write(value);
}
}
public override void Write(ulong value) {
if (SwapBytes) {
byte[] b = BitConverter.GetBytes(value);
WriteInternal(b);
} else {
base.Write(value);
}
}
public override void Write(ushort value) {
if (SwapBytes) {
byte[] b = BitConverter.GetBytes(value);
WriteInternal(b);
} else {
base.Write(value);
}
}
#endregion
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace NServiceKit.Redis.Tests
{
[TestFixture]
public class RedisTransactionTests
: RedisClientTestsBase
{
private const string Key = "rdtmultitest";
private const string ListKey = "rdtmultitest-list";
private const string SetKey = "rdtmultitest-set";
private const string SortedSetKey = "rdtmultitest-sortedset";
public override void TearDown()
{
CleanMask = Key + "*";
base.TearDown();
}
[Test]
public void Can_call_single_operation_in_transaction()
{
Assert.That(Redis.GetValue(Key), Is.Null);
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.IncrementValue(Key));
var map = new Dictionary<string, int>();
trans.QueueCommand(r => r.Get<int>(Key), y => map[Key] = y);
trans.Commit();
}
Assert.That(Redis.GetValue(Key), Is.EqualTo("1"));
}
[Test]
public void No_commit_of_atomic_transactions_discards_all_commands()
{
Assert.That(Redis.GetValue(Key), Is.Null);
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.IncrementValue(Key));
}
Assert.That(Redis.GetValue(Key), Is.Null);
}
[Test]
public void Watch_aborts_transaction()
{
Assert.That(Redis.GetValue(Key), Is.Null);
const string value1 = "value1";
const string value2 = "value2";
try
{
Redis.Watch(Key);
Redis.Set(Key, value1);
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.Set(Key,value1));
var success = trans.Commit();
Assert.False(success);
Assert.AreEqual(value1, Redis.Get<string>(Key));
}
}
catch (NotSupportedException ignore)
{
Assert.That(Redis.GetValue(Key), Is.Null);
}
}
[Test]
public void Exception_in_atomic_transactions_discards_all_commands()
{
Assert.That(Redis.GetValue(Key), Is.Null);
try
{
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.IncrementValue(Key));
throw new NotSupportedException();
}
}
catch (NotSupportedException ignore)
{
Assert.That(Redis.GetValue(Key), Is.Null);
}
}
[Test]
public void Can_call_single_operation_3_Times_in_transaction()
{
Assert.That(Redis.GetValue(Key), Is.Null);
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.IncrementValue(Key));
trans.QueueCommand(r => r.IncrementValue(Key));
trans.QueueCommand(r => r.IncrementValue(Key));
trans.Commit();
}
Assert.That(Redis.GetValue(Key), Is.EqualTo("3"));
}
[Test]
public void Can_call_single_operation_with_callback_3_Times_in_transaction()
{
var results = new List<long>();
Assert.That(Redis.GetValue(Key), Is.Null);
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.IncrementValue(Key), results.Add);
trans.QueueCommand(r => r.IncrementValue(Key), results.Add);
trans.QueueCommand(r => r.IncrementValue(Key), results.Add);
trans.Commit();
}
Assert.That(Redis.GetValue(Key), Is.EqualTo("3"));
Assert.That(results, Is.EquivalentTo(new List<long> { 1, 2, 3 }));
}
[Test]
public void Supports_different_operation_types_in_same_transaction()
{
var incrementResults = new List<long>();
var collectionCounts = new List<long>();
var containsItem = false;
Assert.That(Redis.GetValue(Key), Is.Null);
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.IncrementValue(Key), intResult => incrementResults.Add(intResult));
trans.QueueCommand(r => r.AddItemToList(ListKey, "listitem1"));
trans.QueueCommand(r => r.AddItemToList(ListKey, "listitem2"));
trans.QueueCommand(r => r.AddItemToSet(SetKey, "setitem"));
trans.QueueCommand(r => r.SetContainsItem(SetKey, "setitem"), b => containsItem = b);
trans.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, "sortedsetitem1"));
trans.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, "sortedsetitem2"));
trans.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, "sortedsetitem3"));
trans.QueueCommand(r => r.GetListCount(ListKey), intResult => collectionCounts.Add(intResult));
trans.QueueCommand(r => r.GetSetCount(SetKey), intResult => collectionCounts.Add(intResult));
trans.QueueCommand(r => r.GetSortedSetCount(SortedSetKey), intResult => collectionCounts.Add(intResult));
trans.QueueCommand(r => r.IncrementValue(Key), intResult => incrementResults.Add(intResult));
trans.Commit();
}
Assert.That(containsItem, Is.True);
Assert.That(Redis.GetValue(Key), Is.EqualTo("2"));
Assert.That(incrementResults, Is.EquivalentTo(new List<long> { 1, 2 }));
Assert.That(collectionCounts, Is.EquivalentTo(new List<int> { 2, 1, 3 }));
Assert.That(Redis.GetAllItemsFromList(ListKey), Is.EquivalentTo(new List<string> { "listitem1", "listitem2" }));
Assert.That(Redis.GetAllItemsFromSet(SetKey), Is.EquivalentTo(new List<string> { "setitem" }));
Assert.That(Redis.GetAllItemsFromSortedSet(SortedSetKey), Is.EquivalentTo(new List<string> { "sortedsetitem1", "sortedsetitem2", "sortedsetitem3" }));
}
[Test]
public void Can_call_multi_string_operations_in_transaction()
{
string item1 = null;
string item4 = null;
var results = new List<string>();
Assert.That(Redis.GetListCount(ListKey), Is.EqualTo(0));
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.AddItemToList(ListKey, "listitem1"));
trans.QueueCommand(r => r.AddItemToList(ListKey, "listitem2"));
trans.QueueCommand(r => r.AddItemToList(ListKey, "listitem3"));
trans.QueueCommand(r => r.GetAllItemsFromList(ListKey), x => results = x);
trans.QueueCommand(r => r.GetItemFromList(ListKey, 0), x => item1 = x);
trans.QueueCommand(r => r.GetItemFromList(ListKey, 4), x => item4 = x);
trans.Commit();
}
Assert.That(Redis.GetListCount(ListKey), Is.EqualTo(3));
Assert.That(results, Is.EquivalentTo(new List<string> { "listitem1", "listitem2", "listitem3" }));
Assert.That(item1, Is.EqualTo("listitem1"));
Assert.That(item4, Is.Null);
}
[Test]
public void Can_call_multiple_setexs_in_transaction()
{
Assert.That(Redis.GetValue(Key), Is.Null);
var keys = new[] { "key1", "key2", "key3" };
var values = new[] { "1", "2", "3" };
var trans = Redis.CreateTransaction();
for (int i = 0; i < 3; ++i)
{
int index0 = i;
trans.QueueCommand(r => ((RedisNativeClient)r).SetEx(keys[index0], 100, GetBytes(values[index0])));
}
trans.Commit();
trans.Replay();
for (int i = 0; i < 3; ++i)
Assert.AreEqual(Redis.GetValue(keys[i]), values[i]);
trans.Dispose();
}
[Test]
// Operations that are not supported in older versions will look at server info to determine what to do.
// If server info is fetched each time, then it will interfer with transaction
public void Can_call_operation_not_supported_on_older_servers_in_transaction()
{
var temp = new byte[1];
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => ((RedisNativeClient)r).SetEx(Key,5,temp));
trans.Commit();
}
}
[Test]
public void Transaction_can_be_replayed()
{
string KeySquared = Key + Key;
Assert.That(Redis.GetValue(Key), Is.Null);
Assert.That(Redis.GetValue(KeySquared), Is.Null);
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.IncrementValue(Key));
trans.QueueCommand(r => r.IncrementValue(KeySquared));
trans.Commit();
Assert.That(Redis.GetValue(Key), Is.EqualTo("1"));
Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1"));
Redis.Del(Key);
Redis.Del(KeySquared);
Assert.That(Redis.GetValue(Key), Is.Null);
Assert.That(Redis.GetValue(KeySquared), Is.Null);
trans.Replay();
trans.Dispose();
Assert.That(Redis.GetValue(Key), Is.EqualTo("1"));
Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1"));
}
}
[Test]
public void Transaction_can_issue_watch()
{
Redis.Del(Key);
Assert.That(Redis.GetValue(Key), Is.Null);
string KeySquared = Key + Key;
Redis.Del(KeySquared);
Redis.Watch(Key, KeySquared);
Redis.Set(Key, 7);
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.Set(Key, 1));
trans.QueueCommand(r => r.Set(KeySquared, 2));
trans.Commit();
}
Assert.That(Redis.GetValue(Key), Is.EqualTo("7"));
Assert.That(Redis.GetValue(KeySquared), Is.Null);
}
}
}
| |
// 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.Generic;
using System.Text;
using System.Collections;
using Alachisoft.NCache.Common.DataStructures;
using Alachisoft.NCache.Caching;
namespace Alachisoft.NCache.Web.Caching
{
internal class WebCacheEnumerator : IDictionaryEnumerator, IDisposable
{
private Cache _cache;
private List<EnumerationDataChunk> _currentChunks;
private IEnumerator<string> _currentChunkEnumerator;
private object _currentValue;
private string _serializationContext;
private DictionaryEntry _de;
internal WebCacheEnumerator(string serializationContext, Cache cache)
{
_cache = cache;
_serializationContext = serializationContext;
_de = new DictionaryEntry();
Initialize();
}
public void Initialize()
{
List<EnumerationPointer> pointers = new List<EnumerationPointer>();
pointers.Add(new EnumerationPointer());
_currentChunks = _cache.GetNextChunk(pointers);
List<string> data = new List<string>();
for (int i = 0; i < _currentChunks.Count; i++)
{
if (_currentChunks[i] != null && _currentChunks[i].Data != null)
{
data.AddRange(_currentChunks[i].Data);
}
}
_currentChunkEnumerator = data.GetEnumerator();
}
#region / --- IEnumerator --- /
/// <summary>
/// Set the enumerator to its initial position. which is before the first element in the collection
/// </summary>
public void Reset()
{
if (_currentChunks != null && _currentChunks.Count > 0)
{
for (int i = 0; i < _currentChunks.Count; i++)
{
_currentChunks[i].Pointer.Reset();
}
}
if (_currentChunkEnumerator != null)
_currentChunkEnumerator.Reset();
}
/// <summary>
/// Advance the enumerator to the next element of the collection
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
bool result = false;
if (_currentChunkEnumerator != null)
{
result = _currentChunkEnumerator.MoveNext();
if (!result)
{
if (_currentChunks != null && !IsLastChunk(_currentChunks))
{
_currentChunks = _cache.GetNextChunk(GetPointerList(_currentChunks));
List<string> data = new List<string>();
for (int i = 0; i < _currentChunks.Count; i++)
{
if (_currentChunks[i] != null && _currentChunks[i].Data != null)
{
data.AddRange(_currentChunks[i].Data);
}
}
if (data != null && data.Count > 0)
{
_currentChunkEnumerator = data.GetEnumerator();
result = _currentChunkEnumerator.MoveNext();
}
}
else if (_currentChunks != null && _currentChunks.Count > 0)
{
List<EnumerationPointer> pointers = GetPointerList(_currentChunks);
if (pointers.Count > 0)
_cache.GetNextChunk(pointers); //just an empty call to dispose enumerator for this particular list of pointer
}
}
}
return result;
}
private List<EnumerationPointer> GetPointerList(List<EnumerationDataChunk> chunks)
{
List<EnumerationPointer> pointers = new List<EnumerationPointer>();
for (int i = 0; i < chunks.Count; i++)
{
if (!chunks[i].IsLastChunk)
pointers.Add(chunks[i].Pointer);
}
return pointers;
}
private bool IsLastChunk(List<EnumerationDataChunk> chunks)
{
for (int i = 0; i < chunks.Count; i++)
{
if (!chunks[i].IsLastChunk)
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the current element in the collection
/// </summary>
public object Current
{
get
{
return Entry;
}
}
#endregion
#region / --- IDictionaryEnumerator --- /
/// <summary>
/// Gets the key and value of the current dictionary entry.
/// </summary>
public DictionaryEntry Entry
{
get
{
_de.Key = Key;
_de.Value = Value;
return _de;
}
}
/// <summary>
/// Gets the key of the current dictionary entry
/// </summary>
public object Key
{
get
{
object key = null;
if (_currentChunkEnumerator != null)
key = _currentChunkEnumerator.Current;
return key;
}
}
/// <summary>
/// Gets the value of the current dictionary entry
/// </summary>
public object Value
{
get
{
try
{
return _cache.Get(Key as string);
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Connection with server lost"))
{
try
{
return _cache.Get(Key as string);
}
catch (Exception inner)
{
throw inner;
}
}
throw ex;
}
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (_cache != null && _currentChunks != null)
{
List<EnumerationPointer> pointerlist = GetPointerList(_currentChunks);
if (pointerlist.Count > 0)
{
_cache.GetNextChunk(pointerlist); //just an empty call to dispose enumerator for this particular pointer
}
}
_cache = null;
_serializationContext = null;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace Operation_Cronos.Input {
/// <summary>
/// Generates mouse events.
/// </summary>
public class MouseManager : Microsoft.Xna.Framework.GameComponent {
const int MoveTreshold = 0;
#region Fields
/// <summary>
/// The previous state of the mouse.
/// </summary>
private MouseState oldMouse;
/// <summary>
/// The current state of the mouse.
/// </summary>
private MouseState thisMouse;
/// <summary>
/// The positions of the mouse.
/// </summary>
private Point position;
/// <summary>
/// The mouse button which is currently pressed.
/// </summary>
private MouseButton pressedButton;
#endregion
#region Properties
/// <summary>
/// The previous state of the mouse.
/// </summary>
public MouseState OldMouseState {
get { return oldMouse; }
}
/// <summary>
/// The current state of the mouse.
/// </summary>
public MouseState CurrentMouseState {
get { return thisMouse; }
}
/// <summary>
/// The current mouse positions.
/// </summary>
public Point MousePosition {
get { return position; }
}
#endregion
#region Events
/// <summary>
/// Invoked when a button is pressed.
/// </summary>
public event EventHandler<MouseEventArgs> OnPress = delegate { };
/// <summary>
/// Invoked when a mouse button is released.
/// </summary>
public event EventHandler<MouseEventArgs> OnRelease = delegate { };
/// <summary>
/// Invoked when the mouse wheel is rolled.
/// </summary>
public event EventHandler<MouseEventArgs> OnWheel = delegate { };
/// <summary>
/// Invoked when the mouse is moved.
/// </summary>
public event EventHandler<MouseEventArgs> OnMouseMove = delegate { };
#endregion
#region Constructors
public MouseManager(Game game)
: base(game) {
Game.Components.Add(this);
}
#endregion
#region Overrides
/// <summary>
/// Allows the game component to perform any initialization it needs to before starting
/// to run. This is where it can query for any required services and load content.
/// </summary>
public override void Initialize() {
pressedButton = MouseButton.None;
oldMouse = Mouse.GetState();
base.Initialize();
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
public override void Update(GameTime gameTime) {
base.Update(gameTime);
UpdateCurrentMouse();
PollButtons();
PollWheel();
PollPosition();
UpdateOldMouse();
}
#endregion
#region Methods
/// <summary>
/// Called after all the polling has been made,
/// keeps the current state of the mouse for the next polling.
/// </summary>
private void UpdateOldMouse() {
oldMouse = Mouse.GetState();
}
/// <summary>
/// Called before polling, takes the current mouse state
/// to be able to compare it with the previous.
/// </summary>
private void UpdateCurrentMouse() {
thisMouse = Mouse.GetState();
position = new Point(thisMouse.X, thisMouse.Y);
}
/// <summary>
/// Polls the buttons of the mouse for changes in their states.
/// </summary>
private void PollButtons() {
#region Left Button
if (OldMouseState.LeftButton == ButtonState.Released
&& CurrentMouseState.LeftButton == ButtonState.Pressed) {
pressedButton = MouseButton.LeftButton;
OnPress(this, new MouseEventArgs(MousePosition, MouseButton.LeftButton));
}
if (OldMouseState.LeftButton == ButtonState.Pressed
&& CurrentMouseState.LeftButton == ButtonState.Released) {
pressedButton = MouseButton.None;
OnRelease(this, new MouseEventArgs(MousePosition, MouseButton.LeftButton));
}
#endregion
#region Right Button
if (OldMouseState.RightButton == ButtonState.Released
&& CurrentMouseState.RightButton == ButtonState.Pressed) {
pressedButton = MouseButton.RightButton;
OnPress(this, new MouseEventArgs(MousePosition, MouseButton.RightButton));
}
if (OldMouseState.RightButton == ButtonState.Pressed
&& CurrentMouseState.RightButton == ButtonState.Released) {
pressedButton = MouseButton.None;
OnRelease(this, new MouseEventArgs(MousePosition, MouseButton.RightButton));
}
#endregion
#region Middle Button
if (OldMouseState.MiddleButton == ButtonState.Released
&& CurrentMouseState.MiddleButton == ButtonState.Pressed) {
pressedButton = MouseButton.MiddleButton;
OnPress(this, new MouseEventArgs(MousePosition, MouseButton.MiddleButton));
}
if (OldMouseState.MiddleButton == ButtonState.Pressed
&& CurrentMouseState.MiddleButton == ButtonState.Released) {
pressedButton = MouseButton.None;
OnRelease(this, new MouseEventArgs(MousePosition, MouseButton.MiddleButton));
}
#endregion
#region Extra Button 1
if (OldMouseState.XButton1 == ButtonState.Released
&& CurrentMouseState.XButton1 == ButtonState.Pressed) {
pressedButton = MouseButton.ExtraButton1;
OnPress(this, new MouseEventArgs(MousePosition, MouseButton.ExtraButton1));
}
if (OldMouseState.XButton1 == ButtonState.Pressed
&& CurrentMouseState.XButton1 == ButtonState.Released) {
pressedButton = MouseButton.None;
OnRelease(this, new MouseEventArgs(MousePosition, MouseButton.ExtraButton1));
}
#endregion
#region Extra Button 2
if (OldMouseState.XButton2 == ButtonState.Released
&& CurrentMouseState.XButton2 == ButtonState.Pressed) {
pressedButton = MouseButton.ExtraButton2;
OnPress(this, new MouseEventArgs(MousePosition, MouseButton.ExtraButton2));
}
if (OldMouseState.XButton2 == ButtonState.Pressed
&& CurrentMouseState.XButton2 == ButtonState.Released) {
pressedButton = MouseButton.None;
OnRelease(this, new MouseEventArgs(MousePosition, MouseButton.ExtraButton2));
}
#endregion
}
/// <summary>
/// Checks if the wheel value is changed and
/// generates an OnWheel event if that is true.
/// </summary>
private void PollWheel() {
int value = CurrentMouseState.ScrollWheelValue - OldMouseState.ScrollWheelValue;
if (value < 0) {
OnWheel(this, new MouseEventArgs(MousePosition, MouseButton.WheelBackward));
} else if (value > 0) {
OnWheel(this, new MouseEventArgs(MousePosition, MouseButton.WheelForward));
}
}
/// <summary>
/// Checks if the mouse has been moved from the last
/// polling, and if it's true, generates an MouseMove event,
/// sending the pressed button too.
/// </summary>
private void PollPosition() {
if (Math.Abs(CurrentMouseState.X - OldMouseState.X) > MouseManager.MoveTreshold
|| Math.Abs(CurrentMouseState.Y - OldMouseState.Y) > MouseManager.MoveTreshold) {
OnMouseMove(this, new MouseEventArgs(MousePosition, pressedButton));
}
}
#endregion
}
}
| |
// -----------------------------------------------------------------------
// Licensed to The .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// -----------------------------------------------------------------------
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Security.Cryptography.Asn1
{
[ExcludeFromCodeCoverage]
internal sealed partial class AsnWriter
{
/// <summary>
/// Write a Bit String value with a tag UNIVERSAL 3.
/// </summary>
/// <param name="bitString">The value to write.</param>
/// <param name="unusedBitCount">
/// The number of trailing bits which are not semantic.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="unusedBitCount"/> is not in the range [0,7]
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="bitString"/> has length 0 and <paramref name="unusedBitCount"/> is not 0 --OR--
/// <paramref name="bitString"/> is not empty and any of the bits identified by
/// <paramref name="unusedBitCount"/> is set
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteBitString(ReadOnlySpan<byte> bitString, int unusedBitCount = 0)
{
this.WriteBitStringCore(Asn1Tag.PrimitiveBitString, bitString, unusedBitCount);
}
/// <summary>
/// Write a Bit String value with a specified tag.
/// </summary>
/// <param name="tag">The tag to write.</param>
/// <param name="bitString">The value to write.</param>
/// <param name="unusedBitCount">
/// The number of trailing bits which are not semantic.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="unusedBitCount"/> is not in the range [0,7]
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="bitString"/> has length 0 and <paramref name="unusedBitCount"/> is not 0 --OR--
/// <paramref name="bitString"/> is not empty and any of the bits identified by
/// <paramref name="unusedBitCount"/> is set
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteBitString(Asn1Tag tag, ReadOnlySpan<byte> bitString, int unusedBitCount = 0)
{
CheckUniversalTag(tag, UniversalTagNumber.BitString);
// Primitive or constructed, doesn't matter.
this.WriteBitStringCore(tag, bitString, unusedBitCount);
}
// T-REC-X.690-201508 sec 8.6
private void WriteBitStringCore(Asn1Tag tag, ReadOnlySpan<byte> bitString, int unusedBitCount)
{
// T-REC-X.690-201508 sec 8.6.2.2
if (unusedBitCount < 0 || unusedBitCount > 7)
{
throw new ArgumentOutOfRangeException(
nameof(unusedBitCount),
unusedBitCount,
SR.Resource("Cryptography_Asn_UnusedBitCountRange"));
}
this.CheckDisposed();
// T-REC-X.690-201508 sec 8.6.2.3
if (bitString.Length == 0 && unusedBitCount != 0)
{
throw new CryptographicException(SR.Resource("Cryptography_Der_Invalid_Encoding"));
}
byte lastByte = bitString.IsEmpty ? (byte)0 : bitString[bitString.Length - 1];
// T-REC-X.690-201508 sec 11.2
//
// This could be ignored for BER, but since DER is more common and
// it likely suggests a program error on the caller, leave it enabled for
// BER for now.
if (!CheckValidLastByte(lastByte, unusedBitCount))
{
// TODO: Probably warrants a distinct message.
throw new CryptographicException(SR.Resource("Cryptography_Der_Invalid_Encoding"));
}
if (this.RuleSet == AsnEncodingRules.CER)
{
// T-REC-X.690-201508 sec 9.2
//
// If it's not within a primitive segment, use the constructed encoding.
// (>= instead of > because of the unused bit count byte)
if (bitString.Length >= AsnReader.MaxCERSegmentSize)
{
this.WriteConstructedCerBitString(tag, bitString, unusedBitCount);
return;
}
}
// Clear the constructed flag, if present.
this.WriteTag(tag.AsPrimitive());
// The unused bits byte requires +1.
this.WriteLength(bitString.Length + 1);
this._buffer[this._offset] = (byte)unusedBitCount;
this._offset++;
bitString.CopyTo(this._buffer.AsSpan(this._offset));
this._offset += bitString.Length;
}
#if netcoreapp || uap || NETCOREAPP || netstandard21
/// <summary>
/// Write a Bit String value via a callback, with a tag UNIVERSAL 3.
/// </summary>
/// <param name="byteLength">The total number of bytes to write.</param>
/// <param name="state">A state object to pass to <paramref name="action"/>.</param>
/// <param name="action">A callback to invoke for populating the Bit String.</param>
/// <param name="unusedBitCount">
/// The number of trailing bits which are not semantic.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="byteLength"/> is negative --OR--
/// <paramref name="unusedBitCount"/> is not in the range [0,7]
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="byteLength"/> is 0 and <paramref name="unusedBitCount"/> is not 0 --OR--
/// <paramref name="byteLength"/> is not 0 and any of the bits identified by
/// <paramref name="unusedBitCount"/> is set
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteBitString<TState>(
int byteLength,
TState state,
SpanAction<byte, TState> action,
int unusedBitCount = 0)
{
WriteBitStringCore(Asn1Tag.PrimitiveBitString, byteLength, state, action, unusedBitCount);
}
/// <summary>
/// Write a Bit String value via a callback, with a specified tag.
/// </summary>
/// <param name="tag">The tag to write.</param>
/// <param name="byteLength">The total number of bytes to write.</param>
/// <param name="state">A state object to pass to <paramref name="action"/>.</param>
/// <param name="action">A callback to invoke for populating the Bit String.</param>
/// <param name="unusedBitCount">
/// The number of trailing bits which are not semantic.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="byteLength"/> is negative --OR--
/// <paramref name="unusedBitCount"/> is not in the range [0,7]
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="byteLength"/> is 0 and <paramref name="unusedBitCount"/> is not 0 --OR--
/// <paramref name="byteLength"/> is not 0 and any of the bits identified by
/// <paramref name="unusedBitCount"/> is set
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteBitString<TState>(
Asn1Tag tag,
int byteLength,
TState state,
SpanAction<byte, TState> action,
int unusedBitCount = 0)
{
CheckUniversalTag(tag, UniversalTagNumber.BitString);
// Primitive or constructed, doesn't matter.
WriteBitStringCore(tag, byteLength, state, action, unusedBitCount);
}
// T-REC-X.690-201508 sec 8.6
private void WriteBitStringCore<TState>(
Asn1Tag tag,
int byteLength,
TState state,
SpanAction<byte, TState> action,
int unusedBitCount = 0)
{
if (byteLength == 0)
{
WriteBitStringCore(tag, ReadOnlySpan<byte>.Empty, unusedBitCount);
return;
}
// T-REC-X.690-201508 sec 8.6.2.2
if (unusedBitCount < 0 || unusedBitCount > 7)
{
throw new ArgumentOutOfRangeException(
nameof(unusedBitCount),
unusedBitCount,
SR.Resource("Cryptography_Asn_UnusedBitCountRange"));
}
CheckDisposed();
int savedOffset = _offset;
Span<byte> scratchSpace;
byte[] ensureNoExtraCopy = null;
int expectedSize = 0;
// T-REC-X.690-201508 sec 9.2
//
// If it's not within a primitive segment, use the constructed encoding.
// (>= instead of > because of the unused bit count byte)
bool segmentedWrite =
RuleSet == AsnEncodingRules.CER && byteLength >= AsnReader.MaxCERSegmentSize;
if (segmentedWrite)
{
// Rather than call the callback multiple times, grow the buffer to allow
// for enough space for the final output, then return a buffer where the last segment
// is in the correct place. (Data will shift backwards to the right spot while writing
// other segments).
expectedSize = DetermineCerBitStringTotalLength(tag, byteLength);
EnsureWriteCapacity(expectedSize);
int overhead = expectedSize - byteLength;
// Start writing where the last content byte is in the correct place, which is
// after all of the overhead, but ending before the two byte end-of-contents marker.
int scratchStart = overhead - 2;
ensureNoExtraCopy = _buffer;
scratchSpace = _buffer.AsSpan(scratchStart, byteLength);
// Don't let gapped-writes be unpredictable.
scratchSpace.Clear();
}
else
{
WriteTag(tag.AsPrimitive());
// The unused bits byte requires +1.
WriteLength(byteLength + 1);
_buffer[_offset] = (byte)unusedBitCount;
_offset++;
scratchSpace = _buffer.AsSpan(_offset, byteLength);
}
action(scratchSpace, state);
// T-REC-X.690-201508 sec 11.2
//
// This could be ignored for BER, but since DER is more common and
// it likely suggests a program error on the caller, leave it enabled for
// BER for now.
if (!CheckValidLastByte(scratchSpace[byteLength - 1], unusedBitCount))
{
// Since we are restoring _offset we won't clear this on a grow or Dispose,
// so clear it now.
_offset = savedOffset;
scratchSpace.Clear();
// TODO: Probably warrants a distinct message.
throw new CryptographicException(SR.Resource("Cryptography_Der_Invalid_Encoding"));
}
if (segmentedWrite)
{
WriteConstructedCerBitString(tag, scratchSpace, unusedBitCount);
Debug.Assert(_offset - savedOffset == expectedSize, $"expected size was {expectedSize}, actual was {_offset - savedOffset}");
Debug.Assert(_buffer == ensureNoExtraCopy, $"_buffer was replaced during while writing a bit string via callback");
}
else
{
_offset += byteLength;
}
}
#endif
private static bool CheckValidLastByte(byte lastByte, int unusedBitCount)
{
// If 3 bits are "unused" then build a mask for them to check for 0.
// 1 << 3 => 0b0000_1000
// subtract 1 => 0b000_0111
int mask = (1 << unusedBitCount) - 1;
return ((lastByte & mask) == 0);
}
private static int DetermineCerBitStringTotalLength(Asn1Tag tag, int contentLength)
{
const int MaxCERSegmentSize = AsnReader.MaxCERSegmentSize;
// Every segment has an "unused bit count" byte.
const int MaxCERContentSize = MaxCERSegmentSize - 1;
Debug.Assert(contentLength > MaxCERContentSize);
int fullSegments = Math.DivRem(contentLength, MaxCERContentSize, out int lastContentSize);
// The tag size is 1 byte.
// The length will always be encoded as 82 03 E8 (3 bytes)
// And 1000 content octets (by T-REC-X.690-201508 sec 9.2)
const int FullSegmentEncodedSize = 1004;
Debug.Assert(
1 + 1 + MaxCERSegmentSize + GetEncodedLengthSubsequentByteCount(MaxCERSegmentSize) == FullSegmentEncodedSize);
int remainingEncodedSize;
if (lastContentSize == 0)
{
remainingEncodedSize = 0;
}
else
{
// One byte of tag, minimum one byte of length, and one byte of unused bit count.
remainingEncodedSize = 3 + lastContentSize + GetEncodedLengthSubsequentByteCount(lastContentSize);
}
// Reduce the number of copies by pre-calculating the size.
// +2 for End-Of-Contents
// +1 for 0x80 indefinite length
// +tag length
return (fullSegments * FullSegmentEncodedSize) + remainingEncodedSize + 3 + tag.CalculateEncodedSize();
}
// T-REC-X.690-201508 sec 9.2, 8.6
private void WriteConstructedCerBitString(Asn1Tag tag, ReadOnlySpan<byte> payload, int unusedBitCount)
{
const int MaxCERSegmentSize = AsnReader.MaxCERSegmentSize;
// Every segment has an "unused bit count" byte.
const int MaxCERContentSize = MaxCERSegmentSize - 1;
Debug.Assert(payload.Length > MaxCERContentSize);
int expectedSize = DetermineCerBitStringTotalLength(tag, payload.Length);
this.EnsureWriteCapacity(expectedSize);
int savedOffset = this._offset;
this.WriteTag(tag.AsConstructed());
// T-REC-X.690-201508 sec 9.1
// Constructed CER uses the indefinite form.
this.WriteLength(-1);
byte[] ensureNoExtraCopy = this._buffer;
ReadOnlySpan<byte> remainingData = payload;
Span<byte> dest;
Asn1Tag primitiveBitString = Asn1Tag.PrimitiveBitString;
while (remainingData.Length > MaxCERContentSize)
{
// T-REC-X.690-201508 sec 8.6.4.1
this.WriteTag(primitiveBitString);
this.WriteLength(MaxCERSegmentSize);
// 0 unused bits in this segment.
this._buffer[this._offset] = 0;
this._offset++;
dest = this._buffer.AsSpan(this._offset);
remainingData.Slice(0, MaxCERContentSize).CopyTo(dest);
remainingData = remainingData.Slice(MaxCERContentSize);
this._offset += MaxCERContentSize;
}
this.WriteTag(primitiveBitString);
this.WriteLength(remainingData.Length + 1);
this._buffer[this._offset] = (byte)unusedBitCount;
this._offset++;
dest = this._buffer.AsSpan(this._offset);
remainingData.CopyTo(dest);
this._offset += remainingData.Length;
this.WriteEndOfContents();
Debug.Assert(this._offset - savedOffset == expectedSize, $"expected size was {expectedSize}, actual was {this._offset - savedOffset}");
Debug.Assert(this._buffer == ensureNoExtraCopy, $"_buffer was replaced during {nameof(this.WriteConstructedCerBitString)}");
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009 Oracle. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using BerkeleyDB.Internal;
namespace BerkeleyDB {
/// <summary>
/// A class for traversing the records of a <see cref="BTreeDatabase"/>
/// </summary>
public class BTreeCursor : Cursor {
internal BTreeCursor(DBC dbc, uint pagesize)
: base(dbc, DatabaseType.BTREE, pagesize) { }
internal BTreeCursor(DBC dbc, uint pagesize, CachePriority p)
: base(dbc, DatabaseType.BTREE, pagesize, p) { }
/// <summary>
/// Create a new cursor that uses the same transaction and locker ID as
/// the original cursor.
/// </summary>
/// <remarks>
/// This is useful when an application is using locking and requires two
/// or more cursors in the same thread of control.
/// </remarks>
/// <param name="keepPosition">
/// If true, the newly created cursor is initialized to refer to the
/// same position in the database as the original cursor (if any) and
/// hold the same locks (if any). If false, or the original cursor does
/// not hold a database position and locks, the created cursor is
/// uninitialized and will behave like a cursor newly created by
/// <see cref="BTreeDatabase.Cursor"/>.</param>
/// <returns>A newly created cursor</returns>
public new BTreeCursor Duplicate(bool keepPosition) {
return new BTreeCursor(
dbc.dup(keepPosition ? DbConstants.DB_POSITION : 0), pgsz);
}
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair in <see cref="Cursor.Current"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool Move(uint recno) { return Move(recno, null); }
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair in <see cref="Cursor.Current"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <param name="info">The locking behavior to use</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool Move(uint recno, LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
key.Data = BitConverter.GetBytes(recno);
DatabaseEntry data = new DatabaseEntry();
return base.Get(key, data, DbConstants.DB_SET_RECNO, info);
}
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair and as many duplicate data items that can
/// fit in a buffer the size of one database page in
/// <see cref="Cursor.CurrentMultiple"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveMultiple(uint recno) {
return MoveMultiple(recno, (int)pgsz, null);
}
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair and as many duplicate data items that can
/// fit in a buffer the size of one database page in
/// <see cref="Cursor.CurrentMultiple"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <param name="BufferSize">
/// The size of a buffer to fill with duplicate data items. Must be at
/// least the page size of the underlying database and be a multiple of
/// 1024.
/// </param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveMultiple(uint recno, int BufferSize) {
return MoveMultiple(recno, BufferSize, null);
}
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair and as many duplicate data items that can
/// fit in a buffer the size of one database page in
/// <see cref="Cursor.CurrentMultiple"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <param name="info">The locking behavior to use</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveMultiple(uint recno, LockingInfo info) {
return MoveMultiple(recno, (int)pgsz, info);
}
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair and as many duplicate data items that can
/// fit in a buffer the size of one database page in
/// <see cref="Cursor.CurrentMultiple"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <param name="BufferSize">
/// The size of a buffer to fill with duplicate data items. Must be at
/// least the page size of the underlying database and be a multiple of
/// 1024.
/// </param>
/// <param name="info">The locking behavior to use</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveMultiple(uint recno, int BufferSize, LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
key.Data = BitConverter.GetBytes(recno);
DatabaseEntry data = new DatabaseEntry();
return base.GetMultiple(
key, data, BufferSize, DbConstants.DB_SET_RECNO, info, false);
}
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair and as many ensuing key/data pairs that can
/// fit in a buffer the size of one database page in
/// <see cref="Cursor.CurrentMultipleKey"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveMultipleKey(uint recno) {
return MoveMultipleKey(recno, (int)pgsz, null);
}
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair and as many ensuing key/data pairs that can
/// fit in a buffer the size of one database page in
/// <see cref="Cursor.CurrentMultipleKey"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <param name="BufferSize">
/// The size of a buffer to fill with key/data pairs. Must be at least
/// the page size of the underlying database and be a multiple of 1024.
/// </param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveMultipleKey(uint recno, int BufferSize) {
return MoveMultipleKey(recno, BufferSize, null);
}
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair and as many ensuing key/data pairs that can
/// fit in a buffer the size of one database page in
/// <see cref="Cursor.CurrentMultipleKey"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <param name="info">The locking behavior to use</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveMultipleKey(uint recno, LockingInfo info) {
return MoveMultipleKey(recno, (int)pgsz, info);
}
/// <summary>
/// Position the cursor at a specific key/data pair in the database, and
/// store the key/data pair and as many ensuing key/data pairs that can
/// fit in a buffer the size of one database page in
/// <see cref="Cursor.CurrentMultipleKey"/>.
/// </summary>
/// <param name="recno">
/// The specific numbered record of the database at which to position
/// the cursor.
/// </param>
/// <param name="BufferSize">
/// The size of a buffer to fill with key/data pairs. Must be at least
/// the page size of the underlying database and be a multiple of 1024.
/// </param>
/// <param name="info">The locking behavior to use</param>
/// <returns>
/// True if the cursor was positioned successfully, false otherwise.
/// </returns>
public bool MoveMultipleKey(
uint recno, int BufferSize, LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
key.Data = BitConverter.GetBytes(recno);
DatabaseEntry data = new DatabaseEntry();
return base.GetMultiple(
key, data, BufferSize, DbConstants.DB_SET_RECNO, info, true);
}
/// <summary>
/// Return the record number associated with the cursor's current
/// position.
/// </summary>
/// <returns>The record number associated with the cursor.</returns>
public uint Recno() { return Recno(null); }
/// <summary>
/// Return the record number associated with the cursor's current
/// position.
/// </summary>
/// <param name="info">The locking behavior to use</param>
/// <returns>The record number associated with the cursor.</returns>
public uint Recno(LockingInfo info) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
base.Get(key, data, DbConstants.DB_GET_RECNO, info);
return BitConverter.ToUInt32(base.Current.Value.Data, 0);
}
/// <summary>
/// Insert the data element as a duplicate element of the key to which
/// the cursor refers.
/// </summary>
/// <param name="data">The data element to insert</param>
/// <param name="loc">
/// Specify whether to insert the data item immediately before or
/// immediately after the cursor's current position.
/// </param>
public new void Insert(DatabaseEntry data, InsertLocation loc) {
base.Insert(data, loc);
}
/// <summary>
/// Insert the specified key/data pair into the database, unless a
/// key/data pair comparing equally to it already exists in the
/// database.
/// </summary>
/// <param name="pair">The key/data pair to be inserted</param>
/// <exception cref="KeyExistException">
/// Thrown if a matching key/data pair already exists in the database.
/// </exception>
public new void AddUnique(
KeyValuePair<DatabaseEntry, DatabaseEntry> pair) {
base.AddUnique(pair);
}
/// <summary>
/// Insert the specified key/data pair into the database.
/// </summary>
/// <param name="pair">The key/data pair to be inserted</param>
/// <param name="loc">
/// If the key already exists in the database and no duplicate sort
/// function has been specified, specify whether the inserted data item
/// is added as the first or the last of the data items for that key.
/// </param>
public new void Add(KeyValuePair<DatabaseEntry, DatabaseEntry> pair,
InsertLocation loc) {
base.Add(pair, loc);
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Originally based on the Bartok code base.
//
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Zelig.MetaData.Importer
{
public sealed class MetaDataCustomAttribute : MetaDataObject,
IMetaDataNormalize
{
//
// State
//
private IMetaDataHasCustomAttribute m_parent;
private IMetaDataCustomAttributeType m_type;
private ArrayReader m_buffer;
//
// Constructor Methods
//
private MetaDataCustomAttribute( int index ) : base( TokenType.CustomAttribute, index )
{
}
// Helper methods to work around limitations in generics, see Parser.InitializeTable<T>
internal static MetaDataObject.CreateInstance GetCreator()
{
return new MetaDataObject.CreateInstance( Creator );
}
private static MetaDataObject Creator( int index )
{
return new MetaDataCustomAttribute( index );
}
//--//
internal override void Parse( Parser parser ,
Parser.TableSchema ts ,
ArrayReader reader )
{
Parser.IndexReader parentReader = ts.m_columns[0].m_reader;
Parser.IndexReader typeReader = ts.m_columns[1].m_reader;
int parentIndex;
int typeIndex;
parentIndex = parentReader ( reader );
typeIndex = typeReader ( reader );
m_buffer = new ArrayReader( parser.readIndexAsBlob( reader ) );
m_parent = parser.getHasCustomAttribute ( parentIndex );
m_type = parser.getCustomAttributeType( typeIndex );
((MetaDataObject)m_parent).AddCustomAttribute( this );
//// custom attribute starts with a prolog with value of 0x0001
//if(this.valueBuffer.Length < 2)
//{
// Console.Out.WriteLine( "WARNING: Custome Attrbute should have at least two bytes in size" );
//}
}
//
// IMetaDataNormalize methods
//
Normalized.MetaDataObject IMetaDataNormalize.AllocateNormalizedObject( MetaDataNormalizationContext context )
{
switch(context.Phase)
{
case MetaDataNormalizationPhase.ResolutionOfCustomAttributes:
{
Normalized.MetaDataMethodBase method;
context.GetNormalizedObject( m_type, out method, MetaDataNormalizationMode.Default );
if(method.Name != ".ctor")
{
throw IllegalMetaDataFormatException.Create( "Custom attribute with unexpected method name: {0}", method.Name );
}
ArrayReader reader = new ArrayReader( m_buffer, 0 );
if(reader.ReadUInt8() != 0x01 ||
reader.ReadUInt8() != 0x00 )
{
throw IllegalMetaDataFormatException.Create( "Custom Attribute doesn't start with 0x0001!" );
}
Normalized.SignatureMethod signature = method.Signature;
Normalized.SignatureType[] parameters = signature.Parameters;
int fixedCount = parameters.Length;
Object[] fixedArgs = new Object[fixedCount];
for(int i = 0; i < fixedCount; i++)
{
Normalized.SignatureType parameter = parameters[i];
Object value = ExtractParameter( parameter.Type, reader, context );
fixedArgs[i] = value;
}
short namedCount = ((reader.IsEOF) ? (short)0 : reader.ReadInt16());
////if(namedCount > this.buffer.Length && this.Name == "System.Runtime.CompilerServices.RequiredAttributeAttribute")
////{
//// // Some CLR libraries have been compiled against a version of
//// // mscorlib that had a fixed parameter to RequiredAttribute.
//// // Simply ignore whatever the parameter was!
//// namedCount = 0;
////}
Normalized.MetaDataCustomAttribute.NamedArg[] namedArgs = new Normalized.MetaDataCustomAttribute.NamedArg[namedCount];
for(int i = 0; i < namedCount; i++)
{
SerializationTypes propOrField = (SerializationTypes)reader.ReadUInt8();
if(propOrField == SerializationTypes.FIELD || propOrField == SerializationTypes.PROPERTY)
{
SerializationTypes fieldType = (SerializationTypes)reader.ReadUInt8();
SerializationTypes arrayType = (SerializationTypes)ElementTypes.END;
String enumName = null;
switch(fieldType)
{
case SerializationTypes.SZARRAY:
{
arrayType = (SerializationTypes)reader.ReadUInt8();
if(arrayType == SerializationTypes.ENUM)
{
throw new Exception( "Not implemented: Array of ENUM for named field/property" );
}
}
break;
case SerializationTypes.ENUM:
{
enumName = reader.ReadCompressedString();
}
break;
}
String name = reader.ReadCompressedString();
Object value;
if(fieldType == SerializationTypes.TAGGED_OBJECT)
{
fieldType = (SerializationTypes)reader.ReadUInt8();
}
if(enumName != null)
{
Normalized.MetaDataTypeDefinitionBase typeDef = context.ResolveName( enumName );
value = ExtractEnumValue( typeDef, reader, context );
}
else if(fieldType == SerializationTypes.SZARRAY)
{
value = ExtractArrayValue( arrayType, reader, context );
}
else
{
value = ExtractValue( fieldType, reader, context );
}
namedArgs[i] = new Normalized.MetaDataCustomAttribute.NamedArg( propOrField == SerializationTypes.FIELD, -1, name, fieldType, value );
}
else
{
throw IllegalMetaDataFormatException.Create( "Unknown prop-or-field type: {0}", propOrField );
}
}
Normalized.MetaDataCustomAttribute ca = new Normalized.MetaDataCustomAttribute( context.GetAssemblyFromContext(), m_token );
ca.m_constructor = method;
ca.m_fixedArgs = fixedArgs;
ca.m_namedArgs = namedArgs;
return ca.MakeUnique();
}
}
throw context.InvalidPhase( this );
}
void IMetaDataNormalize.ExecuteNormalizationPhase( Normalized.IMetaDataObject obj ,
MetaDataNormalizationContext context )
{
throw context.InvalidPhase( this );
}
//--//
private static Object ExtractParameter( Normalized.MetaDataTypeDefinitionAbstract type ,
ArrayReader reader ,
MetaDataNormalizationContext context )
{
switch(type.ElementType)
{
case ElementTypes.VALUETYPE:
{
String superName = type.Extends.FullName;
if(superName != "System.Enum")
{
throw IllegalMetaDataFormatException.Create( "Found valuetype that wasn't an Enum: {0}", type.Extends );
}
if(!(type is Normalized.MetaDataTypeDefinition))
{
throw IllegalMetaDataFormatException.Create( "Found valuetype that wasn't a simple type: {0}", type );
}
return ExtractEnumValue( (Normalized.MetaDataTypeDefinition)type, reader, context );
}
case ElementTypes.CLASS:
{
String className = type.FullName;
// handle cases for reference types first
if(className == "System.String")
{
return reader.ReadCompressedString();
}
else if(className == "System.Object")
{
goto case ElementTypes.OBJECT;
}
else if(className == "System.Type")
{
string typeName = reader.ReadCompressedString();
return context.ResolveName( typeName );
}
// Enums are just ints, e.g. the case of AttributeTargets param for AttributeUsage attribute
if (type.Extends.ElementType == ElementTypes.VALUETYPE)
{
return reader.ReadInt32();
}
throw new Exception( "Not implemented: object encoding an array (class was " + type +")" );
}
case ElementTypes.OBJECT:
case (ElementTypes)SerializationTypes.TAGGED_OBJECT:
{
SerializationTypes objectType = (SerializationTypes)reader.ReadUInt8();
switch(objectType)
{
case SerializationTypes.ENUM:
case SerializationTypes.TYPE:
{
return ExtractValue( objectType, reader, context );
}
default:
{
throw new Exception( "Found OBJECT type with type " + objectType );
}
}
}
case ElementTypes.SZARRAY:
{
Normalized.MetaDataTypeDefinitionArraySz typeArray = (Normalized.MetaDataTypeDefinitionArraySz)type;
return ExtractArrayValue( typeArray.ObjectType, reader, context );
}
default:
{
return ExtractValue( (SerializationTypes)type.ElementType, reader, context );
}
}
}
private static Object ExtractValue( SerializationTypes type ,
ArrayReader reader ,
MetaDataNormalizationContext context )
{
switch(type)
{
case SerializationTypes.BOOLEAN: return reader.ReadBoolean();
case SerializationTypes.CHAR : return (char)reader.ReadUInt16 ();
case SerializationTypes.I1 : return reader.ReadInt8 ();
case SerializationTypes.U1 : return reader.ReadUInt8 ();
case SerializationTypes.I2 : return reader.ReadInt16 ();
case SerializationTypes.U2 : return reader.ReadUInt16 ();
case SerializationTypes.I4 : return reader.ReadInt32 ();
case SerializationTypes.U4 : return reader.ReadUInt32 ();
case SerializationTypes.I8 : return reader.ReadInt64 ();
case SerializationTypes.U8 : return reader.ReadUInt64 ();
case SerializationTypes.R4 : return reader.ReadSingle ();
case SerializationTypes.R8 : return reader.ReadDouble ();
case SerializationTypes.STRING:
return reader.ReadCompressedString();
case SerializationTypes.TYPE:
{
String typeName = reader.ReadCompressedString();
return context.ResolveName( typeName );
}
case SerializationTypes.ENUM:
{
String typeName = reader.ReadCompressedString();
Normalized.MetaDataTypeDefinitionBase typeDef = context.ResolveName( typeName );
return ExtractEnumValue( typeDef, reader, context );
}
default:
throw IllegalMetaDataFormatException.Create( "Found unexpected type {0} in custom attribute parameter", type );
}
}
private static Object ExtractEnumValue( Normalized.MetaDataTypeDefinitionBase typeDef ,
ArrayReader reader ,
MetaDataNormalizationContext context )
{
foreach(Normalized.MetaDataField classField in typeDef.Fields)
{
if((classField.Flags & FieldAttributes.Static) == 0)
{
if(classField.Name != "value__")
{
throw IllegalMetaDataFormatException.Create( "Found enum with non-static field '{0}'", classField.Name );
}
return ExtractValue( (SerializationTypes)classField.FieldSignature.TypeSignature.Type.ElementType, reader, context );
}
}
throw IllegalMetaDataFormatException.Create( "Found enum without non-static field" );
}
private static Object ExtractArrayValue( Normalized.MetaDataTypeDefinitionAbstract type ,
ArrayReader reader ,
MetaDataNormalizationContext context )
{
int arraySize = reader.ReadInt32();
if(arraySize >= 0)
{
if(type.ElementType == ElementTypes.CLASS)
{
Object[] array = new Object[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = ExtractParameter( type, reader, context );
}
return array;
}
else
{
return ExtractArrayValue( (SerializationTypes)type.ElementType, arraySize, reader, context );
}
}
else
{
throw new Exception( "Not implemented: custom attribute class array with negative length" );
}
}
private static Object ExtractArrayValue( SerializationTypes elementType ,
ArrayReader reader ,
MetaDataNormalizationContext context )
{
int arraySize = reader.ReadInt32();
if(arraySize >= 0)
{
return ExtractArrayValue( elementType, arraySize, reader, context );
}
else
{
throw new Exception( "Not implemented: custom atribute array with negative length" );
}
}
private static Object ExtractArrayValue( SerializationTypes elementType ,
int arraySize ,
ArrayReader reader ,
MetaDataNormalizationContext context )
{
switch(elementType)
{
case SerializationTypes.BOOLEAN:
{
bool[] array = new bool[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadBoolean();
}
return array;
}
case SerializationTypes.CHAR:
{
char[] array = new char[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = (char)reader.ReadUInt16();
}
return array;
}
case SerializationTypes.I1:
{
sbyte[] array = new sbyte[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadInt8();
}
return array;
}
case SerializationTypes.U1:
{
byte[] array = new byte[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadUInt8();
}
return array;
}
case SerializationTypes.I2:
{
short[] array = new short[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadInt16();
}
return array;
}
case SerializationTypes.U2:
{
ushort[] array = new ushort[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadUInt16();
}
return array;
}
case SerializationTypes.I4:
{
int[] array = new int[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadInt32();
}
return array;
}
case SerializationTypes.U4:
{
uint[] array = new uint[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadUInt32();
}
return array;
}
case SerializationTypes.I8:
{
long[] array = new long[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadInt64();
}
return array;
}
case SerializationTypes.U8:
{
ulong[] array = new ulong[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadUInt64();
}
return array;
}
case SerializationTypes.R4:
{
float[] array = new float[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadSingle();
}
return array;
}
case SerializationTypes.R8:
{
double[] array = new double[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadDouble();
}
return array;
}
case SerializationTypes.STRING:
{
String[] array = new String[arraySize];
for(int i = 0; i < arraySize; i++)
{
array[i] = reader.ReadCompressedString();
}
return array;
}
case SerializationTypes.OBJECT:
{
Object[] array = new Object[arraySize];
for(int i = 0; i < arraySize; i++)
{
SerializationTypes type = (SerializationTypes)reader.ReadUInt8();
array[i] = ExtractValue( type, reader, context );
}
return array;
}
default:
throw new Exception( "Not implemented: custom attribute array of type " + elementType );
}
}
//
// Access Methods
//
public IMetaDataHasCustomAttribute Parent
{
get
{
return m_parent;
}
}
public IMetaDataCustomAttributeType Type
{
get
{
return m_type;
}
}
//--//
//
// Debug Methods
//
public override String ToString()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder( "MetaDataCustomAttribute(" );
sb.Append( m_type );
sb.Append( "," );
sb.Append( m_parent );
sb.Append( ")[" );
sb.Append( m_buffer );
sb.Append( "]" );
return sb.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Collections.Concurrent
{
/// <summary>
/// Represents a thread-safe, unordered collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the bag.</typeparam>
/// <remarks>
/// <para>
/// Bags are useful for storing objects when ordering doesn't matter, and unlike sets, bags support
/// duplicates. <see cref="ConcurrentBag{T}"/> is a thread-safe bag implementation, optimized for
/// scenarios where the same thread will be both producing and consuming data stored in the bag.
/// </para>
/// <para>
/// <see cref="ConcurrentBag{T}"/> accepts null reference (Nothing in Visual Basic) as a valid
/// value for reference types.
/// </para>
/// <para>
/// All public and protected members of <see cref="ConcurrentBag{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class ConcurrentBag<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
/// <summary>The per-bag, per-thread work-stealing queues.</summary>
private ThreadLocal<WorkStealingQueue> _locals;
/// <summary>The head work stealing queue in a linked list of queues.</summary>
private volatile WorkStealingQueue _workStealingQueues;
/// <summary>Initializes a new instance of the <see cref="ConcurrentBag{T}"/> class.</summary>
public ConcurrentBag()
{
_locals = new ThreadLocal<WorkStealingQueue>();
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentBag{T}"/>
/// class that contains elements copied from the specified collection.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new <see
/// cref="ConcurrentBag{T}"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is a null reference
/// (Nothing in Visual Basic).</exception>
public ConcurrentBag(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection), SR.ConcurrentBag_Ctor_ArgumentNullException);
}
_locals = new ThreadLocal<WorkStealingQueue>();
WorkStealingQueue queue = GetCurrentThreadWorkStealingQueue(forceCreate: true);
foreach (T item in collection)
{
queue.LocalPush(item);
}
}
/// <summary>
/// Adds an object to the <see cref="ConcurrentBag{T}"/>.
/// </summary>
/// <param name="item">The object to be added to the
/// <see cref="ConcurrentBag{T}"/>. The value can be a null reference
/// (Nothing in Visual Basic) for reference types.</param>
public void Add(T item) => GetCurrentThreadWorkStealingQueue(forceCreate: true).LocalPush(item);
/// <summary>
/// Attempts to add an object to the <see cref="ConcurrentBag{T}"/>.
/// </summary>
/// <param name="item">The object to be added to the
/// <see cref="ConcurrentBag{T}"/>. The value can be a null reference
/// (Nothing in Visual Basic) for reference types.</param>
/// <returns>Always returns true</returns>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Add(item);
return true;
}
/// <summary>
/// Attempts to remove and return an object from the <see cref="ConcurrentBag{T}"/>.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains the object
/// removed from the <see cref="ConcurrentBag{T}"/> or the default value
/// of <typeparamref name="T"/> if the operation failed.</param>
/// <returns>true if an object was removed successfully; otherwise, false.</returns>
public bool TryTake(out T result)
{
WorkStealingQueue queue = GetCurrentThreadWorkStealingQueue(forceCreate: false);
return (queue != null && queue.TryLocalPop(out result)) || TrySteal(out result, take: true);
}
/// <summary>
/// Attempts to return an object from the <see cref="ConcurrentBag{T}"/> without removing it.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains an object from
/// the <see cref="ConcurrentBag{T}"/> or the default value of
/// <typeparamref name="T"/> if the operation failed.</param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
public bool TryPeek(out T result)
{
WorkStealingQueue queue = GetCurrentThreadWorkStealingQueue(forceCreate: false);
return (queue != null && queue.TryLocalPeek(out result)) || TrySteal(out result, take: false);
}
/// <summary>Gets the work-stealing queue data structure for the current thread.</summary>
/// <param name="forceCreate">Whether to create a new queue if this thread doesn't have one.</param>
/// <returns>The local queue object, or null if the thread doesn't have one.</returns>
private WorkStealingQueue GetCurrentThreadWorkStealingQueue(bool forceCreate) =>
_locals.Value ??
(forceCreate ? CreateWorkStealingQueueForCurrentThread() : null);
private WorkStealingQueue CreateWorkStealingQueueForCurrentThread()
{
lock (GlobalQueuesLock) // necessary to update _workStealingQueues, so as to synchronize with freezing operations
{
WorkStealingQueue head = _workStealingQueues;
WorkStealingQueue queue = head != null ? GetUnownedWorkStealingQueue() : null;
if (queue == null)
{
_workStealingQueues = queue = new WorkStealingQueue(head);
}
_locals.Value = queue;
return queue;
}
}
/// <summary>
/// Try to reuse an unowned queue. If a thread interacts with the bag and then exits,
/// the bag purposefully retains its queue, as it contains data associated with the bag.
/// </summary>
/// <returns>The queue object, or null if no unowned queue could be gathered.</returns>
private WorkStealingQueue GetUnownedWorkStealingQueue()
{
Debug.Assert(Monitor.IsEntered(GlobalQueuesLock));
// Look for a thread that has the same ID as this one. It won't have come from the same thread,
// but if our thread ID is reused, we know that no other thread can have the same ID and thus
// no other thread can be using this queue.
int currentThreadId = Environment.CurrentManagedThreadId;
for (WorkStealingQueue queue = _workStealingQueues; queue != null; queue = queue._nextQueue)
{
if (queue._ownerThreadId == currentThreadId)
{
return queue;
}
}
return null;
}
/// <summary>Local helper method to steal an item from any other non empty thread.</summary>
/// <param name="result">To receive the item retrieved from the bag</param>
/// <param name="take">Whether to remove or peek.</param>
/// <returns>True if succeeded, false otherwise.</returns>
private bool TrySteal(out T result, bool take)
{
if (take)
{
CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryTakeSteals();
}
else
{
CDSCollectionETWBCLProvider.Log.ConcurrentBag_TryPeekSteals();
}
// If there's no local queue for this thread, just start from the head queue
// and try to steal from each queue until we get a result.
WorkStealingQueue localQueue = GetCurrentThreadWorkStealingQueue(forceCreate: false);
if (localQueue == null)
{
return TryStealFromTo(_workStealingQueues, null, out result, take);
}
// If there is a local queue from this thread, then start from the next queue
// after it, and then iterate around back from the head to this queue, not including it.
return
TryStealFromTo(localQueue._nextQueue, null, out result, take) ||
TryStealFromTo(_workStealingQueues, localQueue, out result, take);
// TODO: Investigate storing the queues in an array instead of a linked list, and then
// randomly choosing a starting location from which to start iterating.
}
/// <summary>
/// Attempts to steal from each queue starting from <paramref name="startInclusive"/> to <paramref name="endExclusive"/>.
/// </summary>
private bool TryStealFromTo(WorkStealingQueue startInclusive, WorkStealingQueue endExclusive, out T result, bool take)
{
for (WorkStealingQueue queue = startInclusive; queue != endExclusive; queue = queue._nextQueue)
{
if (queue.TrySteal(out result, take))
{
return true;
}
}
result = default(T);
return false;
}
/// <summary>
/// Copies the <see cref="ConcurrentBag{T}"/> elements to an existing
/// one-dimensional <see cref="T:System.Array">Array</see>, starting at the specified array
/// index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="ConcurrentBag{T}"/>. The <see
/// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
/// length of the <paramref name="array"/>
/// -or- the number of elements in the source <see
/// cref="ConcurrentBag{T}"/> is greater than the available space from
/// <paramref name="index"/> to the end of the destination <paramref name="array"/>.</exception>
public void CopyTo(T[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array), SR.ConcurrentBag_CopyTo_ArgumentNullException);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.Collection_CopyTo_ArgumentOutOfRangeException);
}
// Short path if the bag is empty
if (_workStealingQueues == null)
{
return;
}
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
// Make sure we won't go out of bounds on the array
int count = DangerousCount;
if (index > array.Length - count)
{
throw new ArgumentException(SR.Collection_CopyTo_TooManyElems, nameof(index));
}
// Do the copy
try
{
int copied = CopyFromEachQueueToArray(array, index);
Debug.Assert(copied == count);
}
catch (ArrayTypeMismatchException e)
{
// Propagate same exception as in desktop
throw new InvalidCastException(e.Message, e);
}
}
finally
{
UnfreezeBag(lockTaken);
}
}
/// <summary>Copies from each queue to the target array, starting at the specified index.</summary>
private int CopyFromEachQueueToArray(T[] array, int index)
{
Debug.Assert(Monitor.IsEntered(GlobalQueuesLock));
int i = index;
for (WorkStealingQueue queue = _workStealingQueues; queue != null; queue = queue._nextQueue)
{
i += queue.DangerousCopyTo(array, i);
}
return i - index;
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
/// cref="T:System.Array"/>, starting at a particular
/// <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="ConcurrentBag{T}"/>. The <see
/// cref="T:System.Array">Array</see> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
/// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
// If the destination is actually a T[], use the strongly-typed
// overload that doesn't allocate/copy an extra array.
T[] szArray = array as T[];
if (szArray != null)
{
CopyTo(szArray, index);
return;
}
// Otherwise, fall back to first storing the contents to an array,
// and then relying on its CopyTo to copy to the target Array.
if (array == null)
{
throw new ArgumentNullException(nameof(array), SR.ConcurrentBag_CopyTo_ArgumentNullException);
}
ToArray().CopyTo(array, index);
}
/// <summary>
/// Copies the <see cref="ConcurrentBag{T}"/> elements to a new array.
/// </summary>
/// <returns>A new array containing a snapshot of elements copied from the <see
/// cref="ConcurrentBag{T}"/>.</returns>
public T[] ToArray()
{
if (_workStealingQueues != null)
{
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
int count = DangerousCount;
if (count > 0)
{
var arr = new T[count];
int copied = CopyFromEachQueueToArray(arr, 0);
Debug.Assert(copied == count);
return arr;
}
}
finally
{
UnfreezeBag(lockTaken);
}
}
// Bag was empty
return Array.Empty<T>();
}
/// <summary>
/// Removes all values from the <see cref="ConcurrentBag{T}"/>.
/// </summary>
public void Clear()
{
// If there are no queues in the bag, there's nothing to clear.
if (_workStealingQueues == null)
{
return;
}
// Clear the local queue.
WorkStealingQueue local = GetCurrentThreadWorkStealingQueue(forceCreate: false);
if (local != null)
{
local.LocalClear();
if (local._nextQueue == null && local == _workStealingQueues)
{
// If it's the only queue, nothing more to do.
return;
}
}
// Clear the other queues by stealing all remaining items. We freeze the bag to
// avoid having to contend with too many new items being added while we're trying
// to drain the bag. But we can't just freeze the bag and attempt to remove all
// items from every other queue, as even with freezing the bag it's dangerous to
// manipulate other queues' tail pointers and add/take counts.
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
for (WorkStealingQueue queue = _workStealingQueues; queue != null; queue = queue._nextQueue)
{
T ignored;
while (queue.TrySteal(out ignored, take: true));
}
}
finally
{
UnfreezeBag(lockTaken);
}
}
/// <summary>
/// Returns an enumerator that iterates through the <see
/// cref="ConcurrentBag{T}"/>.
/// </summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentBag{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the bag. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the bag.
/// </remarks>
public IEnumerator<T> GetEnumerator() => new Enumerator(ToArray());
/// <summary>
/// Returns an enumerator that iterates through the <see
/// cref="ConcurrentBag{T}"/>.
/// </summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentBag{T}"/>.</returns>
/// <remarks>
/// The items enumerated represent a moment-in-time snapshot of the contents
/// of the bag. It does not reflect any update to the collection after
/// <see cref="GetEnumerator"/> was called.
/// </remarks>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentBag{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentBag{T}"/>.</value>
/// <remarks>
/// The count returned represents a moment-in-time snapshot of the contents
/// of the bag. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called.
/// </remarks>
public int Count
{
get
{
// Short path if the bag is empty
if (_workStealingQueues == null)
{
return 0;
}
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
return DangerousCount;
}
finally
{
UnfreezeBag(lockTaken);
}
}
}
/// <summary>Gets the number of items stored in the bag.</summary>
/// <remarks>Only provides a stable result when the bag is frozen.</remarks>
private int DangerousCount
{
get
{
int count = 0;
for (WorkStealingQueue queue = _workStealingQueues; queue != null; queue = queue._nextQueue)
{
checked { count += queue.DangerousCount; }
}
Debug.Assert(count >= 0);
return count;
}
}
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentBag{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentBag{T}"/> is empty; otherwise, false.</value>
public bool IsEmpty
{
get
{
// Fast-path based on the current thread's local queue.
WorkStealingQueue local = GetCurrentThreadWorkStealingQueue(forceCreate: false);
if (local != null)
{
// We don't need the lock to check the local queue, as no other thread
// could be adding to it, and a concurrent steal that transitions from
// non-empty to empty doesn't matter because if we see this as non-empty,
// then that's a valid moment-in-time answer, and if we see this as empty,
// we check other things.
if (!local.IsEmpty)
{
return false;
}
// We know the local queue is empty (no one besides this thread could have
// added to it since we checked). If the local queue is the only one
// in the bag, then the bag is empty, too.
if (local._nextQueue == null && local == _workStealingQueues)
{
return true;
}
}
// Couldn't take a fast path. Freeze the bag, and enumerate the queues to see if
// any is non-empty.
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
for (WorkStealingQueue queue = _workStealingQueues; queue != null; queue = queue._nextQueue)
{
if (!queue.IsEmpty)
{
return false;
}
}
}
finally
{
UnfreezeBag(lockTaken);
}
// All queues were empty, so the bag was empty.
return true;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
/// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentBag{T}"/>, this property always
/// returns false.</value>
bool ICollection.IsSynchronized => false;
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
/// cref="T:System.Collections.ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported.</exception>
object ICollection.SyncRoot
{
get { throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported); }
}
/// <summary>Global lock used to synchronize the queues pointer and all bag-wide operations (e.g. ToArray, Count, etc.).</summary>
private object GlobalQueuesLock
{
get
{
Debug.Assert(_locals != null);
return _locals;
}
}
/// <summary>"Freezes" the bag, such that no concurrent operations will be mutating the bag when it returns.</summary>
/// <param name="lockTaken">true if the global lock was taken; otherwise, false.</param>
private void FreezeBag(ref bool lockTaken)
{
// Take the global lock to start freezing the bag. This helps, for example,
// to prevent other threads from joining the bag (adding their local queues)
// while a global operation is in progress.
Debug.Assert(!Monitor.IsEntered(GlobalQueuesLock));
Monitor.Enter(GlobalQueuesLock, ref lockTaken);
WorkStealingQueue head = _workStealingQueues; // stable at least until GlobalQueuesLock is released in UnfreezeBag
// Then acquire all local queue locks, noting on each that it's been taken.
for (WorkStealingQueue queue = head; queue != null; queue = queue._nextQueue)
{
Monitor.Enter(queue, ref queue._frozen);
}
Interlocked.MemoryBarrier(); // prevent reads of _currentOp from moving before writes to _frozen
// Finally, wait for all unsynchronized operations on each queue to be done.
for (WorkStealingQueue queue = head; queue != null; queue = queue._nextQueue)
{
if (queue._currentOp != (int)Operation.None)
{
var spinner = new SpinWait();
do { spinner.SpinOnce(); }
while (queue._currentOp != (int)Operation.None);
}
}
}
/// <summary>"Unfreezes" a bag frozen with <see cref="FreezeBag(ref bool)"/>.</summary>
/// <param name="lockTaken">The result of the <see cref="FreezeBag(ref bool)"/> method.</param>
private void UnfreezeBag(bool lockTaken)
{
Debug.Assert(Monitor.IsEntered(GlobalQueuesLock) == lockTaken);
if (lockTaken)
{
// Release all of the individual queue locks.
for (WorkStealingQueue queue = _workStealingQueues; queue != null; queue = queue._nextQueue)
{
if (queue._frozen)
{
queue._frozen = false;
Monitor.Exit(queue);
}
}
// Then release the global lock.
Monitor.Exit(GlobalQueuesLock);
}
}
/// <summary>Provides a work-stealing queue data structure stored per thread.</summary>
private sealed class WorkStealingQueue
{
/// <summary>Initial size of the queue's array.</summary>
private const int InitialSize = 32;
/// <summary>Starting index for the head and tail indices.</summary>
private const int StartIndex =
#if DEBUG
int.MaxValue; // in debug builds, start at the end so we exercise the index reset logic
#else
0;
#endif
/// <summary>Head index from which to steal. This and'd with the <see cref="_mask"/> is the index into <see cref="_array"/>.</summary>
private volatile int _headIndex = StartIndex;
/// <summary>Tail index at which local pushes/pops happen. This and'd with the <see cref="_mask"/> is the index into <see cref="_array"/>.</summary>
private volatile int _tailIndex = StartIndex;
/// <summary>The array storing the queue's data.</summary>
private volatile T[] _array = new T[InitialSize];
/// <summary>Mask and'd with <see cref="_headIndex"/> and <see cref="_tailIndex"/> to get an index into <see cref="_array"/>.</summary>
private volatile int _mask = InitialSize - 1;
/// <summary>Numbers of elements in the queue from the local perspective; needs to be combined with <see cref="_stealCount"/> to get an actual Count.</summary>
private int _addTakeCount;
/// <summary>Number of steals; needs to be combined with <see cref="_addTakeCount"/> to get an actual Count.</summary>
private int _stealCount;
/// <summary>The current queue operation. Used to quiesce before performing operations from one thread onto another.</summary>
internal volatile int _currentOp;
/// <summary>true if this queue's lock is held as part of a global freeze.</summary>
internal bool _frozen;
/// <summary>Next queue in the <see cref="ConcurrentBag{T}"/>'s set of thread-local queues.</summary>
internal readonly WorkStealingQueue _nextQueue;
/// <summary>Thread ID that owns this queue.</summary>
internal readonly int _ownerThreadId;
/// <summary>Initialize the WorkStealingQueue.</summary>
/// <param name="nextQueue">The next queue in the linked list of work-stealing queues.</param>
internal WorkStealingQueue(WorkStealingQueue nextQueue)
{
_ownerThreadId = Environment.CurrentManagedThreadId;
_nextQueue = nextQueue;
}
/// <summary>Gets whether the queue is empty.</summary>
internal bool IsEmpty
{
get
{
/// _tailIndex can be decremented even while the bag is frozen, as the decrement in TryLocalPop happens prior
/// to the check for _frozen. But that's ok, as if _tailIndex is being decremented such that _headIndex becomes
/// >= _tailIndex, then the queue is about to be empty. This does mean, though, that while holding the lock,
/// it is possible to observe Count == 1 but IsEmpty == true. As such, we simply need to avoid doing any operation
/// while the bag is frozen that requires those values to be consistent.
return _headIndex >= _tailIndex;
}
}
/// <summary>
/// Add new item to the tail of the queue.
/// </summary>
/// <param name="item">The item to add.</param>
internal void LocalPush(T item)
{
Debug.Assert(Environment.CurrentManagedThreadId == _ownerThreadId);
bool lockTaken = false;
try
{
// Full fence to ensure subsequent reads don't get reordered before this
Interlocked.Exchange(ref _currentOp, (int)Operation.Add);
int tail = _tailIndex;
// Rare corner case (at most once every 2 billion pushes on this thread):
// We're going to increment the tail; if we'll overflow, then we need to reset our counts
if (tail == int.MaxValue)
{
_currentOp = (int)Operation.None; // set back to None temporarily to avoid a deadlock
lock (this)
{
Debug.Assert(_tailIndex == int.MaxValue, "No other thread should be changing _tailIndex");
// Rather than resetting to zero, we'll just mask off the bits we don't care about.
// This way we don't need to rearrange the items already in the queue; they'll be found
// correctly exactly where they are. One subtlety here is that we need to make sure that
// if head is currently < tail, it remains that way. This happens to just fall out from
// the bit-masking, because we only do this if tail == int.MaxValue, meaning that all
// bits are set, so all of the bits we're keeping will also be set. Thus it's impossible
// for the head to end up > than the tail, since you can't set any more bits than all of them.
_headIndex = _headIndex & _mask;
_tailIndex = tail = _tailIndex & _mask;
Debug.Assert(_headIndex <= _tailIndex);
_currentOp = (int)Operation.Add;
}
}
// We'd like to take the fast path that doesn't require locking, if possible. It's not possible if another
// thread is currently requesting that the whole bag synchronize, e.g. a ToArray operation. It's also
// not possible if there are fewer than two spaces available. One space is necessary for obvious reasons:
// to store the element we're trying to push. The other is necessary due to synchronization with steals.
// A stealing thread first increments _headIndex to reserve the slot at its old value, and then tries to
// read from that slot. We could potentially have a race condition whereby _headIndex is incremented just
// before this check, in which case we could overwrite the element being stolen as that slot would appear
// to be empty. Thus, we only allow the fast path if there are two empty slots.
if (!_frozen && tail < (_headIndex + _mask))
{
_array[tail & _mask] = item;
_tailIndex = tail + 1;
}
else
{
// We need to contend with foreign operations (e.g. steals, enumeration, etc.), so we lock.
_currentOp = (int)Operation.None; // set back to None to avoid a deadlock
Monitor.Enter(this, ref lockTaken);
int head = _headIndex;
int count = _tailIndex - _headIndex;
// If we're full, expand the array.
if (count >= _mask)
{
// Expand the queue by doubling its size.
var newArray = new T[_array.Length << 1];
int headIdx = head & _mask;
if (headIdx == 0)
{
Array.Copy(_array, 0, newArray, 0, _array.Length);
}
else
{
Array.Copy(_array, headIdx, newArray, 0, _array.Length - headIdx);
Array.Copy(_array, 0, newArray, _array.Length - headIdx, headIdx);
}
// Reset the field values
_array = newArray;
_headIndex = 0;
_tailIndex = tail = count;
_mask = (_mask << 1) | 1;
}
// Add the element
_array[tail & _mask] = item;
_tailIndex = tail + 1;
// Update the count to avoid overflow. We can trust _stealCount here,
// as we're inside the lock and it's only manipulated there.
_addTakeCount -= _stealCount;
_stealCount = 0;
}
// Increment the count from the add/take perspective
checked { _addTakeCount++; }
}
finally
{
_currentOp = (int)Operation.None;
if (lockTaken)
{
Monitor.Exit(this);
}
}
}
/// <summary>Clears the contents of the local queue.</summary>
internal void LocalClear()
{
Debug.Assert(Environment.CurrentManagedThreadId == _ownerThreadId);
lock (this) // synchronize with steals
{
// If the queue isn't empty, reset the state to clear out all items.
if (_headIndex < _tailIndex)
{
_headIndex = _tailIndex = StartIndex;
_addTakeCount = _stealCount = 0;
Array.Clear(_array, 0, _array.Length);
}
}
}
/// <summary>Remove an item from the tail of the queue.</summary>
/// <param name="result">The removed item</param>
internal bool TryLocalPop(out T result)
{
Debug.Assert(Environment.CurrentManagedThreadId == _ownerThreadId);
int tail = _tailIndex;
if (_headIndex >= tail)
{
result = default(T);
return false;
}
bool lockTaken = false;
try
{
// Decrement the tail using a full fence to ensure subsequent reads don't reorder before this.
// If the read of _headIndex moved before this write to _tailIndex, we could erroneously end up
// popping an element that's concurrently being stolen, leading to the same element being
// dequeued from the bag twice.
_currentOp = (int)Operation.Take;
Interlocked.Exchange(ref _tailIndex, --tail);
// If there is no interaction with a steal, we can head down the fast path.
// Note that we use _headIndex < tail rather than _headIndex <= tail to account
// for stealing peeks, which don't increment _headIndex, and which could observe
// the written default(T) in a race condition to peek at the element.
if (!_frozen && _headIndex < tail)
{
int idx = tail & _mask;
result = _array[idx];
_array[idx] = default(T);
_addTakeCount--;
return true;
}
else
{
// Interaction with steals: 0 or 1 elements left.
_currentOp = (int)Operation.None; // set back to None to avoid a deadlock
Monitor.Enter(this, ref lockTaken);
if (_headIndex <= tail)
{
// Element still available. Take it.
int idx = tail & _mask;
result = _array[idx];
_array[idx] = default(T);
_addTakeCount--;
return true;
}
else
{
// We encountered a race condition and the element was stolen, restore the tail.
_tailIndex = tail + 1;
result = default(T);
return false;
}
}
}
finally
{
_currentOp = (int)Operation.None;
if (lockTaken)
{
Monitor.Exit(this);
}
}
}
/// <summary>Peek an item from the tail of the queue.</summary>
/// <param name="result">the peeked item</param>
/// <returns>True if succeeded, false otherwise</returns>
internal bool TryLocalPeek(out T result)
{
Debug.Assert(Environment.CurrentManagedThreadId == _ownerThreadId);
int tail = _tailIndex;
if (_headIndex < tail)
{
// It is possible to enable lock-free peeks, following the same general approach
// that's used in TryLocalPop. However, peeks are more complicated as we can't
// do the same kind of index reservation that's done in TryLocalPop; doing so could
// end up making a steal think that no item is available, even when one is. To do
// it correctly, then, we'd need to add spinning to TrySteal in case of a concurrent
// peek happening. With a lock, the common case (no contention with steals) will
// effectively only incur two interlocked operations (entering/exiting the lock) instead
// of one (setting Peek as the _currentOp). Combined with Peeks on a bag being rare,
// for now we'll use the simpler/safer code.
lock (this)
{
if (_headIndex < tail)
{
result = _array[(tail - 1) & _mask];
return true;
}
}
}
result = default(T);
return false;
}
/// <summary>Steal an item from the head of the queue.</summary>
/// <param name="result">the removed item</param>
/// <param name="take">true to take the item; false to simply peek at it</param>
internal bool TrySteal(out T result, bool take)
{
// Fast-path check to see if the queue is empty.
if (_headIndex < _tailIndex)
{
// Anything other than empty requires synchronization.
lock (this)
{
int head = _headIndex;
if (take)
{
// Increment head to tentatively take an element: a full fence is used to ensure the read
// of _tailIndex doesn't move earlier, as otherwise we could potentially end up stealing
// the same element that's being popped locally.
Interlocked.Exchange(ref _headIndex, unchecked(head + 1));
// If there's an element to steal, do it.
if (head < _tailIndex)
{
int idx = head & _mask;
result = _array[idx];
_array[idx] = default(T);
_stealCount++;
return true;
}
else
{
// We contended with the local thread and lost the race, so restore the head.
_headIndex = head;
}
}
else if (head < _tailIndex)
{
// Peek, if there's an element available
result = _array[head & _mask];
return true;
}
}
}
// The queue was empty.
result = default(T);
return false;
}
/// <summary>Copies the contents of this queue to the target array starting at the specified index.</summary>
internal int DangerousCopyTo(T[] array, int arrayIndex)
{
Debug.Assert(Monitor.IsEntered(this));
Debug.Assert(_frozen);
Debug.Assert(array != null);
Debug.Assert(arrayIndex >= 0 && arrayIndex <= array.Length);
int headIndex = _headIndex;
int count = DangerousCount;
Debug.Assert(
count == (_tailIndex - _headIndex) ||
count == (_tailIndex + 1 - _headIndex),
"Count should be the same as tail - head, but allowing for the possibility that " +
"a peek decremented _tailIndex before seeing that a freeze was happening.");
Debug.Assert(arrayIndex <= array.Length - count);
// Copy from this queue's array to the destination array, but in reverse
// order to match the ordering of desktop.
for (int i = arrayIndex + count - 1; i >= arrayIndex; i--)
{
array[i] = _array[headIndex++ & _mask];
}
return count;
}
/// <summary>Gets the total number of items in the queue.</summary>
/// <remarks>
/// This is not thread safe, only providing an accurate result either from the owning
/// thread while its lock is held or from any thread while the bag is frozen.
/// </remarks>
internal int DangerousCount
{
get
{
Debug.Assert(Monitor.IsEntered(this));
int count = _addTakeCount - _stealCount;
Debug.Assert(count >= 0);
return count;
}
}
}
/// <summary>Lock-free operations performed on a queue.</summary>
internal enum Operation
{
None,
Add,
Take
};
/// <summary>Provides an enumerator for the bag.</summary>
/// <remarks>
/// The original implementation of ConcurrentBag used a <see cref="List{T}"/> as part of
/// the GetEnumerator implementation. That list was then changed to be an array, but array's
/// GetEnumerator has different behavior than does list's, in particular for the case where
/// Current is used after MoveNext returns false. To avoid any concerns around compatibility,
/// we use a custom enumerator rather than just returning array's. This enumerator provides
/// the essential elements of both list's and array's enumerators.
/// </remarks>
private sealed class Enumerator : IEnumerator<T>
{
private readonly T[] _array;
private T _current;
private int _index;
public Enumerator(T[] array)
{
Debug.Assert(array != null);
_array = array;
}
public bool MoveNext()
{
if (_index < _array.Length)
{
_current = _array[_index++];
return true;
}
_index = _array.Length + 1;
return false;
}
public T Current => _current;
object IEnumerator.Current
{
get
{
if (_index == 0 || _index == _array.Length + 1)
{
throw new InvalidOperationException(SR.ConcurrentBag_Enumerator_EnumerationNotStartedOrAlreadyFinished);
}
return Current;
}
}
public void Reset()
{
_index = 0;
_current = default(T);
}
public void Dispose() { }
}
}
}
| |
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Formatting;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
internal abstract class AbstractConvertToInterpolatedStringRefactoringProvider<TInvocationExpressionSyntax, TExpressionSyntax, TArgumentSyntax, TLiteralExpressionSyntax> : CodeRefactoringProvider
where TExpressionSyntax : SyntaxNode
where TInvocationExpressionSyntax : TExpressionSyntax
where TArgumentSyntax : SyntaxNode
where TLiteralExpressionSyntax : SyntaxNode
{
protected abstract SyntaxNode GetInterpolatedString(string text);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
var stringType = semanticModel.Compilation.GetSpecialType(SpecialType.System_String);
if (stringType == null)
{
return;
}
var formatMethods = stringType
.GetMembers("Format")
.OfType<IMethodSymbol>()
.Where(ShouldIncludeFormatMethod)
.ToImmutableArray();
if (formatMethods.Length == 0)
{
return;
}
var syntaxFactsService = context.Document.GetLanguageService<ISyntaxFactsService>();
if (syntaxFactsService == null)
{
return;
}
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
TInvocationExpressionSyntax invocation;
ISymbol invocationSymbol;
if (TryFindInvocation(context.Span, root, semanticModel, formatMethods, syntaxFactsService, context.CancellationToken, out invocation, out invocationSymbol) &&
IsArgumentListCorrect(syntaxFactsService.GetArgumentsForInvocationExpression(invocation), invocationSymbol, formatMethods, semanticModel, syntaxFactsService, context.CancellationToken))
{
context.RegisterRefactoring(
new ConvertToInterpolatedStringCodeAction(
FeaturesResources.Convert_to_interpolated_string,
c => CreateInterpolatedString(invocation, context.Document, syntaxFactsService, c)));
}
}
private bool TryFindInvocation(
TextSpan span,
SyntaxNode root,
SemanticModel semanticModel,
ImmutableArray<IMethodSymbol> formatMethods,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken,
out TInvocationExpressionSyntax invocation,
out ISymbol invocationSymbol)
{
invocationSymbol = null;
invocation = root.FindNode(span, getInnermostNodeForTie: true)?.FirstAncestorOrSelf<TInvocationExpressionSyntax>();
while (invocation != null)
{
var arguments = syntaxFactsService.GetArgumentsForInvocationExpression(invocation);
if (arguments.Count >= 2)
{
var firstArgumentExpression = syntaxFactsService.GetExpressionOfArgument(arguments[0]) as TLiteralExpressionSyntax;
if (firstArgumentExpression != null && syntaxFactsService.IsStringLiteral(firstArgumentExpression.GetFirstToken()))
{
invocationSymbol = semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol;
if (formatMethods.Contains(invocationSymbol))
{
break;
}
}
}
invocation = invocation.Parent?.FirstAncestorOrSelf<TInvocationExpressionSyntax>();
}
return invocation != null;
}
private bool IsArgumentListCorrect(
SeparatedSyntaxList<TArgumentSyntax>? nullableArguments,
ISymbol invocationSymbol,
ImmutableArray<IMethodSymbol> formatMethods,
SemanticModel semanticModel,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
var arguments = nullableArguments.Value;
var firstExpression = syntaxFactsService.GetExpressionOfArgument(arguments[0]) as TLiteralExpressionSyntax;
if (arguments.Count >= 2 &&
firstExpression != null &&
syntaxFactsService.IsStringLiteral(firstExpression.GetFirstToken()))
{
// We do not want to substitute the expression if it is being passed to params array argument
// Example:
// string[] args;
// String.Format("{0}{1}{2}", args);
return IsArgumentListNotPassingArrayToParams(
syntaxFactsService.GetExpressionOfArgument(arguments[1]),
invocationSymbol,
formatMethods,
semanticModel,
cancellationToken);
}
return false;
}
private async Task<Document> CreateInterpolatedString(
TInvocationExpressionSyntax invocation,
Document document,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var arguments = syntaxFactsService.GetArgumentsForInvocationExpression(invocation);
var literalExpression = syntaxFactsService.GetExpressionOfArgument(arguments[0]) as TLiteralExpressionSyntax;
var text = literalExpression.GetFirstToken().ToString();
var syntaxGenerator = document.Project.LanguageServices.GetService<SyntaxGenerator>();
var expandedArguments = GetExpandedArguments(semanticModel, arguments, syntaxGenerator, syntaxFactsService);
var interpolatedString = GetInterpolatedString(text);
var newInterpolatedString = VisitArguments(expandedArguments, interpolatedString, syntaxFactsService);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNode(invocation, newInterpolatedString.WithTriviaFrom(invocation));
return document.WithSyntaxRoot(newRoot);
}
private ImmutableArray<TExpressionSyntax> GetExpandedArguments(
SemanticModel semanticModel,
SeparatedSyntaxList<TArgumentSyntax> arguments,
SyntaxGenerator syntaxGenerator,
ISyntaxFactsService syntaxFactsService)
{
var builder = ImmutableArray.CreateBuilder<TExpressionSyntax>();
for (int i = 1; i < arguments.Count; i++)
{
var argumentExpression = syntaxFactsService.GetExpressionOfArgument(arguments[i]);
var convertedType = semanticModel.GetTypeInfo(argumentExpression).ConvertedType;
if (convertedType == null)
{
builder.Add(syntaxFactsService.Parenthesize(argumentExpression) as TExpressionSyntax);
}
else
{
var castExpression = syntaxGenerator.CastExpression(convertedType, syntaxFactsService.Parenthesize(argumentExpression)).WithAdditionalAnnotations(Simplifier.Annotation);
builder.Add(castExpression as TExpressionSyntax);
}
}
var expandedArguments = builder.ToImmutable();
return expandedArguments;
}
private SyntaxNode VisitArguments(
ImmutableArray<TExpressionSyntax> expandedArguments,
SyntaxNode interpolatedString,
ISyntaxFactsService syntaxFactsService)
{
return interpolatedString.ReplaceNodes(syntaxFactsService.GetContentsOfInterpolatedString(interpolatedString), (oldNode, newNode) =>
{
var interpolationSyntaxNode = newNode;
if (interpolationSyntaxNode != null)
{
var literalExpression = syntaxFactsService.GetExpressionOfInterpolation(interpolationSyntaxNode) as TLiteralExpressionSyntax;
if (literalExpression != null && syntaxFactsService.IsNumericLiteralExpression(literalExpression))
{
int index;
if (int.TryParse(literalExpression.GetFirstToken().ValueText, out index))
{
if (index >= 0 && index < expandedArguments.Length)
{
return interpolationSyntaxNode.ReplaceNode(
syntaxFactsService.GetExpressionOfInterpolation(interpolationSyntaxNode),
syntaxFactsService.ConvertToSingleLine(expandedArguments[index], useElasticTrivia: true).WithAdditionalAnnotations(Formatter.Annotation));
}
}
}
}
return newNode;
});
}
private static bool ShouldIncludeFormatMethod(IMethodSymbol methodSymbol)
{
if (!methodSymbol.IsStatic)
{
return false;
}
if (methodSymbol.Parameters.Length == 0)
{
return false;
}
var firstParameter = methodSymbol.Parameters[0];
if (firstParameter?.Name != "format")
{
return false;
}
return true;
}
private static bool IsArgumentListNotPassingArrayToParams(
SyntaxNode expression,
ISymbol invocationSymbol,
ImmutableArray<IMethodSymbol> formatMethods,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var formatMethodsAcceptingParamsArray = formatMethods
.Where(x => x.Parameters.Length > 1 && x.Parameters[1].Type.Kind == SymbolKind.ArrayType);
if (formatMethodsAcceptingParamsArray.Contains(invocationSymbol))
{
return semanticModel.GetTypeInfo(expression, cancellationToken).Type?.Kind != SymbolKind.ArrayType;
}
return true;
}
private class ConvertToInterpolatedStringCodeAction : CodeAction.DocumentChangeAction
{
public ConvertToInterpolatedStringCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) :
base(title, createChangedDocument)
{
}
}
}
}
| |
/*
Copyright (c) 2005-2006 Ladislav Prosek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
// Uncomment the following line to enable logging of serialization events into fields of instances
// being (de)serialized.
//#define SERIALIZATION_DEBUG_LOG
using System;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.Serialization;
using PHP.Library;
using PHP.Core.Reflection;
namespace PHP.Core
{
/// <summary>
/// Provides services related to serialization.
/// </summary>
/// <remarks>
/// Used by .NET serialization (implemented in Core) as well as by PHP serialization, which is implemented
/// in ClassLibrary.
/// </remarks>
public static class Serialization
{
#region ParsePropertyName, FormatPropertyName
/// <summary>
/// Parses property name used for serialization.
/// </summary>
/// <param name="name">The name found in serialization stream or returned by <B>__sleep</B>.</param>
/// <param name="typeName">Will receive the name of the declaring type or <B>null</B> if no
/// type information is embedded in the property <paramref name="name"/>.</param>
/// <param name="visibility">Will receive the assumed visibility of the property.</param>
/// <returns>The bare (unmangled) property name.</returns>
/// <remarks>
/// Names of protected properties might be prepended with \0*\0, names of private properties might be
/// prepended with \0declaring_class_name\0
/// (see <A href="http://bugs.php.net/bug.php?id=26737">http://bugs.php.net/bug.php?id=26737</A>)
/// </remarks>
public static string/*!*/ ParsePropertyName(string/*!*/ name, out string typeName, out PhpMemberAttributes visibility)
{
if (name.Length >= 3 && name[0] == '\0')
{
if (name[1] == '*' && name[2] == '\0')
{
// probably a protected field
visibility = PhpMemberAttributes.Protected;
typeName = null;
return name.Substring(3);
}
else
{
// probably a private property
int index = name.IndexOf('\0', 2);
if (index > 0)
{
visibility = PhpMemberAttributes.Private;
typeName = name.Substring(1, index - 1); // TODO
return name.Substring(index + 1);
}
}
}
visibility = PhpMemberAttributes.Public;
typeName = null;
return name;
}
/// <summary>
/// Formats a property name for serialization according to its visibility and declaing type.
/// </summary>
/// <param name="property">The property desc.</param>
/// <param name="propertyName">The property name.</param>
/// <returns>The property name formatted according to the <paramref name="property"/> as used by PHP serialization.
/// </returns>
public static string/*!*/ FormatPropertyName(DPropertyDesc/*!*/ property, string/*!*/ propertyName)
{
switch (property.MemberAttributes & PhpMemberAttributes.VisibilityMask)
{
case PhpMemberAttributes.Public: return propertyName;
case PhpMemberAttributes.Protected: return "\0*\0" + propertyName;
case PhpMemberAttributes.Private: return "\0" + property.DeclaringType.MakeFullName() + "\0" + propertyName;
default: Debug.Fail(null); return null;
}
}
#endregion
#region EnumerateSerializableProperties
/// <summary>
/// Returns names and properties of all instance properties (including runtime fields).
/// </summary>
/// <param name="instance">The instance being serialized.</param>
/// <returns>Name-value pairs. Names are properly formatted for serialization.</returns>
public static IEnumerable<KeyValuePair<string, object>> EnumerateSerializableProperties(DObject/*!*/ instance)
{
return EnumerateSerializableProperties(instance, false);
}
/// <summary>
/// Returns names and properties of all instance properties or only PHP fields (including runtime fields).
/// </summary>
/// <param name="instance">The instance being serialized.</param>
/// <param name="phpFieldsOnly"><B>True</B> to return only PHP fields, <B>false</B> to return all
/// instance properties.</param>
/// <returns>Name-value pairs. Names are properly formatted for serialization.</returns>
public static IEnumerable<KeyValuePair<string, object>> EnumerateSerializableProperties(
DObject/*!*/ instance,
bool phpFieldsOnly)
{
// enumerate CT properties:
foreach (KeyValuePair<VariableName, DPropertyDesc> pair in instance.TypeDesc.EnumerateProperties())
{
// skip static props
if (pair.Value.IsStatic) continue;
// skip CLR fields and props if asked so
if (phpFieldsOnly && !(pair.Value is DPhpFieldDesc)) continue;
object property_value = pair.Value.Get(instance);
PhpReference property_value_ref = property_value as PhpReference;
if (property_value_ref == null || property_value_ref.IsSet)
{
yield return new KeyValuePair<string, object>(
Serialization.FormatPropertyName(pair.Value, pair.Key.ToString()),
property_value);
}
}
// enumerate RT fields:
if (instance.RuntimeFields != null)
{
foreach (var pair in instance.RuntimeFields)
{
yield return new KeyValuePair<string, object>(pair.Key.String, pair.Value);
}
}
}
/// <summary>
/// Returns names and values of properties whose names have been returned by <c>__sleep</c>.
/// </summary>
/// <param name="instance">The instance being serialized.</param>
/// <param name="sleepResult">The array returned by <c>__sleep</c>.</param>
/// <param name="context">Current <see cref="ScriptContext"/>.</param>
/// <returns>Name-value pairs. Names are properly formatted for serialization.</returns>
/// <exception cref="PhpException">Property of the name returned from <c>__sleep</c> does not exist.</exception>
/// <remarks>
/// This method returns exactly <paramref name="sleepResult"/>'s <see cref="PhpHashtable.Count"/> items.
/// </remarks>
public static IEnumerable<KeyValuePair<string, object>> EnumerateSerializableProperties(
DObject/*!*/ instance,
PhpArray/*!*/ sleepResult,
ScriptContext/*!*/ context)
{
foreach (object item in sleepResult.Values)
{
PhpMemberAttributes visibility;
string name = PHP.Core.Convert.ObjectToString(item);
string declaring_type_name;
string property_name = ParsePropertyName(name, out declaring_type_name, out visibility);
DTypeDesc declarer;
if (declaring_type_name == null) declarer = instance.TypeDesc;
else
{
declarer = context.ResolveType(declaring_type_name);
if (declarer == null)
{
// property name refers to an unknown class -> value will be null
yield return new KeyValuePair<string, object>(name, null);
continue;
}
}
// obtain the property desc and decorate the prop name according to its visibility and declaring class
DPropertyDesc property;
if (instance.TypeDesc.GetProperty(new VariableName(property_name), declarer, out property) ==
GetMemberResult.OK && !property.IsStatic)
{
if ((Enums.VisibilityEquals(visibility, property.MemberAttributes) &&
visibility != PhpMemberAttributes.Public)
||
(visibility == PhpMemberAttributes.Private &&
declarer != property.DeclaringType))
{
// if certain conditions are met, serialize the property as null
// (this is to precisely mimic the PHP behavior)
yield return new KeyValuePair<string, object>(name, null);
continue;
}
name = FormatPropertyName(property, property_name);
}
else property = null;
// obtain the property value
object val = null;
if (property != null)
{
val = property.Get(instance);
}
else if (instance.RuntimeFields == null || !instance.RuntimeFields.TryGetValue(name, out val))
{
// this is new in PHP 5.1
PhpException.Throw(PhpError.Notice, CoreResources.GetString("sleep_returned_bad_field", name));
}
yield return new KeyValuePair<string, object>(name, val);
}
}
#endregion
#region GetUninitializedInstance, SetProperty
/// <summary>
/// Returns an unitialized instance of the specified type or <see cref="__PHP_Incomplete_Class"/>.
/// </summary>
/// <param name="typeName">The type name.</param>
/// <param name="context">Current <see cref="ScriptContext"/>.</param>
/// <returns>The newly created instance or <B>null</B> if <paramref name="typeName"/> denotes
/// a primitive type.</returns>
/// <remarks>
/// If the <paramref name="typeName"/> denotes a CLR type, no constructor is executed. If the
/// <paramref name="typeName"/> denotes a PHP type, no user constructor (e.g. <c>__construct</c>)
/// is executed.
/// </remarks>
public static DObject GetUninitializedInstance(string/*!*/ typeName, ScriptContext/*!*/ context)
{
// resolve the specified type
DTypeDesc type = context.ResolveType(typeName);
if (type == null || type.IsAbstract)
{
PhpCallback callback = context.Config.Variables.DeserializationCallback;
if (callback != null && !callback.IsInvalid)
{
callback.Invoke(typeName);
type = context.ResolveType(typeName);
if (type == null || type.IsAbstract)
{
// unserialize_callback_func failed
PhpException.Throw(PhpError.Warning, CoreResources.GetString("unserialize_callback_failed",
((IPhpConvertible)callback).ToString()));
}
}
}
if (type == null || type.IsAbstract)
{
// type not found -> create __PHP_Incomplete_Class
__PHP_Incomplete_Class pic = new __PHP_Incomplete_Class(context, false);
pic.__PHP_Incomplete_Class_Name.Value = typeName;
pic.__PHP_Incomplete_Class_Name.IsSet = true;
return pic;
}
else
{
// create the instance
return type.New(context) as DObject;
}
}
/// <summary>
/// Sets a property of a <see cref="DObject"/> instance according to deserialized name and value.
/// </summary>
/// <param name="instance">The instance being deserialized.</param>
/// <param name="name">The property name formatted for serialization (see <see cref="FormatPropertyName"/>).</param>
/// <param name="value">The property value.</param>
/// <param name="context">Current <see cref="ScriptContext"/>.</param>
public static void SetProperty(DObject/*!*/ instance, string/*!*/ name, object value, ScriptContext/*!*/ context)
{
// the property name might encode its visibility and "classification" -> use these
// information for suitable property desc lookups
PhpMemberAttributes visibility;
string type_name;
string property_name = ParsePropertyName(name, out type_name, out visibility);
DTypeDesc declarer;
if (type_name == null) declarer = instance.TypeDesc;
else
{
declarer = context.ResolveType(type_name);
if (declarer == null) declarer = instance.TypeDesc;
}
// try to find a suitable field handle
DPropertyDesc property;
if (instance.TypeDesc.GetProperty(new VariableName(property_name), declarer, out property) ==
PHP.Core.Reflection.GetMemberResult.OK)
{
if ((property.IsPrivate &&
declarer != property.DeclaringType))
{
// if certain conditions are met, don't use the handle even if it was found
// (this is to precisely mimic the PHP behavior)
property = null;
}
}
else property = null;
if (property != null) property.Set(instance, value);
else
{
// suitable CT field not found -> add it to RT fields
// (note: care must be taken so that the serialize(unserialize($x)) round
// trip returns $x even if user classes specified in $x are not declared)
if (instance.RuntimeFields == null) instance.RuntimeFields = new PhpArray();
instance.RuntimeFields[name] = value;
}
}
#endregion
#region Debug log
#if !SILVERLIGHT
[Conditional("SERIALIZATION_DEBUG_LOG")]
internal static void DebugInstanceSerialized(DObject/*!*/ instance, bool forPersistence)
{
instance.SetProperty(
Guid.NewGuid().ToString(),
String.Format(
"Serialized for {0} in process: {1}, app domain: {2}",
forPersistence ? "persistence" : "remoting",
Process.GetCurrentProcess().MainModule.FileName,
AppDomain.CurrentDomain.FriendlyName),
null);
}
[Conditional("SERIALIZATION_DEBUG_LOG")]
internal static void DebugInstanceDeserialized(DObject/*!*/ instance, bool forPersistence)
{
instance.SetProperty(
Guid.NewGuid().ToString(),
String.Format(
"Deserialized for {0} in process: {1}, app domain: {2}",
forPersistence ? "persistence" : "remoting",
Process.GetCurrentProcess().MainModule.FileName,
AppDomain.CurrentDomain.FriendlyName),
null);
}
#endif
#endregion
}
}
| |
// -------------------------------------
// Domain : Avariceonline.com
// Author : Nicholas Ventimiglia
// Product : Unity3d Foundation
// Published : 2015
// -------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Foundation.Tasks;
using UnityEngine;
namespace Realtime.Messaging.Internal
{
/// <summary>
/// A http client which returns HttpTasks's
/// </summary>
public class HttpTaskService
{
/// <summary>
/// content type Header. Default value of "application/json"
/// </summary>
public string ContentType = "application/json";
/// <summary>
/// Accept Header. Default value of "application/json"
/// </summary>
public string Accept = "application/json";
/// <summary>
/// timeout
/// </summary>
public float Timeout = 11f;
/// <summary>
/// Http Headers Collection
/// </summary>
public Dictionary<string, string> Headers = new Dictionary<string, string>();
/// <summary>
/// List of disposed WWW. Shorten around 60 second Android Timeout
/// </summary>
List<WWW> _disposed = new List<WWW>();
public HttpTaskService()
{
}
public HttpTaskService(string contentType)
{
ContentType = contentType;
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public HttpTask GetAsync(string url)
{
var state = new HttpTask
{
Status = TaskStatus.Running,
};
TaskManager.StartRoutine(GetAsync(state, url));
return state;
}
IEnumerator GetAsync(HttpTask task, string url)
{
WWW www;
try
{
www = new WWW(url);
}
catch (Exception ex)
{
Debug.LogException(ex);
task.Exception = ex;
task.Status = TaskStatus.Faulted;
yield break;
}
TaskManager.StartRoutine(StartTimeout(www, Timeout));
yield return www;
if (_disposed.Contains(www))
{
task.StatusCode = HttpStatusCode.RequestTimeout;
task.Exception = new Exception("Request timed out");
task.Status = TaskStatus.Faulted;
_disposed.Remove(www);
yield break;
}
task.StatusCode = GetCode(www);
if (!string.IsNullOrEmpty(www.error))
{
task.Exception = new Exception(www.error);
task.Status = TaskStatus.Faulted;
}
else
{
task.Content = www.text;
task.Status = TaskStatus.Success;
}
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public HttpTask PostAsync(string url)
{
var state = new HttpTask
{
Status = TaskStatus.Running,
};
TaskManager.StartRoutine(PostAsync(state, url, null));
return state;
}
/// <summary>
/// Begins the Http request
/// </summary>
/// <param name="url"></param>
/// <param name="content"></param>
/// <returns></returns>
public HttpTask PostAsync(string url, string content)
{
var state = new HttpTask
{
Status = TaskStatus.Running,
};
TaskManager.StartRoutine(PostAsync(state, url, content));
return state;
}
IEnumerator PostAsync(HttpTask task, string url, string content)
{
if (!Headers.ContainsKey("Accept"))
Headers.Add("Accept", Accept);
if (!Headers.ContainsKey("Content-Type"))
Headers.Add("Content-Type", ContentType);
WWW www;
try
{
www = new WWW(url, content == null ? new byte[1] : Encoding.UTF8.GetBytes(content), Headers);
}
catch (Exception ex)
{
Debug.LogException(ex);
task.Exception = ex;
task.Status = TaskStatus.Faulted;
yield break;
}
if (!www.isDone)
{
TaskManager.StartRoutine(StartTimeout(www, Timeout));
yield return www;
}
if (_disposed.Contains(www))
{
task.StatusCode = HttpStatusCode.RequestTimeout;
task.Exception = new Exception("Request timed out");
task.Status = TaskStatus.Faulted;
_disposed.Remove(www);
yield break;
}
task.StatusCode = GetCode(www);
if (!string.IsNullOrEmpty(www.error))
{
task.Exception = new Exception(www.error);
task.Status = TaskStatus.Faulted;
}
else
{
task.Content = www.text;
task.Status = TaskStatus.Success;
}
}
IEnumerator StartTimeout(WWW www, float time)
{
yield return new WaitForSeconds(time);
if (!www.isDone)
{
www.Dispose();
_disposed.Add(www);
}
}
HttpStatusCode GetCode(WWW www)
{
if (!www.responseHeaders.ContainsKey("STATUS"))
{
return 0;
}
var code = www.responseHeaders["STATUS"].Split(' ')[1];
return (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), code);
}
}
}
| |
// 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 AverageByte()
{
var test = new SimpleBinaryOpTest__AverageByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AverageByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public Vector128<Byte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AverageByte testClass)
{
var result = Sse2.Average(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AverageByte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.Average(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AverageByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__AverageByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, _data2, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Average(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Average(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Average(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Average), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Average), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Average), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Average(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
fixed (Vector128<Byte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Average(
Sse2.LoadVector128((Byte*)(pClsVar1)),
Sse2.LoadVector128((Byte*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.Average(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Average(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Average(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AverageByte();
var result = Sse2.Average(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AverageByte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
fixed (Vector128<Byte>* pFld2 = &test._fld2)
{
var result = Sse2.Average(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Average(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
fixed (Vector128<Byte>* pFld2 = &_fld2)
{
var result = Sse2.Average(
Sse2.LoadVector128((Byte*)(pFld1)),
Sse2.LoadVector128((Byte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Average(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Average(
Sse2.LoadVector128((Byte*)(&test._fld1)),
Sse2.LoadVector128((Byte*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((byte)((left[0] + right[0] + 1) >> 1) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((byte)((left[i] + right[i] + 1) >> 1) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Average)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// 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.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
/// <summary>Provides a pool of connections to the same endpoint.</summary>
internal sealed class HttpConnectionPool : IDisposable
{
private static readonly bool s_isWindows7Or2008R2 = GetIsWindows7Or2008R2();
private readonly HttpConnectionPoolManager _poolManager;
private readonly HttpConnectionKind _kind;
private readonly string _host;
private readonly int _port;
private readonly Uri _proxyUri;
/// <summary>List of idle connections stored in the pool.</summary>
private readonly List<CachedConnection> _idleConnections = new List<CachedConnection>();
/// <summary>The maximum number of connections allowed to be associated with the pool.</summary>
private readonly int _maxConnections;
private bool _http2Enabled;
private Http2Connection _http2Connection;
private SemaphoreSlim _http2ConnectionCreateLock;
/// <summary>For non-proxy connection pools, this is the host name in bytes; for proxies, null.</summary>
private readonly byte[] _hostHeaderValueBytes;
/// <summary>Options specialized and cached for this pool and its <see cref="_key"/>.</summary>
private readonly SslClientAuthenticationOptions _sslOptionsHttp11;
private readonly SslClientAuthenticationOptions _sslOptionsHttp2;
/// <summary>Queue of waiters waiting for a connection. Created on demand.</summary>
private Queue<TaskCompletionSourceWithCancellation<HttpConnection>> _waiters;
/// <summary>The number of connections associated with the pool. Some of these may be in <see cref="_idleConnections"/>, others may be in use.</summary>
private int _associatedConnectionCount;
/// <summary>Whether the pool has been used since the last time a cleanup occurred.</summary>
private bool _usedSinceLastCleanup = true;
/// <summary>Whether the pool has been disposed.</summary>
private bool _disposed;
private const int DefaultHttpPort = 80;
private const int DefaultHttpsPort = 443;
/// <summary>Initializes the pool.</summary>
/// <param name="maxConnections">The maximum number of connections allowed to be associated with the pool at any given time.</param>
public HttpConnectionPool(HttpConnectionPoolManager poolManager, HttpConnectionKind kind, string host, int port, string sslHostName, Uri proxyUri, int maxConnections)
{
_poolManager = poolManager;
_kind = kind;
_host = host;
_port = port;
_proxyUri = proxyUri;
_maxConnections = maxConnections;
_http2Enabled = (_poolManager.Settings._maxHttpVersion == HttpVersion.Version20);
switch (kind)
{
case HttpConnectionKind.Http:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName == null);
Debug.Assert(proxyUri == null);
_http2Enabled = false;
break;
case HttpConnectionKind.Https:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName != null);
Debug.Assert(proxyUri == null);
break;
case HttpConnectionKind.Proxy:
Debug.Assert(host == null);
Debug.Assert(port == 0);
Debug.Assert(sslHostName == null);
Debug.Assert(proxyUri != null);
_http2Enabled = false;
break;
case HttpConnectionKind.ProxyTunnel:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName == null);
Debug.Assert(proxyUri != null);
_http2Enabled = false;
break;
case HttpConnectionKind.SslProxyTunnel:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName != null);
Debug.Assert(proxyUri != null);
break;
case HttpConnectionKind.ProxyConnect:
Debug.Assert(host != null);
Debug.Assert(port != 0);
Debug.Assert(sslHostName == null);
Debug.Assert(proxyUri != null);
_http2Enabled = false;
break;
default:
Debug.Fail("Unkown HttpConnectionKind in HttpConnectionPool.ctor");
break;
}
if (sslHostName != null)
{
_sslOptionsHttp11 = ConstructSslOptions(poolManager, sslHostName);
_sslOptionsHttp11.ApplicationProtocols = null;
if (_http2Enabled)
{
_sslOptionsHttp2 = ConstructSslOptions(poolManager, sslHostName);
_sslOptionsHttp2.ApplicationProtocols = Http2ApplicationProtocols;
_sslOptionsHttp2.AllowRenegotiation = false;
}
}
if (_host != null)
{
// Precalculate ASCII bytes for Host header
// Note that if _host is null, this is a (non-tunneled) proxy connection, and we can't cache the hostname.
string hostHeader =
(_port != (sslHostName == null ? DefaultHttpPort : DefaultHttpsPort)) ?
$"{_host}:{_port}" :
_host;
// Note the IDN hostname should always be ASCII, since it's already been IDNA encoded.
_hostHeaderValueBytes = Encoding.ASCII.GetBytes(hostHeader);
Debug.Assert(Encoding.ASCII.GetString(_hostHeaderValueBytes) == hostHeader);
}
// Set up for PreAuthenticate. Access to this cache is guarded by a lock on the cache itself.
if (_poolManager.Settings._preAuthenticate)
{
PreAuthCredentials = new CredentialCache();
}
}
private static readonly List<SslApplicationProtocol> Http2ApplicationProtocols = new List<SslApplicationProtocol>() { SslApplicationProtocol.Http2, SslApplicationProtocol.Http11 };
private static SslClientAuthenticationOptions ConstructSslOptions(HttpConnectionPoolManager poolManager, string sslHostName)
{
Debug.Assert(sslHostName != null);
SslClientAuthenticationOptions sslOptions = poolManager.Settings._sslOptions?.ShallowClone() ?? new SslClientAuthenticationOptions();
// Set TargetHost for SNI
sslOptions.TargetHost = sslHostName;
// Windows 7 and Windows 2008 R2 support TLS 1.1 and 1.2, but for legacy reasons by default those protocols
// are not enabled when a developer elects to use the system default. However, in .NET Core 2.0 and earlier,
// HttpClientHandler would enable them, due to being a wrapper for WinHTTP, which enabled them. Both for
// compatibility and because we prefer those higher protocols whenever possible, SocketsHttpHandler also
// pretends they're part of the default when running on Win7/2008R2.
if (s_isWindows7Or2008R2 && sslOptions.EnabledSslProtocols == SslProtocols.None)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Info(poolManager, $"Win7OrWin2K8R2 platform, Changing default TLS protocols to {SecurityProtocol.DefaultSecurityProtocols}");
}
sslOptions.EnabledSslProtocols = SecurityProtocol.DefaultSecurityProtocols;
}
return sslOptions;
}
public HttpConnectionSettings Settings => _poolManager.Settings;
public bool IsSecure => _sslOptionsHttp11 != null;
public HttpConnectionKind Kind => _kind;
public bool AnyProxyKind => (_proxyUri != null);
public Uri ProxyUri => _proxyUri;
public ICredentials ProxyCredentials => _poolManager.ProxyCredentials;
public byte[] HostHeaderValueBytes => _hostHeaderValueBytes;
public CredentialCache PreAuthCredentials { get; }
/// <summary>Object used to synchronize access to state in the pool.</summary>
private object SyncObj => _idleConnections;
private ValueTask<(HttpConnectionBase connection, bool isNewConnection, HttpResponseMessage failureResponse)>
GetConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (_http2Enabled && request.Version.Major >= 2)
{
return GetHttp2ConnectionAsync(request, cancellationToken);
}
return GetHttpConnectionAsync(request, cancellationToken);
}
private ValueTask<(HttpConnectionBase connection, bool isNewConnection, HttpResponseMessage failureResponse)>
GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
if (NetEventSource.IsEnabled) Trace("Unable to complete getting HTTP/1.x connection due to requested cancellation.");
return new ValueTask<(HttpConnectionBase, bool, HttpResponseMessage)>(Task.FromCanceled<(HttpConnectionBase, bool, HttpResponseMessage)>(cancellationToken));
}
TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime;
TimeSpan pooledConnectionIdleTimeout = _poolManager.Settings._pooledConnectionIdleTimeout;
DateTimeOffset now = DateTimeOffset.UtcNow;
List<CachedConnection> list = _idleConnections;
// Try to get a cached connection. If we can and if it's usable, return it. If we can but it's not usable,
// try again. And if we can't because there aren't any valid ones, create a new one and return it.
while (true)
{
CachedConnection cachedConnection;
lock (SyncObj)
{
if (list.Count > 0)
{
// Pop off the next connection to try. We'll test it outside of the lock
// to avoid doing expensive validation while holding the lock.
cachedConnection = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
}
else
{
// No valid cached connections, so we need to create a new one. If
// there's no limit on the number of connections associated with this
// pool, or if we haven't reached such a limit, simply create a new
// connection.
if (_associatedConnectionCount < _maxConnections)
{
if (NetEventSource.IsEnabled) Trace("Creating new connection for pool.");
IncrementConnectionCountNoLock();
return WaitForCreatedConnectionAsync(CreateHttp11ConnectionAsync(request, cancellationToken));
}
else
{
// There is a limit, and we've reached it, which means we need to
// wait for a connection to be returned to the pool or for a connection
// associated with the pool to be dropped before we can create a
// new one. Create a waiter object and register it with the pool; it'll
// be signaled with the created connection when one is returned or
// space is available.
if (NetEventSource.IsEnabled) Trace("Connection limit reached, enqueuing waiter.");
TaskCompletionSourceWithCancellation<HttpConnection> waiter = EnqueueWaiter();
return WaitForAvailableHttp11Connection(waiter, request, cancellationToken);
}
// Note that we don't check for _disposed. We may end up disposing the
// created connection when it's returned, but we don't want to block use
// of the pool if it's already been disposed, as there's a race condition
// between getting a pool and someone disposing of it, and we don't want
// to complicate the logic about trying to get a different pool when the
// retrieved one has been disposed of. In the future we could alternatively
// try returning such connections to whatever pool is currently considered
// current for that endpoint, if there is one.
}
}
HttpConnection conn = cachedConnection._connection;
if (cachedConnection.IsUsable(now, pooledConnectionLifetime, pooledConnectionIdleTimeout) &&
!conn.EnsureReadAheadAndPollRead())
{
// We found a valid connection. Return it.
if (NetEventSource.IsEnabled) conn.Trace("Found usable connection in pool.");
return new ValueTask<(HttpConnectionBase, bool, HttpResponseMessage)>((conn, false, null));
}
// We got a connection, but it was already closed by the server or the
// server sent unexpected data or the connection is too old. In any case,
// we can't use the connection, so get rid of it and loop around to try again.
if (NetEventSource.IsEnabled) conn.Trace("Found invalid connection in pool.");
conn.Dispose();
}
}
private async ValueTask<(HttpConnectionBase connection, bool isNewConnection, HttpResponseMessage failureResponse)>
WaitForAvailableHttp11Connection(TaskCompletionSourceWithCancellation<HttpConnection> waiter, HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpConnection connection = await waiter.WaitWithCancellationAsync(cancellationToken).ConfigureAwait(false);
if (connection != null)
{
return (connection, false, null);
}
return await WaitForCreatedConnectionAsync(CreateHttp11ConnectionAsync(request, cancellationToken)).ConfigureAwait(false);
}
private async ValueTask<(HttpConnectionBase connection, bool isNewConnection, HttpResponseMessage failureResponse)>
GetHttp2ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Debug.Assert(_kind == HttpConnectionKind.Https || _kind == HttpConnectionKind.SslProxyTunnel);
// See if we have an HTTP2 connection
Http2Connection http2Connection = _http2Connection;
if (http2Connection != null)
{
if (NetEventSource.IsEnabled) Trace("Using existing HTTP2 connection.");
return (http2Connection, false, null);
}
// Ensure that the connection creation semaphore is created
if (_http2ConnectionCreateLock == null)
{
lock (SyncObj)
{
if (_http2ConnectionCreateLock == null)
{
_http2ConnectionCreateLock = new SemaphoreSlim(1);
}
}
}
// Try to establish an HTTP2 connection
Socket socket = null;
SslStream sslStream = null;
TransportContext transportContext = null;
// Serialize creation attempt
await _http2ConnectionCreateLock.WaitAsync().ConfigureAwait(false);
try
{
if (_http2Connection != null)
{
// Someone beat us to it
if (NetEventSource.IsEnabled)
{
Trace("Using existing HTTP2 connection.");
}
return (_http2Connection, false, null);
}
// Recheck if HTTP2 has been disabled by a previous attempt.
if (_http2Enabled)
{
if (NetEventSource.IsEnabled)
{
Trace("Attempting new HTTP2 connection.");
}
Stream stream;
HttpResponseMessage failureResponse;
(socket, stream, transportContext, failureResponse) =
await ConnectAsync(request, true, cancellationToken).ConfigureAwait(false);
if (failureResponse != null)
{
return (null, true, failureResponse);
}
sslStream = (SslStream)stream;
if (sslStream.NegotiatedApplicationProtocol == SslApplicationProtocol.Http2)
{
// The server accepted our request for HTTP2.
if (sslStream.SslProtocol < SslProtocols.Tls12)
{
throw new HttpRequestException(SR.net_http_invalid_response);
}
http2Connection = new Http2Connection(this, sslStream);
await http2Connection.SetupAsync().ConfigureAwait(false);
Debug.Assert(_http2Connection == null);
_http2Connection = http2Connection;
if (NetEventSource.IsEnabled)
{
Trace("New HTTP2 connection established.");
}
return (_http2Connection, true, null);
}
}
}
finally
{
_http2ConnectionCreateLock.Release();
}
if (sslStream != null)
{
// We established an SSL connection, but the server denied our request for HTTP2.
// Continue as an HTTP/1.1 connection.
if (NetEventSource.IsEnabled)
{
Trace("Server does not support HTTP2; disabling HTTP2 use and proceeding with HTTP/1.1 connection");
}
bool canUse = true;
lock (SyncObj)
{
_http2Enabled = false;
if (_associatedConnectionCount < _maxConnections)
{
IncrementConnectionCountNoLock();
}
else
{
// We are in the weird situation of having established a new HTTP 1.1 connection
// when we were already at the maximum for HTTP 1.1 connections.
// Just discard this connection and get another one from the pool.
// This should be a really rare situation to get into, since it would require
// the user to make multiple HTTP 1.1-only requests first before attempting an
// HTTP2 request, and the server failing to accept HTTP2.
canUse = false;
}
}
if (canUse)
{
return (ConstructHttp11Connection(socket, sslStream, transportContext), true, null);
}
else
{
if (NetEventSource.IsEnabled)
{
Trace("Discarding downgraded HTTP/1.1 connection because connection limit is exceeded");
}
sslStream.Close();
}
}
// If we reach this point, it means we need to fall back to a (new or existing) HTTP/1.1 connection.
return await GetHttpConnectionAsync(request, cancellationToken);
}
public async Task<HttpResponseMessage> SendWithRetryAsync(HttpRequestMessage request, bool doRequestAuth, CancellationToken cancellationToken)
{
while (true)
{
// Loop on connection failures and retry if possible.
(HttpConnectionBase connection, bool isNewConnection, HttpResponseMessage failureResponse) = await GetConnectionAsync(request, cancellationToken).ConfigureAwait(false);
if (failureResponse != null)
{
// Proxy tunnel failure; return proxy response
Debug.Assert(isNewConnection);
Debug.Assert(connection == null);
return failureResponse;
}
try
{
if (connection is HttpConnection)
{
return await SendWithNtConnectionAuthAsync((HttpConnection)connection, request, doRequestAuth, cancellationToken).ConfigureAwait(false);
}
else
{
return await connection.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
catch (HttpRequestException e) when (!isNewConnection && e.AllowRetry)
{
if (NetEventSource.IsEnabled)
{
Trace($"Retrying request after exception on existing connection: {e}");
}
// Eat exception and try again.
}
}
}
public async Task<HttpResponseMessage> SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, bool doRequestAuth, CancellationToken cancellationToken)
{
connection.Acquire();
try
{
if (doRequestAuth && Settings._credentials != null)
{
return await AuthenticationHelper.SendWithNtConnectionAuthAsync(request, Settings._credentials, connection, this, cancellationToken).ConfigureAwait(false);
}
return await SendWithNtProxyAuthAsync(connection, request, cancellationToken).ConfigureAwait(false);
}
finally
{
connection.Release();
}
}
public Task<HttpResponseMessage> SendWithNtProxyAuthAsync(HttpConnection connection, HttpRequestMessage request, CancellationToken cancellationToken)
{
if (AnyProxyKind && ProxyCredentials != null)
{
return AuthenticationHelper.SendWithNtProxyAuthAsync(request, ProxyUri, ProxyCredentials, connection, this, cancellationToken);
}
return connection.SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> SendWithProxyAuthAsync(HttpRequestMessage request, bool doRequestAuth, CancellationToken cancellationToken)
{
if ((_kind == HttpConnectionKind.Proxy || _kind == HttpConnectionKind.ProxyConnect) &&
_poolManager.ProxyCredentials != null)
{
return AuthenticationHelper.SendWithProxyAuthAsync(request, _proxyUri, _poolManager.ProxyCredentials, doRequestAuth, this, cancellationToken);
}
return SendWithRetryAsync(request, doRequestAuth, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, bool doRequestAuth, CancellationToken cancellationToken)
{
if (doRequestAuth && Settings._credentials != null)
{
return AuthenticationHelper.SendWithRequestAuthAsync(request, Settings._credentials, Settings._preAuthenticate, this, cancellationToken);
}
return SendWithProxyAuthAsync(request, doRequestAuth, cancellationToken);
}
private async ValueTask<(Socket, Stream, TransportContext, HttpResponseMessage)> ConnectAsync(HttpRequestMessage request, bool allowHttp2, CancellationToken cancellationToken)
{
// If a non-infinite connect timeout has been set, create and use a new CancellationToken that'll be canceled
// when either the original token is canceled or a connect timeout occurs.
CancellationTokenSource cancellationWithConnectTimeout = null;
if (Settings._connectTimeout != Timeout.InfiniteTimeSpan)
{
cancellationWithConnectTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, default);
cancellationWithConnectTimeout.CancelAfter(Settings._connectTimeout);
cancellationToken = cancellationWithConnectTimeout.Token;
}
try
{
Socket socket = null;
Stream stream = null;
switch (_kind)
{
case HttpConnectionKind.Http:
case HttpConnectionKind.Https:
case HttpConnectionKind.ProxyConnect:
(socket, stream) = await ConnectHelper.ConnectAsync(_host, _port, cancellationToken).ConfigureAwait(false);
break;
case HttpConnectionKind.Proxy:
(socket, stream) = await ConnectHelper.ConnectAsync(_proxyUri.IdnHost, _proxyUri.Port, cancellationToken).ConfigureAwait(false);
break;
case HttpConnectionKind.ProxyTunnel:
case HttpConnectionKind.SslProxyTunnel:
HttpResponseMessage response;
(stream, response) = await EstablishProxyTunnel(cancellationToken).ConfigureAwait(false);
if (response != null)
{
// Return non-success response from proxy.
response.RequestMessage = request;
return (null, null, null, response);
}
break;
}
TransportContext transportContext = null;
if (_kind == HttpConnectionKind.Https || _kind == HttpConnectionKind.SslProxyTunnel)
{
SslStream sslStream = await ConnectHelper.EstablishSslConnectionAsync(allowHttp2 ? _sslOptionsHttp2 : _sslOptionsHttp11, request, stream, cancellationToken).ConfigureAwait(false);
stream = sslStream;
transportContext = sslStream.TransportContext;
}
return (socket, stream, transportContext, null);
}
finally
{
cancellationWithConnectTimeout?.Dispose();
}
}
internal async ValueTask<(HttpConnection, HttpResponseMessage)> CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
(Socket socket, Stream stream, TransportContext transportContext, HttpResponseMessage failureResponse) =
await ConnectAsync(request, false, cancellationToken).ConfigureAwait(false);
if (failureResponse != null)
{
return (null, failureResponse);
}
return (ConstructHttp11Connection(socket, stream, transportContext), null);
}
private HttpConnection ConstructHttp11Connection(Socket socket, Stream stream, TransportContext transportContext)
{
return _maxConnections == int.MaxValue ?
new HttpConnection(this, socket, stream, transportContext) :
new HttpConnectionWithFinalizer(this, socket, stream, transportContext); // finalizer needed to signal the pool when a connection is dropped
}
// Returns the established stream or an HttpResponseMessage from the proxy indicating failure.
private async ValueTask<(Stream, HttpResponseMessage)> EstablishProxyTunnel(CancellationToken cancellationToken)
{
// Send a CONNECT request to the proxy server to establish a tunnel.
HttpRequestMessage tunnelRequest = new HttpRequestMessage(HttpMethod.Connect, _proxyUri);
tunnelRequest.Headers.Host = $"{_host}:{_port}"; // This specifies destination host/port to connect to
HttpResponseMessage tunnelResponse = await _poolManager.SendProxyConnectAsync(tunnelRequest, _proxyUri, cancellationToken).ConfigureAwait(false);
if (tunnelResponse.StatusCode != HttpStatusCode.OK)
{
return (null, tunnelResponse);
}
return (await tunnelResponse.Content.ReadAsStreamAsync().ConfigureAwait(false), null);
}
/// <summary>Enqueues a waiter to the waiters list.</summary>
/// <param name="waiter">The waiter to add.</param>
private TaskCompletionSourceWithCancellation<HttpConnection> EnqueueWaiter()
{
Debug.Assert(Monitor.IsEntered(SyncObj));
Debug.Assert(Settings._maxConnectionsPerServer != int.MaxValue);
Debug.Assert(_idleConnections.Count == 0, $"With {_idleConnections.Count} idle connections, we shouldn't have a waiter.");
if (_waiters == null)
{
_waiters = new Queue<TaskCompletionSourceWithCancellation<HttpConnection>>();
}
var waiter = new TaskCompletionSourceWithCancellation<HttpConnection>();
_waiters.Enqueue(waiter);
return waiter;
}
private bool HasWaiter()
{
Debug.Assert(Monitor.IsEntered(SyncObj));
return (_waiters != null && _waiters.Count > 0);
}
/// <summary>Dequeues a waiter from the waiters list. The list must not be empty.</summary>
/// <returns>The dequeued waiter.</returns>
private TaskCompletionSourceWithCancellation<HttpConnection> DequeueWaiter()
{
Debug.Assert(Monitor.IsEntered(SyncObj));
Debug.Assert(Settings._maxConnectionsPerServer != int.MaxValue);
Debug.Assert(_idleConnections.Count == 0, $"With {_idleConnections.Count} idle connections, we shouldn't have a waiter.");
return _waiters.Dequeue();
}
/// <summary>Waits for and returns the created connection, decrementing the associated connection count if it fails.</summary>
private async ValueTask<(HttpConnectionBase connection, bool isNewConnection, HttpResponseMessage failureResponse)> WaitForCreatedConnectionAsync(ValueTask<(HttpConnection, HttpResponseMessage)> creationTask)
{
try
{
(HttpConnection connection, HttpResponseMessage response) = await creationTask.ConfigureAwait(false);
if (connection == null)
{
DecrementConnectionCount();
}
return (connection, true, response);
}
catch
{
DecrementConnectionCount();
throw;
}
}
private void IncrementConnectionCountNoLock()
{
Debug.Assert(Monitor.IsEntered(SyncObj), $"Expected to be holding {nameof(SyncObj)}");
if (NetEventSource.IsEnabled) Trace(null);
_usedSinceLastCleanup = true;
Debug.Assert(
_associatedConnectionCount >= 0 && _associatedConnectionCount < _maxConnections,
$"Expected 0 <= {_associatedConnectionCount} < {_maxConnections}");
_associatedConnectionCount++;
}
internal void IncrementConnectionCount()
{
lock (SyncObj)
{
IncrementConnectionCountNoLock();
}
}
private bool TransferConnection(HttpConnection connection)
{
Debug.Assert(Monitor.IsEntered(SyncObj));
while (HasWaiter())
{
TaskCompletionSource<HttpConnection> waiter = DequeueWaiter();
// Try to complete the task. If it's been cancelled already, this will fail.
if (waiter.TrySetResult(connection))
{
return true;
}
// Couldn't transfer to that waiter because it was cancelled. Try again.
Debug.Assert(waiter.Task.IsCanceled);
}
return false;
}
/// <summary>
/// Decrements the number of connections associated with the pool.
/// If there are waiters on the pool due to having reached the maximum,
/// this will instead try to transfer the count to one of them.
/// </summary>
public void DecrementConnectionCount()
{
if (NetEventSource.IsEnabled) Trace(null);
lock (SyncObj)
{
Debug.Assert(_associatedConnectionCount > 0 && _associatedConnectionCount <= _maxConnections,
$"Expected 0 < {_associatedConnectionCount} <= {_maxConnections}");
// Mark the pool as not being stale.
_usedSinceLastCleanup = true;
if (TransferConnection(null))
{
if (NetEventSource.IsEnabled) Trace("Transferred connection count to waiter.");
return;
}
// There are no waiters to which the count should logically be transferred,
// so simply decrement the count.
_associatedConnectionCount--;
}
}
/// <summary>Returns the connection to the pool for subsequent reuse.</summary>
/// <param name="connection">The connection to return.</param>
public void ReturnConnection(HttpConnection connection)
{
TimeSpan lifetime = _poolManager.Settings._pooledConnectionLifetime;
bool lifetimeExpired =
lifetime != Timeout.InfiniteTimeSpan &&
(lifetime == TimeSpan.Zero || connection.CreationTime + lifetime <= DateTime.UtcNow);
if (!lifetimeExpired)
{
List<CachedConnection> list = _idleConnections;
lock (SyncObj)
{
Debug.Assert(list.Count <= _maxConnections, $"Expected {list.Count} <= {_maxConnections}");
// Mark the pool as still being active.
_usedSinceLastCleanup = true;
// If there's someone waiting for a connection and this one's still valid, simply transfer this one to them rather than pooling it.
// Note that while we checked connection lifetime above, we don't check idle timeout, as even if idle timeout
// is zero, we consider a connection that's just handed from one use to another to never actually be idle.
bool receivedUnexpectedData = false;
if (HasWaiter())
{
receivedUnexpectedData = connection.EnsureReadAheadAndPollRead();
if (!receivedUnexpectedData && TransferConnection(connection))
{
if (NetEventSource.IsEnabled) connection.Trace("Transferred connection to waiter.");
return;
}
}
// If the connection is still valid, add it to the list.
// If the pool has been disposed of, dispose the connection being returned,
// as the pool is being deactivated. We do this after the above in order to
// use pooled connections to satisfy any requests that pended before the
// the pool was disposed of. We also dispose of connections if connection
// timeouts are such that the connection would immediately expire, anyway, as
// well as for connections that have unexpectedly received extraneous data / EOF.
if (!receivedUnexpectedData &&
!_disposed &&
_poolManager.Settings._pooledConnectionIdleTimeout != TimeSpan.Zero)
{
// Pool the connection by adding it to the list.
list.Add(new CachedConnection(connection));
if (NetEventSource.IsEnabled) connection.Trace("Stored connection in pool.");
return;
}
}
}
// The connection could be not be reused. Dispose of it.
// Disposing it will alert any waiters that a connection slot has become available.
if (NetEventSource.IsEnabled)
{
connection.Trace(
lifetimeExpired ? "Disposing connection return to pool. Connection lifetime expired." :
_poolManager.Settings._pooledConnectionIdleTimeout == TimeSpan.Zero ? "Disposing connection returned to pool. Zero idle timeout." :
_disposed ? "Disposing connection returned to pool. Pool was disposed." :
"Disposing connection returned to pool. Read-ahead unexpectedly completed.");
}
connection.Dispose();
}
public void InvalidateHttp2Connection(Http2Connection connection)
{
Debug.Assert(_http2Connection == connection);
_http2Connection = null;
}
/// <summary>
/// Disposes the connection pool. This is only needed when the pool currently contains
/// or has associated connections.
/// </summary>
public void Dispose()
{
List<CachedConnection> list = _idleConnections;
lock (SyncObj)
{
if (!_disposed)
{
if (NetEventSource.IsEnabled) Trace("Disposing pool.");
_disposed = true;
list.ForEach(c => c._connection.Dispose());
list.Clear();
if (_http2Connection != null)
{
_http2Connection.Dispose();
_http2Connection = null;
}
}
Debug.Assert(list.Count == 0, $"Expected {nameof(list)}.{nameof(list.Count)} == 0");
}
}
/// <summary>
/// Removes any unusable connections from the pool, and if the pool
/// is then empty and stale, disposes of it.
/// </summary>
/// <returns>
/// true if the pool disposes of itself; otherwise, false.
/// </returns>
public bool CleanCacheAndDisposeIfUnused()
{
TimeSpan pooledConnectionLifetime = _poolManager.Settings._pooledConnectionLifetime;
TimeSpan pooledConnectionIdleTimeout = _poolManager.Settings._pooledConnectionIdleTimeout;
List<CachedConnection> list = _idleConnections;
List<HttpConnection> toDispose = null;
bool tookLock = false;
try
{
if (NetEventSource.IsEnabled) Trace("Cleaning pool.");
Monitor.Enter(SyncObj, ref tookLock);
// Get the current time. This is compared against each connection's last returned
// time to determine whether a connection is too old and should be closed.
DateTimeOffset now = DateTimeOffset.UtcNow;
// Find the first item which needs to be removed.
int freeIndex = 0;
while (freeIndex < list.Count && list[freeIndex].IsUsable(now, pooledConnectionLifetime, pooledConnectionIdleTimeout, poll: true))
{
freeIndex++;
}
// If freeIndex == list.Count, nothing needs to be removed.
// But if it's < list.Count, at least one connection needs to be purged.
if (freeIndex < list.Count)
{
// We know the connection at freeIndex is unusable, so dispose of it.
toDispose = new List<HttpConnection> { list[freeIndex]._connection };
// Find the first item after the one to be removed that should be kept.
int current = freeIndex + 1;
while (current < list.Count)
{
// Look for the first item to be kept. Along the way, any
// that shouldn't be kept are disposed of.
while (current < list.Count && !list[current].IsUsable(now, pooledConnectionLifetime, pooledConnectionIdleTimeout, poll: true))
{
toDispose.Add(list[current]._connection);
current++;
}
// If we found something to keep, copy it down to the known free slot.
if (current < list.Count)
{
// copy item to the free slot
list[freeIndex++] = list[current++];
}
// Keep going until there are no more good items.
}
// At this point, good connections have been moved below freeIndex, and garbage connections have
// been added to the dispose list, so clear the end of the list past freeIndex.
list.RemoveRange(freeIndex, list.Count - freeIndex);
// If there are now no connections associated with this pool, we can dispose of it. We
// avoid aggressively cleaning up pools that have recently been used but currently aren't;
// if a pool was used since the last time we cleaned up, give it another chance. New pools
// start out saying they've recently been used, to give them a bit of breathing room and time
// for the initial collection to be added to it.
if (_associatedConnectionCount == 0 && !_usedSinceLastCleanup)
{
Debug.Assert(list.Count == 0, $"Expected {nameof(list)}.{nameof(list.Count)} == 0");
_disposed = true;
return true; // Pool is disposed of. It should be removed.
}
}
// Reset the cleanup flag. Any pools that are empty and not used since the last cleanup
// will be purged next time around.
_usedSinceLastCleanup = false;
}
finally
{
if (tookLock)
{
Monitor.Exit(SyncObj);
}
// Dispose the stale connections outside the pool lock.
toDispose?.ForEach(c => c.Dispose());
}
// Pool is active. Should not be removed.
return false;
}
/// <summary>Gets whether we're running on Windows 7 or Windows 2008 R2.</summary>
private static bool GetIsWindows7Or2008R2()
{
OperatingSystem os = Environment.OSVersion;
if (os.Platform == PlatformID.Win32NT)
{
// Both Windows 7 and Windows 2008 R2 report version 6.1.
Version v = os.Version;
return v.Major == 6 && v.Minor == 1;
}
return false;
}
// For diagnostic purposes
public override string ToString() =>
$"{nameof(HttpConnectionPool)} " +
(_proxyUri == null ?
(_sslOptionsHttp11 == null ?
$"http://{_host}:{_port}" :
$"https://{_host}:{_port}" + (_sslOptionsHttp11.TargetHost != _host ? $", SSL TargetHost={_sslOptionsHttp11.TargetHost}" : null)) :
(_sslOptionsHttp11 == null ?
$"Proxy {_proxyUri}" :
$"https://{_host}:{_port}/ tunnelled via Proxy {_proxyUri}" + (_sslOptionsHttp11.TargetHost != _host ? $", SSL TargetHost={_sslOptionsHttp11.TargetHost}" : null)));
private void Trace(string message, [CallerMemberName] string memberName = null) =>
NetEventSource.Log.HandlerMessage(
GetHashCode(), // pool ID
0, // connection ID
0, // request ID
memberName, // method name
ToString() + ":" + message); // message
/// <summary>A cached idle connection and metadata about it.</summary>
[StructLayout(LayoutKind.Auto)]
private readonly struct CachedConnection : IEquatable<CachedConnection>
{
/// <summary>The cached connection.</summary>
internal readonly HttpConnection _connection;
/// <summary>The last time the connection was used.</summary>
internal readonly DateTimeOffset _returnedTime;
/// <summary>Initializes the cached connection and its associated metadata.</summary>
/// <param name="connection">The connection.</param>
public CachedConnection(HttpConnection connection)
{
Debug.Assert(connection != null);
_connection = connection;
_returnedTime = DateTimeOffset.UtcNow;
}
/// <summary>Gets whether the connection is currently usable.</summary>
/// <param name="now">The current time. Passed in to amortize the cost of calling DateTime.UtcNow.</param>
/// <param name="pooledConnectionLifetime">How long a connection can be open to be considered reusable.</param>
/// <param name="pooledConnectionIdleTimeout">How long a connection can have been idle in the pool to be considered reusable.</param>
/// <returns>
/// true if we believe the connection can be reused; otherwise, false. There is an inherent race condition here,
/// in that the server could terminate the connection or otherwise make it unusable immediately after we check it,
/// but there's not much difference between that and starting to use the connection and then having the server
/// terminate it, which would be considered a failure, so this race condition is largely benign and inherent to
/// the nature of connection pooling.
/// </returns>
public bool IsUsable(
DateTimeOffset now,
TimeSpan pooledConnectionLifetime,
TimeSpan pooledConnectionIdleTimeout,
bool poll = false)
{
// Validate that the connection hasn't been idle in the pool for longer than is allowed.
if ((pooledConnectionIdleTimeout != Timeout.InfiniteTimeSpan) && (now - _returnedTime > pooledConnectionIdleTimeout))
{
if (NetEventSource.IsEnabled) _connection.Trace($"Connection no longer usable. Idle {now - _returnedTime} > {pooledConnectionIdleTimeout}.");
return false;
}
// Validate that the connection hasn't been alive for longer than is allowed.
if ((pooledConnectionLifetime != Timeout.InfiniteTimeSpan) && (now - _connection.CreationTime > pooledConnectionLifetime))
{
if (NetEventSource.IsEnabled) _connection.Trace($"Connection no longer usable. Alive {now - _connection.CreationTime} > {pooledConnectionLifetime}.");
return false;
}
// Validate that the connection hasn't received any stray data while in the pool.
if (poll && _connection.PollRead())
{
if (NetEventSource.IsEnabled) _connection.Trace($"Connection no longer usable. Unexpected data received.");
return false;
}
// The connection is usable.
return true;
}
public bool Equals(CachedConnection other) => ReferenceEquals(other._connection, _connection);
public override bool Equals(object obj) => obj is CachedConnection && Equals((CachedConnection)obj);
public override int GetHashCode() => _connection?.GetHashCode() ?? 0;
}
private sealed class TaskCompletionSourceWithCancellation<T> : TaskCompletionSource<T>
{
private CancellationToken _cancellationToken;
public TaskCompletionSourceWithCancellation() : base(TaskCreationOptions.RunContinuationsAsynchronously)
{
}
private void OnCancellation()
{
TrySetCanceled(_cancellationToken);
}
public async Task<T> WaitWithCancellationAsync(CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
using (cancellationToken.Register(s => ((TaskCompletionSourceWithCancellation<HttpConnection>)s).OnCancellation(), this))
{
return await Task.ConfigureAwait(false);
}
}
}
}
}
| |
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Orleans.Runtime
{
/// <summary>
/// Data class encapsulating the details of silo addresses.
/// </summary>
[Serializable, Immutable]
[JsonConverter(typeof(SiloAddressConverter))]
[DebuggerDisplay("SiloAddress {ToString()}")]
[SuppressReferenceTracking]
public sealed class SiloAddress : IEquatable<SiloAddress>, IComparable<SiloAddress>, IComparable
{
[NonSerialized]
private int hashCode = 0;
[NonSerialized]
private bool hashCodeSet = false;
[NonSerialized]
private List<uint> uniformHashCache;
[Id(0)]
public IPEndPoint Endpoint { get; private set; }
[Id(1)]
public int Generation { get; private set; }
[NonSerialized]
private byte[] utf8;
private const char SEPARATOR = '@';
private static readonly long epoch = new DateTime(2010, 1, 1).Ticks;
private static readonly Interner<Key, SiloAddress> siloAddressInterningCache = new Interner<Key, SiloAddress>(InternerConstants.SIZE_MEDIUM);
/// <summary>Special constant value to indicate an empty SiloAddress.</summary>
public static SiloAddress Zero { get; } = New(new IPEndPoint(0, 0), 0);
/// <summary>
/// Factory for creating new SiloAddresses with specified IP endpoint address and silo generation number.
/// </summary>
/// <param name="ep">IP endpoint address of the silo.</param>
/// <param name="gen">Generation number of the silo.</param>
/// <returns>SiloAddress object initialized with specified address and silo generation.</returns>
public static SiloAddress New(IPEndPoint ep, int gen)
{
return siloAddressInterningCache.FindOrCreate(new Key(ep, gen), k => new SiloAddress(k.Endpoint, k.Generation));
}
private SiloAddress(IPEndPoint endpoint, int gen)
{
// Normalize endpoints
if (endpoint.Address.IsIPv4MappedToIPv6)
{
endpoint = new IPEndPoint(endpoint.Address.MapToIPv4(), endpoint.Port);
}
Endpoint = endpoint;
Generation = gen;
}
public bool IsClient { get { return Generation < 0; } }
/// <summary> Allocate a new silo generation number. </summary>
/// <returns>A new silo generation number.</returns>
public static int AllocateNewGeneration()
{
long elapsed = (DateTime.UtcNow.Ticks - epoch) / TimeSpan.TicksPerSecond;
return unchecked((int)elapsed); // Unchecked to truncate any bits beyond the lower 32
}
/// <summary>
/// Return this SiloAddress in a standard string form, suitable for later use with the <c>FromParsableString</c> method.
/// </summary>
/// <returns>SiloAddress in a standard string format.</returns>
public string ToParsableString()
{
// This must be the "inverse" of FromParsableString, and must be the same across all silos in a deployment.
// Basically, this should never change unless the data content of SiloAddress changes
if (utf8 != null) return Encoding.UTF8.GetString(utf8);
return String.Format("{0}:{1}@{2}", Endpoint.Address, Endpoint.Port, Generation);
}
internal unsafe byte[] ToUtf8String()
{
if (utf8 is null)
{
var addr = Endpoint.Address.ToString();
var size = Encoding.UTF8.GetByteCount(addr);
// Allocate sufficient room for: address + ':' + port + '@' + generation
Span<byte> buf = stackalloc byte[size + 1 + 11 + 1 + 11];
fixed (char* src = addr)
fixed (byte* dst = buf)
{
size = Encoding.UTF8.GetBytes(src, addr.Length, dst, buf.Length);
}
buf[size++] = (byte)':';
var success = Utf8Formatter.TryFormat(Endpoint.Port, buf.Slice(size), out var len);
Debug.Assert(success);
Debug.Assert(len > 0);
Debug.Assert(len <= 11);
size += len;
buf[size++] = (byte)SEPARATOR;
success = Utf8Formatter.TryFormat(Generation, buf.Slice(size), out len);
Debug.Assert(success);
Debug.Assert(len > 0);
Debug.Assert(len <= 11);
size += len;
utf8 = buf.Slice(0, size).ToArray();
}
return utf8;
}
/// <summary>
/// Create a new SiloAddress object by parsing string in a standard form returned from <c>ToParsableString</c> method.
/// </summary>
/// <param name="addr">String containing the SiloAddress info to be parsed.</param>
/// <returns>New SiloAddress object created from the input data.</returns>
public static SiloAddress FromParsableString(string addr)
{
// This must be the "inverse" of ToParsableString, and must be the same across all silos in a deployment.
// Basically, this should never change unless the data content of SiloAddress changes
// First is the IPEndpoint; then '@'; then the generation
int atSign = addr.LastIndexOf(SEPARATOR);
if (atSign < 0)
{
throw new FormatException("Invalid string SiloAddress: " + addr);
}
// IPEndpoint is the host, then ':', then the port
int lastColon = addr.LastIndexOf(':', atSign - 1);
if (lastColon < 0) throw new FormatException("Invalid string SiloAddress: " + addr);
var hostString = addr.Substring(0, lastColon);
var host = IPAddress.Parse(hostString);
var portString = addr.Substring(lastColon + 1, atSign - lastColon - 1);
int port = int.Parse(portString, NumberStyles.None);
var gen = int.Parse(addr.Substring(atSign + 1), NumberStyles.None);
return New(new IPEndPoint(host, port), gen);
}
/// <summary>
/// Create a new SiloAddress object by parsing string in a standard form returned from <c>ToParsableString</c> method.
/// </summary>
/// <param name="addr">String containing the SiloAddress info to be parsed.</param>
/// <returns>New SiloAddress object created from the input data.</returns>
public static SiloAddress FromUtf8String(ReadOnlySpan<byte> addr)
{
// This must be the "inverse" of ToParsableString, and must be the same across all silos in a deployment.
// Basically, this should never change unless the data content of SiloAddress changes
// First is the IPEndpoint; then '@'; then the generation
var atSign = addr.LastIndexOf((byte)SEPARATOR);
if (atSign < 0) ThrowInvalidUtf8SiloAddress(addr);
// IPEndpoint is the host, then ':', then the port
var endpointSlice = addr.Slice(0, atSign);
int lastColon = endpointSlice.LastIndexOf((byte)':');
if (lastColon < 0) ThrowInvalidUtf8SiloAddress(addr);
var hostString = endpointSlice.Slice(0, lastColon).GetUtf8String();
if (!IPAddress.TryParse(hostString, out var host))
ThrowInvalidUtf8SiloAddress(addr);
var portSlice = endpointSlice.Slice(lastColon + 1);
if (!Utf8Parser.TryParse(portSlice, out int port, out var len) || len < portSlice.Length)
ThrowInvalidUtf8SiloAddress(addr);
var genSlice = addr.Slice(atSign + 1);
if (!Utf8Parser.TryParse(genSlice, out int generation, out len) || len < genSlice.Length)
ThrowInvalidUtf8SiloAddress(addr);
return New(new IPEndPoint(host, port), generation);
}
private static void ThrowInvalidUtf8SiloAddress(ReadOnlySpan<byte> addr)
=> throw new FormatException("Invalid string SiloAddress: " + addr.GetUtf8String());
[Immutable]
private readonly struct Key : IEquatable<Key>
{
public readonly IPEndPoint Endpoint;
public readonly int Generation;
public Key(IPEndPoint endpoint, int generation)
{
Endpoint = endpoint;
Generation = generation;
}
public override int GetHashCode() => Endpoint.GetHashCode() ^ Generation;
public bool Equals(Key other) => Generation == other.Generation && Endpoint.Address.Equals(other.Endpoint.Address) && Endpoint.Port == other.Endpoint.Port;
}
/// <summary> Object.ToString method override. </summary>
public override string ToString()
{
return string.Format(IsClient ? "C{0}:{1}" : "S{0}:{1}", Endpoint, Generation);
}
/// <summary>
/// Return a long string representation of this SiloAddress.
/// </summary>
/// <remarks>
/// Note: This string value is not comparable with the <c>FromParsableString</c> method -- use the <c>ToParsableString</c> method for that purpose.
/// </remarks>
/// <returns>String representation of this SiloAddress.</returns>
public string ToLongString()
{
return ToString();
}
/// <summary>
/// Return a long string representation of this SiloAddress, including it's consistent hash value.
/// </summary>
/// <remarks>
/// Note: This string value is not comparable with the <c>FromParsableString</c> method -- use the <c>ToParsableString</c> method for that purpose.
/// </remarks>
/// <returns>String representation of this SiloAddress.</returns>
public string ToStringWithHashCode()
{
return string.Format(IsClient ? "C{0}:{1}/x{2:X8}" : "S{0}:{1}/x{2:X8}", Endpoint, Generation, GetConsistentHashCode());
}
/// <summary> Object.Equals method override. </summary>
public override bool Equals(object obj) => Equals(obj as SiloAddress);
/// <summary> Object.GetHashCode method override. </summary>
public override int GetHashCode() => Endpoint.GetHashCode() ^ Generation;
/// <summary>Get a consistent hash value for this silo address.</summary>
/// <returns>Consistent hash value for this silo address.</returns>
public int GetConsistentHashCode()
{
if (hashCodeSet) return hashCode;
string siloAddressInfoToHash = Endpoint.ToString() + Generation.ToString(CultureInfo.InvariantCulture);
hashCode = CalculateIdHash(siloAddressInfoToHash);
hashCodeSet = true;
return hashCode;
}
// This is the same method as Utils.CalculateIdHash
private static int CalculateIdHash(string text)
{
SHA256 sha = SHA256.Create(); // This is one implementation of the abstract class SHA1.
int hash = 0;
try
{
byte[] data = Encoding.Unicode.GetBytes(text);
byte[] result = sha.ComputeHash(data);
for (int i = 0; i < result.Length; i += 4)
{
int tmp = (result[i] << 24) | (result[i + 1] << 16) | (result[i + 2] << 8) | (result[i + 3]);
hash = hash ^ tmp;
}
}
finally
{
sha.Dispose();
}
return hash;
}
public List<uint> GetUniformHashCodes(int numHashes)
{
if (uniformHashCache != null) return uniformHashCache;
uniformHashCache = GetUniformHashCodesImpl(numHashes);
return uniformHashCache;
}
private List<uint> GetUniformHashCodesImpl(int numHashes)
{
Span<byte> bytes = stackalloc byte[16 + sizeof(int) + sizeof(int) + sizeof(int)]; // ip + port + generation + extraBit
// Endpoint IP Address
var address = Endpoint.Address;
if (address.AddressFamily == AddressFamily.InterNetwork) // IPv4
{
#pragma warning disable CS0618 // Type or member is obsolete
BinaryPrimitives.WriteInt32LittleEndian(bytes.Slice(12), (int)address.Address);
#pragma warning restore CS0618
bytes.Slice(0, 12).Clear();
}
else // IPv6
{
address.GetAddressBytes().CopyTo(bytes);
}
var offset = 16;
// Port
BinaryPrimitives.WriteInt32LittleEndian(bytes.Slice(offset), Endpoint.Port);
offset += sizeof(int);
// Generation
BinaryPrimitives.WriteInt32LittleEndian(bytes.Slice(offset), Generation);
offset += sizeof(int);
var hashes = new List<uint>(numHashes);
for (int extraBit = 0; extraBit < numHashes; extraBit++)
{
BinaryPrimitives.WriteInt32LittleEndian(bytes.Slice(offset), extraBit);
hashes.Add(JenkinsHash.ComputeHash(bytes));
}
return hashes;
}
/// <summary>
/// Two silo addresses match if they are equal or if one generation or the other is 0
/// </summary>
/// <param name="other"> The other SiloAddress to compare this one with. </param>
/// <returns> Returns <c>true</c> if the two SiloAddresses are considered to match -- if they are equal or if one generation or the other is 0. </returns>
internal bool Matches(SiloAddress other)
{
return other != null && Endpoint.Address.Equals(other.Endpoint.Address) && (Endpoint.Port == other.Endpoint.Port) &&
((Generation == other.Generation) || (Generation == 0) || (other.Generation == 0));
}
/// <summary> IEquatable.Equals method override. </summary>
public bool Equals(SiloAddress other)
{
return other != null && Generation == other.Generation && Endpoint.Address.Equals(other.Endpoint.Address) && Endpoint.Port == other.Endpoint.Port;
}
internal bool IsSameLogicalSilo(SiloAddress other)
{
return other != null && this.Endpoint.Address.Equals(other.Endpoint.Address) && this.Endpoint.Port == other.Endpoint.Port;
}
public bool IsSuccessorOf(SiloAddress other)
{
return IsSameLogicalSilo(other) && this.Generation != 0 && other.Generation != 0 && this.Generation > other.Generation;
}
public bool IsPredecessorOf(SiloAddress other)
{
return IsSameLogicalSilo(other) && this.Generation != 0 && other.Generation != 0 && this.Generation < other.Generation;
}
// non-generic version of CompareTo is needed by some contexts. Just calls generic version.
public int CompareTo(object obj)
{
return CompareTo((SiloAddress)obj);
}
public int CompareTo(SiloAddress other)
{
if (other == null) return 1;
// Compare Generation first. It gives a cheap and fast way to compare, avoiding allocations
// and is also semantically meaningfull - older silos (with smaller Generation) will appear first in the comparison order.
// Only if Generations are the same, go on to compare Ports and IPAddress (which is more expansive to compare).
// Alternatively, we could compare ConsistentHashCode or UniformHashCode.
int comp = Generation.CompareTo(other.Generation);
if (comp != 0) return comp;
comp = Endpoint.Port.CompareTo(other.Endpoint.Port);
if (comp != 0) return comp;
return CompareIpAddresses(Endpoint.Address, other.Endpoint.Address);
}
// The comparions code is taken from: http://www.codeproject.com/Articles/26550/Extending-the-IPAddress-object-to-allow-relative-c
// Also note that this comparison does not handle semantic equivalence of IPv4 and IPv6 addresses.
// In particular, 127.0.0.1 and::1 are semanticaly the same, but not syntacticaly.
// For more information refer to: http://stackoverflow.com/questions/16618810/compare-ipv4-addresses-in-ipv6-notation
// and http://stackoverflow.com/questions/22187690/ip-address-class-getaddressbytes-method-putting-octets-in-odd-indices-of-the-byt
// and dual stack sockets, described at https://msdn.microsoft.com/en-us/library/system.net.ipaddress.maptoipv6(v=vs.110).aspx
private static int CompareIpAddresses(IPAddress one, IPAddress two)
{
var f1 = one.AddressFamily;
var f2 = two.AddressFamily;
if (f1 != f2)
return f1 < f2 ? -1 : 1;
if (f1 == AddressFamily.InterNetwork)
{
#pragma warning disable CS0618 // Type or member is obsolete
return one.Address.CompareTo(two.Address);
#pragma warning restore CS0618
}
byte[] b1 = one.GetAddressBytes();
byte[] b2 = two.GetAddressBytes();
for (int i = 0; i < b1.Length; i++)
{
if (b1[i] < b2[i])
{
return -1;
}
else if (b1[i] > b2[i])
{
return 1;
}
}
return 0;
}
}
public class SiloAddressConverter : JsonConverter<SiloAddress>
{
public override SiloAddress Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => SiloAddress.FromParsableString(reader.GetString());
public override void Write(Utf8JsonWriter writer, SiloAddress value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToParsableString());
}
}
| |
using System;
using System.Net;
using System.Threading.Tasks;
using AspNetCore_netcoreapp3._1_TestApp.Authentication;
using AspNetCore_netcoreapp3._1_TestApp.Endpoints;
using AspNetCore_netcoreapp3_1_TestApp.Middleware;
using AspNetCore_netcoreapp3_1_TestApp.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using tusdotnet;
using tusdotnet.Helpers;
using tusdotnet.Models;
using tusdotnet.Models.Concatenation;
using tusdotnet.Models.Configuration;
using tusdotnet.Models.Expiration;
using tusdotnet.Stores;
namespace AspNetCore_netcoreapp3._1_TestApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddSingleton(CreateTusConfiguration);
services.AddHostedService<ExpiredFilesCleanupService>();
services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use((context, next) =>
{
// Default limit was changed some time ago. Should work by setting MaxRequestBodySize to null using ConfigureKestrel but this does not seem to work for IISExpress.
// Source: https://github.com/aspnet/Announcements/issues/267
context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = null;
return next.Invoke();
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSimpleExceptionHandler();
app.UseAuthentication();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.WithExposedHeaders(CorsHelper.GetExposedHeaders()));
// httpContext parameter can be used to create a tus configuration based on current user, domain, host, port or whatever.
// In this case we just return the same configuration for everyone.
app.UseTus(httpContext => Task.FromResult(httpContext.RequestServices.GetService<DefaultTusConfiguration>()));
app.UseRouting();
// All GET requests to tusdotnet are forwarded so that you can handle file downloads.
// This is done because the file's metadata is domain specific and thus cannot be handled
// in a generic way by tusdotnet.
app.UseEndpoints(endpoints => endpoints.MapGet("/files/{fileId}", DownloadFileEndpoint.HandleRoute));
}
private DefaultTusConfiguration CreateTusConfiguration(IServiceProvider serviceProvider)
{
var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Startup>();
// Change the value of EnableOnAuthorize in appsettings.json to enable or disable
// the new authorization event.
var enableAuthorize = Configuration.GetValue<bool>("EnableOnAuthorize");
return new DefaultTusConfiguration
{
UrlPath = "/files",
Store = new TusDiskStore(@"C:\tusfiles\"),
MetadataParsingStrategy = MetadataParsingStrategy.AllowEmptyValues,
UsePipelinesIfAvailable = true,
Events = new Events
{
OnAuthorizeAsync = ctx =>
{
if (!enableAuthorize)
return Task.CompletedTask;
if (!ctx.HttpContext.User.Identity.IsAuthenticated)
{
ctx.HttpContext.Response.Headers.Add("WWW-Authenticate", new StringValues("Basic realm=tusdotnet-test-netcoreapp2.2"));
ctx.FailRequest(HttpStatusCode.Unauthorized);
return Task.CompletedTask;
}
if (ctx.HttpContext.User.Identity.Name != "test")
{
ctx.FailRequest(HttpStatusCode.Forbidden, "'test' is the only allowed user");
return Task.CompletedTask;
}
// Do other verification on the user; claims, roles, etc.
// Verify different things depending on the intent of the request.
// E.g.:
// Does the file about to be written belong to this user?
// Is the current user allowed to create new files or have they reached their quota?
// etc etc
switch (ctx.Intent)
{
case IntentType.CreateFile:
break;
case IntentType.ConcatenateFiles:
break;
case IntentType.WriteFile:
break;
case IntentType.DeleteFile:
break;
case IntentType.GetFileInfo:
break;
case IntentType.GetOptions:
break;
default:
break;
}
return Task.CompletedTask;
},
OnBeforeCreateAsync = ctx =>
{
// Partial files are not complete so we do not need to validate
// the metadata in our example.
if (ctx.FileConcatenation is FileConcatPartial)
{
return Task.CompletedTask;
}
if (!ctx.Metadata.ContainsKey("name") || ctx.Metadata["name"].HasEmptyValue)
{
ctx.FailRequest("name metadata must be specified. ");
}
if (!ctx.Metadata.ContainsKey("contentType") || ctx.Metadata["contentType"].HasEmptyValue)
{
ctx.FailRequest("contentType metadata must be specified. ");
}
return Task.CompletedTask;
},
OnCreateCompleteAsync = ctx =>
{
logger.LogInformation($"Created file {ctx.FileId} using {ctx.Store.GetType().FullName}");
return Task.CompletedTask;
},
OnBeforeDeleteAsync = ctx =>
{
// Can the file be deleted? If not call ctx.FailRequest(<message>);
return Task.CompletedTask;
},
OnDeleteCompleteAsync = ctx =>
{
logger.LogInformation($"Deleted file {ctx.FileId} using {ctx.Store.GetType().FullName}");
return Task.CompletedTask;
},
OnFileCompleteAsync = ctx =>
{
logger.LogInformation($"Upload of {ctx.FileId} completed using {ctx.Store.GetType().FullName}");
// If the store implements ITusReadableStore one could access the completed file here.
// The default TusDiskStore implements this interface:
//var file = await ctx.GetFileAsync();
return Task.CompletedTask;
}
},
// Set an expiration time where incomplete files can no longer be updated.
// This value can either be absolute or sliding.
// Absolute expiration will be saved per file on create
// Sliding expiration will be saved per file on create and updated on each patch/update.
Expiration = new AbsoluteExpiration(TimeSpan.FromMinutes(5))
};
}
}
}
| |
//! \file ImageXTX.cs
//! \date Mon Feb 29 19:14:55 2016
//! \brief Xbox 360 texture.
//
// Copyright (C) 2016 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using GameRes.Utility;
namespace GameRes.Formats.Cri
{
internal class XtxMetaData : ImageMetaData
{
public byte Format;
public uint DataOffset;
public int AlignedWidth;
public int AlignedHeight;
}
[Export(typeof(ImageFormat))]
public class XtxFormat : ImageFormat
{
public override string Tag { get { return "XTX"; } }
public override string Description { get { return "Xbox 360 texture format"; } }
public override uint Signature { get { return 0x00787478; } } // 'xtx'
public XtxFormat ()
{
Signatures = new uint[] { 0x00787478, 0 };
}
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x20).ToArray();
if (!Binary.AsciiEqual (header, 0, "xtx\0"))
{
var header_size = LittleEndian.ToUInt32 (header, 0);
if (header_size >= 0x1000) // XXX use some arbitrary "large" value to avoid call to Stream.Length
return null;
stream.Position = header_size;
if (0x20 != stream.Read (header, 0, 0x20))
return null;
if (!Binary.AsciiEqual (header, 0, "xtx\0"))
return null;
}
if (header[4] > 2)
return null;
int aligned_width = BigEndian.ToInt32 (header, 8);
int aligned_height = BigEndian.ToInt32 (header, 0xC);
if (aligned_width <= 0 || aligned_height <= 0)
return null;
return new XtxMetaData
{
Width = BigEndian.ToUInt32 (header, 0x10),
Height = BigEndian.ToUInt32 (header, 0x14),
OffsetX = BigEndian.ToInt32 (header, 0x18),
OffsetY = BigEndian.ToInt32 (header, 0x1C),
BPP = 32,
Format = header[4],
AlignedWidth = aligned_width,
AlignedHeight = aligned_height,
DataOffset = (uint)stream.Position,
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var reader = new XtxReader (stream.AsStream, (XtxMetaData)info);
var pixels = reader.Unpack();
return ImageData.Create (info, reader.Format, null, pixels);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("XtxFormat.Write not implemented");
}
}
internal sealed class XtxReader
{
Stream m_input;
int m_width;
int m_height;
XtxMetaData m_info;
public PixelFormat Format { get; private set; }
public XtxReader (Stream input, XtxMetaData info)
{
m_input = input;
m_info = info;
m_width = (int)m_info.Width;
m_height = (int)m_info.Height;
}
public byte[] Unpack ()
{
m_input.Position = m_info.DataOffset;
Format = PixelFormats.Bgra32;
if (0 == m_info.Format)
return ReadTex0();
else if (1 == m_info.Format)
return ReadTex1();
else
return ReadTex2();
}
byte[] ReadTex0 ()
{
int output_stride = m_width * 4;
var output = new byte[output_stride*m_height];
int total = m_info.AlignedWidth * m_info.AlignedHeight;
var texture = new byte[total*4];
m_input.Read (texture, 0, texture.Length);
int src = 0;
for (int i = 0; i < total; ++i)
{
int y = GetY (i, m_info.AlignedWidth, 4);
int x = GetX (i, m_info.AlignedWidth, 4);
if (y < m_height && x < m_width)
{
int dst = output_stride * y + x * 4;
output[dst] = texture[src+3];
output[dst+1] = texture[src+2];
output[dst+2] = texture[src+1];
output[dst+3] = texture[src];
}
src += 4;
}
return output;
}
byte[] ReadTex1 ()
{
int total = m_info.AlignedWidth * m_info.AlignedHeight;
var texture = new byte[total*2];
var packed = new byte[total*2];
m_input.Read (texture, 0, texture.Length);
int stride = m_info.AlignedWidth;
int src = 0;
for (int i = 0; i < total; ++i)
{
int y = GetY (i, m_info.AlignedWidth, 2);
int x = GetX (i, m_info.AlignedWidth, 2);
int dst = (x + y * stride) * 2;
packed[dst] = texture[src+1];
packed[dst+1] = texture[src];
src += 2;
}
Format = PixelFormats.Bgr565;
throw new NotImplementedException ("XTX textures format 1 not implemented");
// return packed;
}
byte[] ReadTex2 ()
{
int tex_width = m_info.AlignedWidth >> 2;
int total = tex_width * (m_info.AlignedHeight >> 2);
var texture = new byte[m_info.AlignedWidth * m_info.AlignedHeight];
var packed = new byte[m_info.AlignedWidth * m_info.AlignedHeight];
m_input.Read (texture, 0, texture.Length);
int src = 0;
for (int i = 0; i < total; ++i)
{
int y = GetY (i, tex_width, 0x10);
int x = GetX (i, tex_width, 0x10);
int dst = (x + y * tex_width) * 16;
for (int j = 0; j < 8; ++j)
{
packed[dst++] = texture[src+1];
packed[dst++] = texture[src];
src += 2;
}
}
var dxt = new DirectDraw.DxtDecoder (packed, m_info);
return dxt.UnpackDXT5();
}
static int GetY (int i, int width, byte level)
{
int v1 = (level >> 2) + (level >> 1 >> (level >> 2));
int v2 = i << v1;
int v3 = (v2 & 0x3F) + ((v2 >> 2) & 0x1C0) + ((v2 >> 3) & 0x1FFFFE00);
return ((v3 >> 4) & 1)
+ ((((v3 & ((level << 6) - 1) & -0x20)
+ ((((v2 & 0x3F) + ((v2 >> 2) & 0xC0)) & 0xF) << 1)) >> (v1 + 3)) & -2)
+ ((((v2 >> 10) & 2) + ((v3 >> (v1 + 6)) & 1)
+ (((v3 >> (v1 + 7)) / ((width + 31) >> 5)) << 2)) << 3);
}
static int GetX (int i, int width, byte level)
{
int v1 = (level >> 2) + (level >> 1 >> (level >> 2));
int v2 = i << v1;
int v3 = (v2 & 0x3F) + ((v2 >> 2) & 0x1C0) + ((v2 >> 3) & 0x1FFFFE00);
return ((((level << 3) - 1) & ((v3 >> 1) ^ (v3 ^ (v3 >> 1)) & 0xF)) >> v1)
+ ((((((v2 >> 6) & 0xFF) + ((v3 >> (v1 + 5)) & 0xFE)) & 3)
+ (((v3 >> (v1 + 7)) % (((width + 31)) >> 5)) << 2)) << 3);
}
}
}
| |
//BSD, 2014-present, WinterDev
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// classes dda_line_interpolator, dda2_line_interpolator
//
//----------------------------------------------------------------------------
using System;
namespace PixelFarm.CpuBlit.FragmentProcessing
{
//===================================================dda_line_interpolator
struct LineInterpolatorDDA
{
int _y;
int _dy;
readonly int _inc;
readonly int _fractionShift;
public LineInterpolatorDDA(int y1, int y2, int count, int fractionShift)
{
_fractionShift = fractionShift;
_y = (y1);
_inc = (((y2 - y1) << _fractionShift) / (int)(count));
_dy = (0);
}
public void Next() => _dy += _inc;//public void operator ++ ()
public void Prev() => _dy -= _inc;//public void operator -- ()
public void Next(int n) => _dy += _inc * n;//public void operator += (int n)
public void Prev(int n) => _dy -= _inc * n;//public void operator -= (int n)
//--------------------------------------------------------------------
public int y() => _y + (_dy >> (_fractionShift)); // - m_YShift)); }
//
public int dy() => _dy;
}
//=================================================dda2_line_interpolator
class LineInterpolatorDDA2
{
//----------------------
//this need to be class ***?
//----------------------
int _cnt;
int _lft;
int _rem;
int _mod;
int _y;
//-------------------------------------------- Forward-adjusted line
public LineInterpolatorDDA2()
{
}
public LineInterpolatorDDA2(int y1, int y2, int count) => Set(y1, y2, count);
public void Set(int y1, int y2, int count)
{
//dbugIdN = 0;
_cnt = (count <= 0 ? 1 : count);
_lft = ((y2 - y1) / _cnt);
_rem = ((y2 - y1) % _cnt);
_mod = (_rem);
_y = (y1);
if (_mod <= 0)
{
_mod += count;
_rem += count;
_lft--;
}
_mod -= count;
}
public void Set(int y, int count)
{
//dbugIdN = 0;
_cnt = (count <= 0 ? 1 : count);
_lft = ((y) / _cnt);
_rem = ((y) % _cnt);
_mod = (_rem);
_y = (0);
if (_mod <= 0)
{
_mod += count;
_rem += count;
_lft--;
}
}
#if DEBUG
//static int dbugIdN;
#endif
//public void operator ++()
public void Next()
{
//dbugIdN++;
_mod += _rem;
_y += _lft;
if (_mod > 0)
{
_mod -= _cnt;
_y++;
}
}
//--------------------------------------------------------------------
//public void operator--()
public void Prev()
{
if (_mod <= _rem)
{
_mod += _cnt;
_y--;
}
_mod -= _rem;
_y -= _lft;
}
//--------------------------------------------------------------------
public void adjust_forward() => _mod -= _cnt;
public void adjust_backward() => _mod += _cnt;
//
public int Y => _y;
//
}
struct LineInterpolatorDDA2S
{
readonly int _cnt;
readonly int _lft;
readonly int _rem;
int _mod;
int _y;
//-------------------------------------------- Forward-adjusted line
public LineInterpolatorDDA2S(int y1, int y2, int count)
{
_cnt = (count <= 0 ? 1 : count);
_lft = ((y2 - y1) / _cnt);
_rem = ((y2 - y1) % _cnt);
_mod = (_rem);
_y = (y1);
if (_mod <= 0)
{
_mod += count;
_rem += count;
_lft--;
}
_mod -= count;
}
//public void operator ++()
public void Next()
{
_mod += _rem;
_y += _lft;
if (_mod > 0)
{
_mod -= _cnt;
_y++;
}
}
//
public int Y => _y;
//
}
//---------------------------------------------line_bresenham_interpolator
sealed class LineInterpolatorBresenham
{
int _x1_lr;
int _y1_lr;
int _x2_lr;
int _y2_lr;
bool _ver;
int _len;
int _inc;
LineInterpolatorDDA2 _interpolator;
//
const int SUBPIXEL_SHIFT = 8;
const int SUBPIXEL_SCALE = 1 << SUBPIXEL_SHIFT;
const int SUBPIXEL_MASK = SUBPIXEL_SCALE - 1;
//
//--------------------------------------------------------------------
public static int line_lr(int v) => v >> (int)SUBPIXEL_SHIFT;
//--------------------------------------------------------------------
public LineInterpolatorBresenham(int x1, int y1, int x2, int y2)
{
_x1_lr = (line_lr(x1));
_y1_lr = (line_lr(y1));
_x2_lr = (line_lr(x2));
_y2_lr = (line_lr(y2));
_ver = (Math.Abs(_x2_lr - _x1_lr) < Math.Abs(_y2_lr - _y1_lr));
if (_ver)
{
_len = (int)Math.Abs(_y2_lr - _y1_lr);
}
else
{
_len = (int)Math.Abs(_x2_lr - _x1_lr);
}
_inc = (_ver ? ((y2 > y1) ? 1 : -1) : ((x2 > x1) ? 1 : -1));
_interpolator = new LineInterpolatorDDA2(_ver ? x1 : y1,
_ver ? x2 : y2,
_len);
}
//--------------------------------------------------------------------
public bool is_ver() => _ver;
public int len() => _len;
public int inc() => _inc;
//--------------------------------------------------------------------
public void hstep()
{
_interpolator.Next();
_x1_lr += _inc;
}
//--------------------------------------------------------------------
public void vstep()
{
_interpolator.Next();
_y1_lr += _inc;
}
//--------------------------------------------------------------------
public int x1() => _x1_lr;
public int y1() => _y1_lr;
public int x2() => line_lr(_interpolator.Y);
public int y2() => line_lr(_interpolator.Y);
public int x2_hr() => _interpolator.Y;
public int y2_hr() => _interpolator.Y;
}
}
| |
using System;
using Moscrif.IDE.Iface.Entities;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;
namespace Moscrif.IDE.Iface
{
public class KeyBindings
{
[XmlIgnore]
public string FilePath
{
get;
set;
}
public enum TypeKeyBinding {
Nothing,
VisualStudio,
XCode,
Eclipse,
VisualC
}
[XmlAttribute("typeBinding")]
public TypeKeyBinding TypeBinding;
[XmlArrayAttribute("sections")]
[XmlArrayItem("section")]
public List<KeyBindingSection> KeyBindingSection;
public KeyBindings()
{
}
public string FindAccelerator(string action){
if(KeyBindingSection == null) return null;
foreach(KeyBindingSection kbs in KeyBindingSection){
KeyBinding kb = kbs.KeyBinding.Find(x=> x.Action == action);
if(kb != null){
return KeyToAccel(kb.Key);
}
}
return null;
}
public string KeyToAccel(string key){
/*while (i < accel.Length) {
for (j = i + 1; j < accel.Length; j++) {
if (accel[j] == '+' || accel[j] == '|')
break;
}
str = accel.Substring (i, j - i);
if ((mod = ModifierMask (str)) == Gdk.ModifierType.None) {
if (str == "Space")
k = (uint) Gdk.Key.space;
else if (str.Length > 1)
k = Gdk.Keyval.FromName (str);
else
k = (uint) str[0];
break;
}
mask |= mod;
i = j + 1;
}*/
key = key.ToUpper();
key=key.Replace("<",Gdk.Key.less.ToString());
key=key.Replace(">",Gdk.Key.equal.ToString());
key=key.Replace("CONTROL","<control>");
if(MainClass.Platform.IsMac){
key=key.Replace("ALT","<alt>");//Gdk.Key.Alt_L.ToString());//Gdk.Key.Meta_L.ToString());//"<alt>");
} else {
key=key.Replace("ALT","<alt>");//Gdk.Key.Alt_L.ToString());//"<alt>");
}
key=key.Replace("SHIFT","<shift>");
key=key.Replace("COMMAND","<meta>");
key=key.Replace("SUPER","<super>");
key=key.Replace("SPACE",Gdk.Key.space.ToString());
key=key.Replace("RETURN",Gdk.Key.Return.ToString());
key=key.Replace("TAB",Gdk.Key.Tab.ToString());
key=key.Replace("HOME",Gdk.Key.Home.ToString());
key=key.Replace("END",Gdk.Key.End.ToString());
key=key.Replace(",",Gdk.Key.comma.ToString());
key=key.Replace(".",Gdk.Key.period.ToString());
key=key.Replace(";",Gdk.Key.semicolon.ToString());
key=key.Replace("`",Gdk.Key.grave.ToString());
key=key.Replace("/",Gdk.Key.slash.ToString());
key=key.Replace("UP",Gdk.Key.Up.ToString());
key=key.Replace("DOWN",Gdk.Key.Down.ToString());
key=key.Replace("LEFT",Gdk.Key.Left.ToString());
key=key.Replace("RIGHT",Gdk.Key.Right.ToString());
key=key.Replace("+","");
//Console.WriteLine("key->{0}",key);
return key;
}
public void ConnectAccelerator(Gtk.Action action, string keyBind, Gtk.AccelGroup ag)
{
string path = "<Actions>/MainWindow/" + action.Name;
Gdk.ModifierType mods;
uint key;
/*Console.WriteLine(action.AccelPath);
if(action.AccelPath == "<Actions>/MainWindow/idepreferences"){
Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
}*/
Gtk.Accelerator.Parse(keyBind,out key, out mods);
/*
Console.WriteLine("keyBind->{0}",keyBind);
Console.WriteLine("key->{0}",key);
Console.WriteLine("mods->{0}",mods);
Console.WriteLine("action->{0}",action.Name);
*/
if((keyBind.Contains("<alt>") && MainClass.Platform.IsMac)){
//mods |= Gdk.ModifierType.Mod2Mask;
mods ^= Gdk.ModifierType.Mod1Mask;
mods |= Gdk.ModifierType.Mod5Mask;
//mods |= Gdk.ModifierType.Mod5Mask;
}
//Console.WriteLine("mods 2->{0}",mods);
Gtk.AccelMap.ChangeEntry(path, key, mods,true);
action.AccelGroup = ag;
action.AccelPath = path;
//Console.WriteLine("action->{0}",action.AccelPath);
//Console.WriteLine("action->{0}",action.AccelGroup);
}
public KeyBindings(string filePath)
{
FilePath = filePath;
}
public void SaveKeyBindings()
{
using (FileStream fs = new FileStream(FilePath, FileMode.Create)) {
XmlSerializer serializer = new XmlSerializer(typeof(KeyBindings));
serializer.Serialize(fs, this);
}
}
static public void SaveKeyBindings(KeyBindings kb){
using (FileStream fs = new FileStream(kb.FilePath, FileMode.Create)) {
XmlSerializer serializer = new XmlSerializer(typeof(KeyBindings));
serializer.Serialize(fs, kb);
}
}
static public void CreateKeyBindingsJava(string filePath){
string keyBindFileOld;
using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream ("keybinding.java"))
using (var sr = new StreamReader (stream))
keyBindFileOld = sr.ReadToEnd ();
try {
if(File.Exists(filePath)){
File.Delete(filePath);
}
using (StreamWriter file = new StreamWriter(filePath)) {
file.Write (keyBindFileOld);
file.Close();
file.Dispose();
}
//return s;
} catch (Exception ex) {
Tool.Logger.Error("Cannot Create keybinding"+ex.Message);
}
}
static public void CreateKeyBindingsVisualC(string filePath){
string keyBindFileOld;
using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream ("keybinding.visualC"))
using (var sr = new StreamReader (stream))
keyBindFileOld = sr.ReadToEnd ();
try {
if(File.Exists(filePath)){
File.Delete(filePath);
}
using (StreamWriter file = new StreamWriter(filePath)) {
file.Write (keyBindFileOld);
file.Close();
file.Dispose();
}
//return s;
} catch (Exception ex) {
Tool.Logger.Error("Cannot Create keybinding"+ex.Message);
}
}
static public void CreateKeyBindingsMac(string filePath){
string keyBindFileOld;
using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream ("keybinding.mac"))
using (var sr = new StreamReader (stream))
keyBindFileOld = sr.ReadToEnd ();
try {
if(File.Exists(filePath)){
File.Delete(filePath);
}
using (StreamWriter file = new StreamWriter(filePath)) {
file.Write (keyBindFileOld);
file.Close();
file.Dispose();
}
//return s;
} catch (Exception ex) {
Tool.Logger.Error("Cannot Create keybinding"+ex.Message);
}
}
static public void CreateKeyBindingsWin(string filePath){
string keyBindFileOld;
using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream ("keybinding.win"))
using (var sr = new StreamReader (stream))
keyBindFileOld = sr.ReadToEnd ();
try {
if(File.Exists(filePath)){
File.Delete(filePath);
}
using (StreamWriter file = new StreamWriter(filePath)) {
file.Write (keyBindFileOld);
file.Close();
file.Dispose();
}
//return s;
} catch (Exception ex) {
Tool.Logger.Error("Cannot Create keybinding"+ex.Message);
}
}
static public KeyBindings OpenKeyBindings(string filePath)
{
if (System.IO.File.Exists(filePath)) {
try {
using (FileStream fs = File.OpenRead(filePath)) {
XmlSerializer serializer = new XmlSerializer(typeof(KeyBindings));
KeyBindings s = (KeyBindings)serializer.Deserialize(fs);
s.FilePath= filePath;
return s;
}
} catch (Exception ex) {
throw ex;
/*MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, \"Error\", \"Settings file is corrupted!\", Gtk.MessageType.Error);
ms.ShowDialog();
return new Settings();*/
}
} else {
KeyBindings kb= new KeyBindings(filePath);
kb.KeyBindingSection = new List<KeyBindingSection>();
kb.KeyBindingSection.Add(new KeyBindingSection("section_name"));
kb.KeyBindingSection[0].KeyBinding.Add(new KeyBinding("name","description","action","key"));
//kb.KeyBinding
return kb;
/*MessageDialogs ms = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, "Error", "Settings file does not exist!", Gtk.MessageType.Error);
ms.ShowDialog();
return new Settings();*/
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Settings.Configuration.Assemblies;
namespace Serilog.Settings.Configuration
{
class ConfigurationReader : IConfigurationReader
{
const string LevelSwitchNameRegex = @"^\${0,1}[A-Za-z]+[A-Za-z0-9]*$";
readonly IConfigurationSection _section;
readonly IReadOnlyCollection<Assembly> _configurationAssemblies;
readonly ResolutionContext _resolutionContext;
public ConfigurationReader(IConfigurationSection configSection, AssemblyFinder assemblyFinder, IConfiguration configuration = null)
{
_section = configSection ?? throw new ArgumentNullException(nameof(configSection));
_configurationAssemblies = LoadConfigurationAssemblies(_section, assemblyFinder);
_resolutionContext = new ResolutionContext(configuration);
}
// Used internally for processing nested configuration sections -- see GetMethodCalls below.
internal ConfigurationReader(IConfigurationSection configSection, IReadOnlyCollection<Assembly> configurationAssemblies, ResolutionContext resolutionContext)
{
_section = configSection ?? throw new ArgumentNullException(nameof(configSection));
_configurationAssemblies = configurationAssemblies ?? throw new ArgumentNullException(nameof(configurationAssemblies));
_resolutionContext = resolutionContext ?? throw new ArgumentNullException(nameof(resolutionContext));
}
public void Configure(LoggerConfiguration loggerConfiguration)
{
ProcessLevelSwitchDeclarations();
ProcessFilterSwitchDeclarations();
ApplyMinimumLevel(loggerConfiguration);
ApplyEnrichment(loggerConfiguration);
ApplyFilters(loggerConfiguration);
ApplyDestructuring(loggerConfiguration);
ApplySinks(loggerConfiguration);
ApplyAuditSinks(loggerConfiguration);
}
void ProcessFilterSwitchDeclarations()
{
var filterSwitchesDirective = _section.GetSection("FilterSwitches");
foreach (var filterSwitchDeclaration in filterSwitchesDirective.GetChildren())
{
var filterSwitch = LoggingFilterSwitchProxy.Create();
if (filterSwitch == null)
{
SelfLog.WriteLine($"FilterSwitches section found, but neither Serilog.Expressions nor Serilog.Filters.Expressions is referenced.");
break;
}
var switchName = filterSwitchDeclaration.Key;
// switchName must be something like $switch to avoid ambiguities
if (!IsValidSwitchName(switchName))
{
throw new FormatException($"\"{switchName}\" is not a valid name for a Filter Switch declaration. The first character of the name must be a letter or '$' sign, like \"FilterSwitches\" : {{\"$switchName\" : \"{{FilterExpression}}\"}}");
}
SetFilterSwitch(throwOnError: true);
SubscribeToFilterExpressionChanges();
_resolutionContext.AddFilterSwitch(switchName, filterSwitch);
void SubscribeToFilterExpressionChanges()
{
ChangeToken.OnChange(filterSwitchDeclaration.GetReloadToken, () => SetFilterSwitch(throwOnError: false));
}
void SetFilterSwitch(bool throwOnError)
{
var filterExpr = filterSwitchDeclaration.Value;
if (string.IsNullOrWhiteSpace(filterExpr))
{
filterSwitch.Expression = null;
return;
}
try
{
filterSwitch.Expression = filterExpr;
}
catch (Exception e)
{
var errMsg = $"The expression '{filterExpr}' is invalid filter expression: {e.Message}.";
if (throwOnError)
{
throw new InvalidOperationException(errMsg, e);
}
SelfLog.WriteLine(errMsg);
}
}
}
}
void ProcessLevelSwitchDeclarations()
{
var levelSwitchesDirective = _section.GetSection("LevelSwitches");
foreach (var levelSwitchDeclaration in levelSwitchesDirective.GetChildren())
{
var switchName = levelSwitchDeclaration.Key;
var switchInitialLevel = levelSwitchDeclaration.Value;
// switchName must be something like $switch to avoid ambiguities
if (!IsValidSwitchName(switchName))
{
throw new FormatException($"\"{switchName}\" is not a valid name for a Level Switch declaration. The first character of the name must be a letter or '$' sign, like \"LevelSwitches\" : {{\"$switchName\" : \"InitialLevel\"}}");
}
LoggingLevelSwitch newSwitch;
if (string.IsNullOrEmpty(switchInitialLevel))
{
newSwitch = new LoggingLevelSwitch();
}
else
{
var initialLevel = ParseLogEventLevel(switchInitialLevel);
newSwitch = new LoggingLevelSwitch(initialLevel);
}
SubscribeToLoggingLevelChanges(levelSwitchDeclaration, newSwitch);
// make them available later on when resolving argument values
_resolutionContext.AddLevelSwitch(switchName, newSwitch);
}
}
void ApplyMinimumLevel(LoggerConfiguration loggerConfiguration)
{
var minimumLevelDirective = _section.GetSection("MinimumLevel");
var defaultMinLevelDirective = minimumLevelDirective.Value != null ? minimumLevelDirective : minimumLevelDirective.GetSection("Default");
if (defaultMinLevelDirective.Value != null)
{
ApplyMinimumLevel(defaultMinLevelDirective, (configuration, levelSwitch) => configuration.ControlledBy(levelSwitch));
}
var minLevelControlledByDirective = minimumLevelDirective.GetSection("ControlledBy");
if (minLevelControlledByDirective.Value != null)
{
var globalMinimumLevelSwitch = _resolutionContext.LookUpLevelSwitchByName(minLevelControlledByDirective.Value);
// not calling ApplyMinimumLevel local function because here we have a reference to a LogLevelSwitch already
loggerConfiguration.MinimumLevel.ControlledBy(globalMinimumLevelSwitch);
}
foreach (var overrideDirective in minimumLevelDirective.GetSection("Override").GetChildren())
{
var overridePrefix = overrideDirective.Key;
var overridenLevelOrSwitch = overrideDirective.Value;
if (Enum.TryParse(overridenLevelOrSwitch, out LogEventLevel _))
{
ApplyMinimumLevel(overrideDirective, (configuration, levelSwitch) => configuration.Override(overridePrefix, levelSwitch));
}
else
{
var overrideSwitch = _resolutionContext.LookUpLevelSwitchByName(overridenLevelOrSwitch);
// not calling ApplyMinimumLevel local function because here we have a reference to a LogLevelSwitch already
loggerConfiguration.MinimumLevel.Override(overridePrefix, overrideSwitch);
}
}
void ApplyMinimumLevel(IConfigurationSection directive, Action<LoggerMinimumLevelConfiguration, LoggingLevelSwitch> applyConfigAction)
{
var minimumLevel = ParseLogEventLevel(directive.Value);
var levelSwitch = new LoggingLevelSwitch(minimumLevel);
applyConfigAction(loggerConfiguration.MinimumLevel, levelSwitch);
SubscribeToLoggingLevelChanges(directive, levelSwitch);
}
}
void SubscribeToLoggingLevelChanges(IConfigurationSection levelSection, LoggingLevelSwitch levelSwitch)
{
ChangeToken.OnChange(
levelSection.GetReloadToken,
() =>
{
if (Enum.TryParse(levelSection.Value, out LogEventLevel minimumLevel))
levelSwitch.MinimumLevel = minimumLevel;
else
SelfLog.WriteLine($"The value {levelSection.Value} is not a valid Serilog level.");
});
}
void ApplyFilters(LoggerConfiguration loggerConfiguration)
{
var filterDirective = _section.GetSection("Filter");
if (filterDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(filterDirective);
CallConfigurationMethods(methodCalls, FindFilterConfigurationMethods(_configurationAssemblies), loggerConfiguration.Filter);
}
}
void ApplyDestructuring(LoggerConfiguration loggerConfiguration)
{
var destructureDirective = _section.GetSection("Destructure");
if (destructureDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(destructureDirective);
CallConfigurationMethods(methodCalls, FindDestructureConfigurationMethods(_configurationAssemblies), loggerConfiguration.Destructure);
}
}
void ApplySinks(LoggerConfiguration loggerConfiguration)
{
var writeToDirective = _section.GetSection("WriteTo");
if (writeToDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(writeToDirective);
CallConfigurationMethods(methodCalls, FindSinkConfigurationMethods(_configurationAssemblies), loggerConfiguration.WriteTo);
}
}
void ApplyAuditSinks(LoggerConfiguration loggerConfiguration)
{
var auditToDirective = _section.GetSection("AuditTo");
if (auditToDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(auditToDirective);
CallConfigurationMethods(methodCalls, FindAuditSinkConfigurationMethods(_configurationAssemblies), loggerConfiguration.AuditTo);
}
}
void IConfigurationReader.ApplySinks(LoggerSinkConfiguration loggerSinkConfiguration)
{
var methodCalls = GetMethodCalls(_section);
CallConfigurationMethods(methodCalls, FindSinkConfigurationMethods(_configurationAssemblies), loggerSinkConfiguration);
}
void IConfigurationReader.ApplyEnrichment(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration)
{
var methodCalls = GetMethodCalls(_section);
CallConfigurationMethods(methodCalls, FindEventEnricherConfigurationMethods(_configurationAssemblies), loggerEnrichmentConfiguration);
}
void ApplyEnrichment(LoggerConfiguration loggerConfiguration)
{
var enrichDirective = _section.GetSection("Enrich");
if (enrichDirective.GetChildren().Any())
{
var methodCalls = GetMethodCalls(enrichDirective);
CallConfigurationMethods(methodCalls, FindEventEnricherConfigurationMethods(_configurationAssemblies), loggerConfiguration.Enrich);
}
var propertiesDirective = _section.GetSection("Properties");
if (propertiesDirective.GetChildren().Any())
{
foreach (var enrichProperyDirective in propertiesDirective.GetChildren())
{
loggerConfiguration.Enrich.WithProperty(enrichProperyDirective.Key, enrichProperyDirective.Value);
}
}
}
internal ILookup<string, Dictionary<string, IConfigurationArgumentValue>> GetMethodCalls(IConfigurationSection directive)
{
var children = directive.GetChildren().ToList();
var result =
(from child in children
where child.Value != null // Plain string
select new { Name = child.Value, Args = new Dictionary<string, IConfigurationArgumentValue>() })
.Concat(
(from child in children
where child.Value == null
let name = GetSectionName(child)
let callArgs = (from argument in child.GetSection("Args").GetChildren()
select new
{
Name = argument.Key,
Value = GetArgumentValue(argument, _configurationAssemblies)
}).ToDictionary(p => p.Name, p => p.Value)
select new { Name = name, Args = callArgs }))
.ToLookup(p => p.Name, p => p.Args);
return result;
static string GetSectionName(IConfigurationSection s)
{
var name = s.GetSection("Name");
if (name.Value == null)
throw new InvalidOperationException($"The configuration value in {name.Path} has no 'Name' element.");
return name.Value;
}
}
internal static IConfigurationArgumentValue GetArgumentValue(IConfigurationSection argumentSection, IReadOnlyCollection<Assembly> configurationAssemblies)
{
IConfigurationArgumentValue argumentValue;
// Reject configurations where an element has both scalar and complex
// values as a result of reading multiple configuration sources.
if (argumentSection.Value != null && argumentSection.GetChildren().Any())
throw new InvalidOperationException(
$"The value for the argument '{argumentSection.Path}' is assigned different value " +
"types in more than one configuration source. Ensure all configurations consistently " +
"use either a scalar (int, string, boolean) or a complex (array, section, list, " +
"POCO, etc.) type for this argument value.");
if (argumentSection.Value != null)
{
argumentValue = new StringArgumentValue(argumentSection.Value);
}
else
{
argumentValue = new ObjectArgumentValue(argumentSection, configurationAssemblies);
}
return argumentValue;
}
static IReadOnlyCollection<Assembly> LoadConfigurationAssemblies(IConfigurationSection section, AssemblyFinder assemblyFinder)
{
var serilogAssembly = typeof(ILogger).Assembly;
var assemblies = new Dictionary<string, Assembly> { [serilogAssembly.FullName] = serilogAssembly };
var usingSection = section.GetSection("Using");
if (usingSection.GetChildren().Any())
{
foreach (var simpleName in usingSection.GetChildren().Select(c => c.Value))
{
if (string.IsNullOrWhiteSpace(simpleName))
throw new InvalidOperationException(
"A zero-length or whitespace assembly name was supplied to a Serilog.Using configuration statement.");
var assembly = Assembly.Load(new AssemblyName(simpleName));
if (!assemblies.ContainsKey(assembly.FullName))
assemblies.Add(assembly.FullName, assembly);
}
}
foreach (var assemblyName in assemblyFinder.FindAssembliesContainingName("serilog"))
{
var assumed = Assembly.Load(assemblyName);
if (assumed != null && !assemblies.ContainsKey(assumed.FullName))
assemblies.Add(assumed.FullName, assumed);
}
return assemblies.Values.ToList().AsReadOnly();
}
void CallConfigurationMethods(ILookup<string, Dictionary<string, IConfigurationArgumentValue>> methods, IList<MethodInfo> configurationMethods, object receiver)
{
foreach (var method in methods.SelectMany(g => g.Select(x => new { g.Key, Value = x })))
{
var methodInfo = SelectConfigurationMethod(configurationMethods, method.Key, method.Value.Keys);
if (methodInfo != null)
{
var call = (from p in methodInfo.GetParameters().Skip(1)
let directive = method.Value.FirstOrDefault(s => ParameterNameMatches(p.Name, s.Key))
select directive.Key == null
? GetImplicitValueForNotSpecifiedKey(p, methodInfo)
: directive.Value.ConvertTo(p.ParameterType, _resolutionContext)).ToList();
call.Insert(0, receiver);
methodInfo.Invoke(null, call.ToArray());
}
}
}
static bool HasImplicitValueWhenNotSpecified(ParameterInfo paramInfo)
{
return paramInfo.HasDefaultValue
// parameters of type IConfiguration are implicitly populated with provided Configuration
|| paramInfo.ParameterType == typeof(IConfiguration);
}
object GetImplicitValueForNotSpecifiedKey(ParameterInfo parameter, MethodInfo methodToInvoke)
{
if (!HasImplicitValueWhenNotSpecified(parameter))
{
throw new InvalidOperationException("GetImplicitValueForNotSpecifiedKey() should only be called for parameters for which HasImplicitValueWhenNotSpecified() is true. " +
"This means something is wrong in the Serilog.Settings.Configuration code.");
}
if (parameter.ParameterType == typeof(IConfiguration))
{
if (_resolutionContext.HasAppConfiguration)
{
return _resolutionContext.AppConfiguration;
}
if (parameter.HasDefaultValue)
{
return parameter.DefaultValue;
}
throw new InvalidOperationException("Trying to invoke a configuration method accepting a `IConfiguration` argument. " +
$"This is not supported when only a `IConfigSection` has been provided. (method '{methodToInvoke}')");
}
return parameter.DefaultValue;
}
internal static MethodInfo SelectConfigurationMethod(IEnumerable<MethodInfo> candidateMethods, string name, IEnumerable<string> suppliedArgumentNames)
{
// Per issue #111, it is safe to use case-insensitive matching on argument names. The CLR doesn't permit this type
// of overloading, and the Microsoft.Extensions.Configuration keys are case-insensitive (case is preserved with some
// config sources, but key-matching is case-insensitive and case-preservation does not appear to be guaranteed).
var selectedMethod = candidateMethods
.Where(m => m.Name == name)
.Where(m => m.GetParameters()
.Skip(1)
.All(p => HasImplicitValueWhenNotSpecified(p) ||
ParameterNameMatches(p.Name, suppliedArgumentNames)))
.OrderByDescending(m =>
{
var matchingArgs = m.GetParameters().Where(p => ParameterNameMatches(p.Name, suppliedArgumentNames)).ToList();
// Prefer the configuration method with most number of matching arguments and of those the ones with
// the most string type parameters to predict best match with least type casting
return new Tuple<int, int>(
matchingArgs.Count,
matchingArgs.Count(p => p.ParameterType == typeof(string)));
})
.FirstOrDefault();
if (selectedMethod == null)
{
var methodsByName = candidateMethods
.Where(m => m.Name == name)
.Select(m => $"{m.Name}({string.Join(", ", m.GetParameters().Skip(1).Select(p => p.Name))})")
.ToList();
if (!methodsByName.Any())
SelfLog.WriteLine($"Unable to find a method called {name}. Candidate methods are:{Environment.NewLine}{string.Join(Environment.NewLine, candidateMethods)}");
else
SelfLog.WriteLine($"Unable to find a method called {name} "
+ (suppliedArgumentNames.Any()
? "for supplied arguments: " + string.Join(", ", suppliedArgumentNames)
: "with no supplied arguments")
+ ". Candidate methods are:"
+ Environment.NewLine
+ string.Join(Environment.NewLine, methodsByName));
}
return selectedMethod;
}
static bool ParameterNameMatches(string actualParameterName, string suppliedName)
{
return suppliedName.Equals(actualParameterName, StringComparison.OrdinalIgnoreCase);
}
static bool ParameterNameMatches(string actualParameterName, IEnumerable<string> suppliedNames)
{
return suppliedNames.Any(s => ParameterNameMatches(actualParameterName, s));
}
static IList<MethodInfo> FindSinkConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerSinkConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerSinkConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.WriteTo);
return found;
}
static IList<MethodInfo> FindAuditSinkConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerAuditSinkConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerAuditSinkConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.AuditTo);
return found;
}
static IList<MethodInfo> FindFilterConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerFilterConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerFilterConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.Filter);
return found;
}
static IList<MethodInfo> FindDestructureConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerDestructuringConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerDestructuringConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.Destructure);
return found;
}
static IList<MethodInfo> FindEventEnricherConfigurationMethods(IReadOnlyCollection<Assembly> configurationAssemblies)
{
var found = FindConfigurationExtensionMethods(configurationAssemblies, typeof(LoggerEnrichmentConfiguration));
if (configurationAssemblies.Contains(typeof(LoggerEnrichmentConfiguration).GetTypeInfo().Assembly))
found.AddRange(SurrogateConfigurationMethods.Enrich);
return found;
}
static List<MethodInfo> FindConfigurationExtensionMethods(IReadOnlyCollection<Assembly> configurationAssemblies, Type configType)
{
return configurationAssemblies
.SelectMany(a => a.ExportedTypes
.Select(t => t.GetTypeInfo())
.Where(t => t.IsSealed && t.IsAbstract && !t.IsNested))
.SelectMany(t => t.DeclaredMethods)
.Where(m => m.IsStatic && m.IsPublic && m.IsDefined(typeof(ExtensionAttribute), false))
.Where(m => m.GetParameters()[0].ParameterType == configType)
.ToList();
}
internal static bool IsValidSwitchName(string input)
{
return Regex.IsMatch(input, LevelSwitchNameRegex);
}
static LogEventLevel ParseLogEventLevel(string value)
{
if (!Enum.TryParse(value, out LogEventLevel parsedLevel))
throw new InvalidOperationException($"The value {value} is not a valid Serilog level.");
return parsedLevel;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Globalization;
using System.Text;
using System.Windows.Forms;
using SPD.CommonObjects;
using SPD.BL.Interfaces;
using SPD.Print;
namespace SPD.GUI {
/// <summary>
///
/// </summary>
public delegate void NewPatientStoreEventHandler(object sender,
NewPatientStoreEventArgs e);
/// <summary>
///
/// </summary>
public partial class NewPatientControl : UserControl {
private PatientData currentPatient;
private ISPDBL patComp;
/// <summary>
/// Gets or sets the text box surname.
/// </summary>
/// <value>The text box surname.</value>
public System.Windows.Forms.TextBox TextBoxSurname {
set { textBoxSurname = value; }
get { return textBoxSurname; }
}
/// <summary>
/// Initializes a new instance of the <see cref="NewPatientControl"/> class.
/// </summary>
public NewPatientControl(ISPDBL patComp) {
InitializeComponent();
this.patComp = patComp;
foreach (String sex in Enum.GetNames(new Sex().GetType())) {
this.listBoxSex.Items.Add(sex);
}
foreach (String ambulant in Enum.GetNames(new Ambulant().GetType())) {
this.listBoxAmbulant.Items.Add(ambulant);
}
foreach (String resident in Enum.GetNames(new ResidentOfAsmara().GetType())) {
this.listBoxResidentOfAsmara.Items.Add(resident);
}
foreach (String finished in Enum.GetNames(new Finished().GetType())) {
this.listBoxFinished.Items.Add(finished);
}
foreach (String linz in Enum.GetNames(new Linz().GetType())) {
this.listBoxLinz.Items.Add(linz);
}
this.labelLastHighestPiD.Text = "";
}
/// <summary>
/// Gets or sets the button clear data.
/// </summary>
/// <value>The button clear data.</value>
public Button ButtonClearData {
get { return buttonClearData; }
set { buttonClearData = value; }
}
/// <summary>
/// Gets or sets the button save data.
/// </summary>
/// <value>The button save data.</value>
public Button ButtonSaveData {
get { return buttonSaveData; }
set { buttonSaveData = value; }
}
/// <summary>
/// Get or sets the button print Id Card
/// </summary>
public Button ButtonPrintIdCard {
get { return buttonPrintIdCard; }
set { buttonPrintIdCard = value; }
}
private void NewPatientControl_Load(object sender, EventArgs e) {
}
/// <summary>
/// Initts this instance.
/// </summary>
public void Init(PatientData currentPatient) {
this.currentPatient = currentPatient;
enabler(true);
monthCalendarBirth.Visible = false;
buttonSubmitCalendar.Visible = false;
buttonNoCalender.Visible = false;
textBoxSurname.Select();
fillTextBoxes();
this.textBoxSurname.Focus();
this.textBoxSurname.Select(0, 0);
labelLastHighestPiD.Text = Convert.ToString(this.patComp.getHighesPatientId());
}
//public event System.EventHandler Store;
/// <summary>
/// Occurs when [store].
/// </summary>
public event NewPatientStoreEventHandler Store;
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear(){
textBoxFirstName.Text = string.Empty;
textBoxSurname.Text = string.Empty;
textBoxBirthYear.Text = string.Empty;
textBoxBirthMonth.Text = string.Empty;
textBoxBirthDay.Text = string.Empty;
textBoxWeight.Text = string.Empty;
textBoxAge.Text = string.Empty;
textBoxAddress.Text = string.Empty;
textBoxPhone.Text = string.Empty;
listBoxSex.SelectedItems.Clear();
listBoxAmbulant.SelectedItems.Clear();
listBoxAmbulant.SelectedIndex = 1;
listBoxResidentOfAsmara.SelectedItems.Clear();
listBoxResidentOfAsmara.SelectedIndex = 0;
listBoxFinished.SelectedItems.Clear();
listBoxFinished.SelectedIndex = 0;
listBoxLinz.SelectedItems.Clear();
listBoxLinz.SelectedIndex = 0;
listBoxAssignedDiagnoseGroups.Items.Clear();
listBoxAvailableDiagnoseGroups.Items.Clear();
foreach(DiagnoseGroupData dgd in patComp.FindAllDiagnoseGroups()) {
listBoxAvailableDiagnoseGroups.Items.Add(dgd);
}
labelWaitListDateValue.Text = string.Empty;
}
private void buttonClearData_Click(object sender, EventArgs e) {
if (currentPatient == null) {
Clear();
} else {
fillTextBoxes();
}
}
private void buttonSaveData_Click(object sender, EventArgs e) {
DateTime birthDate = new DateTime();
if (!(textBoxBirthYear.Text.Trim().Equals("") &&
textBoxBirthMonth.Text.Trim().Equals("") &&
textBoxBirthDay.Text.Trim().Equals(""))) {
try {
birthDate = new DateTime(Int32.Parse(textBoxBirthYear.Text.Trim()),
Int32.Parse(textBoxBirthMonth.Text.Trim()),
Int32.Parse(textBoxBirthDay.Text.Trim()));
} catch (Exception exxx) {
MessageBox.Show("Sorry - but the date is not correct" + exxx.ToString());
return;
}
}
DateTime? waitListDate = null;
if (!string.IsNullOrWhiteSpace(labelWaitListDateValue.Text))
{
waitListDate = DateTime.Parse(labelWaitListDateValue.Text, DateTimeFormatInfo.InvariantInfo);
}
if (listBoxSex.SelectedItems.Count == 0) {
MessageBox.Show("No gender is selected");
return;
}
if (listBoxAmbulant.SelectedItems.Count == 0) {
MessageBox.Show("Ambulant is not selected");
return;
}
if (listBoxResidentOfAsmara.SelectedItems.Count == 0) {
MessageBox.Show("Resident of Asmara is not selected");
return;
}
if (listBoxFinished.SelectedItems.Count == 0) {
MessageBox.Show("Finished is not selected");
return;
}
if (listBoxLinz.SelectedItems.Count == 0) {
MessageBox.Show("Linz is not selected");
return;
}
Sex sex = (Sex)Enum.Parse(new Sex().GetType(), this.listBoxSex.Text);
Ambulant ambulant = (Ambulant)Enum.Parse(new Ambulant().GetType(), this.listBoxAmbulant.Text);
ResidentOfAsmara residentOfAsmara = (ResidentOfAsmara)Enum.Parse(new ResidentOfAsmara().GetType(), this.listBoxResidentOfAsmara.Text);
Finished finished = (Finished)Enum.Parse(new Finished().GetType(), this.listBoxFinished.Text);
Linz linz = (Linz)Enum.Parse(new Linz().GetType(), this.listBoxLinz.Text);
long pId;
if (currentPatient == null)
pId = 0;
else
pId = currentPatient.Id;
int weight;
try {
weight = Int32.Parse(textBoxWeight.Text.Trim());
} catch (Exception) {
weight = 0;
if (textBoxWeight.Text.Trim().Equals("")){
weight = 0;
}else{
MessageBox.Show("In the weight field has to be a integer number");
return;
}
}
if (this.patComp.DoesPhoneExist(this.textBoxPhone.Text.Trim())) {
IList<PatientData> patients = this.patComp.FindPatientByPhone(this.textBoxPhone.Text.Trim());
if (!(patients.Count == 1 && currentPatient != null && patients[0].Id == currentPatient.Id)) {
StringBuilder sb = new StringBuilder();
foreach (PatientData pd in patients) {
sb.Append(Environment.NewLine + "-----------------------------------" + Environment.NewLine).Append(pd.ToLineBreakedString()).Append(Environment.NewLine);
}
DialogResult res = MessageBox.Show("This phone Number is already stored." + Environment.NewLine + "Do you want to add the Patient anyway?" + "Patient(s):" + sb.ToString(), "Warning!", MessageBoxButtons.YesNo);
if (res == DialogResult.No) {
return;
}
}
}
PatientData patient = new PatientData(pId, textBoxFirstName.Text.Trim(), textBoxSurname.Text.Trim(),
birthDate, sex, textBoxPhone.Text.Trim(),
weight, textBoxAddress.Text.Trim(), residentOfAsmara, ambulant, finished, linz, waitListDate);
IList<DiagnoseGroupData> diagnoseGroups = new List<DiagnoseGroupData>();
foreach (DiagnoseGroupData dg in listBoxAssignedDiagnoseGroups.Items) {
diagnoseGroups.Add(dg);
}
NewPatientStoreEventArgs e2 = new NewPatientStoreEventArgs(patient, diagnoseGroups);
Store(this, e2);
}
/// <summary>
/// Enablers the specified enable.
/// </summary>
/// <param name="enable">if set to <c>true</c> [enable].</param>
public void enabler(bool enable) {
textBoxFirstName.Enabled = enable;
textBoxSurname.Enabled = enable;
textBoxBirthYear.Enabled = enable;
textBoxBirthMonth.Enabled = enable;
textBoxBirthDay.Enabled = enable;
textBoxPhone.Enabled = enable;
textBoxAddress.Enabled = enable;
textBoxAge.Enabled = enable;
textBoxWeight.Enabled = enable;
listBoxSex.Enabled = enable;
listBoxResidentOfAsmara.Enabled = enable;
listBoxAmbulant.Enabled = enable;
listBoxFinished.Enabled = enable;
listBoxLinz.Enabled = enable;
buttonSaveData.Enabled = enable;
buttonCalendar.Enabled = enable;
buttonNoCalender.Enabled = enable;
buttonClearData.Enabled = enable;
buttonSubmitCalendar.Enabled = enable;
listBoxAssignedDiagnoseGroups.Enabled = enable;
listBoxAvailableDiagnoseGroups.Enabled = enable;
buttonAssign.Enabled = enable;
buttonUnassign.Enabled = enable;
buttonPrintIdCard.Enabled = enable;
}
private void buttonCalendar_Click(object sender, EventArgs e) {
enabler(false);
monthCalendarBirth.Visible = true;
buttonSubmitCalendar.Enabled = true;
buttonSubmitCalendar.Visible = true;
buttonNoCalender.Enabled = true;
buttonNoCalender.Visible = true;
}
private void buttonSubmitCalendar_Click(object sender, EventArgs e) {
enabler(true);
monthCalendarBirth.Visible = false;
buttonSubmitCalendar.Visible = false;
buttonNoCalender.Visible = false;
if (this.currentPatient == null || currentPatient.Id < 1) {
this.buttonPrintIdCard.Enabled = false;
}
textBoxBirthMonth.Text = monthCalendarBirth.SelectionStart.Month.ToString();
textBoxBirthYear.Text = monthCalendarBirth.SelectionStart.Year.ToString();
textBoxBirthDay.Text = monthCalendarBirth.SelectionStart.Day.ToString();
}
private void buttonNoCalender_Click(object sender, EventArgs e) {
enabler(true);
monthCalendarBirth.Visible = false;
buttonSubmitCalendar.Visible = false;
buttonNoCalender.Visible = false;
if (this.currentPatient == null || currentPatient.Id < 1) {
this.buttonPrintIdCard.Enabled = false;
}
}
///// <summary>
///// Sets the patient.
///// </summary>
///// <value>The patient.</value>
//public PatientData Patient {
// set {
// currentPatient = value;
// fillTextBoxes();
// }
//}
/// <summary>
/// Fills the text boxes.
/// </summary>
private void fillTextBoxes(){
if (currentPatient != null) {
textBoxFirstName.Text = currentPatient.FirstName;
textBoxSurname.Text = currentPatient.SurName;
textBoxBirthDay.Text = currentPatient.DateOfBirth.Day.ToString();
textBoxBirthMonth.Text = currentPatient.DateOfBirth.Month.ToString();
textBoxBirthYear.Text = currentPatient.DateOfBirth.Year.ToString();
textBoxPhone.Text = currentPatient.Phone;
textBoxAge.Text = SPD.CommonUtilities.StaticUtilities.getAgeFromBirthDate(currentPatient.DateOfBirth);
textBoxWeight.Text = currentPatient.Weight.ToString();
textBoxAddress.Text = currentPatient.Address;
listBoxSex.SelectedItem = currentPatient.Sex.ToString();
listBoxResidentOfAsmara.SelectedItem = currentPatient.ResidentOfAsmara.ToString();
listBoxAmbulant.SelectedItem = currentPatient.Ambulant.ToString();
listBoxFinished.SelectedItem = currentPatient.Finished.ToString();
listBoxLinz.SelectedItem = currentPatient.Linz.ToString();
listBoxAvailableDiagnoseGroups.Items.Clear();
listBoxAssignedDiagnoseGroups.Items.Clear();
if (currentPatient.WaitListStartDate == null) {
labelWaitListDateValue.Text = string.Empty;
} else {
labelWaitListDateValue.Text = ((DateTime)currentPatient.WaitListStartDate).ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
}
foreach(DiagnoseGroupData dgd in patComp.FindDiagnoseGroupIdByPatientId(currentPatient.Id)) {
listBoxAssignedDiagnoseGroups.Items.Add(dgd);
}
foreach(DiagnoseGroupData dgd in patComp.FindAllDiagnoseGroupsThatAreNotAssignedByPatient(currentPatient.Id)) {
listBoxAvailableDiagnoseGroups.Items.Add(dgd);
}
} else {
Clear();
}
}
/// <summary>
/// Handles the Leave event of the textBoxAge control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void textBoxAge_Leave(object sender, EventArgs e) {
int age;
if (textBoxAge.Text.Equals("")) {
return;
}
try {
age = Int32.Parse(textBoxAge.Text);
} catch {
textBoxAge.Text = "";
MessageBox.Show("The Age must be a natural Number");
return;
}
DateTime date = CommonUtilities.StaticUtilities.getBirthDateFromAge(age);
textBoxBirthDay.Text = date.Day.ToString();
textBoxBirthMonth.Text = date.Month.ToString();
textBoxBirthYear.Text = date.Year.ToString();
}
private void buttonAssign_Click(object sender, EventArgs e) {
if (listBoxAvailableDiagnoseGroups.SelectedItems.Count < 1) {
MessageBox.Show("Please select a Diagnosegroup to assign.");
return;
}
listBoxAssignedDiagnoseGroups.Items.Add(listBoxAvailableDiagnoseGroups.SelectedItem);
listBoxAvailableDiagnoseGroups.Items.Remove(listBoxAvailableDiagnoseGroups.SelectedItem);
}
private void buttonUnassign_Click(object sender, EventArgs e) {
if (listBoxAssignedDiagnoseGroups.SelectedItems.Count < 1) {
MessageBox.Show("Please select a Diagnosegroup to unassign.");
return;
}
listBoxAvailableDiagnoseGroups.Items.Add(listBoxAssignedDiagnoseGroups.SelectedItem);
listBoxAssignedDiagnoseGroups.Items.Remove(listBoxAssignedDiagnoseGroups.SelectedItem);
}
private void listBoxAssignedDiagnoseGroups_DoubleClick(object sender, EventArgs e) {
if (listBoxAssignedDiagnoseGroups.SelectedItems.Count < 1) {
MessageBox.Show("Please select a Diagnosegroup to unassign.");
return;
}
listBoxAvailableDiagnoseGroups.Items.Add(listBoxAssignedDiagnoseGroups.SelectedItem);
listBoxAssignedDiagnoseGroups.Items.Remove(listBoxAssignedDiagnoseGroups.SelectedItem);
}
private void listBoxAvailableDiagnoseGroups_DoubleClick(object sender, EventArgs e) {
if (listBoxAvailableDiagnoseGroups.SelectedItems.Count < 1) {
MessageBox.Show("Please select a Diagnosegroup to assign.");
return;
}
listBoxAssignedDiagnoseGroups.Items.Add(listBoxAvailableDiagnoseGroups.SelectedItem);
listBoxAvailableDiagnoseGroups.Items.Remove(listBoxAvailableDiagnoseGroups.SelectedItem);
}
private void buttonPrintIdCard_Click(object sender, EventArgs e) {
if (currentPatient == null)
{
return;
}
SPDPrint print = new SPDPrint(this.patComp);
IList<PatientData> patients = new List<PatientData>();
patients.Add(currentPatient);
print.PrintIdCard(patients);
}
}
/// <summary>
///
/// </summary>
public class NewPatientStoreEventArgs : EventArgs {
private PatientData patient;
private IList<DiagnoseGroupData> diagnoseGroups;
/// <summary>
/// Initializes a new instance of the <see cref="NewPatientStoreEventArgs" /> class.
/// </summary>
/// <param name="patient">The patient.</param>
/// <param name="diagnoseGroups">The diagnose groups.</param>
public NewPatientStoreEventArgs(PatientData patient, IList<DiagnoseGroupData> diagnoseGroups) {
this.patient = patient;
this.diagnoseGroups = diagnoseGroups;
}
/// <summary>
/// Gets the patient.
/// </summary>
/// <value>The patient.</value>
public PatientData Patient {
get {
return patient;
}
}
/// <summary>
/// Gets the diagnose groups.
/// </summary>
/// <value>
/// The diagnose groups.
/// </value>
public IList<DiagnoseGroupData> DiagnoseGroups {
get {
return diagnoseGroups;
}
}
}
}
| |
/*
* 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 IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using TermPositions = Lucene.Net.Index.TermPositions;
using ComplexExplanation = Lucene.Net.Search.ComplexExplanation;
using Explanation = Lucene.Net.Search.Explanation;
using Scorer = Lucene.Net.Search.Scorer;
using Searcher = Lucene.Net.Search.Searcher;
using Similarity = Lucene.Net.Search.Similarity;
using Weight = Lucene.Net.Search.Weight;
using SpanScorer = Lucene.Net.Search.Spans.SpanScorer;
using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery;
using SpanWeight = Lucene.Net.Search.Spans.SpanWeight;
using TermSpans = Lucene.Net.Search.Spans.TermSpans;
namespace Lucene.Net.Search.Payloads
{
/// <summary> This class is very similar to
/// {@link Lucene.Net.Search.Spans.SpanTermQuery} except that it factors
/// in the value of the payload located at each of the positions where the
/// {@link Lucene.Net.Index.Term} occurs.
/// <p/>
/// In order to take advantage of this, you must override
/// {@link Lucene.Net.Search.Similarity#ScorePayload(String, byte[],int,int)}
/// which returns 1 by default.
/// <p/>
/// Payload scores are aggregated using a pluggable {@link PayloadFunction}.
///
/// </summary>
[Serializable]
public class PayloadTermQuery:SpanTermQuery
{
protected internal PayloadFunction function;
private bool includeSpanScore;
public PayloadTermQuery(Term term, PayloadFunction function):this(term, function, true)
{
}
public PayloadTermQuery(Term term, PayloadFunction function, bool includeSpanScore):base(term)
{
this.function = function;
this.includeSpanScore = includeSpanScore;
}
public override Weight CreateWeight(Searcher searcher)
{
return new PayloadTermWeight(this, this, searcher);
}
[Serializable]
protected internal class PayloadTermWeight:SpanWeight
{
private void InitBlock(PayloadTermQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private PayloadTermQuery enclosingInstance;
public PayloadTermQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public PayloadTermWeight(PayloadTermQuery enclosingInstance, PayloadTermQuery query, Searcher searcher):base(query, searcher)
{
InitBlock(enclosingInstance);
}
public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer)
{
return new PayloadTermSpanScorer(this, (TermSpans) query.GetSpans(reader), this, similarity, reader.Norms(query.GetField()));
}
protected internal class PayloadTermSpanScorer:SpanScorer
{
private void InitBlock(PayloadTermWeight enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private PayloadTermWeight enclosingInstance;
public PayloadTermWeight Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
// TODO: is this the best way to allocate this?
protected internal byte[] payload = new byte[256];
protected internal TermPositions positions;
protected internal float payloadScore;
protected internal int payloadsSeen;
public PayloadTermSpanScorer(PayloadTermWeight enclosingInstance, TermSpans spans, Weight weight, Similarity similarity, byte[] norms):base(spans, weight, similarity, norms)
{
InitBlock(enclosingInstance);
positions = spans.GetPositions();
}
public /*protected internal*/ override bool SetFreqCurrentDoc()
{
if (!more)
{
return false;
}
doc = spans.Doc();
freq = 0.0f;
payloadScore = 0;
payloadsSeen = 0;
Similarity similarity1 = GetSimilarity();
while (more && doc == spans.Doc())
{
int matchLength = spans.End() - spans.Start();
freq += similarity1.SloppyFreq(matchLength);
ProcessPayload(similarity1);
more = spans.Next(); // this moves positions to the next match in this
// document
}
return more || (freq != 0);
}
protected internal virtual void ProcessPayload(Similarity similarity)
{
if (positions.IsPayloadAvailable())
{
payload = positions.GetPayload(payload, 0);
payloadScore = Enclosing_Instance.Enclosing_Instance.function.CurrentScore(doc, Enclosing_Instance.Enclosing_Instance.term.Field(), spans.Start(), spans.End(), payloadsSeen, payloadScore, similarity.ScorePayload(doc, Enclosing_Instance.Enclosing_Instance.term.Field(), spans.Start(), spans.End(), payload, 0, positions.GetPayloadLength()));
payloadsSeen++;
}
else
{
// zero out the payload?
}
}
/// <summary> </summary>
/// <returns> {@link #GetSpanScore()} * {@link #GetPayloadScore()}
/// </returns>
/// <throws> IOException </throws>
public override float Score()
{
return Enclosing_Instance.Enclosing_Instance.includeSpanScore?GetSpanScore() * GetPayloadScore():GetPayloadScore();
}
/// <summary> Returns the SpanScorer score only.
/// <p/>
/// Should not be overriden without good cause!
///
/// </summary>
/// <returns> the score for just the Span part w/o the payload
/// </returns>
/// <throws> IOException </throws>
/// <summary>
/// </summary>
/// <seealso cref="Score()">
/// </seealso>
protected internal virtual float GetSpanScore()
{
return base.Score();
}
/// <summary> The score for the payload
///
/// </summary>
/// <returns> The score, as calculated by
/// {@link PayloadFunction#DocScore(int, String, int, float)}
/// </returns>
protected internal virtual float GetPayloadScore()
{
return Enclosing_Instance.Enclosing_Instance.function.DocScore(doc, Enclosing_Instance.Enclosing_Instance.term.Field(), payloadsSeen, payloadScore);
}
public override Explanation Explain(int doc)
{
ComplexExplanation result = new ComplexExplanation();
Explanation nonPayloadExpl = base.Explain(doc);
result.AddDetail(nonPayloadExpl);
// QUESTION: Is there a way to avoid this skipTo call? We need to know
// whether to load the payload or not
Explanation payloadBoost = new Explanation();
result.AddDetail(payloadBoost);
float payloadScore = GetPayloadScore();
payloadBoost.SetValue(payloadScore);
// GSI: I suppose we could toString the payload, but I don't think that
// would be a good idea
payloadBoost.SetDescription("scorePayload(...)");
result.SetValue(nonPayloadExpl.GetValue() * payloadScore);
result.SetDescription("btq, product of:");
result.SetMatch(nonPayloadExpl.GetValue() == 0?false:true); // LUCENE-1303
return result;
}
}
}
public override int GetHashCode()
{
int prime = 31;
int result = base.GetHashCode();
result = prime * result + ((function == null)?0:function.GetHashCode());
result = prime * result + (includeSpanScore?1231:1237);
return result;
}
public override bool Equals(System.Object obj)
{
if (this == obj)
return true;
if (!base.Equals(obj))
return false;
if (GetType() != obj.GetType())
return false;
PayloadTermQuery other = (PayloadTermQuery) obj;
if (function == null)
{
if (other.function != null)
return false;
}
else if (!function.Equals(other.function))
return false;
if (includeSpanScore != other.includeSpanScore)
return false;
return true;
}
}
}
| |
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MessageTransferModule")]
public class MessageTransferModule : ISharedRegionModule, IMessageTransferModule
{
protected List<Scene> m_Scenes = new List<Scene>();
protected Dictionary<UUID, UUID> m_UserRegionMap = new Dictionary<UUID, UUID>();
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private IPresenceService m_PresenceService;
/// <summary>
/// delegate for sending a grid instant message asynchronously
/// </summary>
public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID);
public event UndeliveredMessage OnUndeliveredMessage;
public virtual string Name
{
get { return "MessageTransferModule"; }
}
public virtual Type ReplaceableInterface
{
get { return null; }
}
protected IPresenceService PresenceService
{
get
{
if (m_PresenceService == null)
m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
return m_PresenceService;
}
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_log.Debug("[MESSAGE TRANSFER]: Message transfer module active");
scene.RegisterModuleInterface<IMessageTransferModule>(this);
m_Scenes.Add(scene);
}
}
public virtual void Close()
{
}
public virtual void Initialise(IConfigSource config)
{
IConfig cnf = config.Configs["Messaging"];
if (cnf != null && cnf.GetString(
"MessageTransferModule", "MessageTransferModule") !=
"MessageTransferModule")
{
m_log.Debug("[MESSAGE TRANSFER]: Disabled by configuration");
return;
}
m_Enabled = true;
}
public virtual void PostInitialise()
{
if (!m_Enabled)
return;
MainServer.Instance.AddXmlRPCHandler(
"grid_instant_message", processXMLRPCGridInstantMessage);
}
public virtual void RegionLoaded(Scene scene)
{
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
lock (m_Scenes)
{
m_Scenes.Remove(scene);
}
}
public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
{
UUID toAgentID = new UUID(im.toAgentID);
// Try root avatar only first
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for root agent {0} in {1}",
// toAgentID.ToString(), scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
// Local message
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", sp.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// try child avatar second
foreach (Scene scene in m_Scenes)
{
// m_log.DebugFormat(
// "[INSTANT MESSAGE]: Looking for child of {0} in {1}", toAgentID, scene.RegionInfo.RegionName);
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null)
{
// Local message
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", sp.Name, toAgentID);
sp.ControllingClient.SendInstantMessage(im);
// Message sent
result(true);
return;
}
}
// m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
SendGridInstantMessageViaXMLRPC(im, result);
}
/// <summary>
/// Takes a GridInstantMessage and converts it into a Hashtable for XMLRPC
/// </summary>
/// <param name="msg">The GridInstantMessage object</param>
/// <returns>Hashtable containing the XMLRPC request</returns>
protected virtual Hashtable ConvertGridInstantMessageToXMLRPC(GridInstantMessage msg)
{
Hashtable gim = new Hashtable();
gim["from_agent_id"] = msg.fromAgentID.ToString();
// Kept for compatibility
gim["from_agent_session"] = UUID.Zero.ToString();
gim["to_agent_id"] = msg.toAgentID.ToString();
gim["im_session_id"] = msg.imSessionID.ToString();
gim["timestamp"] = msg.timestamp.ToString();
gim["from_agent_name"] = msg.fromAgentName;
gim["message"] = msg.message;
byte[] dialogdata = new byte[1]; dialogdata[0] = msg.dialog;
gim["dialog"] = Convert.ToBase64String(dialogdata, Base64FormattingOptions.None);
if (msg.fromGroup)
gim["from_group"] = "TRUE";
else
gim["from_group"] = "FALSE";
byte[] offlinedata = new byte[1]; offlinedata[0] = msg.offline;
gim["offline"] = Convert.ToBase64String(offlinedata, Base64FormattingOptions.None);
gim["parent_estate_id"] = msg.ParentEstateID.ToString();
gim["position_x"] = msg.Position.X.ToString();
gim["position_y"] = msg.Position.Y.ToString();
gim["position_z"] = msg.Position.Z.ToString();
gim["region_id"] = new UUID(msg.RegionID).ToString();
gim["binary_bucket"] = Convert.ToBase64String(msg.binaryBucket, Base64FormattingOptions.None);
return gim;
}
/// <summary>
/// This actually does the XMLRPC Request
/// </summary>
/// <param name="reginfo">RegionInfo we pull the data out of to send the request to</param>
/// <param name="xmlrpcdata">The Instant Message data Hashtable</param>
/// <returns>Bool if the message was successfully delivered at the other side.</returns>
protected virtual bool doIMSending(GridRegion reginfo, Hashtable xmlrpcdata)
{
ArrayList SendParams = new ArrayList();
SendParams.Add(xmlrpcdata);
XmlRpcRequest GridReq = new XmlRpcRequest("grid_instant_message", SendParams);
try
{
XmlRpcResponse GridResp = GridReq.Send(reginfo.ServerURI, 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("success"))
{
if ((string)responseData["success"] == "TRUE")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch (WebException e)
{
m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to {0} the host didn't respond " + e.ToString(), reginfo.ServerURI.ToString());
}
return false;
}
protected virtual void GridInstantMessageCompleted(IAsyncResult iar)
{
GridInstantMessageDelegate icon =
(GridInstantMessageDelegate)iar.AsyncState;
icon.EndInvoke(iar);
}
/// <summary>
/// Process a XMLRPC Grid Instant Message
/// </summary>
/// <param name="request">XMLRPC parameters
/// </param>
/// <returns>Nothing much</returns>
protected virtual XmlRpcResponse processXMLRPCGridInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient)
{
bool successful = false;
// TODO: For now, as IMs seem to be a bit unreliable on OSGrid, catch all exception that
// happen here and aren't caught and log them.
try
{
// various rational defaults
UUID fromAgentID = UUID.Zero;
UUID toAgentID = UUID.Zero;
UUID imSessionID = UUID.Zero;
uint timestamp = 0;
string fromAgentName = "";
string message = "";
byte dialog = (byte)0;
bool fromGroup = false;
byte offline = (byte)0;
uint ParentEstateID = 0;
Vector3 Position = Vector3.Zero;
UUID RegionID = UUID.Zero;
byte[] binaryBucket = new byte[0];
float pos_x = 0;
float pos_y = 0;
float pos_z = 0;
//m_log.Info("Processing IM");
Hashtable requestData = (Hashtable)request.Params[0];
// Check if it's got all the data
if (requestData.ContainsKey("from_agent_id")
&& requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id")
&& requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name")
&& requestData.ContainsKey("message") && requestData.ContainsKey("dialog")
&& requestData.ContainsKey("from_group")
&& requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id")
&& requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y")
&& requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id")
&& requestData.ContainsKey("binary_bucket"))
{
// Do the easy way of validating the UUIDs
UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID);
UUID.TryParse((string)requestData["to_agent_id"], out toAgentID);
UUID.TryParse((string)requestData["im_session_id"], out imSessionID);
UUID.TryParse((string)requestData["region_id"], out RegionID);
try
{
timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
fromAgentName = (string)requestData["from_agent_name"];
message = (string)requestData["message"];
if (message == null)
message = string.Empty;
// Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
string requestData1 = (string)requestData["dialog"];
if (string.IsNullOrEmpty(requestData1))
{
dialog = 0;
}
else
{
byte[] dialogdata = Convert.FromBase64String(requestData1);
dialog = dialogdata[0];
}
if ((string)requestData["from_group"] == "TRUE")
fromGroup = true;
string requestData2 = (string)requestData["offline"];
if (String.IsNullOrEmpty(requestData2))
{
offline = 0;
}
else
{
byte[] offlinedata = Convert.FromBase64String(requestData2);
offline = offlinedata[0];
}
try
{
ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_x = (uint)Convert.ToInt32((string)requestData["position_x"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_y = (uint)Convert.ToInt32((string)requestData["position_y"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
try
{
pos_z = (uint)Convert.ToInt32((string)requestData["position_z"]);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
Position = new Vector3(pos_x, pos_y, pos_z);
string requestData3 = (string)requestData["binary_bucket"];
if (string.IsNullOrEmpty(requestData3))
{
binaryBucket = new byte[0];
}
else
{
binaryBucket = Convert.FromBase64String(requestData3);
}
// Create a New GridInstantMessageObject the the data
GridInstantMessage gim = new GridInstantMessage();
gim.fromAgentID = fromAgentID.Guid;
gim.fromAgentName = fromAgentName;
gim.fromGroup = fromGroup;
gim.imSessionID = imSessionID.Guid;
gim.RegionID = RegionID.Guid;
gim.timestamp = timestamp;
gim.toAgentID = toAgentID.Guid;
gim.message = message;
gim.dialog = dialog;
gim.offline = offline;
gim.ParentEstateID = ParentEstateID;
gim.Position = Position;
gim.binaryBucket = binaryBucket;
// Trigger the Instant message in the scene.
foreach (Scene scene in m_Scenes)
{
ScenePresence sp = scene.GetScenePresence(toAgentID);
if (sp != null && !sp.IsChildAgent)
{
scene.EventManager.TriggerIncomingInstantMessage(gim);
successful = true;
}
}
if (!successful)
{
// If the message can't be delivered to an agent, it
// is likely to be a group IM. On a group IM, the
// imSessionID = toAgentID = group id. Raise the
// unhandled IM event to give the groups module
// a chance to pick it up. We raise that in a random
// scene, since the groups module is shared.
//
m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim);
}
}
}
catch (Exception e)
{
m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e);
successful = false;
}
//Send response back to region calling if it was successful
// calling region uses this to know when to look up a user's location again.
XmlRpcResponse resp = new XmlRpcResponse();
Hashtable respdata = new Hashtable();
if (successful)
respdata["success"] = "TRUE";
else
respdata["success"] = "FALSE";
resp.Value = respdata;
return resp;
}
protected virtual void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result)
{
GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync;
d.BeginInvoke(im, result, UUID.Zero, GridInstantMessageCompleted, d);
}
/// <summary>
/// Recursive SendGridInstantMessage over XMLRPC method.
/// This is called from within a dedicated thread.
/// The first time this is called, prevRegionHandle will be 0 Subsequent times this is called from
/// itself, prevRegionHandle will be the last region handle that we tried to send.
/// If the handles are the same, we look up the user's location using the grid.
/// If the handles are still the same, we end. The send failed.
/// </summary>
/// <param name="prevRegionHandle">
/// Pass in 0 the first time this method is called. It will be called recursively with the last
/// regionhandle tried
/// </param>
protected virtual void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID)
{
UUID toAgentID = new UUID(im.toAgentID);
PresenceInfo upd = null;
bool lookupAgent = false;
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
upd = new PresenceInfo();
upd.RegionID = m_UserRegionMap[toAgentID];
// We need to compare the current regionhandle with the previous region handle
// or the recursive loop will never end because it will never try to lookup the agent again
if (prevRegionID == upd.RegionID)
{
lookupAgent = true;
}
}
else
{
lookupAgent = true;
}
}
// Are we needing to look-up an agent?
if (lookupAgent)
{
// Non-cached user agent lookup.
PresenceInfo[] presences = PresenceService.GetAgents(new string[] { toAgentID.ToString() });
if (presences != null && presences.Length > 0)
{
foreach (PresenceInfo p in presences)
{
if (p.RegionID != UUID.Zero)
{
upd = p;
break;
}
}
}
if (upd != null)
{
// check if we've tried this before..
// This is one way to end the recursive loop
//
if (upd.RegionID == prevRegionID)
{
// m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
HandleUndeliveredMessage(im, result);
return;
}
}
else
{
// m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
HandleUndeliveredMessage(im, result);
return;
}
}
if (upd != null)
{
GridRegion reginfo = m_Scenes[0].GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID,
upd.RegionID);
if (reginfo != null)
{
Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im);
// Not actually used anymore, left in for compatibility
// Remove at next interface change
//
msgdata["region_handle"] = 0;
bool imresult = doIMSending(reginfo, msgdata);
if (imresult)
{
// IM delivery successful, so store the Agent's location in our local cache.
lock (m_UserRegionMap)
{
if (m_UserRegionMap.ContainsKey(toAgentID))
{
m_UserRegionMap[toAgentID] = upd.RegionID;
}
else
{
m_UserRegionMap.Add(toAgentID, upd.RegionID);
}
}
result(true);
}
else
{
// try again, but lookup user this time.
// Warning, this must call the Async version
// of this method or we'll be making thousands of threads
// The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
// The version that spawns the thread is SendGridInstantMessageViaXMLRPC
// This is recursive!!!!!
SendGridInstantMessageViaXMLRPCAsync(im, result,
upd.RegionID);
}
}
else
{
m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", upd.RegionID);
HandleUndeliveredMessage(im, result);
}
}
else
{
HandleUndeliveredMessage(im, result);
}
}
private void HandleUndeliveredMessage(GridInstantMessage im, MessageResultNotification result)
{
UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage;
// If this event has handlers, then an IM from an agent will be
// considered delivered. This will suppress the error message.
//
if (handlerUndeliveredMessage != null)
{
handlerUndeliveredMessage(im);
if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
result(true);
else
result(false);
return;
}
//m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable");
result(false);
}
/// <summary>
/// Get ulong region handle for region by it's Region UUID.
/// We use region handles over grid comms because there's all sorts of free and cool caching.
/// </summary>
/// <param name="regionID">UUID of region to get the region handle for</param>
/// <returns></returns>
// private virtual ulong getLocalRegionHandleFromUUID(UUID regionID)
// {
// ulong returnhandle = 0;
//
// lock (m_Scenes)
// {
// foreach (Scene sn in m_Scenes)
// {
// if (sn.RegionInfo.RegionID == regionID)
// {
// returnhandle = sn.RegionInfo.RegionHandle;
// break;
// }
// }
// }
// return returnhandle;
// }
}
}
| |
// 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.IO;
using System.Linq;
using Microsoft.Win32;
using osu.Framework.Allocation;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Platform.Windows;
using osu.Framework.Threading;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Legacy;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Rulesets;
using osu.Game.Tournament.Models;
namespace osu.Game.Tournament.IPC
{
public class FileBasedIPC : MatchIPCInfo
{
[Resolved]
protected IAPIProvider API { get; private set; }
[Resolved]
protected RulesetStore Rulesets { get; private set; }
[Resolved]
private GameHost host { get; set; }
[Resolved]
private LadderInfo ladder { get; set; }
private int lastBeatmapId;
private ScheduledDelegate scheduled;
public Storage Storage { get; private set; }
[BackgroundDependencyLoader]
private void load()
{
LocateStableStorage();
}
public Storage LocateStableStorage()
{
scheduled?.Cancel();
Storage = null;
try
{
Storage = new StableStorage(host as DesktopGameHost);
const string file_ipc_filename = "ipc.txt";
const string file_ipc_state_filename = "ipc-state.txt";
const string file_ipc_scores_filename = "ipc-scores.txt";
const string file_ipc_channel_filename = "ipc-channel.txt";
if (Storage.Exists(file_ipc_filename))
scheduled = Scheduler.AddDelayed(delegate
{
try
{
using (var stream = Storage.GetStream(file_ipc_filename))
using (var sr = new StreamReader(stream))
{
var beatmapId = int.Parse(sr.ReadLine());
var mods = int.Parse(sr.ReadLine());
if (lastBeatmapId != beatmapId)
{
lastBeatmapId = beatmapId;
var existing = ladder.CurrentMatch.Value?.Round.Value?.Beatmaps.FirstOrDefault(b => b.ID == beatmapId && b.BeatmapInfo != null);
if (existing != null)
Beatmap.Value = existing.BeatmapInfo;
else
{
var req = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = beatmapId });
req.Success += b => Beatmap.Value = b.ToBeatmap(Rulesets);
API.Queue(req);
}
}
Mods.Value = (LegacyMods)mods;
}
}
catch
{
// file might be in use.
}
try
{
using (var stream = Storage.GetStream(file_ipc_channel_filename))
using (var sr = new StreamReader(stream))
{
ChatChannel.Value = sr.ReadLine();
}
}
catch (Exception)
{
// file might be in use.
}
try
{
using (var stream = Storage.GetStream(file_ipc_state_filename))
using (var sr = new StreamReader(stream))
{
State.Value = (TourneyState)Enum.Parse(typeof(TourneyState), sr.ReadLine());
}
}
catch (Exception)
{
// file might be in use.
}
try
{
using (var stream = Storage.GetStream(file_ipc_scores_filename))
using (var sr = new StreamReader(stream))
{
Score1.Value = int.Parse(sr.ReadLine());
Score2.Value = int.Parse(sr.ReadLine());
}
}
catch (Exception)
{
// file might be in use.
}
}, 250, true);
}
catch (Exception e)
{
Logger.Error(e, "Stable installation could not be found; disabling file based IPC");
}
return Storage;
}
/// <summary>
/// A method of accessing an osu-stable install in a controlled fashion.
/// </summary>
private class StableStorage : WindowsStorage
{
protected override string LocateBasePath()
{
bool checkExists(string p)
{
return File.Exists(Path.Combine(p, "ipc.txt"));
}
string stableInstallPath = string.Empty;
try
{
try
{
stableInstallPath = "G:\\My Drive\\Main\\osu!tourney";
if (checkExists(stableInstallPath))
return stableInstallPath;
stableInstallPath = "G:\\My Drive\\Main\\osu!mappool";
if (checkExists(stableInstallPath))
return stableInstallPath;
}
catch
{
}
try
{
using (RegistryKey key = Registry.ClassesRoot.OpenSubKey("osu"))
stableInstallPath = key?.OpenSubKey(@"shell\open\command")?.GetValue(String.Empty).ToString().Split('"')[1].Replace("osu!.exe", "");
if (checkExists(stableInstallPath))
return stableInstallPath;
}
catch
{
}
stableInstallPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"osu!");
if (checkExists(stableInstallPath))
return stableInstallPath;
stableInstallPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".osu");
if (checkExists(stableInstallPath))
return stableInstallPath;
return null;
}
finally
{
Logger.Log($"Stable path for tourney usage: {stableInstallPath}");
}
}
public StableStorage(DesktopGameHost host)
: base(string.Empty, host)
{
}
}
}
}
| |
//
// Copyright (C) 2017, NinjaTrader LLC <www.ninjatrader.com>.
// NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
//
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion
// This namespace holds indicators in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Indicators
{
/// <summary>
/// The MACD (Moving Average Convergence/Divergence) is a trend following momentum indicator
/// that shows the relationship between two moving averages of prices.
/// </summary>
public class MyMACD : Indicator
{
private Series<double> fastEma;
private Series<double> slowEma;
private double constant1;
private double constant2;
private double constant3;
private double constant4;
private double constant5;
private double constant6;
private LinReg rl10, rl30;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = "My MACD";
Name = "My MACD";
Fast = 12;
IsSuspendedWhileInactive = true;
Slow = 26;
Smooth = 9;
AddPlot(Brushes.DarkCyan, NinjaTrader.Custom.Resource.NinjaScriptIndicatorNameMACD);
AddPlot(Brushes.Crimson, NinjaTrader.Custom.Resource.NinjaScriptIndicatorAvg);
AddPlot(new Stroke(Brushes.DodgerBlue, 2), PlotStyle.Bar, NinjaTrader.Custom.Resource.NinjaScriptIndicatorDiff);
AddLine(Brushes.DarkGray, 0, NinjaTrader.Custom.Resource.NinjaScriptIndicatorZeroLine);
}
else if (State == State.Configure)
{
constant1 = 2.0 / (1 + Fast);
constant2 = (1 - (2.0 / (1 + Fast)));
constant3 = 2.0 / (1 + Slow);
constant4 = (1 - (2.0 / (1 + Slow)));
constant5 = 2.0 / (1 + Smooth);
constant6 = (1 - (2.0 / (1 + Smooth)));
}
else if (State == State.DataLoaded)
{
fastEma = new Series<double>(this);
slowEma = new Series<double>(this);
rl10 = LinReg(10);
rl30 = LinReg(30);
}
}
protected override void OnBarUpdate()
{
double input0 = Input[0];
if (CurrentBar == 0)
{
fastEma[0] = input0;
slowEma[0] = input0;
Value[0] = 0;
Avg[0] = 0;
Diff[0] = 0;
}
else
{
double fastEma0 = constant1 * input0 + constant2 * fastEma[1];
double slowEma0 = constant3 * input0 + constant4 * slowEma[1];
double macd = fastEma0 - slowEma0;
double macdAvg = constant5 * macd + constant6 * Avg[1];
fastEma[0] = fastEma0;
slowEma[0] = slowEma0;
Value[0] = macd;
Avg[0] = macdAvg;
// Diff[0] = macd - macdAvg;
Diff[0] = rl10[0] - rl30[0];
}
}
#region Properties
[Browsable(false)]
[XmlIgnore]
public Series<double> Avg
{
get { return Values[1]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> Default
{
get { return Values[0]; }
}
[Browsable(false)]
[XmlIgnore]
public Series<double> Diff
{
get { return Values[2]; }
}
[Range(1, int.MaxValue), NinjaScriptProperty]
[Display(ResourceType = typeof(Custom.Resource), Name = "Fast", GroupName = "NinjaScriptParameters", Order = 0)]
public int Fast
{ get; set; }
[Range(1, int.MaxValue), NinjaScriptProperty]
[Display(ResourceType = typeof(Custom.Resource), Name = "Slow", GroupName = "NinjaScriptParameters", Order = 1)]
public int Slow
{ get; set; }
[Range(1, int.MaxValue), NinjaScriptProperty]
[Display(ResourceType = typeof(Custom.Resource), Name = "Smooth", GroupName = "NinjaScriptParameters", Order = 2)]
public int Smooth
{ get; set; }
#endregion
}
}
#region NinjaScript generated code. Neither change nor remove.
namespace NinjaTrader.NinjaScript.Indicators
{
public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
{
private MyMACD[] cacheMyMACD;
public MyMACD MyMACD(int fast, int slow, int smooth)
{
return MyMACD(Input, fast, slow, smooth);
}
public MyMACD MyMACD(ISeries<double> input, int fast, int slow, int smooth)
{
if (cacheMyMACD != null)
for (int idx = 0; idx < cacheMyMACD.Length; idx++)
if (cacheMyMACD[idx] != null && cacheMyMACD[idx].Fast == fast && cacheMyMACD[idx].Slow == slow && cacheMyMACD[idx].Smooth == smooth && cacheMyMACD[idx].EqualsInput(input))
return cacheMyMACD[idx];
return CacheIndicator<MyMACD>(new MyMACD(){ Fast = fast, Slow = slow, Smooth = smooth }, input, ref cacheMyMACD);
}
}
}
namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
{
public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
{
public Indicators.MyMACD MyMACD(int fast, int slow, int smooth)
{
return indicator.MyMACD(Input, fast, slow, smooth);
}
public Indicators.MyMACD MyMACD(ISeries<double> input , int fast, int slow, int smooth)
{
return indicator.MyMACD(input, fast, slow, smooth);
}
}
}
namespace NinjaTrader.NinjaScript.Strategies
{
public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
{
public Indicators.MyMACD MyMACD(int fast, int slow, int smooth)
{
return indicator.MyMACD(Input, fast, slow, smooth);
}
public Indicators.MyMACD MyMACD(ISeries<double> input , int fast, int slow, int smooth)
{
return indicator.MyMACD(input, fast, slow, smooth);
}
}
}
#endregion
| |
/*++
Copyright (c) 2004 Microsoft Corporation
Module Name:
testobj.cs
Abstract:
Exposes test hooks.
Only present in TESTHOOK builds.
History:
06-May-2004 MattRim Created
--*/
#if TESTHOOK
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Globalization;
namespace System.DirectoryServices.AccountManagement
{
public class TestHook
{
static public void TestADStoreKeys()
{
// GUID-based ADStoreKeys
Guid adGuid1 = Guid.NewGuid();
Guid adGuid2 = Guid.NewGuid();
ADStoreKey key1a = new ADStoreKey(adGuid1);
ADStoreKey key1b = new ADStoreKey(adGuid1);
ADStoreKey key2 = new ADStoreKey(adGuid2);
Debug.Assert(key1a.Equals(key1b));
Debug.Assert(!key1a.Equals(key2));
Debug.Assert(key1a.GetHashCode() == key1b.GetHashCode());
Debug.Assert(key1a.GetHashCode() != key2.GetHashCode());
// SID-based ADStoreKeys
string mach1 = "machine1";
string mach1a = "machine1";
string mach2 = "machine2";
byte[] sid1a = new byte[]{0x1, 0x2, 0x3};
byte[] sid1b = new byte[]{0x1, 0x2, 0x3};
byte[] sid2 = new byte[]{0x10, 0x20, 0x30};
ADStoreKey key3a = new ADStoreKey(mach1, sid1a);
ADStoreKey key3b = new ADStoreKey(mach1, sid1a);
ADStoreKey key3c = new ADStoreKey(mach1a, sid1b);
ADStoreKey key4 = new ADStoreKey(mach2, sid2);
ADStoreKey key5 = new ADStoreKey(mach1, sid2);
Debug.Assert(key3a.Equals(key3b));
Debug.Assert(key3a.Equals(key3c));
Debug.Assert(!key3a.Equals(key4));
Debug.Assert(!key3a.Equals(key5));
Debug.Assert(!key3a.Equals(key1a));
Debug.Assert(!key1a.Equals(key3a));
Debug.Assert(key3a.GetHashCode() != key4.GetHashCode());
// Shouldn't matter, since SAMStoreKey should make a copy of the byte[] sid
sid1b[1] = 0xf;
Debug.Assert(key3a.Equals(key3b));
Debug.Assert(key3a.Equals(key3c));
}
static public void TestSAMStoreKeys()
{
string mach1 = "machine1";
string mach1a = "machine1";
string mach2 = "machine2";
byte[] sid1a = new byte[]{0x1, 0x2, 0x3};
byte[] sid1b = new byte[]{0x1, 0x2, 0x3};
byte[] sid2 = new byte[]{0x10, 0x20, 0x30};
SAMStoreKey key1a = new SAMStoreKey(mach1, sid1a);
SAMStoreKey key1b = new SAMStoreKey(mach1, sid1a);
SAMStoreKey key1c = new SAMStoreKey(mach1a, sid1b);
SAMStoreKey key2 = new SAMStoreKey(mach2, sid2);
SAMStoreKey key3 = new SAMStoreKey(mach1, sid2);
Debug.Assert(key1a.Equals(key1b));
Debug.Assert(key1a.Equals(key1c));
Debug.Assert(!key1a.Equals(key2));
Debug.Assert(!key1a.Equals(key3));
Debug.Assert(key1a.GetHashCode() != key2.GetHashCode());
// Shouldn't matter, since SAMStoreKey should make a copy of the byte[] sid
sid1b[1] = 0xf;
Debug.Assert(key1a.Equals(key1b));
Debug.Assert(key1a.Equals(key1c));
}
//
// ValueCollection
//
static public PrincipalValueCollection<T> ValueCollectionConstruct<T>()
{
return new PrincipalValueCollection<T>();
}
static public void ValueCollectionLoad<T>(PrincipalValueCollection<T> trackList, List<T> initial)
{
trackList.Load(initial);
}
static public List<T> ValueCollectionInserted<T>(PrincipalValueCollection<T> trackList)
{
return trackList.Inserted;
}
static public List<T> ValueCollectionRemoved<T>(PrincipalValueCollection<T> trackList)
{
return trackList.Removed;
}
static public List<T> ValueCollectionChangedValues<T>(PrincipalValueCollection<T> trackList, out List<T> rightOut)
{
// We'd like to just return the List<Pair<T,T>>, but Pair<T,T> isn't a public class
List<T> left = new List<T>();
List<T> right = new List<T>();
List<Pair<T,T>> pairList = trackList.ChangedValues;
foreach (Pair<T,T> pair in pairList)
{
left.Add(pair.Left);
right.Add(pair.Right);
}
rightOut = right;
return left;
}
static public bool ValueCollectionChanged<T>(PrincipalValueCollection<T> trackList)
{
return trackList.Changed;
}
static public void ValueCollectionResetTracking<T>(PrincipalValueCollection<T> trackList)
{
trackList.ResetTracking();
}
//
// IdentityClaimCollection
//
static public IdentityClaimCollection ICCConstruct()
{
Group g = new Group();
return new IdentityClaimCollection(g);
}
static public IdentityClaimCollection ICCConstruct2()
{
Group g = new Group();
g.Context = PrincipalContext.Test;
return new IdentityClaimCollection(g);
}
static public IdentityClaimCollection ICCConstructAlt()
{
Group g = new Group();
g.Context = PrincipalContext.TestAltValidation;
return new IdentityClaimCollection(g);
}
static public IdentityClaimCollection ICCConstructNoTimeLimited()
{
Group g = new Group();
g.Context = PrincipalContext.TestNoTimeLimited;
return new IdentityClaimCollection(g);
}
static public void ICCLoad(IdentityClaimCollection trackList, List<IdentityClaim> initial)
{
trackList.Load(initial);
}
static public List<IdentityClaim> ICCInserted(IdentityClaimCollection trackList)
{
return trackList.Inserted;
}
static public List<IdentityClaim> ICCRemoved(IdentityClaimCollection trackList)
{
return trackList.Removed;
}
static public List<IdentityClaim> ICCChangedValues(IdentityClaimCollection trackList, out List<IdentityClaim> rightOut)
{
// We'd like to just return the List<Pair<T,T>>, but Pair<T,T> isn't a public class
List<IdentityClaim> left = new List<IdentityClaim>();
List<IdentityClaim> right = new List<IdentityClaim>();
List<Pair<IdentityClaim,IdentityClaim>> pairList = trackList.ChangedValues;
foreach (Pair<IdentityClaim,IdentityClaim> pair in pairList)
{
left.Add(pair.Left);
right.Add(pair.Right);
}
rightOut = right;
return left;
}
static public bool ICCChanged(IdentityClaimCollection trackList)
{
return trackList.Changed;
}
static public void ICCResetTracking(IdentityClaimCollection trackList)
{
trackList.ResetTracking();
}
//
// PrincipalCollection
//
static public Group MakeAGroup(string s)
{
Group g = new Group(PrincipalContext.Test);
g.DisplayName = s;
g.Key = new TestStoreKey(s);
return g;
}
static public PrincipalCollection MakePrincipalCollection()
{
BookmarkableResultSet rs = PrincipalContext.Test.QueryCtx.GetGroupMembership(null, false);
PrincipalCollection mc = new PrincipalCollection(rs, new Group());
return mc;
}
static public List<Principal> MCInserted(PrincipalCollection trackList)
{
return trackList.Inserted;
}
static public List<Principal> MCRemoved(PrincipalCollection trackList)
{
return trackList.Removed;
}
static public bool MCChanged(PrincipalCollection trackList)
{
return trackList.Changed;
}
static public void MCResetTracking(PrincipalCollection trackList)
{
trackList.ResetTracking();
}
//
// AuthenticablePrincipal
//
static public User APGetNoninsertedAP()
{
User u = new User(PrincipalContext.Test);
u.unpersisted = false;
return u;
}
static public void APInitNested(AuthenticablePrincipal ap)
{
ap.LoadValueIntoProperty(PropertyNames.PwdInfoCannotChangePassword, true);
ap.LoadValueIntoProperty(PropertyNames.AcctInfoBadLogonCount, 3);
}
static public void APLoadValue(AuthenticablePrincipal ap, string name, object value)
{
ap.LoadValueIntoProperty(name, value);
}
static public bool APGetChangeStatus(AuthenticablePrincipal ap, string name)
{
return ap.GetChangeStatusForProperty(name);
}
static public object APGetValue(AuthenticablePrincipal ap, string name)
{
return ap.GetValueForProperty(name);
}
static public void APResetChanges(AuthenticablePrincipal ap)
{
ap.ResetAllChangeStatus();
}
//
// PasswordInfo
//
static public PasswordInfo ExtractPI(AuthenticablePrincipal ap)
{
Type t = typeof(AuthenticablePrincipal);
return (PasswordInfo) t.InvokeMember(
"PasswordInfo",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty,
null,
ap,
new object[]{},
CultureInfo.InvariantCulture);
}
static public void PILoadValue(PasswordInfo pi, string name, object value)
{
pi.LoadValueIntoProperty(name, value);
}
static public bool PIGetChangeStatus(PasswordInfo pi, string name)
{
return pi.GetChangeStatusForProperty(name);
}
static public object PIGetValue(PasswordInfo pi, string name)
{
return pi.GetValueForProperty(name);
}
static public void PIResetChanges(PasswordInfo pi)
{
pi.ResetAllChangeStatus();
}
//
// AccountInfo
//
static public AccountInfo ExtractAI(AuthenticablePrincipal ap)
{
Type t = typeof(AuthenticablePrincipal);
return (AccountInfo) t.InvokeMember(
"AccountInfo",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty,
null,
ap,
new object[]{},
CultureInfo.InvariantCulture);
}
static public void AILoadValue(AccountInfo ai, string name, object value)
{
ai.LoadValueIntoProperty(name, value);
}
static public bool AIGetChangeStatus(AccountInfo ai, string name)
{
return ai.GetChangeStatusForProperty(name);
}
static public object AIGetValue(AccountInfo ai, string name)
{
return ai.GetValueForProperty(name);
}
static public void AIResetChanges(AccountInfo ai)
{
ai.ResetAllChangeStatus();
}
//
// User
//
static public void UserLoadValue(User u, string name, object value)
{
u.LoadValueIntoProperty(name, value);
}
static public bool UserGetChangeStatus(User u, string name)
{
return u.GetChangeStatusForProperty(name);
}
static public object UserGetValue(User u, string name)
{
return u.GetValueForProperty(name);
}
static public void UserResetChanges(User u)
{
u.ResetAllChangeStatus();
}
static public Group GroupGetNonInsertedGroup()
{
Group g = new Group(PrincipalContext.Test);
g.unpersisted = false;
return g;
}
//
// Computer
//
static public void ComputerLoadValue(Computer computer, string name, object value)
{
computer.LoadValueIntoProperty(name, value);
}
static public bool ComputerGetChangeStatus(Computer computer, string name)
{
return computer.GetChangeStatusForProperty(name);
}
static public object ComputerGetValue(Computer computer, string name)
{
return computer.GetValueForProperty(name);
}
static public void ComputerResetChanges(Computer computer)
{
computer.ResetAllChangeStatus();
}
//
// QBE
//
static public void BuildQbeFilter(Principal p)
{
PrincipalContext ctx = PrincipalContext.Test;
((TestStoreCtx)ctx.QueryCtx).CallBuildQbeFilterDescription(p);
}
}
}
#endif // TESTHOOK
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
namespace System.Globalization {
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StringInfo
{
[OptionalField(VersionAdded = 2)]
private String m_str;
// We allow this class to be serialized but there is no conceivable reason
// for them to do so. Thus, we do not serialize the instance variables.
[NonSerialized] private int[] m_indexes;
// Legacy constructor
public StringInfo() : this(""){}
// Primary, useful constructor
public StringInfo(String value) {
this.String = value;
}
#region Serialization
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
m_str = String.Empty;
}
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
if (m_str.Length == 0)
{
m_indexes = null;
}
}
#endregion Serialization
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object value)
{
StringInfo that = value as StringInfo;
if (that != null)
{
return (this.m_str.Equals(that.m_str));
}
return (false);
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
return this.m_str.GetHashCode();
}
// Our zero-based array of index values into the string. Initialize if
// our private array is not yet, in fact, initialized.
private int[] Indexes {
get {
if((null == this.m_indexes) && (0 < this.String.Length)) {
this.m_indexes = StringInfo.ParseCombiningCharacters(this.String);
}
return(this.m_indexes);
}
}
public String String {
get {
return(this.m_str);
}
set {
if (null == value) {
throw new ArgumentNullException("String",
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
this.m_str = value;
this.m_indexes = null;
}
}
public int LengthInTextElements {
get {
if(null == this.Indexes) {
// Indexes not initialized, so assume length zero
return(0);
}
return(this.Indexes.Length);
}
}
public String SubstringByTextElements(int startingTextElement) {
// If the string is empty, no sense going further.
if(null == this.Indexes) {
// Just decide which error to give depending on the param they gave us....
if(startingTextElement < 0) {
throw new ArgumentOutOfRangeException("startingTextElement",
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
else {
throw new ArgumentOutOfRangeException("startingTextElement",
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
}
return (this.SubstringByTextElements(startingTextElement, this.Indexes.Length - startingTextElement));
}
public String SubstringByTextElements(int startingTextElement, int lengthInTextElements) {
//
// Parameter checking
//
if(startingTextElement < 0) {
throw new ArgumentOutOfRangeException("startingTextElement",
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) {
throw new ArgumentOutOfRangeException("startingTextElement",
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
if(lengthInTextElements < 0) {
throw new ArgumentOutOfRangeException("lengthInTextElements",
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
if(startingTextElement > this.Indexes.Length - lengthInTextElements) {
throw new ArgumentOutOfRangeException("lengthInTextElements",
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
int start = this.Indexes[startingTextElement];
if(startingTextElement + lengthInTextElements == this.Indexes.Length) {
// We are at the last text element in the string and because of that
// must handle the call differently.
return(this.String.Substring(start));
}
else {
return(this.String.Substring(start, (this.Indexes[lengthInTextElements + startingTextElement] - start)));
}
}
public static String GetNextTextElement(String str)
{
return (GetNextTextElement(str, 0));
}
////////////////////////////////////////////////////////////////////////
//
// Get the code point count of the current text element.
//
// A combining class is defined as:
// A character/surrogate that has the following Unicode category:
// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
//
// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
//
// 1. If a character/surrogate is in the following category, it is a text element.
// It can NOT further combine with characters in the combinging class to form a text element.
// * one of the Unicode category in the combinging class
// * UnicodeCategory.Format
// * UnicodeCateogry.Control
// * UnicodeCategory.OtherNotAssigned
// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
//
// Return:
// The length of the current text element
//
// Parameters:
// String str
// index The starting index
// len The total length of str (to define the upper boundary)
// ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element.
// currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
//
////////////////////////////////////////////////////////////////////////
internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return (currentCharCount);
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext)) {
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
} else {
int startIndex = index; // Remember the current index.
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext)) {
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return (index - startIndex);
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return (ret);
}
// Returns the str containing the next text element in str starting at
// index index. If index is not supplied, then it will start at the beginning
// of str. It recognizes a base character plus one or more combining
// characters or a properly formed surrogate pair as a text element. See also
// the ParseCombiningCharacters() and the ParseSurrogates() methods.
public static String GetNextTextElement(String str, int index) {
//
// Validate parameters.
//
if (str==null) {
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || index >= len) {
if (index == len) {
return (String.Empty);
}
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
}
public static TextElementEnumerator GetTextElementEnumerator(String str)
{
return (GetTextElementEnumerator(str, 0));
}
public static TextElementEnumerator GetTextElementEnumerator(String str, int index)
{
//
// Validate parameters.
//
if (str==null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
if (index < 0 || (index > len))
{
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
return (new TextElementEnumerator(str, index, len));
}
/*
* Returns the indices of each base character or properly formed surrogate pair
* within the str. It recognizes a base character plus one or more combining
* characters or a properly formed surrogate pair as a text element and returns
* the index of the base character or high surrogate. Each index is the
* beginning of a text element within a str. The length of each element is
* easily computed as the difference between successive indices. The length of
* the array will always be less than or equal to the length of the str. For
* example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would
* return the indices: 0, 2, 4.
*/
public static int[] ParseCombiningCharacters(String str)
{
if (str == null)
{
throw new ArgumentNullException("str");
}
Contract.EndContractBlock();
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return (result);
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len) {
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, returnArray, resultCount);
return (returnArray);
}
return (result);
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.DotNet.ProjectJsonMigration
{
internal class PackageDependencyInfo
{
public string Name { get; set; }
public string Version { get; set; }
public string PrivateAssets { get; set; }
public bool IsMetaPackage
{
get
{
return !string.IsNullOrEmpty(Name) &&
(Name.Equals("Microsoft.NETCore.App", StringComparison.OrdinalIgnoreCase) ||
Name.Equals("NETStandard.Library", StringComparison.OrdinalIgnoreCase));
}
}
}
internal class SupportedPackageVersions
{
public const string SdkPackageName = "Microsoft.NET.Sdk";
public const string WebSdkPackageName = "Microsoft.NET.Sdk.Web";
public const string TestSdkPackageName = "Microsoft.NET.Test.Sdk";
public const string XUnitPackageName = "xunit";
public const string XUnitRunnerPackageName = "xunit.runner.visualstudio";
public const string MstestTestAdapterName = "MSTest.TestAdapter";
public const string MstestTestFrameworkName = "MSTest.TestFramework";
public const string NetStandardPackageName = "NETStandard.Library";
public const string NetStandardPackageVersion = "1.6.0";
public const string DotnetTestXunit = "dotnet-test-xunit";
public const string DotnetTestMSTest = "dotnet-test-mstest";
public readonly IDictionary<PackageDependencyInfo, PackageDependencyInfo> ProjectDependencyPackages;
public static readonly IDictionary<PackageDependencyInfo, PackageDependencyInfo> ProjectToolPackages =
new Dictionary<PackageDependencyInfo, PackageDependencyInfo> {
{
new PackageDependencyInfo
{
Name = "Microsoft.EntityFrameworkCore.Tools",
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = "Microsoft.EntityFrameworkCore.Tools.DotNet",
Version = ConstantPackageVersions.AspNetToolsVersion
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.EntityFrameworkCore.Tools.DotNet",
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = "Microsoft.EntityFrameworkCore.Tools.DotNet",
Version = ConstantPackageVersions.AspNetToolsVersion
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.AspNetCore.Razor.Tools",
Version = "[1.0.0-*,)"
},
null
},
{
new PackageDependencyInfo
{
Name = "Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.Tools",
Version = "[1.0.0-*,)"
},
null
},
{
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.CodeGeneration.Tools",
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = "Microsoft.VisualStudio.Web.CodeGeneration.Tools",
Version = ConstantPackageVersions.AspNetToolsVersion
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.DotNet.Watcher.Tools",
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = "Microsoft.DotNet.Watcher.Tools",
Version = ConstantPackageVersions.AspNetToolsVersion
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.Extensions.SecretManager.Tools",
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = "Microsoft.Extensions.SecretManager.Tools",
Version = ConstantPackageVersions.AspNetToolsVersion
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.AspNetCore.Server.IISIntegration.Tools",
Version = "[1.0.0-*,)"
},
null
},
{
new PackageDependencyInfo{
Name = "BundlerMinifier.Core",
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = "BundlerMinifier.Core",
Version = ConstantPackageVersions.BundleMinifierToolVersion
}
}
};
public SupportedPackageVersions()
{
ProjectDependencyPackages =
new Dictionary<PackageDependencyInfo, PackageDependencyInfo> {
{
new PackageDependencyInfo {
Name = "Microsoft.EntityFrameworkCore.Tools",
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = "Microsoft.EntityFrameworkCore.Tools",
Version = ConstantPackageVersions.AspNetToolsVersion }
},
{
new PackageDependencyInfo
{
Name = "Microsoft.AspNetCore.Razor.Tools",
Version = "[1.0.0-*,)"
},
null
},
{
new PackageDependencyInfo
{
Name = "Microsoft.AspNetCore.Razor.Design",
Version = "[1.0.0-*,)"
},
null
},
// I hate to do this, but ordering here matters. The higher version needs to come first, otherwise
// the lower version mapping will match to it.
{
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.CodeGenerators.Mvc",
Version = "[1.1.0-*,)"
},
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.CodeGeneration.Design",
Version = ConstantPackageVersions.AspNet110ToolsVersion
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.CodeGenerators.Mvc",
Version = "[1.0.0-*,1.1.0)"
},
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.CodeGeneration.Design",
Version = ConstantPackageVersions.AspNetToolsVersion
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.BrowserLink.Loader",
Version = "[14.1.0-*,)"
},
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.BrowserLink",
Version = "1.1.0"
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.BrowserLink.Loader",
Version = "[14.0.0-*,14.1.0)"
},
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.BrowserLink",
Version = "1.0.1"
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.Design",
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = "Microsoft.AspNetCore.Mvc.Razor.ViewCompilation",
Version = ConstantPackageVersions.AspNet110ToolsVersion
}
},
{
new PackageDependencyInfo
{
Name = "Microsoft.VisualStudio.Web.CodeGeneration.Tools",
Version = "[1.0.0-*,)"
},
null
},
{
new PackageDependencyInfo
{
Name = TestSdkPackageName,
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo
{
Name = TestSdkPackageName,
Version = ConstantPackageVersions.TestSdkPackageVersion
}
},
{
new PackageDependencyInfo
{
Name = XUnitPackageName,
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo
{
Name = XUnitPackageName,
Version = ConstantPackageVersions.XUnitPackageVersion
}
},
{
new PackageDependencyInfo
{
Name = XUnitRunnerPackageName,
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = XUnitRunnerPackageName,
Version = ConstantPackageVersions.XUnitRunnerPackageVersion
}
},
{
new PackageDependencyInfo
{
Name = MstestTestAdapterName,
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo
{
Name = MstestTestAdapterName,
Version = ConstantPackageVersions.MstestTestAdapterVersion
}
},
{
new PackageDependencyInfo
{
Name = MstestTestFrameworkName,
Version = "[1.0.0-*,)"
},
new PackageDependencyInfo {
Name = MstestTestFrameworkName,
Version = ConstantPackageVersions.MstestTestFrameworkVersion
}
},
{
new PackageDependencyInfo
{
Name = DotnetTestXunit,
Version = "[1.0.0-*,)"
},
null
},
{
new PackageDependencyInfo
{
Name = DotnetTestMSTest,
Version = "[1.0.0-*,)"
},
null
}
};
new DotnetSupportedPackageVersionsCsvProvider()
.AddDotnetSupportedPackageVersions(ProjectDependencyPackages);
}
}
}
| |
// 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.Text;
using System.Globalization;
using System.IO;
using System.Collections;
namespace System.Diagnostics
{
public class DelimitedListTraceListener : TextWriterTraceListener
{
private string _delimiter = ";";
private string _secondaryDelim = ",";
public DelimitedListTraceListener(Stream stream) : base(stream)
{
}
public DelimitedListTraceListener(Stream stream, string name) : base(stream, name)
{
}
public DelimitedListTraceListener(TextWriter writer) : base(writer)
{
}
public DelimitedListTraceListener(TextWriter writer, string name) : base(writer, name)
{
}
public DelimitedListTraceListener(string fileName) : base(fileName)
{
}
public DelimitedListTraceListener(string fileName, string name) : base(fileName, name)
{
}
public string Delimiter
{
get
{
return _delimiter;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(Delimiter));
if (value.Length == 0)
throw new ArgumentException(SR.Format(SR.Generic_ArgCantBeEmptyString, nameof(Delimiter)));
lock (this)
{
_delimiter = value;
}
if (_delimiter == ",")
_secondaryDelim = ";";
else
_secondaryDelim = ",";
}
}
// base class method is protected internal but since its base class is in another assembly can't override it as protected internal because a CS0507
// warning would be hitted.
protected override string[] GetSupportedAttributes() => new string[] { "delimiter" };
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null))
return;
WriteHeader(source, eventType, id);
if (args != null)
WriteEscaped(string.Format(CultureInfo.InvariantCulture, format, args));
else
WriteEscaped(format);
Write(Delimiter); // Use get_Delimiter
// one more delimiter for the data object
Write(Delimiter); // Use get_Delimiter
WriteFooter(eventCache);
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null))
return;
WriteHeader(source, eventType, id);
WriteEscaped(message);
Write(Delimiter); // Use get_Delimiter
// one more delimiter for the data object
Write(Delimiter); // Use get_Delimiter
WriteFooter(eventCache);
}
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null))
return;
WriteHeader(source, eventType, id);
// first a delimiter for the message
Write(Delimiter); // Use get_Delimiter
WriteEscaped(data.ToString());
Write(Delimiter); // Use get_Delimiter
WriteFooter(eventCache);
}
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, params object[] data)
{
if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data))
return;
WriteHeader(source, eventType, id);
// first a delimiter for the message
Write(Delimiter); // Use get_Delimiter
if (data != null)
{
for (int i = 0; i < data.Length; i++)
{
if (i != 0)
Write(_secondaryDelim);
WriteEscaped(data[i].ToString());
}
}
Write(Delimiter); // Use get_Delimiter
WriteFooter(eventCache);
}
private void WriteHeader(string source, TraceEventType eventType, int id)
{
WriteEscaped(source);
Write(Delimiter); // Use get_Delimiter
Write(eventType.ToString());
Write(Delimiter); // Use get_Delimiter
Write(id.ToString(CultureInfo.InvariantCulture));
Write(Delimiter); // Use get_Delimiter
}
private void WriteFooter(TraceEventCache eventCache)
{
if (eventCache != null)
{
if (IsEnabled(TraceOptions.ProcessId))
Write(eventCache.ProcessId.ToString(CultureInfo.InvariantCulture));
Write(Delimiter); // Use get_Delimiter
if (IsEnabled(TraceOptions.LogicalOperationStack))
WriteStackEscaped(eventCache.LogicalOperationStack);
Write(Delimiter); // Use get_Delimiter
if (IsEnabled(TraceOptions.ThreadId))
WriteEscaped(eventCache.ThreadId);
Write(Delimiter); // Use get_Delimiter
if (IsEnabled(TraceOptions.DateTime))
WriteEscaped(eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture));
Write(Delimiter); // Use get_Delimiter
if (IsEnabled(TraceOptions.Timestamp))
Write(eventCache.Timestamp.ToString(CultureInfo.InvariantCulture));
Write(Delimiter); // Use get_Delimiter
if (IsEnabled(TraceOptions.Callstack))
WriteEscaped(eventCache.Callstack);
}
else
{
for (int i = 0; i < 5; i++)
Write(Delimiter); // Use get_Delimiter
}
WriteLine("");
}
private void WriteEscaped(string message)
{
if (!string.IsNullOrEmpty(message))
{
StringBuilder sb = new StringBuilder("\"");
EscapeMessage(message, sb);
sb.Append("\"");
Write(sb.ToString());
}
}
private void WriteStackEscaped(Stack stack)
{
StringBuilder sb = new StringBuilder("\"");
bool first = true;
foreach (object obj in stack)
{
if (!first)
{
sb.Append(", ");
}
else
{
first = false;
}
string operation = obj.ToString();
EscapeMessage(operation, sb);
}
sb.Append("\"");
Write(sb.ToString());
}
private void EscapeMessage(string message, StringBuilder sb)
{
int index;
int lastindex = 0;
while ((index = message.IndexOf('"', lastindex)) != -1)
{
sb.Append(message, lastindex, index - lastindex);
sb.Append("\"\"");
lastindex = index + 1;
}
sb.Append(message, lastindex, message.Length - lastindex);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using gciv = Google.Cloud.Iam.V1;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.BigQuery.Connection.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedConnectionServiceClientTest
{
[xunit::FactAttribute]
public void CreateConnectionRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.CreateConnection(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConnectionRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.CreateConnectionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.CreateConnectionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConnection()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.CreateConnection(request.Parent, request.Connection, request.ConnectionId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConnectionAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.CreateConnectionAsync(request.Parent, request.Connection, request.ConnectionId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.CreateConnectionAsync(request.Parent, request.Connection, request.ConnectionId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateConnectionResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.CreateConnection(request.ParentAsLocationName, request.Connection, request.ConnectionId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateConnectionResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
CreateConnectionRequest request = new CreateConnectionRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
ConnectionId = "connection_id78489b28",
Connection = new Connection(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.CreateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.CreateConnectionAsync(request.ParentAsLocationName, request.Connection, request.ConnectionId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.CreateConnectionAsync(request.ParentAsLocationName, request.Connection, request.ConnectionId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnectionRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.GetConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.GetConnection(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.GetConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.GetConnectionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.GetConnectionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnection()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.GetConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.GetConnection(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.GetConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.GetConnectionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.GetConnectionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnectionResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.GetConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.GetConnection(request.ConnectionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
GetConnectionRequest request = new GetConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.GetConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.GetConnectionAsync(request.ConnectionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.GetConnectionAsync(request.ConnectionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConnectionRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.UpdateConnection(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConnectionRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.UpdateConnectionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.UpdateConnectionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConnection()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.UpdateConnection(request.Name, request.Connection, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConnectionAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.UpdateConnectionAsync(request.Name, request.Connection, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.UpdateConnectionAsync(request.Name, request.Connection, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateConnectionResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection response = client.UpdateConnection(request.ConnectionName, request.Connection, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateConnectionResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
UpdateConnectionRequest request = new UpdateConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
Connection = new Connection(),
UpdateMask = new wkt::FieldMask(),
};
Connection expectedResponse = new Connection
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
FriendlyName = "friendly_name6171e36b",
Description = "description2cf9da67",
CloudSql = new CloudSqlProperties(),
CreationTime = -5025413042314785256L,
LastModifiedTime = 1315234198627015670L,
HasCredential = true,
Aws = new AwsProperties(),
CloudSpanner = new CloudSpannerProperties(),
};
mockGrpcClient.Setup(x => x.UpdateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
Connection responseCallSettings = await client.UpdateConnectionAsync(request.ConnectionName, request.Connection, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Connection responseCancellationToken = await client.UpdateConnectionAsync(request.ConnectionName, request.Connection, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConnectionRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteConnection(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConnectionRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteConnectionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConnectionAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConnection()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteConnection(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConnectionAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteConnectionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConnectionAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteConnectionResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteConnection(request.ConnectionName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteConnectionResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
DeleteConnectionRequest request = new DeleteConnectionRequest
{
ConnectionName = ConnectionName.FromProjectLocationConnection("[PROJECT]", "[LOCATION]", "[CONNECTION]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteConnectionAsync(request.ConnectionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteConnectionAsync(request.ConnectionName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicy()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.Resource, request.Options);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, request.Options, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, request.Options, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName, request.Options);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, request.Options, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, request.Options, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicy()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request.Resource, request.Policy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, request.Policy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request.ResourceAsResourceName, request.Policy);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissions()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.Resource, request.Permissions);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsResourceNames()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.ResourceAsResourceName, request.Permissions);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsResourceNamesAsync()
{
moq::Mock<ConnectionService.ConnectionServiceClient> mockGrpcClient = new moq::Mock<ConnectionService.ConnectionServiceClient>(moq::MockBehavior.Strict);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConnectionServiceClient client = new ConnectionServiceClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Controls.ContextMenu.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
public partial class ContextMenu : System.Windows.Controls.Primitives.MenuBase
{
#region Methods and constructors
public ContextMenu()
{
}
protected virtual new void OnClosed(System.Windows.RoutedEventArgs e)
{
}
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return default(System.Windows.Automation.Peers.AutomationPeer);
}
protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
{
}
protected override void OnKeyUp(System.Windows.Input.KeyEventArgs e)
{
}
protected virtual new void OnOpened(System.Windows.RoutedEventArgs e)
{
}
protected override void OnVisualParentChanged(System.Windows.DependencyObject oldParent)
{
}
protected override void PrepareContainerForItemOverride(System.Windows.DependencyObject element, Object item)
{
}
#endregion
#region Properties and indexers
public System.Windows.Controls.Primitives.CustomPopupPlacementCallback CustomPopupPlacementCallback
{
get
{
return default(System.Windows.Controls.Primitives.CustomPopupPlacementCallback);
}
set
{
}
}
internal protected override bool HandlesScrolling
{
get
{
return default(bool);
}
}
public bool HasDropShadow
{
get
{
return default(bool);
}
set
{
}
}
public double HorizontalOffset
{
get
{
return default(double);
}
set
{
}
}
public bool IsOpen
{
get
{
return default(bool);
}
set
{
}
}
public System.Windows.Controls.Primitives.PlacementMode Placement
{
get
{
return default(System.Windows.Controls.Primitives.PlacementMode);
}
set
{
}
}
public System.Windows.Rect PlacementRectangle
{
get
{
return default(System.Windows.Rect);
}
set
{
}
}
public System.Windows.UIElement PlacementTarget
{
get
{
return default(System.Windows.UIElement);
}
set
{
}
}
public bool StaysOpen
{
get
{
return default(bool);
}
set
{
}
}
public double VerticalOffset
{
get
{
return default(double);
}
set
{
}
}
#endregion
#region Events
public event System.Windows.RoutedEventHandler Closed
{
add
{
}
remove
{
}
}
public event System.Windows.RoutedEventHandler Opened
{
add
{
}
remove
{
}
}
#endregion
#region Fields
public readonly static System.Windows.RoutedEvent ClosedEvent;
public readonly static System.Windows.DependencyProperty CustomPopupPlacementCallbackProperty;
public readonly static System.Windows.DependencyProperty HasDropShadowProperty;
public readonly static System.Windows.DependencyProperty HorizontalOffsetProperty;
public readonly static System.Windows.DependencyProperty IsOpenProperty;
public readonly static System.Windows.RoutedEvent OpenedEvent;
public readonly static System.Windows.DependencyProperty PlacementProperty;
public readonly static System.Windows.DependencyProperty PlacementRectangleProperty;
public readonly static System.Windows.DependencyProperty PlacementTargetProperty;
public readonly static System.Windows.DependencyProperty StaysOpenProperty;
public readonly static System.Windows.DependencyProperty VerticalOffsetProperty;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// System.Array.LastIndexOf<>(T[],T)
/// </summary>
public class ArrayIndexOf2
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Find out the last value which is equal to 3");
try
{
int length = TestLibrary.Generator.GetInt16(-55);
int[] i1 = new int[length];
for (int i = 0; i < length; i++)
{
if (i % 3 == 0)
{
i1[i] = 3;
}
else
{
i1[i] = i;
}
}
for (int a = length - 1; a > length - 4; a--)
{
if (a % 3 == 0)
{
int i2 = Array.LastIndexOf<int>(i1, 3);
if (i2 != a)
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected ");
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Find the last string value in an array ");
try
{
string[] s1 = new string[5]{"Jack",
"Mary",
"Mike",
"Peter",
"Jack"};
if (Array.LastIndexOf<string>(s1, "Jack") != 4)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Find out the null element in an array of string ");
try
{
string[] s1 = new string[7]{"Jack",
"Mary",
"Mike",
null,
"Peter",
null,
"Jack"};
if (Array.LastIndexOf<string>(s1, null) != 5)
{
TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Find out no expected value in an array of string ");
try
{
string[] s1 = new string[5]{"Jack",
"Mary",
"Mike",
"Peter",
"Jack"};
if (Array.LastIndexOf<string>(s1, "Tom") != -1)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest5: Find out the last empty string ");
try
{
string[] s1 = new string[5]{"",
"",
"",
"",
"Tom"};
if (Array.LastIndexOf<string>(s1, "") != 3)
{
TestLibrary.TestFramework.LogError("007", "The result is not the value as expected");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The array is a null reference");
try
{
string[] s1 = null;
int i1 = Array.LastIndexOf<string>(s1, "");
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not thrown as expected ");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ArrayIndexOf2 test = new ArrayIndexOf2();
TestLibrary.TestFramework.BeginTestCase("ArrayIndexOf2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Sequence(Name = "DataParameters", IsSet = false)]
public class DataParameters : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DataParameters));
private long bcd_;
private bool bcd_present;
private bool binary_time_;
private bool binary_time_present;
private long bit_string_;
private bool bit_string_present;
private Floating_pointSequenceType floating_point_;
private bool floating_point_present;
private long integer_;
private bool integer_present;
private long mmsString_;
private bool mmsString_present;
private long octet_string_;
private bool octet_string_present;
private long unsigned_;
private bool unsigned_present;
private long visible_string_;
private bool visible_string_present;
[ASN1Integer(Name = "")]
[ASN1Element(Name = "bit-string", IsOptional = true, HasTag = true, Tag = 0, HasDefaultValue = false)]
public long Bit_string
{
get
{
return bit_string_;
}
set
{
bit_string_ = value;
bit_string_present = true;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "integer", IsOptional = true, HasTag = true, Tag = 1, HasDefaultValue = false)]
public long Integer
{
get
{
return integer_;
}
set
{
integer_ = value;
integer_present = true;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "unsigned", IsOptional = true, HasTag = true, Tag = 2, HasDefaultValue = false)]
public long Unsigned
{
get
{
return unsigned_;
}
set
{
unsigned_ = value;
unsigned_present = true;
}
}
[ASN1Element(Name = "floating-point", IsOptional = true, HasTag = true, Tag = 3, HasDefaultValue = false)]
public Floating_pointSequenceType Floating_point
{
get
{
return floating_point_;
}
set
{
floating_point_ = value;
floating_point_present = true;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "octet-string", IsOptional = true, HasTag = true, Tag = 10, HasDefaultValue = false)]
public long Octet_string
{
get
{
return octet_string_;
}
set
{
octet_string_ = value;
octet_string_present = true;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "visible-string", IsOptional = true, HasTag = true, Tag = 11, HasDefaultValue = false)]
public long Visible_string
{
get
{
return visible_string_;
}
set
{
visible_string_ = value;
visible_string_present = true;
}
}
[ASN1Boolean(Name = "")]
[ASN1Element(Name = "binary-time", IsOptional = true, HasTag = true, Tag = 12, HasDefaultValue = false)]
public bool Binary_time
{
get
{
return binary_time_;
}
set
{
binary_time_ = value;
binary_time_present = true;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "bcd", IsOptional = true, HasTag = true, Tag = 13, HasDefaultValue = false)]
public long Bcd
{
get
{
return bcd_;
}
set
{
bcd_ = value;
bcd_present = true;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "mmsString", IsOptional = true, HasTag = true, Tag = 14, HasDefaultValue = false)]
public long MmsString
{
get
{
return mmsString_;
}
set
{
mmsString_ = value;
mmsString_present = true;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isBit_stringPresent()
{
return bit_string_present;
}
public bool isIntegerPresent()
{
return integer_present;
}
public bool isUnsignedPresent()
{
return unsigned_present;
}
public bool isFloating_pointPresent()
{
return floating_point_present;
}
public bool isOctet_stringPresent()
{
return octet_string_present;
}
public bool isVisible_stringPresent()
{
return visible_string_present;
}
public bool isBinary_timePresent()
{
return binary_time_present;
}
public bool isBcdPresent()
{
return bcd_present;
}
public bool isMmsStringPresent()
{
return mmsString_present;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "floating-point", IsSet = false)]
public class Floating_pointSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Floating_pointSequenceType));
private long exponent_;
private long total_;
[ASN1Integer(Name = "")]
[ASN1Element(Name = "total", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)]
public long Total
{
get
{
return total_;
}
set
{
total_ = value;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "exponent", IsOptional = false, HasTag = true, Tag = 5, HasDefaultValue = false)]
public long Exponent
{
get
{
return exponent_;
}
set
{
exponent_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
}
}
| |
/**
* Generic tokenizer used by the parser in the Syntax tool.
*
* https://www.npmjs.com/package/syntax-cli
*
* See `--custom-tokinzer` to skip this generation, and use a custom one.
*/
/* These should be inserted by yyparse already:
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Reflection;
*/
namespace SyntaxParser
{
// --------------------------------------------
// Tokenizer.
/**
* Token class: encapsulates token type, and the matched value.
*/
public class Token
{
// Basic data.
public int Type;
public string Value;
// Location data.
public int StartOffset;
public int EndOffset;
public int StartLine;
public int EndLine;
public int StartColumn;
public int EndColumn;
public Token(int type, string value) :
// Special token with no location data (e.g. EOF).
this(type, value, 0, 0, 0, 0, 0, 0) {}
public Token(int type, string value, int startOffset,
int endOffset, int startLine, int endLine,
int startColumn, int endColumn)
{
Type = type;
Value = value;
StartOffset = startOffset;
EndOffset = endOffset;
StartLine = startLine;
EndLine = endLine;
StartColumn = startColumn;
EndColumn = endColumn;
}
}
/**
* Regexp-based tokenizer. Applies lexical rules in order, until gets
* a match; otherwise, throws the "Unexpected token" exception.
*
* Tokenizer should implement at least the following API:
*
* - getNextToken(): Token
* - hasMoreTokens(): boolean
* - isEOF(): boolean
*
* For state-based tokenizer, also:
*
* - getCurrentState(): number
* - pushState(string stateName): void
* - popState(): void
* - begin(string stateName): void - alias for pushState
*/
public class Tokenizer
{
/**
* Tokenizing string.
*/
private string mString;
/**
* Maps a string name of a token type to its encoded number (the first
* token number starts after all numbers for non-terminal).
*
* Example (assuming non-terminals reserved numbers 1-4, so token
* numbers start from 5):
*
* {"+", 5},
* {"*", 6},
* {"NUMBER", 7},
* {yyparse.EOF, 8},
*/
private static Dictionary<string, int> mTokensMap = new Dictionary<string, int>()
{{{TOKENS}}};
public static Token EOF_TOKEN = new Token(
mTokensMap[yyparse.EOF],
yyparse.EOF
);
/**
* Lex rules, and their handler names.
*
* Example:
*
* {
* new string[] {@"^\s+", "_lexRule1"},
* new string[] {@"^\d+", "_lexRule2"},
* }
*
*/
private static string[][] mLexRules = {{{LEX_RULES}}};
/**
* Lex rules grouped by tokenizer state.
*
* Example:
*
* {
* { "INITIAL", new int[] { 0, 1, 2, 3 } },
* }
*/
private static Dictionary<string, int[]> mLexRulesByConditions = new Dictionary<string, int[]>()
{{{LEX_RULES_BY_START_CONDITIONS}}};
/**
* Stack of lexer states.
*/
private Stack<string> mStates = null;
/**
* Cursor tracking current position.
*/
private int mCursor = 0;
/**
* Line-based location tracking.
*/
int mCurrentLine;
int mCurrentColumn;
int mCurrentLineBeginOffset;
/**
* Location data of a matched token.
*/
int mTokenStartOffset;
int mTokenEndOffset;
int mTokenStartLine;
int mTokenEndLine;
int mTokenStartColumn;
int mTokenEndColumn;
/**
* In case if a token handler returns multiple tokens from one rule,
* we still return tokens one by one in the `getNextToken`, putting
* other "fake" tokens into the queue. If there is still something in
* this queue, it's just returned.
*/
private Queue<string> mTokensQueue = null;
/**
* Lex rule handlers.
*
* Example:
*
* public string _lexRule1()
* {
* // skip whitespace
* return null;
* }
*
* public string _lexRule2()
* {
* return "NUMBER";
* }
*/
{{{LEX_RULE_HANDLERS}}}
// --------------------------------------------
// Constructor.
public Tokenizer()
{
//
}
public Tokenizer(string tokenizingString)
{
initString(tokenizingString);
}
public void initString(string tokenizingString)
{
mString = tokenizingString;
mCursor = 0;
mStates = new Stack<string>();
begin("INITIAL");
mTokensQueue = new Queue<string>();
// Init locations.
mCurrentLine = 1;
mCurrentColumn = 0;
mCurrentLineBeginOffset = 0;
// Token locationis.
mTokenStartOffset = 0;
mTokenEndOffset = 0;
mTokenStartLine = 0;
mTokenEndLine = 0;
mTokenStartColumn = 0;
mTokenEndColumn = 0;
}
// --------------------------------------------
// States.
public string getCurrentState()
{
return mStates.Peek();
}
public void pushState(string state)
{
mStates.Push(state);
}
public void begin(string state)
{
pushState(state);
}
public string popState()
{
if (mStates.Count > 1)
{
return mStates.Pop();
}
return getCurrentState();
}
// --------------------------------------------
// Tokenizing.
public Token getNextToken()
{
// Something was queued, return it.
if (mTokensQueue.Count > 0)
{
return toToken(mTokensQueue.Dequeue(), "");
}
if (!hasMoreTokens())
{
return EOF_TOKEN;
}
var str = mString.Substring(mCursor);
var lexRulesForState = mLexRulesByConditions[getCurrentState()];
for (int i = 0; i < lexRulesForState.Length; i++)
{
var lexRule = mLexRules[i];
var matched = match(str, new Regex(lexRule[0]));
// Manual handling of EOF token (the end of string). Return it
// as `EOF` symbol.
if (str.Length == 0 && matched != null && matched.Length == 0)
{
mCursor++;
}
if (matched != null)
{
yyparse.yytext = matched;
yyparse.yyleng = matched.Length;
MethodInfo tokenHandler = GetType().GetMethod(lexRule[1]);
var tokenType = tokenHandler.Invoke(this, null);
if (tokenType == null)
{
return getNextToken();
}
Type tokenDataType = tokenType.GetType();
if (tokenType.GetType().IsArray)
{
var tokensArray = (string[])tokenType;
tokenType = (string)tokensArray[0];
if (tokensArray.Length > 1) {
for (var j = 1; j < tokensArray.Length; j++)
{
mTokensQueue.Enqueue(tokensArray[j]);
}
}
}
return toToken((string)tokenType, matched);
}
}
if (isEOF())
{
mCursor++;
return EOF_TOKEN;
}
throwUnexpectedToken(
str[0].ToString(),
mCurrentLine,
mCurrentColumn
);
return null;
}
/**
* Throws default "Unexpected token" exception, showing the actual
* line from the source, pointing with the ^ marker to the bad token.
* In addition, shows `line:column` location.
*/
public void throwUnexpectedToken(string symbol, int line, int column)
{
var lineSource = mString.Split('\n')[line - 1];
var pad = new String(' ', column);
string lineData = "\n\n" + lineSource + "\n" + pad + "^\n";
throw new SyntaxException(
lineData + "Unexpected token: \"" + symbol +"\" " +
"at " + line + ":" + column + "."
);
}
private void captureLocation(string matched)
{
Regex nlRe = new Regex("\n");
// Absolute offsets.
mTokenStartOffset = mCursor;
// Line-based locations, start.
mTokenStartLine = mCurrentLine;
mTokenStartColumn = mTokenStartOffset - mCurrentLineBeginOffset;
// Extract `\n` in the matched token.
foreach (Match nlMatch in nlRe.Matches(matched))
{
mCurrentLine++;
mCurrentLineBeginOffset = mTokenStartOffset + nlMatch.Index + 1;
}
mTokenEndOffset = mCursor + matched.Length;
// Line-based locations, end.
mTokenEndLine = mCurrentLine;
mTokenEndColumn = mCurrentColumn =
(mTokenEndOffset - mCurrentLineBeginOffset);
}
private Token toToken(string tokenType, string yytext)
{
return new Token(
mTokensMap[tokenType],
yytext,
mTokenStartOffset,
mTokenEndOffset,
mTokenStartLine,
mTokenEndLine,
mTokenStartColumn,
mTokenEndColumn
);
}
public bool hasMoreTokens()
{
return mCursor <= mString.Length;
}
public bool isEOF()
{
return mCursor == mString.Length;
}
private string match(string str, Regex re)
{
Match m = re.Match(str);
string v = null;
if (m.Success)
{
v = m.Groups[0].Value;
captureLocation(v);
mCursor += v.Length;
}
return v;
}
public string get()
{
return mString;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
// ReSharper disable InconsistentNaming
#pragma warning disable 169, 649
namespace Avalonia.Win32.Interop
{
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Using Win32 naming for consistency.")]
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Using Win32 naming for consistency.")]
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Using Win32 naming for consistency.")]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements must be documented", Justification = "Look in Win32 docs.")]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1602:Enumeration items must be documented", Justification = "Look in Win32 docs.")]
internal static class UnmanagedMethods
{
public const int CW_USEDEFAULT = unchecked((int)0x80000000);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, IntPtr nIDEvent, uint dwTime);
public delegate void TimeCallback(uint uTimerID, uint uMsg, UIntPtr dwUser, UIntPtr dw1, UIntPtr dw2);
public delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
public enum Cursor
{
IDC_ARROW = 32512,
IDC_IBEAM = 32513,
IDC_WAIT = 32514,
IDC_CROSS = 32515,
IDC_UPARROW = 32516,
IDC_SIZE = 32640,
IDC_ICON = 32641,
IDC_SIZENWSE = 32642,
IDC_SIZENESW = 32643,
IDC_SIZEWE = 32644,
IDC_SIZENS = 32645,
IDC_SIZEALL = 32646,
IDC_NO = 32648,
IDC_HAND = 32649,
IDC_APPSTARTING = 32650,
IDC_HELP = 32651
}
public enum MouseActivate : int
{
MA_ACTIVATE = 1,
MA_ACTIVATEANDEAT = 2,
MA_NOACTIVATE = 3,
MA_NOACTIVATEANDEAT = 4
}
[Flags]
public enum SetWindowPosFlags : uint
{
SWP_ASYNCWINDOWPOS = 0x4000,
SWP_DEFERERASE = 0x2000,
SWP_DRAWFRAME = 0x0020,
SWP_FRAMECHANGED = 0x0020,
SWP_HIDEWINDOW = 0x0080,
SWP_NOACTIVATE = 0x0010,
SWP_NOCOPYBITS = 0x0100,
SWP_NOMOVE = 0x0002,
SWP_NOOWNERZORDER = 0x0200,
SWP_NOREDRAW = 0x0008,
SWP_NOREPOSITION = 0x0200,
SWP_NOSENDCHANGING = 0x0400,
SWP_NOSIZE = 0x0001,
SWP_NOZORDER = 0x0004,
SWP_SHOWWINDOW = 0x0040,
SWP_RESIZE = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER
}
public enum SizeCommand
{
Restored,
Minimized,
Maximized,
MaxShow,
MaxHide,
}
public enum ShowWindowCommand
{
Hide = 0,
Normal = 1,
ShowMinimized = 2,
Maximize = 3,
ShowMaximized = 3,
ShowNoActivate = 4,
Show = 5,
Minimize = 6,
ShowMinNoActive = 7,
ShowNA = 8,
Restore = 9,
ShowDefault = 10,
ForceMinimize = 11
}
public enum SystemMetric
{
SM_CXSCREEN = 0, // 0x00
SM_CYSCREEN = 1, // 0x01
SM_CXVSCROLL = 2, // 0x02
SM_CYHSCROLL = 3, // 0x03
SM_CYCAPTION = 4, // 0x04
SM_CXBORDER = 5, // 0x05
SM_CYBORDER = 6, // 0x06
SM_CXDLGFRAME = 7, // 0x07
SM_CXFIXEDFRAME = 7, // 0x07
SM_CYDLGFRAME = 8, // 0x08
SM_CYFIXEDFRAME = 8, // 0x08
SM_CYVTHUMB = 9, // 0x09
SM_CXHTHUMB = 10, // 0x0A
SM_CXICON = 11, // 0x0B
SM_CYICON = 12, // 0x0C
SM_CXCURSOR = 13, // 0x0D
SM_CYCURSOR = 14, // 0x0E
SM_CYMENU = 15, // 0x0F
SM_CXFULLSCREEN = 16, // 0x10
SM_CYFULLSCREEN = 17, // 0x11
SM_CYKANJIWINDOW = 18, // 0x12
SM_MOUSEPRESENT = 19, // 0x13
SM_CYVSCROLL = 20, // 0x14
SM_CXHSCROLL = 21, // 0x15
SM_DEBUG = 22, // 0x16
SM_SWAPBUTTON = 23, // 0x17
SM_CXMIN = 28, // 0x1C
SM_CYMIN = 29, // 0x1D
SM_CXSIZE = 30, // 0x1E
SM_CYSIZE = 31, // 0x1F
SM_CXSIZEFRAME = 32, // 0x20
SM_CXFRAME = 32, // 0x20
SM_CYSIZEFRAME = 33, // 0x21
SM_CYFRAME = 33, // 0x21
SM_CXMINTRACK = 34, // 0x22
SM_CYMINTRACK = 35, // 0x23
SM_CXDOUBLECLK = 36, // 0x24
SM_CYDOUBLECLK = 37, // 0x25
SM_CXICONSPACING = 38, // 0x26
SM_CYICONSPACING = 39, // 0x27
SM_MENUDROPALIGNMENT = 40, // 0x28
SM_PENWINDOWS = 41, // 0x29
SM_DBCSENABLED = 42, // 0x2A
SM_CMOUSEBUTTONS = 43, // 0x2B
SM_SECURE = 44, // 0x2C
SM_CXEDGE = 45, // 0x2D
SM_CYEDGE = 46, // 0x2E
SM_CXMINSPACING = 47, // 0x2F
SM_CYMINSPACING = 48, // 0x30
SM_CXSMICON = 49, // 0x31
SM_CYSMICON = 50, // 0x32
SM_CYSMCAPTION = 51, // 0x33
SM_CXSMSIZE = 52, // 0x34
SM_CYSMSIZE = 53, // 0x35
SM_CXMENUSIZE = 54, // 0x36
SM_CYMENUSIZE = 55, // 0x37
SM_ARRANGE = 56, // 0x38
SM_CXMINIMIZED = 57, // 0x39
SM_CYMINIMIZED = 58, // 0x3A
SM_CXMAXTRACK = 59, // 0x3B
SM_CYMAXTRACK = 60, // 0x3C
SM_CXMAXIMIZED = 61, // 0x3D
SM_CYMAXIMIZED = 62, // 0x3E
SM_NETWORK = 63, // 0x3F
SM_CLEANBOOT = 67, // 0x43
SM_CXDRAG = 68, // 0x44
SM_CYDRAG = 69, // 0x45
SM_SHOWSOUNDS = 70, // 0x46
SM_CXMENUCHECK = 71, // 0x47
SM_CYMENUCHECK = 72, // 0x48
SM_SLOWMACHINE = 73, // 0x49
SM_MIDEASTENABLED = 74, // 0x4A
SM_MOUSEWHEELPRESENT = 75, // 0x4B
SM_XVIRTUALSCREEN = 76, // 0x4C
SM_YVIRTUALSCREEN = 77, // 0x4D
SM_CXVIRTUALSCREEN = 78, // 0x4E
SM_CYVIRTUALSCREEN = 79, // 0x4F
SM_CMONITORS = 80, // 0x50
SM_SAMEDISPLAYFORMAT = 81, // 0x51
SM_IMMENABLED = 82, // 0x52
SM_CXFOCUSBORDER = 83, // 0x53
SM_CYFOCUSBORDER = 84, // 0x54
SM_TABLETPC = 86, // 0x56
SM_MEDIACENTER = 87, // 0x57
SM_STARTER = 88, // 0x58
SM_SERVERR2 = 89, // 0x59
SM_MOUSEHORIZONTALWHEELPRESENT = 91, // 0x5B
SM_CXPADDEDBORDER = 92, // 0x5C
SM_DIGITIZER = 94, // 0x5E
SM_MAXIMUMTOUCHES = 95, // 0x5F
SM_REMOTESESSION = 0x1000, // 0x1000
SM_SHUTTINGDOWN = 0x2000, // 0x2000
SM_REMOTECONTROL = 0x2001, // 0x2001
SM_CONVERTABLESLATEMODE = 0x2003,
SM_SYSTEMDOCKED = 0x2004,
}
[Flags]
public enum ModifierKeys
{
MK_CONTROL = 0x0008,
MK_LBUTTON = 0x0001,
MK_MBUTTON = 0x0010,
MK_RBUTTON = 0x0002,
MK_SHIFT = 0x0004,
MK_XBUTTON1 = 0x0020,
MK_XBUTTON2 = 0x0040
}
public enum WindowActivate
{
WA_INACTIVE,
WA_ACTIVE,
WA_CLICKACTIVE,
}
public enum HitTestValues
{
HTERROR = -2,
HTTRANSPARENT = -1,
HTNOWHERE = 0,
HTCLIENT = 1,
HTCAPTION = 2,
HTSYSMENU = 3,
HTGROWBOX = 4,
HTMENU = 5,
HTHSCROLL = 6,
HTVSCROLL = 7,
HTMINBUTTON = 8,
HTMAXBUTTON = 9,
HTLEFT = 10,
HTRIGHT = 11,
HTTOP = 12,
HTTOPLEFT = 13,
HTTOPRIGHT = 14,
HTBOTTOM = 15,
HTBOTTOMLEFT = 16,
HTBOTTOMRIGHT = 17,
HTBORDER = 18,
HTOBJECT = 19,
HTCLOSE = 20,
HTHELP = 21
}
[Flags]
public enum WindowStyles : uint
{
WS_BORDER = 0x800000,
WS_CAPTION = 0xc00000,
WS_CHILD = 0x40000000,
WS_CLIPCHILDREN = 0x2000000,
WS_CLIPSIBLINGS = 0x4000000,
WS_DISABLED = 0x8000000,
WS_DLGFRAME = 0x400000,
WS_GROUP = 0x20000,
WS_HSCROLL = 0x100000,
WS_MAXIMIZE = 0x1000000,
WS_MAXIMIZEBOX = 0x10000,
WS_MINIMIZE = 0x20000000,
WS_MINIMIZEBOX = 0x20000,
WS_OVERLAPPED = 0x0,
WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_SIZEFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
WS_POPUP = 0x80000000u,
WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU,
WS_SIZEFRAME = 0x40000,
WS_SYSMENU = 0x80000,
WS_TABSTOP = 0x10000,
WS_VISIBLE = 0x10000000,
WS_VSCROLL = 0x200000,
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_NOPARENTNOTIFY = 0x00000004,
WS_EX_TOPMOST = 0x00000008,
WS_EX_ACCEPTFILES = 0x00000010,
WS_EX_TRANSPARENT = 0x00000020,
WS_EX_MDICHILD = 0x00000040,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_WINDOWEDGE = 0x00000100,
WS_EX_CLIENTEDGE = 0x00000200,
WS_EX_CONTEXTHELP = 0x00000400,
WS_EX_RIGHT = 0x00001000,
WS_EX_LEFT = 0x00000000,
WS_EX_RTLREADING = 0x00002000,
WS_EX_LTRREADING = 0x00000000,
WS_EX_LEFTSCROLLBAR = 0x00004000,
WS_EX_RIGHTSCROLLBAR = 0x00000000,
WS_EX_CONTROLPARENT = 0x00010000,
WS_EX_STATICEDGE = 0x00020000,
WS_EX_APPWINDOW = 0x00040000,
WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE,
WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST,
WS_EX_LAYERED = 0x00080000,
WS_EX_NOINHERITLAYOUT = 0x00100000,
WS_EX_LAYOUTRTL = 0x00400000,
WS_EX_COMPOSITED = 0x02000000,
WS_EX_NOACTIVATE = 0x08000000
}
public enum WindowsMessage : uint
{
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUERYOPEN = 0x0013,
WM_ENDSESSION = 0x0016,
WM_QUIT = 0x0012,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = WM_WININICHANGE,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_DELETEITEM = 0x002D,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_SYNCPAINT = 0x0088,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_NCXBUTTONDOWN = 0x00AB,
WM_NCXBUTTONUP = 0x00AC,
WM_NCXBUTTONDBLCLK = 0x00AD,
WM_INPUT_DEVICE_CHANGE = 0x00FE,
WM_INPUT = 0x00FF,
WM_KEYFIRST = 0x0100,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_UNICHAR = 0x0109,
WM_KEYLAST = 0x0109,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_MENURBUTTONUP = 0x0122,
WM_MENUDRAG = 0x0123,
WM_MENUGETOBJECT = 0x0124,
WM_UNINITMENUPOPUP = 0x0125,
WM_MENUCOMMAND = 0x0126,
WM_CHANGEUISTATE = 0x0127,
WM_UPDATEUISTATE = 0x0128,
WM_QUERYUISTATE = 0x0129,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEFIRST = 0x0200,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_MOUSEWHEEL = 0x020A,
WM_XBUTTONDOWN = 0x020B,
WM_XBUTTONUP = 0x020C,
WM_XBUTTONDBLCLK = 0x020D,
WM_MOUSEHWHEEL = 0x020E,
WM_MOUSELAST = 0x020E,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_POWERBROADCAST = 0x0218,
WM_DEVICECHANGE = 0x0219,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_REQUEST = 0x0288,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_NCMOUSEHOVER = 0x02A0,
WM_NCMOUSELEAVE = 0x02A2,
WM_WTSSESSION_CHANGE = 0x02B1,
WM_TABLET_FIRST = 0x02c0,
WM_TABLET_LAST = 0x02df,
WM_DPICHANGED = 0x02E0,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_APPCOMMAND = 0x0319,
WM_THEMECHANGED = 0x031A,
WM_CLIPBOARDUPDATE = 0x031D,
WM_DWMCOMPOSITIONCHANGED = 0x031E,
WM_DWMNCRENDERINGCHANGED = 0x031F,
WM_DWMCOLORIZATIONCOLORCHANGED = 0x0320,
WM_DWMWINDOWMAXIMIZEDCHANGE = 0x0321,
WM_GETTITLEBARINFOEX = 0x033F,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = 0x8000,
WM_USER = 0x0400,
WM_DISPATCH_WORK_ITEM = WM_USER,
}
public enum BitmapCompressionMode : uint
{
BI_RGB = 0,
BI_RLE8 = 1,
BI_RLE4 = 2,
BI_BITFIELDS = 3,
BI_JPEG = 4,
BI_PNG = 5
}
public enum DIBColorTable
{
DIB_RGB_COLORS = 0, /* color table in RGBs */
DIB_PAL_COLORS /* color table in palette indices */
}
public enum WindowLongParam
{
GWL_WNDPROC = -4,
GWL_HINSTANCE = -6,
GWL_HWNDPARENT = -8,
GWL_ID = -12,
GWL_STYLE = -16,
GWL_EXSTYLE = -20,
GWL_USERDATA = -21
}
[StructLayout(LayoutKind.Sequential)]
public struct RGBQUAD
{
public byte rgbBlue;
public byte rgbGreen;
public byte rgbRed;
public byte rgbReserved;
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFOHEADER
{
public uint biSize;
public int biWidth;
public int biHeight;
public ushort biPlanes;
public ushort biBitCount;
public uint biCompression;
public uint biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public uint biClrUsed;
public uint biClrImportant;
public void Init()
{
biSize = (uint)Marshal.SizeOf(this);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFO
{
// C# cannot inlay structs in structs so must expand directly here
//
//[StructLayout(LayoutKind.Sequential)]
//public struct BITMAPINFOHEADER
//{
public uint biSize;
public int biWidth;
public int biHeight;
public ushort biPlanes;
public ushort biBitCount;
public BitmapCompressionMode biCompression;
public uint biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public uint biClrUsed;
public uint biClrImportant;
//}
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public uint[] cols;
}
[StructLayout(LayoutKind.Sequential)]
public struct MINMAXINFO
{
public POINT ptReserved;
public POINT ptMaxSize;
public POINT ptMaxPosition;
public POINT ptMinTrackSize;
public POINT ptMaxTrackSize;
}
public const int SizeOf_BITMAPINFOHEADER = 40;
[DllImport("user32.dll")]
public static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip,
MonitorEnumDelegate lpfnEnum, IntPtr dwData);
public delegate bool MonitorEnumDelegate(IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
public static extern int SetDIBitsToDevice(IntPtr hdc, int XDest, int YDest,
uint dwWidth, uint dwHeight,
int XSrc, int YSrc,
uint uStartScan, uint cScanLines,
IntPtr lpvBits, [In] ref BITMAPINFO lpbmi, uint fuColorUse);
[DllImport("user32.dll")]
public static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool AdjustWindowRectEx(ref RECT lpRect, uint dwStyle, bool bMenu, uint dwExStyle);
[DllImport("user32.dll")]
public static extern IntPtr BeginPaint(IntPtr hwnd, out PAINTSTRUCT lpPaint);
[DllImport("user32.dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr CreateWindowEx(
int dwExStyle,
uint lpClassName,
string lpWindowName,
uint dwStyle,
int x,
int y,
int nWidth,
int nHeight,
IntPtr hWndParent,
IntPtr hMenu,
IntPtr hInstance,
IntPtr lpParam);
[DllImport("user32.dll", EntryPoint = "DefWindowProcW")]
public static extern IntPtr DefWindowProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "DispatchMessageW")]
public static extern IntPtr DispatchMessage(ref MSG lpmsg);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool DestroyWindow(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
[DllImport("user32.dll")]
public static extern bool EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint);
[DllImport("user32.dll")]
public static extern uint GetCaretBlinkTime();
[DllImport("user32.dll")]
public static extern bool GetClientRect(IntPtr hwnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("user32.dll")]
public static extern uint GetDoubleClickTime();
[DllImport("user32.dll")]
public static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll", EntryPoint = "GetMessageW")]
public static extern sbyte GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
[DllImport("user32.dll")]
public static extern int GetMessageTime();
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll")]
public static extern uint GetCurrentThreadId();
[DllImport("user32.dll")]
public static extern int GetSystemMetrics(SystemMetric smIndex);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowLongPtr(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true, EntryPoint = "GetWindowLong")]
public static extern uint GetWindowLong32b(IntPtr hWnd, int nIndex);
public static uint GetWindowLong(IntPtr hWnd, int nIndex)
{
if(IntPtr.Size == 4)
{
return GetWindowLong32b(hWnd, nIndex);
}
else
{
return GetWindowLongPtr(hWnd, nIndex);
}
}
[DllImport("user32.dll", SetLastError = true, EntryPoint = "SetWindowLong")]
private static extern uint SetWindowLong32b(IntPtr hWnd, int nIndex, uint value);
[DllImport("user32.dll", SetLastError = true)]
private static extern uint SetWindowLongPtr(IntPtr hWnd, int nIndex, uint value);
public static uint SetWindowLong(IntPtr hWnd, int nIndex, uint value)
{
if (IntPtr.Size == 4)
{
return SetWindowLong32b(hWnd, nIndex, value);
}
else
{
return SetWindowLongPtr(hWnd, nIndex, value);
}
}
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern bool GetUpdateRect(IntPtr hwnd, out RECT lpRect, bool bErase);
[DllImport("user32.dll")]
public static extern bool InvalidateRect(IntPtr hWnd, ref RECT lpRect, bool bErase);
[DllImport("user32.dll")]
public static extern bool IsWindowEnabled(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool IsWindowUnicode(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool KillTimer(IntPtr hWnd, IntPtr uIDEvent);
[DllImport("user32.dll")]
public static extern IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName);
[DllImport("user32.dll")]
public static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "RegisterClassExW")]
public static extern ushort RegisterClassEx(ref WNDCLASSEX lpwcx);
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetActiveWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr SetCapture(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr SetTimer(IntPtr hWnd, IntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);
[DllImport("user32.dll")]
public static extern bool SetFocus(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool SetParent(IntPtr hWnd, IntPtr hWndNewParent);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, ShowWindowCommand nCmdShow);
[DllImport("Winmm.dll")]
public static extern uint timeKillEvent(uint uTimerID);
[DllImport("Winmm.dll")]
public static extern uint timeSetEvent(uint uDelay, uint uResolution, TimeCallback lpTimeProc, UIntPtr dwUser, uint fuEvent);
[DllImport("user32.dll")]
public static extern int ToUnicode(
uint virtualKeyCode,
uint scanCode,
byte[] keyboardState,
[Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)]
StringBuilder receivingBuffer,
int bufferSize,
uint flags);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack);
[DllImport("user32.dll")]
public static extern bool TranslateMessage(ref MSG lpMsg);
[DllImport("user32.dll")]
public static extern bool UnregisterClass(string lpClassName, IntPtr hInstance);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetWindowTextW")]
public static extern bool SetWindowText(IntPtr hwnd, string lpString);
public enum ClassLongIndex : int
{
GCL_HCURSOR = -12,
GCL_HICON = -14
}
[DllImport("user32.dll", EntryPoint = "SetClassLongPtr")]
private static extern IntPtr SetClassLong64(IntPtr hWnd, ClassLongIndex nIndex, IntPtr dwNewLong);
[DllImport("user32.dll", EntryPoint = "SetClassLong")]
private static extern IntPtr SetClassLong32(IntPtr hWnd, ClassLongIndex nIndex, IntPtr dwNewLong);
public static IntPtr SetClassLong(IntPtr hWnd, ClassLongIndex nIndex, IntPtr dwNewLong)
{
if (IntPtr.Size == 4)
{
return SetClassLong32(hWnd, nIndex, dwNewLong);
}
return SetClassLong64(hWnd, nIndex, dwNewLong);
}
[DllImport("user32.dll", EntryPoint = "SetCursor")]
internal static extern IntPtr SetCursor(IntPtr hCursor);
[DllImport("ole32.dll", PreserveSig = true)]
internal static extern int CoCreateInstance(ref Guid clsid,
IntPtr ignore1, int ignore2, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown), Out] out object pUnkOuter);
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool OpenClipboard(IntPtr hWndOwner);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool CloseClipboard();
[DllImport("user32.dll")]
public static extern bool EmptyClipboard();
[DllImport("user32.dll")]
public static extern IntPtr GetClipboardData(ClipboardFormat uFormat);
[DllImport("user32.dll")]
public static extern IntPtr SetClipboardData(ClipboardFormat uFormat, IntPtr hMem);
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GlobalLock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern bool GlobalUnlock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GlobalAlloc(int uFlags, int dwBytes);
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GlobalFree(IntPtr hMem);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr LoadLibrary(string fileName);
[DllImport("comdlg32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetSaveFileNameW")]
public static extern bool GetSaveFileName(IntPtr lpofn);
[DllImport("comdlg32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetOpenFileNameW")]
public static extern bool GetOpenFileName(IntPtr lpofn);
[DllImport("comdlg32.dll")]
public static extern int CommDlgExtendedError();
public static bool ShCoreAvailable => LoadLibrary("shcore.dll") != IntPtr.Zero;
[DllImport("shcore.dll")]
public static extern void SetProcessDpiAwareness(PROCESS_DPI_AWARENESS value);
[DllImport("shcore.dll")]
public static extern long GetDpiForMonitor(IntPtr hmonitor, MONITOR_DPI_TYPE dpiType, out uint dpiX, out uint dpiY);
[DllImport("shcore.dll")]
public static extern void GetScaleFactorForMonitor(IntPtr hMon, out uint pScale);
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromPoint(POINT pt, MONITOR dwFlags);
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromRect(RECT rect, MONITOR dwFlags);
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromWindow(IntPtr hwnd, MONITOR dwFlags);
[DllImport("user32", EntryPoint = "GetMonitorInfoW", ExactSpelling = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetMonitorInfo([In] IntPtr hMonitor, [Out] MONITORINFO lpmi);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "PostMessageW")]
public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("gdi32.dll")]
public static extern int SetDIBitsToDevice(IntPtr hdc, int XDest, int YDest, uint
dwWidth, uint dwHeight, int XSrc, int YSrc, uint uStartScan, uint cScanLines,
IntPtr lpvBits, [In] ref BITMAPINFOHEADER lpbmi, uint fuColorUse);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("gdi32.dll", SetLastError = true)]
public static extern IntPtr CreateDIBSection(IntPtr hDC, ref BITMAPINFOHEADER pBitmapInfo, int un, out IntPtr lplpVoid, IntPtr handle, int dw);
[DllImport("gdi32.dll")]
public static extern int DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll", SetLastError = true)]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateFileMapping(IntPtr hFile,
IntPtr lpFileMappingAttributes,
uint flProtect,
uint dwMaximumSizeHigh,
uint dwMaximumSizeLow,
string lpName);
[DllImport("msvcrt.dll", EntryPoint="memcpy", SetLastError = false, CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr CopyMemory(IntPtr dest, IntPtr src, UIntPtr count);
[DllImport("ole32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern HRESULT RegisterDragDrop(IntPtr hwnd, IDropTarget target);
[DllImport("ole32.dll", EntryPoint = "OleInitialize")]
public static extern HRESULT OleInitialize(IntPtr val);
[DllImport("ole32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern void ReleaseStgMedium(ref STGMEDIUM medium);
[DllImport("user32.dll", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetClipboardFormatName(int format, StringBuilder lpString, int cchMax);
[DllImport("user32.dll", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)]
public static extern int RegisterClipboardFormat(string format);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GlobalSize(IntPtr hGlobal);
[DllImport("shell32.dll", BestFitMapping = false, CharSet = CharSet.Auto)]
public static extern int DragQueryFile(IntPtr hDrop, int iFile, StringBuilder lpszFile, int cch);
[DllImport("ole32.dll", CharSet = CharSet.Auto, ExactSpelling = true, PreserveSig = false)]
public static extern void DoDragDrop(IOleDataObject dataObject, IDropSource dropSource, int allowedEffects, int[] finalEffect);
public enum MONITOR
{
MONITOR_DEFAULTTONULL = 0x00000000,
MONITOR_DEFAULTTOPRIMARY = 0x00000001,
MONITOR_DEFAULTTONEAREST = 0x00000002,
}
[StructLayout(LayoutKind.Sequential)]
internal class MONITORINFO
{
public int cbSize = Marshal.SizeOf<MONITORINFO>();
public RECT rcMonitor = new RECT();
public RECT rcWork = new RECT();
public int dwFlags = 0;
public enum MonitorOptions : uint
{
MONITOR_DEFAULTTONULL = 0x00000000,
MONITOR_DEFAULTTOPRIMARY = 0x00000001,
MONITOR_DEFAULTTONEAREST = 0x00000002
}
}
public enum PROCESS_DPI_AWARENESS
{
PROCESS_DPI_UNAWARE = 0,
PROCESS_SYSTEM_DPI_AWARE = 1,
PROCESS_PER_MONITOR_DPI_AWARE = 2
}
public enum MONITOR_DPI_TYPE
{
MDT_EFFECTIVE_DPI = 0,
MDT_ANGULAR_DPI = 1,
MDT_RAW_DPI = 2,
MDT_DEFAULT = MDT_EFFECTIVE_DPI
}
public enum ClipboardFormat
{
/// <summary>
/// Text format. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data. Use this format for ANSI text.
/// </summary>
CF_TEXT = 1,
/// <summary>
/// A handle to a bitmap
/// </summary>
CF_BITMAP = 2,
/// <summary>
/// A memory object containing a BITMAPINFO structure followed by the bitmap bits.
/// </summary>
CF_DIB = 3,
/// <summary>
/// Unicode text format. Each line ends with a carriage return/linefeed (CR-LF) combination. A null character signals the end of the data.
/// </summary>
CF_UNICODETEXT = 13,
/// <summary>
/// A handle to type HDROP that identifies a list of files.
/// </summary>
CF_HDROP = 15,
}
public struct MSG
{
public IntPtr hwnd;
public uint message;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public POINT pt;
}
[StructLayout(LayoutKind.Sequential)]
public struct PAINTSTRUCT
{
public IntPtr hdc;
public bool fErase;
public RECT rcPaint;
public bool fRestore;
public bool fIncUpdate;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] rgbReserved;
}
public struct POINT
{
public int X;
public int Y;
}
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public RECT(Rect rect)
{
left = (int)rect.X;
top = (int)rect.Y;
right = (int)(rect.X + rect.Width);
bottom = (int)(rect.Y + rect.Height);
}
}
public struct TRACKMOUSEEVENT
{
public int cbSize;
public uint dwFlags;
public IntPtr hwndTrack;
public int dwHoverTime;
}
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWPLACEMENT
{
/// <summary>
/// The length of the structure, in bytes. Before calling the GetWindowPlacement or SetWindowPlacement functions, set this member to sizeof(WINDOWPLACEMENT).
/// <para>
/// GetWindowPlacement and SetWindowPlacement fail if this member is not set correctly.
/// </para>
/// </summary>
public int Length;
/// <summary>
/// Specifies flags that control the position of the minimized window and the method by which the window is restored.
/// </summary>
public int Flags;
/// <summary>
/// The current show state of the window.
/// </summary>
public ShowWindowCommand ShowCmd;
/// <summary>
/// The coordinates of the window's upper-left corner when the window is minimized.
/// </summary>
public POINT MinPosition;
/// <summary>
/// The coordinates of the window's upper-left corner when the window is maximized.
/// </summary>
public POINT MaxPosition;
/// <summary>
/// The window's coordinates when the window is in the restored position.
/// </summary>
public RECT NormalPosition;
/// <summary>
/// Gets the default (empty) value.
/// </summary>
public static WINDOWPLACEMENT Default
{
get
{
WINDOWPLACEMENT result = new WINDOWPLACEMENT();
result.Length = Marshal.SizeOf(result);
return result;
}
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WNDCLASSEX
{
public int cbSize;
public int style;
public WndProc lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
public string lpszMenuName;
public string lpszClassName;
public IntPtr hIconSm;
}
[Flags]
public enum OpenFileNameFlags
{
OFN_ALLOWMULTISELECT = 0x00000200,
OFN_EXPLORER = 0x00080000,
OFN_HIDEREADONLY = 0x00000004,
OFN_NOREADONLYRETURN = 0x00008000,
OFN_OVERWRITEPROMPT = 0x00000002
}
public enum HRESULT : long
{
S_FALSE = 0x0001,
S_OK = 0x0000,
E_INVALIDARG = 0x80070057,
E_OUTOFMEMORY = 0x8007000E,
E_NOTIMPL = 0x80004001,
E_UNEXPECTED = 0x8000FFFF,
}
public enum Icons
{
ICON_SMALL = 0,
ICON_BIG = 1
}
public const uint SIGDN_FILESYSPATH = 0x80058000;
[Flags]
internal enum FOS : uint
{
FOS_OVERWRITEPROMPT = 0x00000002,
FOS_STRICTFILETYPES = 0x00000004,
FOS_NOCHANGEDIR = 0x00000008,
FOS_PICKFOLDERS = 0x00000020,
FOS_FORCEFILESYSTEM = 0x00000040, // Ensure that items returned are filesystem items.
FOS_ALLNONSTORAGEITEMS = 0x00000080, // Allow choosing items that have no storage.
FOS_NOVALIDATE = 0x00000100,
FOS_ALLOWMULTISELECT = 0x00000200,
FOS_PATHMUSTEXIST = 0x00000800,
FOS_FILEMUSTEXIST = 0x00001000,
FOS_CREATEPROMPT = 0x00002000,
FOS_SHAREAWARE = 0x00004000,
FOS_NOREADONLYRETURN = 0x00008000,
FOS_NOTESTFILECREATE = 0x00010000,
FOS_HIDEMRUPLACES = 0x00020000,
FOS_HIDEPINNEDPLACES = 0x00040000,
FOS_NODEREFERENCELINKS = 0x00100000,
FOS_DONTADDTORECENT = 0x02000000,
FOS_FORCESHOWHIDDEN = 0x10000000,
FOS_DEFAULTNOMINIMODE = 0x20000000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct OpenFileName
{
public int lStructSize;
public IntPtr hwndOwner;
public IntPtr hInstance;
public IntPtr lpstrFilter;
public IntPtr lpstrCustomFilter;
public int nMaxCustFilter;
public int nFilterIndex;
public IntPtr lpstrFile;
public int nMaxFile;
public IntPtr lpstrFileTitle;
public int nMaxFileTitle;
public IntPtr lpstrInitialDir;
public IntPtr lpstrTitle;
public OpenFileNameFlags Flags;
private readonly ushort Unused;
private readonly ushort Unused2;
public IntPtr lpstrDefExt;
public IntPtr lCustData;
public IntPtr lpfnHook;
public IntPtr lpTemplateName;
public IntPtr reservedPtr;
public int reservedInt;
public int flagsEx;
}
}
[ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileDialog
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig()]
uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypeIndex([In] uint iFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileTypeIndex(out uint piFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Unadvise([In] uint dwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOptions([In] uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetOptions(out uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Close([MarshalAs(UnmanagedType.Error)] uint hr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetClientGuid([In] ref Guid guid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint ClearClientData();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellItem
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
}
[Flags]
internal enum DropEffect : int
{
None = 0,
Copy = 1,
Move = 2,
Link = 4,
Scroll = -2147483648,
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("00000122-0000-0000-C000-000000000046")]
internal interface IDropTarget
{
[PreserveSig]
UnmanagedMethods.HRESULT DragEnter([MarshalAs(UnmanagedType.Interface)] [In] IOleDataObject pDataObj, [MarshalAs(UnmanagedType.U4)] [In] int grfKeyState, [MarshalAs(UnmanagedType.U8)] [In] long pt, [In] [Out] ref DropEffect pdwEffect);
[PreserveSig]
UnmanagedMethods.HRESULT DragOver([MarshalAs(UnmanagedType.U4)] [In] int grfKeyState, [MarshalAs(UnmanagedType.U8)] [In] long pt, [In] [Out] ref DropEffect pdwEffect);
[PreserveSig]
UnmanagedMethods.HRESULT DragLeave();
[PreserveSig]
UnmanagedMethods.HRESULT Drop([MarshalAs(UnmanagedType.Interface)] [In] IOleDataObject pDataObj, [MarshalAs(UnmanagedType.U4)] [In] int grfKeyState, [MarshalAs(UnmanagedType.U8)] [In] long pt, [In] [Out] ref DropEffect pdwEffect);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("00000121-0000-0000-C000-000000000046")]
internal interface IDropSource
{
[PreserveSig]
int QueryContinueDrag(int fEscapePressed, [MarshalAs(UnmanagedType.U4)] [In] int grfKeyState);
[PreserveSig]
int GiveFeedback([MarshalAs(UnmanagedType.U4)] [In] int dwEffect);
}
[ComImport]
[Guid("0000010E-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleDataObject
{
void GetData([In] ref FORMATETC format, out STGMEDIUM medium);
void GetDataHere([In] ref FORMATETC format, ref STGMEDIUM medium);
[PreserveSig]
int QueryGetData([In] ref FORMATETC format);
[PreserveSig]
int GetCanonicalFormatEtc([In] ref FORMATETC formatIn, out FORMATETC formatOut);
void SetData([In] ref FORMATETC formatIn, [In] ref STGMEDIUM medium, [MarshalAs(UnmanagedType.Bool)] bool release);
IEnumFORMATETC EnumFormatEtc(DATADIR direction);
[PreserveSig]
int DAdvise([In] ref FORMATETC pFormatetc, ADVF advf, IAdviseSink adviseSink, out int connection);
void DUnadvise(int connection);
[PreserveSig]
int EnumDAdvise(out IEnumSTATDATA enumAdvise);
}
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct _DROPFILES
{
public Int32 pFiles;
public Int32 X;
public Int32 Y;
public bool fNC;
public bool fWide;
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RenderingCapabilities.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Provides rendering capability examples.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ExampleLibrary
{
using System;
using System.Diagnostics;
using System.Globalization;
using OxyPlot;
using OxyPlot.Annotations;
using System.Linq;
/// <summary>
/// Provides rendering capability examples.
/// </summary>
[Examples("9 Rendering capabilities")]
public class RenderingCapabilities
{
/// <summary>
/// Shows color capabilities for the DrawText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - Colors")]
public static PlotModel DrawTextColors()
{
var model = new PlotModel();
model.Annotations.Add(new DelegateAnnotation(rc =>
{
const string Font = "Arial";
const double FontSize = 32d;
const double FontWeight = FontWeights.Bold;
const double D = FontSize * 1.6;
const double X = 20;
double y = 20 - D;
rc.DrawText(new ScreenPoint(X, y += D), "Black", OxyColors.Black, Font, FontSize, FontWeight);
rc.DrawText(new ScreenPoint(X, y += D), "Red", OxyColors.Red, Font, FontSize, FontWeight);
rc.DrawText(new ScreenPoint(X, y += D), "Green", OxyColors.Green, Font, FontSize, FontWeight);
rc.DrawText(new ScreenPoint(X, y += D), "Blue", OxyColors.Blue, Font, FontSize, FontWeight);
rc.FillRectangle(new OxyRect(X, y + D + 15, 200, 10), OxyColors.Black);
rc.DrawText(new ScreenPoint(X, y + D), "Yellow 50%", OxyColor.FromAColor(128, OxyColors.Yellow), Font, FontSize, FontWeight);
}));
return model;
}
/// <summary>
/// Shows font capabilities for the DrawText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - Fonts")]
public static PlotModel DrawTextFonts()
{
var model = new PlotModel();
model.Annotations.Add(new DelegateAnnotation(rc =>
{
const double FontSize = 20d;
const double D = FontSize * 1.6;
const double X = 20;
double y = 20 - D;
rc.DrawText(new ScreenPoint(X, y += D), "Default font", OxyColors.Black, null, FontSize);
rc.DrawText(new ScreenPoint(X, y += D), "Helvetica", OxyColors.Black, "Helvetica", FontSize);
rc.DrawText(new ScreenPoint(X, y += D), "Arial", OxyColors.Black, "Arial", FontSize);
rc.DrawText(new ScreenPoint(X, y += D), "Courier", OxyColors.Black, "Courier", FontSize);
rc.DrawText(new ScreenPoint(X, y += D), "Courier New", OxyColors.Black, "Courier New", FontSize);
rc.DrawText(new ScreenPoint(X, y += D), "Times", OxyColors.Black, "Times", FontSize);
rc.DrawText(new ScreenPoint(X, y + D), "Times New Roman", OxyColors.Black, "Times New Roman", FontSize);
}));
return model;
}
/// <summary>
/// Shows font size capabilities for the DrawText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - Font sizes")]
public static PlotModel DrawTextFontSizes()
{
var model = new PlotModel();
model.Annotations.Add(new DelegateAnnotation(rc =>
{
const double X = 20;
double y = 20;
// Font sizes
foreach (var size in new[] { 10, 16, 24, 36, 48 })
{
rc.DrawText(new ScreenPoint(X, y), size + "pt", OxyColors.Black, "Arial", size);
rc.DrawText(new ScreenPoint(X + 200, y), size + "pt", OxyColors.Black, "Arial", size, FontWeights.Bold);
y += size * 1.6;
}
}));
return model;
}
/// <summary>
/// Shows rotation capabilities for the DrawText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - Rotation")]
public static PlotModel DrawTextRotation()
{
var model = new PlotModel();
model.Annotations.Add(new DelegateAnnotation(rc =>
{
var origin = new ScreenPoint(200, 200);
rc.FillCircle(origin, 3, OxyColors.Blue);
for (int rotation = 0; rotation < 360; rotation += 45)
{
rc.DrawText(origin, string.Format("Rotation {0}", rotation), OxyColors.Black, fontSize: 20d, rotation: rotation);
}
}));
return model;
}
/// <summary>
/// Shows alignment capabilities for the DrawText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - Alignment")]
public static PlotModel DrawTextAlignment()
{
var model = new PlotModel();
model.Annotations.Add(new DelegateAnnotation(rc =>
{
const double FontSize = 20d;
for (var ha = HorizontalAlignment.Left; ha <= HorizontalAlignment.Right; ha++)
{
for (var va = VerticalAlignment.Top; va <= VerticalAlignment.Bottom; va++)
{
var origin = new ScreenPoint((((int)ha + 1) * 200) + 20, (((int)va + 1) * FontSize * 3) + 20);
rc.FillCircle(origin, 3, OxyColors.Blue);
rc.DrawText(origin, ha + "-" + va, OxyColors.Black, fontSize: FontSize, horizontalAlignment: ha, verticalAlignment: va);
}
}
}));
return model;
}
/// <summary>
/// Shows rotation capabilities for the DrawMathText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawMathText - Rotation")]
public static PlotModel MathTextRotation()
{
var model = new PlotModel();
var fontFamily = "Arial";
var fontSize = 24;
var fontWeight = FontWeights.Normal;
model.Annotations.Add(new DelegateAnnotation(rc =>
{
var origin = new ScreenPoint(200, 200);
var origin2 = new ScreenPoint(400, 200);
rc.FillCircle(origin, 3, OxyColors.Blue);
for (int rotation = 0; rotation < 360; rotation += 45)
{
var text = " A_{2}^{3}B";
rc.DrawMathText(origin, text, OxyColors.Black, fontFamily, fontSize, fontWeight, rotation, HorizontalAlignment.Left, VerticalAlignment.Middle);
var size = rc.MeasureMathText(text, fontFamily, fontSize, fontWeight);
var outline1 = size.GetPolygon(origin, rotation, HorizontalAlignment.Left, VerticalAlignment.Middle).ToArray();
rc.DrawPolygon(outline1, OxyColors.Undefined, OxyColors.Blue);
// Compare with normal text
var text2 = " A B";
rc.DrawText(origin2, text2, OxyColors.Red, fontFamily, fontSize, fontWeight, rotation, HorizontalAlignment.Left, VerticalAlignment.Middle);
var size2 = rc.MeasureText(text2, fontFamily, fontSize, fontWeight);
var outline2 = size2.GetPolygon(origin2, rotation, HorizontalAlignment.Left, VerticalAlignment.Middle).ToArray();
rc.DrawPolygon(outline2, OxyColors.Undefined, OxyColors.Blue);
}
}));
return model;
}
/// <summary>
/// Shows alignment capabilities for the DrawMathText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawMathText - Alignment")]
public static PlotModel DrawMathTextAlignment()
{
var text = "A_{2}^{3}B";
var model = new PlotModel();
model.Annotations.Add(new DelegateAnnotation(rc =>
{
const string FontFamily = "Arial";
const double FontSize = 20d;
const double FontWeight = FontWeights.Normal;
for (var ha = HorizontalAlignment.Left; ha <= HorizontalAlignment.Right; ha++)
{
for (var va = VerticalAlignment.Top; va <= VerticalAlignment.Bottom; va++)
{
var origin = new ScreenPoint((((int)ha + 1) * 200) + 20, (((int)va + 1) * FontSize * 3) + 20);
rc.FillCircle(origin, 3, OxyColors.Blue);
rc.DrawMathText(origin, text, OxyColors.Black, FontFamily, FontSize, FontWeight, 0, ha, va);
}
}
}));
return model;
}
/// <summary>
/// Shows alignment capabilities for the DrawText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - Alignment/Rotation")]
public static PlotModel DrawTextAlignmentRotation()
{
var model = new PlotModel();
model.Annotations.Add(new DelegateAnnotation(rc =>
{
for (var ha = HorizontalAlignment.Left; ha <= HorizontalAlignment.Right; ha++)
{
for (var va = VerticalAlignment.Top; va <= VerticalAlignment.Bottom; va++)
{
var origin = new ScreenPoint(((int)ha + 2) * 130, ((int)va + 2) * 130);
rc.FillCircle(origin, 3, OxyColors.Blue);
for (int rotation = 0; rotation < 360; rotation += 90)
{
rc.DrawText(origin, string.Format("R{0:000}", rotation), OxyColors.Black, fontSize: 20d, rotation: rotation, horizontalAlignment: ha, verticalAlignment: va);
}
}
}
}));
return model;
}
/// <summary>
/// Shows color capabilities for the DrawText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - MaxSize")]
public static PlotModel DrawTextMaxSize()
{
var model = new PlotModel();
model.Annotations.Add(new DelegateAnnotation(rc =>
{
const string Font = "Arial";
const double FontSize = 32d;
const double FontWeight = FontWeights.Bold;
const double D = FontSize * 1.6;
const double X = 20;
const double X2 = 200;
double y = 20;
var testStrings = new[] { "iii", "jjj", "OxyPlot", "Bottom", "100", "KML" };
foreach (var text in testStrings)
{
var maxSize = rc.MeasureText(text, Font, FontSize, FontWeight);
var p = new ScreenPoint(X, y);
rc.DrawText(p, text, OxyColors.Black, Font, FontSize, FontWeight, maxSize: maxSize);
var rect = new OxyRect(p, maxSize);
rc.DrawRectangle(rect, OxyColors.Undefined, OxyColors.Black);
var p2 = new ScreenPoint(X2, y);
var maxSize2 = new OxySize(maxSize.Width / 2, maxSize.Height / 2);
rc.DrawText(p2, text, OxyColors.Black, Font, FontSize, FontWeight, maxSize: maxSize2);
var rect2 = new OxyRect(p2, maxSize2);
rc.DrawRectangle(rect2, OxyColors.Undefined, OxyColors.Black);
y += D;
}
}));
return model;
}
/// <summary>
/// Draws text and shows marks for ascent/descent/baseline/x-height and the expected bounding box.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - WPF metrics")]
public static PlotModel DrawTextWithWpfMetrics()
{
return DrawTextWithMetrics("OxyPlot", "Arial", 60, 226, 69, 105, 73, 61, 116, 23, 228, "WPF");
}
/// <summary>
/// Draws text and shows marks for ascent/descent/baseline/x-height and the expected bounding box.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - WinForms metrics (StringFormat = GenericDefault)")]
public static PlotModel DrawTextWithWinFormsMetricsDefault()
{
return DrawTextWithMetrics("OxyPlot", "Arial", 60, 252.145812988281, 79.4999847412109, 108, 73, 61, 121, 34, 252, "WinForms");
}
/// <summary>
/// Draws text and shows marks for ascent/descent/baseline/x-height and the expected bounding box.
/// </summary>
/// <returns>A plot model.</returns>
[Example("DrawText - WinForms metrics (StringFormat = GenericTypographic)")]
public static PlotModel DrawTextWithWinFormsMetricsTypographic()
{
return DrawTextWithMetrics("OxyPlot", "Arial", 60, 224.1, 71.5, 108, 73, 61, 121, 23, 242, "WinForms");
}
/// <summary>
/// Shows capabilities for the MeasureText method.
/// </summary>
/// <returns>A plot model.</returns>
[Example("MeasureText")]
public static PlotModel MeasureText()
{
var model = new PlotModel();
model.Annotations.Add(new DelegateAnnotation(rc =>
{
const string Font = "Arial";
var strings = new[] { "OxyPlot", "MMM", "III", "jikq", "gh", "123", "!#$&" };
var fontSizes = new[] { 10d, 20, 40, 60 };
var x = 5d;
foreach (double fontSize in fontSizes)
{
var y = 5d;
var maxWidth = 0d;
foreach (var s in strings)
{
var size = rc.MeasureText(s, Font, fontSize);
maxWidth = Math.Max(maxWidth, size.Width);
rc.DrawRectangle(new OxyRect(x, y, size.Width, size.Height), OxyColors.LightYellow, OxyColors.Black);
rc.DrawText(new ScreenPoint(x, y), s, OxyColors.Black, Font, fontSize);
y += size.Height + 20;
}
x += maxWidth + 20;
}
}));
return model;
}
/// <summary>
/// Draws text with metrics.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="font">The font.</param>
/// <param name="fontSize">Size of the font.</param>
/// <param name="expectedWidth">The expected width.</param>
/// <param name="expectedHeight">The expected height.</param>
/// <param name="baseline">The baseline position.</param>
/// <param name="xheight">The x-height position.</param>
/// <param name="ascent">The ascent position.</param>
/// <param name="descent">The descent position.</param>
/// <param name="before">The before position.</param>
/// <param name="after">The after position.</param>
/// <param name="platform">The platform.</param>
/// <returns>
/// A plot model.
/// </returns>
private static PlotModel DrawTextWithMetrics(string text, string font, double fontSize, double expectedWidth, double expectedHeight, double baseline, double xheight, double ascent, double descent, double before, double after, string platform)
{
// http://msdn.microsoft.com/en-us/library/ms742190(v=vs.110).aspx
// http://msdn.microsoft.com/en-us/library/xwf9s90b(v=vs.110).aspx
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms533824(v=vs.85).aspx
// https://developer.apple.com/library/mac/documentation/TextFonts/Conceptual/CocoaTextArchitecture/FontHandling/FontHandling.html
var model = new PlotModel();
model.Annotations.Add(
new DelegateAnnotation(
rc =>
{
var size = rc.MeasureText(text, font, fontSize);
var expectedSize = new OxySize(expectedWidth, expectedHeight);
rc.DrawText(new ScreenPoint(300, 50), "Font size: " + fontSize, OxyColors.Black, font, 12);
rc.DrawText(new ScreenPoint(300, 70), "Actual size: " + size.ToString("0.00", CultureInfo.InvariantCulture), OxyColors.Black, font, 12);
rc.DrawText(new ScreenPoint(300, 90), "Size on " + platform + ": " + expectedSize.ToString("0.00", CultureInfo.InvariantCulture), OxyColors.Green, font, 12);
var p = new ScreenPoint(20, 50);
rc.DrawText(p, text, OxyColors.Black, font, fontSize);
rc.FillCircle(p, 3, OxyColors.Black);
// actual bounds
rc.DrawRectangle(new OxyRect(p, size), OxyColors.Undefined, OxyColors.Black);
// Expected bounds (WPF)
rc.DrawRectangle(new OxyRect(p, expectedSize), OxyColors.Undefined, OxyColors.Green);
var color = OxyColor.FromAColor(180, OxyColors.Red);
var pen = new OxyPen(color);
// Expected vertical positions (WPF)
var x1 = p.X - 10;
var x2 = p.X + expectedSize.Width + 10;
rc.DrawLine(x1, baseline, x2, baseline, pen);
rc.DrawLine(x1, xheight, x2, xheight, pen);
rc.DrawLine(x1, ascent, x2, ascent, pen);
rc.DrawLine(x1, descent, x2, descent, pen);
// Expected horizonal positions (WPF)
var y1 = p.Y - 10;
var y2 = p.Y + expectedSize.Height + 10;
rc.DrawLine(before, y1, before, y2, pen);
rc.DrawLine(after, y1, after, y2, pen);
}));
model.MouseDown += (s, e) => Debug.WriteLine(e.Position);
return model;
}
/// <summary>
/// Represents an annotation that renders by a delegate.
/// </summary>
private class DelegateAnnotation : Annotation
{
/// <summary>
/// Initializes a new instance of the <see cref="DelegateAnnotation"/> class.
/// </summary>
/// <param name="rendering">The rendering delegate.</param>
public DelegateAnnotation(Action<IRenderContext> rendering)
{
this.Rendering = rendering;
}
/// <summary>
/// Gets the rendering delegate.
/// </summary>
/// <value>
/// The rendering.
/// </value>
public Action<IRenderContext> Rendering { get; private set; }
/// <summary>
/// Renders the annotation on the specified context.
/// </summary>
/// <param name="rc">The render context.</param>
public override void Render(IRenderContext rc)
{
base.Render(rc);
this.Rendering(rc);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.