context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//--------------------------------------------------------------------------- // // <copyright file="TableRowGroup.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Table row group implementation // // See spec at http://avalon/layout/Tables/WPP%20TableOM.doc // // History: // 05/19/2003 : olego - Created // //--------------------------------------------------------------------------- //In order to avoid generating warnings about unknown message numbers and //unknown pragmas when compiling your C# source code with the actual C# compiler, //you need to disable warnings 1634 and 1691. (Presharp Documentation) #pragma warning disable 1634, 1691 using MS.Internal.PtsHost; using MS.Internal.PtsTable; using MS.Utility; using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Windows.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; using System.Windows.Markup; using System.Collections.Generic; using MS.Internal.Documents; using MS.Internal; using MS.Internal.Data; using MS.Internal.PtsHost.UnsafeNativeMethods; namespace System.Windows.Documents { /// <summary> /// Table row group implementation /// </summary> [ContentProperty("Rows")] public class TableRowGroup : TextElement, IAddChild, IIndexedChild<Table>, IAcceptInsertion { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Creates an instance of a RowGroup /// </summary> public TableRowGroup() : base() { Initialize(); } // common initialization for all constructors private void Initialize() { _rows = new TableRowCollection(this); _rowInsertionIndex = -1; _parentIndex = -1; } #endregion //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// <see cref="IAddChild.AddChild"/> /// </summary> void IAddChild.AddChild(object value) { if (value == null) { throw new ArgumentNullException("value"); } TableRow row = value as TableRow; if (row != null) { Rows.Add(row); return; } throw (new ArgumentException(SR.Get(SRID.UnexpectedParameterType, value.GetType(), typeof(TableRow)), "value")); } /// <summary> /// <see cref="IAddChild.AddText"/> /// </summary> void IAddChild.AddText(string text) { XamlSerializerUtil.ThrowIfNonWhiteSpaceInAddText(text, this); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// Returns the row group's row collection /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TableRowCollection Rows { get { return (_rows); } } /// <summary> /// This method is used by TypeDescriptor to determine if this property should /// be serialized. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeRows() { return Rows.Count > 0; } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods #endregion Protected Methods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #region IIndexedChild implementation /// <summary> /// Callback used to notify about entering model tree. /// </summary> void IIndexedChild<Table>.OnEnterParentTree() { this.OnEnterParentTree(); } /// <summary> /// Callback used to notify about exitting model tree. /// </summary> void IIndexedChild<Table>.OnExitParentTree() { this.OnExitParentTree(); } void IIndexedChild<Table>.OnAfterExitParentTree(Table parent) { this.OnAfterExitParentTree(parent); } int IIndexedChild<Table>.Index { get { return this.Index; } set { this.Index = value; } } #endregion IIndexedChild implementation /// <summary> /// Callback used to notify the RowGroup about entering model tree. /// </summary> internal void OnEnterParentTree() { if(Table != null) { Table.OnStructureChanged(); } } /// <summary> /// Callback used to notify the RowGroup about exitting model tree. /// </summary> internal void OnExitParentTree() { } /// <summary> /// Callback used to notify the RowGroup about exitting model tree. /// </summary> internal void OnAfterExitParentTree(Table table) { table.OnStructureChanged(); } /// <summary> /// ValidateStructure /// </summary> internal void ValidateStructure() { RowSpanVector rowSpanVector = new RowSpanVector(); _columnCount = 0; for (int i = 0; i < Rows.Count; ++i) { Rows[i].ValidateStructure(rowSpanVector); _columnCount = Math.Max(_columnCount, Rows[i].ColumnCount); } Table.EnsureColumnCount(_columnCount); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties /// <summary> /// Table owner accessor /// </summary> internal Table Table { get { return Parent as Table; } } /// <summary> /// RowGroup's index in the parents row group collection. /// </summary> internal int Index { get { return (_parentIndex); } set { Debug.Assert(value >= -1 && _parentIndex != value); _parentIndex = value; } } int IAcceptInsertion.InsertionIndex { get { return this.InsertionIndex; } set { this.InsertionIndex = value; } } /// <summary> /// Stores temporary data for where to insert a new row /// </summary> internal int InsertionIndex { get { return _rowInsertionIndex; } set { _rowInsertionIndex = value; } } /// <summary> /// Marks this element's left edge as visible to IMEs. /// This means element boundaries will act as word breaks. /// </summary> internal override bool IsIMEStructuralElement { get { return true; } } #endregion Internal Properties //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods /// <summary> /// Called when body receives a new parent (via OM or text tree) /// </summary> /// <param name="newParent"> /// New parent of body /// </param> internal override void OnNewParent(DependencyObject newParent) { DependencyObject oldParent = this.Parent; if (newParent != null && !(newParent is Table)) { throw new InvalidOperationException(SR.Get(SRID.TableInvalidParentNodeType, newParent.GetType().ToString())); } if (oldParent != null) { OnExitParentTree(); ((Table)oldParent).RowGroups.InternalRemove(this); OnAfterExitParentTree(oldParent as Table); } base.OnNewParent(newParent); if (newParent != null) { ((Table)newParent).RowGroups.InternalAdd(this); OnEnterParentTree(); } } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private TableRowCollection _rows; // children rows store private int _parentIndex; // row group's index in parent's children collection private int _rowInsertionIndex; // Insertion index for row private int _columnCount; // Column count. #endregion Private Fields //------------------------------------------------------ // // Private Structures / Classes // //------------------------------------------------------ } } #pragma warning restore 1634, 1691
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using Debug = System.Diagnostics.Debug; using Internal.NativeFormat; namespace Internal.TypeSystem.Ecma { /// <summary> /// Override of MetadataType that uses actual Ecma335 metadata. /// </summary> public sealed partial class EcmaType : MetadataType, EcmaModule.IEntityHandleObject { private EcmaModule _module; private TypeDefinitionHandle _handle; private TypeDefinition _typeDefinition; // Cached values private string _typeName; private string _typeNamespace; private TypeDesc[] _genericParameters; private MetadataType _baseType; private int _hashcode; internal EcmaType(EcmaModule module, TypeDefinitionHandle handle) { _module = module; _handle = handle; _typeDefinition = module.MetadataReader.GetTypeDefinition(handle); _baseType = this; // Not yet initialized flag #if DEBUG // Initialize name eagerly in debug builds for convenience this.ToString(); #endif } public override int GetHashCode() { if (_hashcode != 0) return _hashcode; return InitializeHashCode(); } private int InitializeHashCode() { TypeDesc containingType = ContainingType; if (containingType == null) { string ns = Namespace; var hashCodeBuilder = new TypeHashingAlgorithms.HashCodeBuilder(ns); if (ns.Length > 0) hashCodeBuilder.Append("."); hashCodeBuilder.Append(Name); _hashcode = hashCodeBuilder.ToHashCode(); } else { _hashcode = TypeHashingAlgorithms.ComputeNestedTypeHashCode( containingType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name)); } return _hashcode; } EntityHandle EcmaModule.IEntityHandleObject.Handle { get { return _handle; } } public override TypeSystemContext Context { get { return _module.Context; } } private void ComputeGenericParameters() { var genericParameterHandles = _typeDefinition.GetGenericParameters(); int count = genericParameterHandles.Count; if (count > 0) { TypeDesc[] genericParameters = new TypeDesc[count]; int i = 0; foreach (var genericParameterHandle in genericParameterHandles) { genericParameters[i++] = new EcmaGenericParameter(_module, genericParameterHandle); } Interlocked.CompareExchange(ref _genericParameters, genericParameters, null); } else { _genericParameters = TypeDesc.EmptyTypes; } } public override Instantiation Instantiation { get { if (_genericParameters == null) ComputeGenericParameters(); return new Instantiation(_genericParameters); } } public override ModuleDesc Module { get { return _module; } } public EcmaModule EcmaModule { get { return _module; } } public MetadataReader MetadataReader { get { return _module.MetadataReader; } } public TypeDefinitionHandle Handle { get { return _handle; } } private MetadataType InitializeBaseType() { var baseTypeHandle = _typeDefinition.BaseType; if (baseTypeHandle.IsNil) { _baseType = null; return null; } var type = _module.GetType(baseTypeHandle) as MetadataType; if (type == null) { // PREFER: "new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadBadFormat, this)" but the metadata is too broken ThrowHelper.ThrowTypeLoadException(Namespace, Name, Module); } _baseType = type; return type; } public override DefType BaseType { get { if (_baseType == this) return InitializeBaseType(); return _baseType; } } public override MetadataType MetadataBaseType { get { if (_baseType == this) return InitializeBaseType(); return _baseType; } } protected override TypeFlags ComputeTypeFlags(TypeFlags mask) { TypeFlags flags = 0; if ((mask & TypeFlags.CategoryMask) != 0) { TypeDesc baseType = this.BaseType; if (baseType != null && baseType.IsWellKnownType(WellKnownType.ValueType)) { flags |= TypeFlags.ValueType; } else if (baseType != null && baseType.IsWellKnownType(WellKnownType.Enum)) { flags |= TypeFlags.Enum; } else { if ((_typeDefinition.Attributes & TypeAttributes.Interface) != 0) flags |= TypeFlags.Interface; else flags |= TypeFlags.Class; } // All other cases are handled during TypeSystemContext intitialization } if ((mask & TypeFlags.HasGenericVarianceComputed) != 0) { flags |= TypeFlags.HasGenericVarianceComputed; foreach (GenericParameterDesc genericParam in Instantiation) { if (genericParam.Variance != GenericVariance.None) { flags |= TypeFlags.HasGenericVariance; break; } } } if ((mask & TypeFlags.HasFinalizerComputed) != 0) { flags |= TypeFlags.HasFinalizerComputed; if (GetFinalizer() != null) flags |= TypeFlags.HasFinalizer; } if ((mask & TypeFlags.IsByRefLikeComputed) != 0) { flags |= TypeFlags.IsByRefLikeComputed; if (IsValueType && HasCustomAttribute("System.Runtime.CompilerServices", "IsByRefLikeAttribute")) flags |= TypeFlags.IsByRefLike; } return flags; } private string InitializeName() { var metadataReader = this.MetadataReader; _typeName = metadataReader.GetString(_typeDefinition.Name); return _typeName; } public override string Name { get { if (_typeName == null) return InitializeName(); return _typeName; } } private string InitializeNamespace() { var metadataReader = this.MetadataReader; _typeNamespace = metadataReader.GetString(_typeDefinition.Namespace); return _typeNamespace; } public override string Namespace { get { if (_typeNamespace == null) return InitializeNamespace(); return _typeNamespace; } } public override IEnumerable<MethodDesc> GetMethods() { foreach (var handle in _typeDefinition.GetMethods()) { yield return (MethodDesc)_module.GetObject(handle); } } public override MethodDesc GetMethod(string name, MethodSignature signature) { var metadataReader = this.MetadataReader; var stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetMethods()) { if (stringComparer.Equals(metadataReader.GetMethodDefinition(handle).Name, name)) { MethodDesc method = (MethodDesc)_module.GetObject(handle); if (signature == null || signature.Equals(method.Signature)) return method; } } return null; } public override MethodDesc GetStaticConstructor() { var metadataReader = this.MetadataReader; var stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetMethods()) { var methodDefinition = metadataReader.GetMethodDefinition(handle); if (methodDefinition.Attributes.IsRuntimeSpecialName() && stringComparer.Equals(methodDefinition.Name, ".cctor")) { MethodDesc method = (MethodDesc)_module.GetObject(handle); return method; } } return null; } public override MethodDesc GetDefaultConstructor() { if (IsAbstract) return null; MetadataReader metadataReader = this.MetadataReader; MetadataStringComparer stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetMethods()) { var methodDefinition = metadataReader.GetMethodDefinition(handle); MethodAttributes attributes = methodDefinition.Attributes; if (attributes.IsRuntimeSpecialName() && attributes.IsPublic() && stringComparer.Equals(methodDefinition.Name, ".ctor")) { MethodDesc method = (MethodDesc)_module.GetObject(handle); if (method.Signature.Length != 0) continue; return method; } } return null; } public override MethodDesc GetFinalizer() { // System.Object defines Finalize but doesn't use it, so we can determine that a type has a Finalizer // by checking for a virtual method override that lands anywhere other than Object in the inheritance // chain. if (!HasBaseType) return null; TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object); MethodDesc decl = objectType.GetMethod("Finalize", null); if (decl != null) { MethodDesc impl = this.FindVirtualFunctionTargetMethodOnObjectType(decl); if (impl == null) { // TODO: invalid input: the type doesn't derive from our System.Object throw new TypeLoadException(this.GetFullName()); } if (impl.OwningType != objectType) { return impl; } return null; } // TODO: Better exception type. Should be: "CoreLib doesn't have a required thing in it". throw new NotImplementedException(); } public override IEnumerable<FieldDesc> GetFields() { foreach (var handle in _typeDefinition.GetFields()) { var field = (EcmaField)_module.GetObject(handle); yield return field; } } public override FieldDesc GetField(string name) { var metadataReader = this.MetadataReader; var stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetFields()) { if (stringComparer.Equals(metadataReader.GetFieldDefinition(handle).Name, name)) { var field = (EcmaField)_module.GetObject(handle); return field; } } return null; } public override IEnumerable<MetadataType> GetNestedTypes() { foreach (var handle in _typeDefinition.GetNestedTypes()) { yield return (MetadataType)_module.GetObject(handle); } } public override MetadataType GetNestedType(string name) { var metadataReader = this.MetadataReader; var stringComparer = metadataReader.StringComparer; foreach (var handle in _typeDefinition.GetNestedTypes()) { bool nameMatched; TypeDefinition type = metadataReader.GetTypeDefinition(handle); if (type.Namespace.IsNil) { nameMatched = stringComparer.Equals(type.Name, name); } else { string typeName = metadataReader.GetString(type.Name); typeName = metadataReader.GetString(type.Namespace) + "." + typeName; nameMatched = typeName == name; } if (nameMatched) return (MetadataType)_module.GetObject(handle); } return null; } public TypeAttributes Attributes { get { return _typeDefinition.Attributes; } } public override DefType ContainingType { get { if (!_typeDefinition.Attributes.IsNested()) return null; var handle = _typeDefinition.GetDeclaringType(); return (DefType)_module.GetType(handle); } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return !MetadataReader.GetCustomAttributeHandle(_typeDefinition.GetCustomAttributes(), attributeNamespace, attributeName).IsNil; } public override string ToString() { return "[" + _module.ToString() + "]" + this.GetFullName(); } public override ClassLayoutMetadata GetClassLayout() { TypeLayout layout = _typeDefinition.GetLayout(); ClassLayoutMetadata result; result.PackingSize = layout.PackingSize; result.Size = layout.Size; // Skip reading field offsets if this is not explicit layout if (IsExplicitLayout) { var fieldDefinitionHandles = _typeDefinition.GetFields(); var numInstanceFields = 0; foreach (var handle in fieldDefinitionHandles) { var fieldDefinition = MetadataReader.GetFieldDefinition(handle); if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0) continue; numInstanceFields++; } result.Offsets = new FieldAndOffset[numInstanceFields]; int index = 0; foreach (var handle in fieldDefinitionHandles) { var fieldDefinition = MetadataReader.GetFieldDefinition(handle); if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0) continue; // Note: GetOffset() returns -1 when offset was not set in the metadata int specifiedOffset = fieldDefinition.GetOffset(); result.Offsets[index] = new FieldAndOffset((FieldDesc)_module.GetObject(handle), specifiedOffset == -1 ? FieldAndOffset.InvalidOffset : new LayoutInt(specifiedOffset)); index++; } } else result.Offsets = null; return result; } public override MarshalAsDescriptor[] GetFieldMarshalAsDescriptors() { var fieldDefinitionHandles = _typeDefinition.GetFields(); MarshalAsDescriptor[] marshalAsDescriptors = new MarshalAsDescriptor[fieldDefinitionHandles.Count]; int index = 0; foreach (var handle in fieldDefinitionHandles) { var fieldDefinition = MetadataReader.GetFieldDefinition(handle); if ((fieldDefinition.Attributes & FieldAttributes.Static) != 0) continue; MarshalAsDescriptor marshalAsDescriptor = GetMarshalAsDescriptor(fieldDefinition); marshalAsDescriptors[index++] = marshalAsDescriptor; } return marshalAsDescriptors; } private MarshalAsDescriptor GetMarshalAsDescriptor(FieldDefinition fieldDefinition) { if ((fieldDefinition.Attributes & FieldAttributes.HasFieldMarshal) == FieldAttributes.HasFieldMarshal) { MetadataReader metadataReader = MetadataReader; BlobReader marshalAsReader = metadataReader.GetBlobReader(fieldDefinition.GetMarshallingDescriptor()); EcmaSignatureParser parser = new EcmaSignatureParser(EcmaModule, marshalAsReader); MarshalAsDescriptor marshalAs = parser.ParseMarshalAsDescriptor(); Debug.Assert(marshalAs != null); return marshalAs; } return null; } public override bool IsExplicitLayout { get { return (_typeDefinition.Attributes & TypeAttributes.ExplicitLayout) != 0; } } public override bool IsSequentialLayout { get { return (_typeDefinition.Attributes & TypeAttributes.SequentialLayout) != 0; } } public override bool IsBeforeFieldInit { get { return (_typeDefinition.Attributes & TypeAttributes.BeforeFieldInit) != 0; } } public override bool IsModuleType { get { return _handle.Equals(MetadataTokens.TypeDefinitionHandle(0x00000001 /* COR_GLOBAL_PARENT_TOKEN */)); } } public override bool IsSealed { get { return (_typeDefinition.Attributes & TypeAttributes.Sealed) != 0; } } public override bool IsAbstract { get { return (_typeDefinition.Attributes & TypeAttributes.Abstract) != 0; } } public override PInvokeStringFormat PInvokeStringFormat { get { return (PInvokeStringFormat)(_typeDefinition.Attributes & TypeAttributes.StringFormatMask); } } } }
// 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.Sql { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ServersOperations operations. /// </summary> public partial interface IServersOperations { /// <summary> /// Determines whether a resource can be created with the specified /// name. /// </summary> /// <param name='parameters'> /// The parameters to request for name availability. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckNameAvailabilityResponse>> CheckNameAvailabilityWithHttpMessagesAsync(CheckNameAvailabilityRequest parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of all servers in the subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Server>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of servers in a resource groups. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Server>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Server>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='parameters'> /// The requested server resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Server>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, Server parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='parameters'> /// The requested server resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Server>> UpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, ServerUpdate parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='parameters'> /// The requested server resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Server>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, Server parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a server. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can /// obtain this value from the Azure Resource Manager API or the /// portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='parameters'> /// The requested server resource state. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Server>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, ServerUpdate parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of all servers in the subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Server>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of servers in a resource groups. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Server>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using System.Threading; using Thrift.Collections; using Thrift.Protocol; using Thrift.Transport; namespace Thrift.Server { /// <summary> /// Server that uses C# threads (as opposed to the ThreadPool) when handling requests /// </summary> public class TThreadedServer : TServer { private const int DEFAULT_MAX_THREADS = 100; private volatile bool stop = false; private readonly int maxThreads; private Queue<TTransport> clientQueue; private THashSet<Thread> clientThreads; private object clientLock; private Thread workerThread; public int ClientThreadsCount { get { return clientThreads.Count; } } public TThreadedServer(TProcessor processor, TServerTransport serverTransport) : this(new TSingletonProcessorFactory(processor), serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), DEFAULT_MAX_THREADS, DefaultLogDelegate) { } public TThreadedServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate) : this(new TSingletonProcessorFactory(processor), serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), DEFAULT_MAX_THREADS, logDelegate) { } public TThreadedServer(TProcessor processor, TServerTransport serverTransport, TTransportFactory transportFactory, TProtocolFactory protocolFactory) : this(new TSingletonProcessorFactory(processor), serverTransport, transportFactory, transportFactory, protocolFactory, protocolFactory, DEFAULT_MAX_THREADS, DefaultLogDelegate) { } public TThreadedServer(TProcessorFactory processorFactory, TServerTransport serverTransport, TTransportFactory transportFactory, TProtocolFactory protocolFactory) : this(processorFactory, serverTransport, transportFactory, transportFactory, protocolFactory, protocolFactory, DEFAULT_MAX_THREADS, DefaultLogDelegate) { } public TThreadedServer(TProcessorFactory processorFactory, TServerTransport serverTransport, TTransportFactory inputTransportFactory, TTransportFactory outputTransportFactory, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, int maxThreads, LogDelegate logDel) : base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory, inputProtocolFactory, outputProtocolFactory, logDel) { this.maxThreads = maxThreads; clientQueue = new Queue<TTransport>(); clientLock = new object(); clientThreads = new THashSet<Thread>(); } /// <summary> /// Use new Thread for each new client connection. block until numConnections < maxThreads /// </summary> public override void Serve() { try { //start worker thread workerThread = new Thread(new ThreadStart(Execute)); workerThread.Start(); serverTransport.Listen(); } catch (TTransportException ttx) { logDelegate("Error, could not listen on ServerTransport: " + ttx); return; } //Fire the preServe server event when server is up but before any client connections if (serverEventHandler != null) serverEventHandler.preServe(); while (!stop) { int failureCount = 0; try { TTransport client = serverTransport.Accept(); lock (clientLock) { clientQueue.Enqueue(client); Monitor.Pulse(clientLock); } } catch (TTransportException ttx) { if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted) { ++failureCount; logDelegate(ttx.ToString()); } } } if (stop) { try { serverTransport.Close(); } catch (TTransportException ttx) { logDelegate("TServeTransport failed on close: " + ttx.Message); } stop = false; } } /// <summary> /// Loops on processing a client forever /// threadContext will be a TTransport instance /// </summary> /// <param name="threadContext"></param> private void Execute() { while (!stop) { TTransport client; Thread t; lock (clientLock) { //don't dequeue if too many connections while (clientThreads.Count >= maxThreads) { Monitor.Wait(clientLock); } while (clientQueue.Count == 0) { Monitor.Wait(clientLock); } client = clientQueue.Dequeue(); t = new Thread(new ParameterizedThreadStart(ClientWorker)); clientThreads.Add(t); } //start processing requests from client on new thread t.Start(client); } } private void ClientWorker(Object context) { TTransport client = (TTransport)context; TProcessor processor = processorFactory.GetProcessor(client); TTransport inputTransport = null; TTransport outputTransport = null; TProtocol inputProtocol = null; TProtocol outputProtocol = null; Object connectionContext = null; try { using (inputTransport = inputTransportFactory.GetTransport(client)) { using (outputTransport = outputTransportFactory.GetTransport(client)) { inputProtocol = inputProtocolFactory.GetProtocol(inputTransport); outputProtocol = outputProtocolFactory.GetProtocol(outputTransport); //Recover event handler (if any) and fire createContext server event when a client connects if (serverEventHandler != null) connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol); //Process client requests until client disconnects while (!stop) { if (!inputTransport.Peek()) break; //Fire processContext server event //N.B. This is the pattern implemented in C++ and the event fires provisionally. //That is to say it may be many minutes between the event firing and the client request //actually arriving or the client may hang up without ever makeing a request. if (serverEventHandler != null) serverEventHandler.processContext(connectionContext, inputTransport); //Process client request (blocks until transport is readable) if (!processor.Process(inputProtocol, outputProtocol)) break; } } } } catch (TTransportException) { //Usually a client disconnect, expected } catch (Exception x) { //Unexpected logDelegate("Error: " + x); } //Fire deleteContext server event after client disconnects if (serverEventHandler != null) serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); lock (clientLock) { clientThreads.Remove(Thread.CurrentThread); Monitor.Pulse(clientLock); } return; } public override void Stop() { stop = true; serverTransport.Close(); //clean up all the threads myself workerThread.Abort(); foreach (Thread t in clientThreads) { t.Abort(); } } } }
// 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.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Xml.Linq; using Microsoft.DotNet.InternalAbstractions; using Microsoft.DotNet.ProjectModel.Utilities; using Microsoft.Extensions.DependencyModel.Resolution; using NuGet.Frameworks; namespace Microsoft.DotNet.ProjectModel.Resolution { public class FrameworkReferenceResolver { // FrameworkConstants doesn't have dnx46 yet private static readonly NuGetFramework Dnx46 = new NuGetFramework( FrameworkConstants.FrameworkIdentifiers.Dnx, new Version(4, 6)); private static FrameworkReferenceResolver _default; private readonly ConcurrentDictionary<NuGetFramework, FrameworkInformation> _cache = new ConcurrentDictionary<NuGetFramework, FrameworkInformation>(); private static readonly IDictionary<NuGetFramework, NuGetFramework[]> _aliases = new Dictionary<NuGetFramework, NuGetFramework[]> { { FrameworkConstants.CommonFrameworks.Dnx451, new [] { FrameworkConstants.CommonFrameworks.Net451 } }, { Dnx46, new [] { FrameworkConstants.CommonFrameworks.Net46 } } }; public FrameworkReferenceResolver(string referenceAssembliesPath) { ReferenceAssembliesPath = referenceAssembliesPath; } public string ReferenceAssembliesPath { get; } public static FrameworkReferenceResolver Default { get { if (_default == null) { _default = new FrameworkReferenceResolver(GetDefaultReferenceAssembliesPath()); } return _default; } } public static string GetDefaultReferenceAssembliesPath() { // Allow setting the reference assemblies path via an environment variable var referenceAssembliesPath = DotNetReferenceAssembliesPathResolver.Resolve(); if (!string.IsNullOrEmpty(referenceAssembliesPath)) { return referenceAssembliesPath; } if (RuntimeEnvironment.OperatingSystemPlatform != Platform.Windows) { // There is no reference assemblies path outside of windows // The environment variable can be used to specify one return null; } // References assemblies are in %ProgramFiles(x86)% on // 64 bit machines var programFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); if (string.IsNullOrEmpty(programFiles)) { // On 32 bit machines they are in %ProgramFiles% programFiles = Environment.GetEnvironmentVariable("ProgramFiles"); } if (string.IsNullOrEmpty(programFiles)) { // Reference assemblies aren't installed return null; } return Path.Combine( programFiles, "Reference Assemblies", "Microsoft", "Framework"); } public bool TryGetAssembly(string name, NuGetFramework targetFramework, out string path, out Version version) { path = null; version = null; var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); if (information == null || !information.Exists) { return false; } lock (information.Assemblies) { AssemblyEntry entry; if (information.Assemblies.TryGetValue(name, out entry)) { if (string.IsNullOrEmpty(entry.Path)) { entry.Path = GetAssemblyPath(information.SearchPaths, name); } if (!string.IsNullOrEmpty(entry.Path) && entry.Version == null) { // This code path should only run on mono entry.Version = VersionUtility.GetAssemblyVersion(entry.Path).Version; } path = entry.Path; version = entry.Version; } } return !string.IsNullOrEmpty(path); } public bool IsInstalled(NuGetFramework targetFramework) { var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); return information?.Exists == true; } public string GetFrameworkRedistListPath(NuGetFramework targetFramework) { var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); if (information == null || !information.Exists) { return null; } return information.RedistListPath; } public string GetFriendlyFrameworkName(NuGetFramework targetFramework) { var frameworkName = new FrameworkName(targetFramework.DotNetFrameworkName); // We don't have a friendly name for this anywhere on the machine so hard code it if (string.Equals(frameworkName.Identifier, VersionUtility.DnxCoreFrameworkIdentifier, StringComparison.OrdinalIgnoreCase)) { return "DNX Core 5.0"; } else if (string.Equals(frameworkName.Identifier, VersionUtility.DnxFrameworkIdentifier, StringComparison.OrdinalIgnoreCase)) { return "DNX " + targetFramework.Version.ToString(); } else if (string.Equals(frameworkName.Identifier, VersionUtility.NetPlatformFrameworkIdentifier, StringComparison.OrdinalIgnoreCase)) { var version = targetFramework.Version > Constants.Version50 ? (" " + targetFramework.Version.ToString()) : string.Empty; return ".NET Platform" + version; } var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); if (information == null) { return SynthesizeFrameworkFriendlyName(targetFramework); } return information.Name; } private FrameworkInformation GetFrameworkInformation(NuGetFramework targetFramework) { string referenceAssembliesPath = ReferenceAssembliesPath; if (string.IsNullOrEmpty(referenceAssembliesPath)) { return null; } NuGetFramework[] candidates; if (_aliases.TryGetValue(targetFramework, out candidates)) { foreach (var framework in candidates) { var information = GetFrameworkInformation(framework); if (information != null) { return information; } } return null; } else { return GetFrameworkInformation(targetFramework, referenceAssembliesPath); } } private static FrameworkInformation GetFrameworkInformation(NuGetFramework targetFramework, string referenceAssembliesPath) { // Check for legacy frameworks if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows && targetFramework.IsDesktop() && targetFramework.Version <= new Version(3, 5, 0, 0)) { return GetLegacyFrameworkInformation(targetFramework, referenceAssembliesPath); } var basePath = Path.Combine(referenceAssembliesPath, targetFramework.Framework, "v" + GetDisplayVersion(targetFramework)); if (!string.IsNullOrEmpty(targetFramework.Profile)) { basePath = Path.Combine(basePath, "Profile", targetFramework.Profile); } var version = new DirectoryInfo(basePath); if (!version.Exists) { return null; } return GetFrameworkInformation(version, targetFramework, referenceAssembliesPath); } private static FrameworkInformation GetLegacyFrameworkInformation(NuGetFramework targetFramework, string referenceAssembliesPath) { var frameworkInfo = new FrameworkInformation(); // Always grab .NET 2.0 data var searchPaths = new List<string>(); var net20Dir = Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "Microsoft.NET", "Framework", "v2.0.50727"); if (!Directory.Exists(net20Dir)) { return null; } // Grab reference assemblies first, if present for this framework if (targetFramework.Version.Major == 3) { // Most specific first (i.e. 3.5) if (targetFramework.Version.Minor == 5) { var refAsms35Dir = Path.Combine(referenceAssembliesPath, "v3.5"); if (!string.IsNullOrEmpty(targetFramework.Profile)) { // The 3.5 Client Profile assemblies ARE in .NETFramework... it's weird. refAsms35Dir = Path.Combine(referenceAssembliesPath, ".NETFramework", "v3.5", "Profile", targetFramework.Profile); } if (Directory.Exists(refAsms35Dir)) { searchPaths.Add(refAsms35Dir); } } // Always search the 3.0 reference assemblies if (string.IsNullOrEmpty(targetFramework.Profile)) { // a) 3.0 didn't have profiles // b) When using a profile, we don't want to fall back to 3.0 or 2.0 var refAsms30Dir = Path.Combine(referenceAssembliesPath, "v3.0"); if (Directory.Exists(refAsms30Dir)) { searchPaths.Add(refAsms30Dir); } } } // .NET 2.0 reference assemblies go last (but only if there's no profile in the TFM) if (string.IsNullOrEmpty(targetFramework.Profile)) { searchPaths.Add(net20Dir); } frameworkInfo.Exists = true; frameworkInfo.Path = searchPaths.First(); frameworkInfo.SearchPaths = searchPaths; // Load the redist list in reverse order (most general -> most specific) for (int i = searchPaths.Count - 1; i >= 0; i--) { var dir = new DirectoryInfo(searchPaths[i]); if (dir.Exists) { PopulateFromRedistList(dir, targetFramework, referenceAssembliesPath, frameworkInfo); } } if (string.IsNullOrEmpty(frameworkInfo.Name)) { frameworkInfo.Name = SynthesizeFrameworkFriendlyName(targetFramework); } return frameworkInfo; } private static string SynthesizeFrameworkFriendlyName(NuGetFramework targetFramework) { // Names are not present in the RedistList.xml file for older frameworks or on Mono // We do some custom version string rendering to match how net40 is rendered (.NET Framework 4) if (targetFramework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.Net)) { string versionString = targetFramework.Version.Minor == 0 ? targetFramework.Version.Major.ToString() : GetDisplayVersion(targetFramework).ToString(); string profileString = string.IsNullOrEmpty(targetFramework.Profile) ? string.Empty : $" {targetFramework.Profile} Profile"; return ".NET Framework " + versionString + profileString; } return targetFramework.ToString(); } private static FrameworkInformation GetFrameworkInformation(DirectoryInfo directory, NuGetFramework targetFramework, string referenceAssembliesPath) { var frameworkInfo = new FrameworkInformation(); frameworkInfo.Exists = true; frameworkInfo.Path = directory.FullName; frameworkInfo.SearchPaths = new[] { frameworkInfo.Path, Path.Combine(frameworkInfo.Path, "Facades") }; PopulateFromRedistList(directory, targetFramework, referenceAssembliesPath, frameworkInfo); if (string.IsNullOrEmpty(frameworkInfo.Name)) { frameworkInfo.Name = SynthesizeFrameworkFriendlyName(targetFramework); } return frameworkInfo; } private static void PopulateFromRedistList(DirectoryInfo directory, NuGetFramework targetFramework, string referenceAssembliesPath, FrameworkInformation frameworkInfo) { // The redist list contains the list of assemblies for this target framework string redistList = Path.Combine(directory.FullName, "RedistList", "FrameworkList.xml"); if (File.Exists(redistList)) { frameworkInfo.RedistListPath = redistList; using (var stream = File.OpenRead(redistList)) { var frameworkList = XDocument.Load(stream); // Remember the original search paths, because we might need them later var originalSearchPaths = frameworkInfo.SearchPaths; // There are some frameworks, that "inherit" from a base framework, like // e.g. .NET 4.0.3, and MonoAndroid. var includeFrameworkVersion = frameworkList.Root.Attribute("IncludeFramework")?.Value; if (includeFrameworkVersion != null) { // Get the NuGetFramework identifier for the framework to include var includeFramework = NuGetFramework.Parse($"{targetFramework.Framework}, Version={includeFrameworkVersion}"); // Recursively call the code to get the framework information var includeFrameworkInfo = GetFrameworkInformation(includeFramework, referenceAssembliesPath); // Append the search paths of the included framework frameworkInfo.SearchPaths = frameworkInfo.SearchPaths.Concat(includeFrameworkInfo.SearchPaths).ToArray(); // Add the assemblies of the included framework foreach (var assemblyEntry in includeFrameworkInfo.Assemblies) { frameworkInfo.Assemblies[assemblyEntry.Key] = assemblyEntry.Value; } } // On mono, the RedistList.xml has an entry pointing to the TargetFrameworkDirectory // It basically uses the GAC as the reference assemblies for all .NET framework // profiles var targetFrameworkDirectory = frameworkList.Root.Attribute("TargetFrameworkDirectory")?.Value; IEnumerable<string> populateFromPaths; if (!string.IsNullOrEmpty(targetFrameworkDirectory)) { // For some odd reason, the paths are actually listed as \ so normalize them here targetFrameworkDirectory = targetFrameworkDirectory.Replace('\\', Path.DirectorySeparatorChar); // The specified path is the relative path from the RedistList.xml itself var resovledPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(redistList), targetFrameworkDirectory)); // Update the path to the framework frameworkInfo.Path = resovledPath; populateFromPaths = new List<string> { resovledPath, Path.Combine(resovledPath, "Facades") }; } else { var emptyFileElements = true; foreach (var e in frameworkList.Root.Elements()) { // Remember that we had at least one framework assembly emptyFileElements = false; var assemblyName = e.Attribute("AssemblyName").Value; var version = e.Attribute("Version")?.Value; var entry = new AssemblyEntry(); entry.Version = version != null ? Version.Parse(version) : null; frameworkInfo.Assemblies[assemblyName] = entry; } if (emptyFileElements) { // When we haven't found any file elements, we probably processed a // Mono/Xamarin FrameworkList.xml. That means, that we have to // populate the assembly list from the files. populateFromPaths = originalSearchPaths; } else { populateFromPaths = null; } } // Do we need to populate from search paths? if (populateFromPaths != null) { foreach (var populateFromPath in populateFromPaths) { PopulateAssemblies(frameworkInfo.Assemblies, populateFromPath); } } var nameAttribute = frameworkList.Root.Attribute("Name"); frameworkInfo.Name = nameAttribute == null ? null : nameAttribute.Value; } } } private static void PopulateAssemblies(IDictionary<string, AssemblyEntry> assemblies, string path) { if (!Directory.Exists(path)) { return; } foreach (var assemblyPath in Directory.GetFiles(path, "*.dll")) { var name = Path.GetFileNameWithoutExtension(assemblyPath); var entry = new AssemblyEntry(); entry.Path = assemblyPath; assemblies[name] = entry; } } private static string GetAssemblyPath(IEnumerable<string> basePaths, string assemblyName) { foreach (var basePath in basePaths) { var assemblyPath = Path.Combine(basePath, assemblyName + ".dll"); if (File.Exists(assemblyPath)) { return assemblyPath; } } return null; } private static Version GetDisplayVersion(NuGetFramework framework) { // Fix the target framework version due to https://github.com/NuGet/Home/issues/1600, this is relevant // when looking up in the reference assembly folder return new FrameworkName(framework.DotNetFrameworkName).Version; } } }
// --------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // The MIT License (MIT) // // 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 ContosoModels; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace Yodo1APICaller.ViewModels { /// <summary> /// Encapsulates data for the Order detail page. /// </summary> public class OrderDetailPageViewModel : INotifyPropertyChanged { /// <summary> /// Creates an OrderDetailPageViewModel that wraps the specified EnterpriseModels.Order. /// </summary> /// <param name="order">The order to wrap.</param> public OrderDetailPageViewModel(Order order) { _order = order; // Create an ObservableCollection to wrap Order.LineItems so we can track // product additions and deletions. _lineItems = order != null && order.LineItems != null ? new ObservableCollection<LineItem>(_order.LineItems) : new ObservableCollection<LineItem>(); _lineItems.CollectionChanged += lineItems_Changed; NewLineItem = new LineItemWrapper(); if (order.Customer == null) { Task.Run(() => loadCustomer(_order.CustomerId)); } } /// <summary> /// Creates a OrderDetailPageViewModel from an Order ID. /// </summary> /// <param name="orderId">The ID of the order to retrieve. </param> /// <returns></returns> public async static Task<OrderDetailPageViewModel> CreateFromGuid(Guid orderId) { var order = await getOrder(orderId); return new OrderDetailPageViewModel(order); } /// <summary> /// The EnterpriseModels.Order this object wraps. /// </summary> private Order _order; /// <summary> /// Loads the customer with the specified ID. /// </summary> /// <param name="customerId">The ID of the customer to load.</param> private async void loadCustomer(Guid customerId) { var db = new ContosoDataSource(); var customer = await db.Customers.GetAsync(customerId); await Utilities.CallOnUiThreadAsync(() => { Customer = customer; }); } /// <summary> /// Returns the order with the specified ID. /// </summary> /// <param name="orderId">The ID of the order to retrieve.</param> /// <returns>The order, if it exists; otherwise, null. </returns> private static async Task<Order> getOrder(Guid orderId) { var db = new ContosoDataSource(); var order = await db.Orders.GetAsync(orderId); return order; } /// <summary> /// Gets a value that specifies whether the user can refresh the page. /// </summary> public bool CanRefresh { get { return _order != null && !HasChanges && IsExistingOrder; } } /// <summary> /// Gets a value that specifies whether the user can revert changes. /// </summary> public bool CanRevert { get { return _order != null && HasChanges && IsExistingOrder; } } /// <summary> /// Gets or sets the order's ID. /// </summary> public Guid Id { get { return _order.Id; } set { if (_order.Id != value) { _order.Id = value; OnPropertyChanged(nameof(Id)); HasChanges = true; } } } /// <summary> /// Gets or sets the ID of the order's customer. /// </summary> public Guid CustomerId { get { return _order.CustomerId; } set { if (_order.CustomerId != value) { _order.CustomerId = value; OnPropertyChanged(nameof(CustomerId)); HasChanges = true; } } } /// <summary> /// Gets or sets a value that indicates whether the user has changed the order. /// </summary> bool _hasChanges = false; public bool HasChanges { get { return _hasChanges; } set { if (value != _hasChanges) { // Only record changes after the order has loaded. if (IsLoaded) { _hasChanges = value; OnPropertyChanged(nameof(HasChanges)); } } } } /// <summary> /// Gets a value that specifies whether htis is an existing order. /// </summary> public bool IsExistingOrder => !IsNewOrder; public bool IsLoaded => _order != null && (IsNewOrder || _order.Customer != null); public bool IsNotLoaded => !IsLoaded; public bool IsNewOrder => _order.InvoiceNumber == 0; /// <summary> /// Gets or sets the invoice number for this order. /// </summary> public int InvoiceNumber { get { return _order.InvoiceNumber; } set { if (_order.InvoiceNumber != value) { _order.InvoiceNumber = value; OnPropertyChanged(nameof(InvoiceNumber)); HasChanges = true; } } } /// <summary> /// Gets or sets the customer for this order. This value is null /// unless you manually retrieve the customer (using CustomerId) and /// set it. /// </summary> public Customer Customer { get { return _order.Customer; } set { if (_order.Customer != value) { var isLoadingOperation = _order.Customer == null && value != null && !IsNewOrder; _order.Customer = value; OnPropertyChanged(nameof(Customer)); if (isLoadingOperation) { OnPropertyChanged(nameof(IsLoaded)); OnPropertyChanged(nameof(IsNotLoaded)); } else { HasChanges = true; } } } } private ObservableCollection<LineItem> _lineItems = new ObservableCollection<LineItem>(); /// <summary> /// Gets the line items in this invoice. /// </summary> public virtual ObservableCollection<LineItem> LineItems { get { return _lineItems; } set { if (_lineItems != value) { if (value != null) { value.CollectionChanged += lineItems_Changed; } if (_lineItems != null) { _lineItems.CollectionChanged -= lineItems_Changed; } _lineItems = value; OnPropertyChanged(nameof(LineItems)); HasChanges = true; } } } /// <summary> /// Notifies anyone listening to this object that a line item changed. /// </summary> private void lineItems_Changed(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (LineItems != null) { _order.LineItems = LineItems.ToList<LineItem>(); } OnPropertyChanged(nameof(LineItems)); OnPropertyChanged(nameof(Subtotal)); OnPropertyChanged(nameof(Tax)); OnPropertyChanged(nameof(GrandTotal)); HasChanges = true; } private LineItemWrapper _newLineItem; /// <summary> /// Gets or sets the line item that the user is currently working on. /// </summary> public LineItemWrapper NewLineItem { get { return _newLineItem; } set { if (value != _newLineItem) { if (value != null) { value.PropertyChanged += _newLineItem_PropertyChanged; } if (_newLineItem != null) { _newLineItem.PropertyChanged -= _newLineItem_PropertyChanged; } _newLineItem = value; OnPropertyChanged(nameof(NewLineItem)); } } } private void _newLineItem_PropertyChanged(object sender, PropertyChangedEventArgs e) { OnPropertyChanged(nameof(NewLineItem)); OnPropertyChanged(nameof(HasNewLineItem)); } /// <summary> /// Gets or sets whether there is a new line item in progress. /// </summary> public bool HasNewLineItem { get { return NewLineItem != null && NewLineItem.Product != null; } } /// <summary> /// Gets or sets the date this order was placed. /// </summary> public DateTime DatePlaced { get { return _order.DatePlaced; } set { if (_order.DatePlaced != value) { _order.DatePlaced = value; OnPropertyChanged(nameof(DatePlaced)); HasChanges = true; } } } /// <summary> /// Gets or sets the date this order was filled. /// This value is automatically updated when the /// OrderStatus changes. /// </summary> public DateTime? DateFilled { get { return _order.DateFilled; } set { if (value != _order.DateFilled) { _order.DateFilled = value; OnPropertyChanged(nameof(DateFilled)); HasChanges = true; } } } /// <summary> /// Gets the subtotal. This value is calculated automatically. /// </summary> public decimal Subtotal => _order.Subtotal; /// <summary> /// Gets the tax. This value is calculated automatically. /// </summary> public decimal Tax => _order.Tax; /// <summary> /// Gets the total. This value is calculated automatically. /// </summary> public decimal GrandTotal => _order.GrandTotal; /// <summary> /// Gets or sets the shipping address, which may be different /// from the customer's primary address. /// </summary> public string Address { get { return _order.Address; } set { if (_order.Address != value) { _order.Address = value; OnPropertyChanged(nameof(Address)); HasChanges = true; } } } /// <summary> /// Gets or sets the payment status. /// </summary> public PaymentStatus PaymentStatus { get { return _order.PaymentStatus; } set { if (_order.PaymentStatus != value) { _order.PaymentStatus = value; OnPropertyChanged(nameof(PaymentStatus)); HasChanges = true; } } } /// <summary> /// Gets or sets the payment term. /// </summary> public Term Term { get { return _order.Term; } set { if (_order.Term != value) { _order.Term = value; OnPropertyChanged(nameof(Term)); HasChanges = true; } } } /// <summary> /// Gets or sets the order status. /// </summary> public OrderStatus Status { get { return _order.Status; } set { if (_order.Status != value) { _order.Status = value; OnPropertyChanged(nameof(Status)); // Update the DateFilled value. DateFilled = _order.Status == OrderStatus.Filled ? (Nullable<DateTime>)DateTime.Now : null; HasChanges = true; } } } /// <summary> /// Gets or sets the name of the order's customer. /// </summary> public string CustomerName { get { return _order.CustomerName; } set { if (_order.CustomerName != value) { _order.CustomerName = value; OnPropertyChanged("CustomerName"); } } } /// <summary> /// Gets a string representation of the order. /// </summary> /// <returns></returns> public override string ToString() => $"{_order.InvoiceNumber}"; /// <summary> /// Fired when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Notifies listeners that a property value changed. /// </summary> /// <param name="propertyName">The name of the property that changed. </param> protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Converts an Order to an OrderDetailPageViewModel. /// </summary> /// <param name="order">The EnterpriseModels.Order to convert.</param> public static implicit operator OrderDetailPageViewModel(Order order) { return new OrderDetailPageViewModel(order); } /// <summary> /// Converts an OrderDetailPageViewModel to an Order. /// </summary> /// <param name="order">The OrderDetailPageViewModel to convert.</param> public static implicit operator Order(OrderDetailPageViewModel order) { order._order.LineItems = order.LineItems.ToList<LineItem>(); return order._order; } /// <summary> /// Gets the set of order status values so we can populate the order status combo box. /// </summary> public List<string> OrderStatusValues => Enum.GetNames(typeof(OrderStatus)).ToList(); /// <summary> /// Gets the set of payment status values so we can populate the payment status combo box. /// </summary> public List<string> PaymentStatusValues => Enum.GetNames(typeof(PaymentStatus)).ToList(); /// <summary> /// Gets the set of payment term values, so we can populate the term status combo box. /// </summary> public List<string> TermValues => Enum.GetNames(typeof(Term)).ToList(); /// <summary> /// Saves the current order to the database. /// </summary> public async Task SaveOrder() { Order result = null; try { var db = new ContosoModels.ContosoDataSource(); result = await db.Orders.PostAsync(_order); } catch (Exception ex) { throw new OrderSavingException("Unable to save. There might have been a problem " + "connecting to the database. Please try again.", ex); } if (result != null) { await Utilities.CallOnUiThreadAsync(() => HasChanges = false); } else { await Utilities.CallOnUiThreadAsync(() => new OrderSavingException( "Unable to save. There might have been a problem " + "connecting to the database. Please try again.")); } } /// <summary> /// Stores the product suggestions. /// </summary> public ObservableCollection<Product> ProductSuggestions { get; } = new ObservableCollection<Product>(); /// <summary> /// Queries the database and updates the list of new product suggestions. /// </summary> /// <param name="queryText">The query to submit.</param> public async void UpdateProductSuggestions(string queryText) { ProductSuggestions.Clear(); if (!string.IsNullOrEmpty(queryText)) { var dataSource = new ContosoModels.ContosoDataSource(); var suggestions = await dataSource.Products.GetAsync(queryText); foreach (Product p in suggestions) { ProductSuggestions.Add(p); } } } } public class LineItemWrapper : INotifyPropertyChanged { LineItem _item; public LineItemWrapper() { _item = new LineItem(); } public LineItemWrapper(LineItem item) { _item = item; } public Product Product { get { return _item.Product; } set { if (_item.Product != value) { _item.Product = value; OnPropertyChanged(); } } } public Guid ProductId { get { return _item.ProductId; } set { if (_item.ProductId != value) { _item.ProductId = value; OnPropertyChanged(); } } } public int Quantity { get { return _item.Quantity; } set { if (_item.Quantity != value) { _item.Quantity = value; OnPropertyChanged(); } } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); /// <summary> /// Converts an LineItem to an LineItemWrapper. /// </summary> /// <param name="order">The LineItem to convert.</param> public static implicit operator LineItemWrapper(LineItem item) => new LineItemWrapper(item); /// <summary> /// Converts an LineItemWrapper to an LineItem. /// </summary> /// <param name="item">The LineItemWrapper to convert.</param> public static implicit operator LineItem(LineItemWrapper item) => item._item; } public class OrderSavingException : Exception { public OrderSavingException() : base("Error saving an order.") { } public OrderSavingException(string message) : base(message) { } public OrderSavingException(string message, Exception innerException) : base(message, innerException) { } } }
//for details on this class see my article 'The Helper Trinity' at http://www.codeproject.com/csharp/thehelpertrinity.asp using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; namespace SyNet.BindingHelpers { /// <summary> /// Provides helper methods for asserting arguments. /// </summary> /// <remarks> /// <para> /// This class provides helper methods for asserting the validity of arguments. It can be used to reduce the number of /// laborious <c>if</c>, <c>throw</c> sequences in your code. /// </para> /// </remarks> /// <example> /// The following code ensures that the <c>name</c> argument is not <see langword="null"/>: /// <code> /// public void DisplayDetails(string name) /// { /// ArgumentHelper.AssertNotNull(name, "name"); /// //now we know that name is not null /// ... /// } /// </code> /// </example> /// <example> /// The following code ensures that the <c>name</c> argument is not <see langword="null"/> or an empty <c>string</c>: /// <code> /// public void DisplayDetails(string name) /// { /// ArgumentHelper.AssertNotNullOrEmpty(name, "name", true); /// //now we know that name is not null and is not an empty string (or blank) /// ... /// } /// </code> /// </example> /// <example> /// The following code ensures that the <c>day</c> parameter is a valid member of its enumeration: /// <code> /// public void DisplayInformation(DayOfWeek day) /// { /// ArgumentHelper.AssertEnumMember(day); /// //now we know that day is a valid member of DayOfWeek /// ... /// } /// </code> /// </example> /// <example> /// The following code ensures that the <c>day</c> parameter is either DayOfWeek.Monday or DayOfWeek.Thursday: /// <code> /// public void DisplayInformation(DayOfWeek day) /// { /// ArgumentHelper.AssertEnumMember(day, DayOfWeek.Monday, DayOfWeek.Thursday); /// //now we know that day is either Monday or Thursday /// ... /// } /// </code> /// </example> /// <example> /// The following code ensures that the <c>bindingFlags</c> parameter is either BindingFlags.Public, BindingFlags.NonPublic /// or both: /// <code> /// public void GetInformation(BindingFlags bindingFlags) /// { /// ArgumentHelper.AssertEnumMember(bindingFlags, BindingFlags.Public, BindingFlags.NonPublic); /// //now we know that bindingFlags is either Public, NonPublic or both /// ... /// } /// </code> /// </example> /// <example> /// The following code ensures that the <c>bindingFlags</c> parameter is either BindingFlags.Public, BindingFlags.NonPublic, /// both or neither (BindingFlags.None): /// <code> /// public void GetInformation(BindingFlags bindingFlags) /// { /// ArgumentHelper.AssertEnumMember(bindingFlags, BindingFlags.Public, BindingFlags.NonPublic, BindingFlags.None); /// //now we know that bindingFlags is either Public, NonPublic, both or neither /// ... /// } /// </code> /// </example> public static class ArgumentHelper { /// <summary> /// Ensures that <paramref name="arg"/> is not <see langword="null"/>. If it is, an <see cref="ArgumentNullException"/> /// is thrown. /// </summary> /// <typeparam name="T"> /// The type of the argument. /// </typeparam> /// <param name="arg"> /// The argument to check for <see langword="null"/>. /// </param> /// <param name="argName"> /// The name of the argument. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="arg"/> is <see langword="null"/>. /// </exception> [DebuggerHidden] public static void AssertNotNull<T>(T arg, string argName) where T : class { if (arg == null) { throw new ArgumentNullException(argName); } } /// <summary> /// Ensures that <paramref name="arg"/> is not <see langword="null"/>. If it is, an <see cref="ArgumentNullException"/> /// is thrown. /// </summary> /// <typeparam name="T"> /// The type of the nullable argument. /// </typeparam> /// <param name="arg"> /// The nullable argument. /// </param> /// <param name="argName"> /// The name of the argument. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="arg"/> is <see langword="null"/>. /// </exception> [DebuggerHidden] public static void AssertNotNull<T>(Nullable<T> arg, string argName) where T : struct { if (!arg.HasValue) { throw new ArgumentNullException(argName); } } /// <summary> /// Ensures that <paramref name="arg"/> is not <see langword="null"/>. If it is, an <see cref="ArgumentNullException"/> /// is thrown. /// </summary> /// <remarks> /// <para> /// This method can be used instead of one of the overloads in the case where the argument /// being checked is generic. It will ensure that <paramref name="arg"/> is nto <see langword="null"/> if it is a /// reference type or if it is an instance of <see cref="Nullable{T}"/>. /// </para> /// </remarks> /// <typeparam name="T"> /// The type of the argument. /// </typeparam> /// <param name="arg"> /// The argument. /// </param> /// <param name="argName"> /// The name of the argument. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="arg"/> is <see langword="null"/>. /// </exception> /// <example> /// The following code ensures that the <c>name</c> argument is not <see langword="null"/> or an empty <c>string</c>: /// <code> /// public void SomeMethod&lt;T&gt;(T arg) /// { /// ArgumentHelper.AssertGenericArgumentNotNull(arg, "arg"); /// //now we know that arg is not null, regardless of whether it is a reference type or a Nullable type /// ... /// } /// </code> /// </example> [DebuggerHidden] public static void AssertGenericArgumentNotNull<T>(T arg, string argName) { Type type = typeof(T); if (type.IsClass || (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))) { AssertNotNull((object) arg, argName); } } /// <summary> /// Ensures that <paramref name="arg"/> is not <see langword="null"/>, optionally checking each item in it for /// <see langword="null"/>. If any checked items are <see langword="null"/>, an exception is thrown. /// </summary> /// <remarks> /// <para> /// This method throws an <see cref="ArgumentNullException"/> if <paramref name="arg"/> is <see langword="null"/>. If /// <paramref name="assertContentsNotNull"/> is <see langword="true"/> and one of the items in <paramref name="arg"/> /// is found to be <see langword="null"/>, an <see cref="ArgumentException"/> is thrown. /// </para> /// </remarks> /// <typeparam name="T"> /// The type of the items in the <paramref name="arg"/> enumeration. /// </typeparam> /// <param name="arg"> /// The argument to check for <see langword="null"/>. /// </param> /// <param name="argName"> /// The name of the argument. /// </param> /// <param name="assertContentsNotNull"> /// If <see langword="true"/>, each item inside the <paramref name="arg"/> enumeration is also checked for /// <see langword="null"/>. If <see langword="false"/>, only <paramref name="arg"/> itself is checked for /// <see langword="null"/>. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="assertContentsNotNull"/> is <see langword="true"/> and one of the items in <paramref name="arg"/> /// is <see langword="null"/>. /// </exception> [DebuggerHidden] public static void AssertNotNull<T>(IEnumerable<T> arg, string argName, bool assertContentsNotNull) { //make sure the enumerable item itself isn't null AssertNotNull(arg, argName); if (assertContentsNotNull && typeof(T).IsClass) { //make sure each item in the enumeration isn't null foreach (T item in arg) { if (item == null) { throw new ArgumentException("An item inside the enumeration was null.", argName); } } } } /// <summary> /// Ensures that <paramref name="arg"/> is not <see langword="null"/> or an empty <c>string</c>. If it is, an /// <see cref="ArgumentException"/> is thrown. /// </summary> /// <param name="arg"> /// The argument to check for <see langword="null"/> or an empty <c>string</c>. /// </param> /// <param name="argName"> /// The name of the argument. /// </param> [DebuggerHidden] public static void AssertNotNullOrEmpty(string arg, string argName) { AssertNotNullOrEmpty(arg, argName, false); } /// <summary> /// Ensures that <paramref name="arg"/> is not <see langword="null"/> or an empty <c>string</c>, optionally trimming /// <paramref name="arg"/> first. If it is, an <see cref="ArgumentException"/> is thrown. /// </summary> /// <param name="arg"> /// The argument to check for <see langword="null"/> or an empty <c>string</c>. /// </param> /// <param name="argName"> /// The name of the argument. /// </param> /// <param name="trim"> /// If <see langword="true"/> and <paramref name="arg"/> is not <see langword="null"/> or an empty <c>string</c>, it is /// trimmed and re-tested for being empty. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="arg"/> is <see langword="null"/> or an empty <c>string</c>, or if it is a blank <c>string</c> and /// <paramref name="trim"/> is <see langword="true"/>. /// </exception> [DebuggerHidden] public static void AssertNotNullOrEmpty(string arg, string argName, bool trim) { if (string.IsNullOrEmpty(arg) || (trim && (arg.Trim().Length == 0))) { throw new ArgumentException("Cannot be null or empty.", argName); } } /// <summary> /// Ensures that <paramref name="enumValue"/> is a valid member of the <typeparamref name="TEnum"/> enumeration. If it /// is not, an <see cref="ArgumentException"/> is thrown. /// </summary> /// <remarks> /// <para> /// This method can be used to validate all publicly-supplied enumeration values. Without such an assertion, it is /// possible to cast any <c>int</c> value to the enumeration type and pass it in. /// </para> /// <para> /// This method works for both flags and non-flags enumerations. In the case of a flags enumeration, any combination of /// values in the enumeration is accepted. In the case of a non-flags enumeration, <paramref name="enumValue"/> must /// be equal to one of the values in the enumeration. /// </para> /// <para> /// This method is generic and quite slow as a result. You should prefer using the /// <see cref="AssertEnumMember{TEnum}(TEnum, TEnum[])"/> overload where possible. That overload is both faster and /// safer. Faster because it does not incur reflection costs, and safer because you are able to specify the exact /// values accepted by your method. /// </para> /// </remarks> /// <typeparam name="TEnum"> /// The enumeration type. /// </typeparam> /// <param name="enumValue"> /// The value of the enumeration. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="enumValue"/> is not a valid member of the <typeparamref name="TEnum"/> enumeration. /// </exception> [DebuggerHidden] public static void AssertEnumMember<TEnum>(TEnum enumValue) where TEnum : struct, IConvertible { if (Attribute.IsDefined(typeof(TEnum), typeof(FlagsAttribute), false)) { //flag enumeration - we can only get here if TEnum is a valid enumeration type, since the FlagsAttribute can //only be applied to enumerations bool throwEx = false; long longValue = enumValue.ToInt64(CultureInfo.InvariantCulture); if (longValue == 0) { //only throw if zero isn't defined in the enum - we have to convert zero to the underlying type of the enum throwEx = !Enum.IsDefined(typeof(TEnum), ((IConvertible) 0).ToType(Enum.GetUnderlyingType(typeof(TEnum)), CultureInfo.InvariantCulture)); } else { foreach (TEnum value in Enum.GetValues(typeof(TEnum))) { longValue &= ~value.ToInt64(CultureInfo.InvariantCulture); } //throw if there is a value left over after removing all valid values throwEx = (longValue != 0); } if (throwEx) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Enum value '{0}' is not valid for flags enumeration '{1}'.", enumValue, typeof(TEnum).FullName)); } } else { //not a flag enumeration if (!Enum.IsDefined(typeof(TEnum), enumValue)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Enum value '{0}' is not defined for enumeration '{1}'.", enumValue, typeof(TEnum).FullName)); } } } /// <summary> /// Ensures that <paramref name="enumValue"/> is included in the values specified by <paramref name="validValues"/>. If /// it is not, an <see cref="ArgumentException"/> is thrown. /// </summary> /// <remarks> /// <para> /// This method can be used to ensure that an enumeration argument is valid for the context of the method. It works for /// both flags and non-flags enumerations. For flags enumerations, <paramref name="enumValue"/> must be any combination /// of values specified by <paramref name="validValues"/>. For non-flags enumerations, <paramref name="enumValue"/> /// must be one of the values specified by <paramref name="validValues"/>. /// </para> /// <para> /// This method is much faster than the <see cref="AssertEnumMember{TEnum}(TEnum)"/> overload. This is because it does /// not use reflection to determine the values defined by the enumeration. For this reason you should prefer this method /// when validating enumeration arguments. /// </para> /// <para> /// Another reason why this method is prefered is because it allows you to explicitly specify the values that your code /// handles. If you use the <see cref="AssertEnumMember{TEnum}(TEnum)"/> overload and a new value is later added to the /// enumeration, the assertion will not fail but your code probably will. /// </para> /// </remarks> /// <typeparam name="TEnum"> /// The enumeration type. /// </typeparam> /// <param name="enumValue"> /// The value of the enumeration. /// </param> /// <param name="validValues"> /// An array of all valid values. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="validValues"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="enumValue"/> is not present in <paramref name="validValues"/>, or (for flag enumerations) if /// <paramref name="enumValue"/> is not some combination of values specified in <paramref name="validValues"/>. /// </exception> [DebuggerHidden] public static void AssertEnumMember<TEnum>(TEnum enumValue, params TEnum[] validValues) where TEnum : struct, IConvertible { AssertNotNull(validValues, "validValues"); if (Attribute.IsDefined(typeof(TEnum), typeof(FlagsAttribute), false)) { //flag enumeration bool throwEx = false; long longValue = enumValue.ToInt64(CultureInfo.InvariantCulture); if (longValue == 0) { //only throw if zero isn't permitted by the valid values throwEx = true; foreach (TEnum value in validValues) { if (value.ToInt64(CultureInfo.InvariantCulture) == 0) { throwEx = false; break; } } } else { foreach (TEnum value in validValues) { longValue &= ~value.ToInt64(CultureInfo.InvariantCulture); } //throw if there is a value left over after removing all valid values throwEx = (longValue != 0); } if (throwEx) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Enum value '{0}' is not allowed for flags enumeration '{1}'.", enumValue, typeof(TEnum).FullName)); } } else { //not a flag enumeration foreach (TEnum value in validValues) { if (enumValue.Equals(value)) { return; } } //at this point we know an exception is required - however, we want to tailor the message based on whether the //specified value is undefined or simply not allowed if (!Enum.IsDefined(typeof(TEnum), enumValue)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Enum value '{0}' is not defined for enumeration '{1}'.", enumValue, typeof(TEnum).FullName)); } else { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Enum value '{0}' is defined for enumeration '{1}' but it is not permitted in this context.", enumValue, typeof(TEnum).FullName)); } } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmStockList2 { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmStockList2() : base() { FormClosed += frmStockList2_FormClosed; KeyPress += frmStockList2_KeyPress; KeyDown += frmStockList2_KeyDown; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private myDataGridView withEventsField_DataList1; public myDataGridView DataList1 { get { return withEventsField_DataList1; } set { if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick -= DataList1_DblClick; withEventsField_DataList1.KeyPress -= DataList1_KeyPress; } withEventsField_DataList1 = value; if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick += DataList1_DblClick; withEventsField_DataList1.KeyPress += DataList1_KeyPress; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter -= txtSearch_Enter; withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter += txtSearch_Enter; withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.Button withEventsField_cmdNamespace; public System.Windows.Forms.Button cmdNamespace { get { return withEventsField_cmdNamespace; } set { if (withEventsField_cmdNamespace != null) { withEventsField_cmdNamespace.Click -= cmdNamespace_Click; } withEventsField_cmdNamespace = value; if (withEventsField_cmdNamespace != null) { withEventsField_cmdNamespace.Click += cmdNamespace_Click; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Label lbl; public System.Windows.Forms.Label lblHeading; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmStockList2)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.DataList1 = new myDataGridView(); this.txtSearch = new System.Windows.Forms.TextBox(); this.cmdNamespace = new System.Windows.Forms.Button(); this.cmdExit = new System.Windows.Forms.Button(); this.lbl = new System.Windows.Forms.Label(); this.lblHeading = new System.Windows.Forms.Label(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Select a Stock Item"; this.ClientSize = new System.Drawing.Size(362, 451); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmStockList2"; //DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State) this.DataList1.Size = new System.Drawing.Size(244, 342); this.DataList1.Location = new System.Drawing.Point(6, 27); this.DataList1.TabIndex = 2; this.DataList1.Name = "DataList1"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(302, 19); this.txtSearch.Location = new System.Drawing.Point(51, 3); this.txtSearch.TabIndex = 1; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.cmdNamespace.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNamespace.Text = "&Filter"; this.cmdNamespace.Size = new System.Drawing.Size(97, 52); this.cmdNamespace.Location = new System.Drawing.Point(256, 32); this.cmdNamespace.TabIndex = 3; this.cmdNamespace.TabStop = false; this.cmdNamespace.BackColor = System.Drawing.SystemColors.Control; this.cmdNamespace.CausesValidation = true; this.cmdNamespace.Enabled = true; this.cmdNamespace.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNamespace.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNamespace.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNamespace.Name = "cmdNamespace"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(258, 318); this.cmdExit.TabIndex = 4; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lbl.Text = "&Search :"; this.lbl.Size = new System.Drawing.Size(40, 13); this.lbl.Location = new System.Drawing.Point(8, 6); this.lbl.TabIndex = 0; this.lbl.BackColor = System.Drawing.Color.Transparent; this.lbl.Enabled = true; this.lbl.ForeColor = System.Drawing.SystemColors.ControlText; this.lbl.Cursor = System.Windows.Forms.Cursors.Default; this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lbl.UseMnemonic = true; this.lbl.Visible = true; this.lbl.AutoSize = true; this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lbl.Name = "lbl"; this.lblHeading.Text = "Using the \"Stock Item Selector\" ....."; this.lblHeading.Size = new System.Drawing.Size(349, 70); this.lblHeading.Location = new System.Drawing.Point(6, 375); this.lblHeading.TabIndex = 5; this.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblHeading.BackColor = System.Drawing.SystemColors.Control; this.lblHeading.Enabled = true; this.lblHeading.ForeColor = System.Drawing.SystemColors.ControlText; this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default; this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblHeading.UseMnemonic = true; this.lblHeading.Visible = true; this.lblHeading.AutoSize = false; this.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblHeading.Name = "lblHeading"; this.Controls.Add(DataList1); this.Controls.Add(txtSearch); this.Controls.Add(cmdNamespace); this.Controls.Add(cmdExit); this.Controls.Add(lbl); this.Controls.Add(lblHeading); ((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.Versioning; using FluentMigrator.Infrastructure.Extensions; namespace FluentMigrator.Runner { public class MigrationRunner : IMigrationRunner { private IAssemblyCollection _migrationAssemblies; private IAnnouncer _announcer; private IStopWatch _stopWatch; private bool _alreadyOutputPreviewOnlyModeWarning; private readonly MigrationValidator _migrationValidator; private readonly MigrationScopeHandler _migrationScopeHandler; public bool TransactionPerSession { get { return RunnerContext.TransactionPerSession; } } public bool SilentlyFail { get; set; } public IMigrationProcessor Processor { get; private set; } public IMigrationInformationLoader MigrationLoader { get; set; } public IProfileLoader ProfileLoader { get; set; } public IMaintenanceLoader MaintenanceLoader { get; set; } public IMigrationConventions Conventions { get; private set; } public IList<Exception> CaughtExceptions { get; private set; } public IMigrationScope CurrentScope { get { return _migrationScopeHandler.CurrentScope; } set { _migrationScopeHandler.CurrentScope = value; } } public IRunnerContext RunnerContext { get; private set; } public MigrationRunner(Assembly assembly, IRunnerContext runnerContext, IMigrationProcessor processor) : this(new SingleAssembly(assembly), runnerContext, processor) { } public MigrationRunner(IAssemblyCollection assemblies, IRunnerContext runnerContext, IMigrationProcessor processor) { _migrationAssemblies = assemblies; _announcer = runnerContext.Announcer; Processor = processor; _stopWatch = runnerContext.StopWatch; RunnerContext = runnerContext; SilentlyFail = false; CaughtExceptions = null; Conventions = GetMigrationConventions(runnerContext); if (!string.IsNullOrEmpty(runnerContext.WorkingDirectory)) Conventions.GetWorkingDirectory = () => runnerContext.WorkingDirectory; _migrationScopeHandler = new MigrationScopeHandler(Processor); _migrationValidator = new MigrationValidator(_announcer, Conventions); MigrationLoader = new DefaultMigrationInformationLoader(Conventions, _migrationAssemblies, runnerContext.Namespace, runnerContext.NestedNamespaces, runnerContext.Tags); ProfileLoader = new ProfileLoader(runnerContext, this, Conventions); MaintenanceLoader = new MaintenanceLoader(_migrationAssemblies, runnerContext.Tags, Conventions); if (runnerContext.NoConnection){ VersionLoader = new ConnectionlessVersionLoader(this, _migrationAssemblies, Conventions, runnerContext.StartVersion, runnerContext.Version); } else{ VersionLoader = new VersionLoader(this, _migrationAssemblies, Conventions); } } private IMigrationConventions GetMigrationConventions(IRunnerContext runnerContext) { Type matchedType = this._migrationAssemblies.GetExportedTypes().FirstOrDefault(t => typeof(IMigrationConventions).IsAssignableFrom(t)); if (matchedType == null) { if (!string.IsNullOrEmpty(runnerContext.SchemaName)) { return new MigrationConventionsWithDefaultSchema(runnerContext.SchemaName); } return new MigrationConventions(); } return (IMigrationConventions)Activator.CreateInstance(matchedType); } public IVersionLoader VersionLoader { get; set; } public void ApplyProfiles() { ProfileLoader.ApplyProfiles(); } public void ApplyMaintenance(MigrationStage stage, bool useAutomaticTransactionManagement) { var maintenanceMigrations = MaintenanceLoader.LoadMaintenance(stage); foreach (var maintenanceMigration in maintenanceMigrations) { ApplyMigrationUp(maintenanceMigration, useAutomaticTransactionManagement && maintenanceMigration.TransactionBehavior == TransactionBehavior.Default); } } public void MigrateUp() { MigrateUp(true); } public void MigrateUp(bool useAutomaticTransactionManagement) { var migrations = MigrationLoader.LoadMigrations(); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { try { ApplyMaintenance(MigrationStage.BeforeAll, useAutomaticTransactionManagement); foreach (var pair in migrations) { ApplyMaintenance(MigrationStage.BeforeEach, useAutomaticTransactionManagement); ApplyMigrationUp(pair.Value, useAutomaticTransactionManagement && pair.Value.TransactionBehavior == TransactionBehavior.Default); ApplyMaintenance(MigrationStage.AfterEach, useAutomaticTransactionManagement); } ApplyMaintenance(MigrationStage.BeforeProfiles, useAutomaticTransactionManagement); ApplyProfiles(); ApplyMaintenance(MigrationStage.AfterAll, useAutomaticTransactionManagement); scope.Complete(); } catch { if (scope.IsActive) scope.Cancel(); // SQLAnywhere needs explicit call to rollback transaction throw; } } VersionLoader.LoadVersionInfo(); } public void MigrateUp(long targetVersion) { MigrateUp(targetVersion, true); } public void MigrateUp(long targetVersion, bool useAutomaticTransactionManagement) { var migrationInfos = GetUpMigrationsToApply(targetVersion); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { try { foreach (var migrationInfo in migrationInfos) { ApplyMigrationUp(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default); } ApplyProfiles(); scope.Complete(); } catch { if (scope.IsActive) scope.Cancel(); // SQLAnywhere needs explicit call to rollback transaction throw; } } VersionLoader.LoadVersionInfo(); } private IEnumerable<IMigrationInfo> GetUpMigrationsToApply(long version) { var migrations = MigrationLoader.LoadMigrations(); return from pair in migrations where IsMigrationStepNeededForUpMigration(pair.Key, version) select pair.Value; } private bool IsMigrationStepNeededForUpMigration(long versionOfMigration, long targetVersion) { if (versionOfMigration <= targetVersion && !VersionLoader.VersionInfo.HasAppliedMigration(versionOfMigration)) { return true; } return false; } public void MigrateDown(long targetVersion) { MigrateDown(targetVersion, true); } public void MigrateDown(long targetVersion, bool useAutomaticTransactionManagement) { var migrationInfos = GetDownMigrationsToApply(targetVersion); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { try { foreach (var migrationInfo in migrationInfos) { ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default); } ApplyProfiles(); scope.Complete(); } catch { if (scope.IsActive) scope.Cancel(); // SQLAnywhere needs explicit call to rollback transaction throw; } } VersionLoader.LoadVersionInfo(); } private IEnumerable<IMigrationInfo> GetDownMigrationsToApply(long targetVersion) { var migrations = MigrationLoader.LoadMigrations(); var migrationsToApply = (from pair in migrations where IsMigrationStepNeededForDownMigration(pair.Key, targetVersion) select pair.Value) .ToList(); return migrationsToApply.OrderByDescending(x => x.Version); } private bool IsMigrationStepNeededForDownMigration(long versionOfMigration, long targetVersion) { if (versionOfMigration > targetVersion && VersionLoader.VersionInfo.HasAppliedMigration(versionOfMigration)) { return true; } return false; } public virtual void ApplyMigrationUp(IMigrationInfo migrationInfo, bool useTransaction) { if (migrationInfo == null) throw new ArgumentNullException("migrationInfo"); if (!_alreadyOutputPreviewOnlyModeWarning && Processor.Options.PreviewOnly) { _announcer.Heading("PREVIEW-ONLY MODE"); _alreadyOutputPreviewOnlyModeWarning = true; } if (!migrationInfo.IsAttributed() || !VersionLoader.VersionInfo.HasAppliedMigration(migrationInfo.Version)) { var name = migrationInfo.GetName(); _announcer.Heading(string.Format("{0} migrating", name)); _stopWatch.Start(); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useTransaction)) { try { ExecuteMigration(migrationInfo.Migration, (m, c) => m.GetUpExpressions(c)); if (migrationInfo.IsAttributed()) { VersionLoader.UpdateVersionInfo(migrationInfo.Version, migrationInfo.Description ?? migrationInfo.Migration.GetType().Name); } scope.Complete(); } catch { if (useTransaction && scope.IsActive) scope.Cancel(); // SQLAnywhere needs explicit call to rollback transaction throw; } _stopWatch.Stop(); _announcer.Say(string.Format("{0} migrated", name)); _announcer.ElapsedTime(_stopWatch.ElapsedTime()); } } } public virtual void ApplyMigrationDown(IMigrationInfo migrationInfo, bool useTransaction) { if (migrationInfo == null) throw new ArgumentNullException("migrationInfo"); var name = migrationInfo.GetName(); _announcer.Heading(string.Format("{0} reverting", name)); _stopWatch.Start(); using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useTransaction)) { try { ExecuteMigration(migrationInfo.Migration, (m, c) => m.GetDownExpressions(c)); if (migrationInfo.IsAttributed()) VersionLoader.DeleteVersion(migrationInfo.Version); scope.Complete(); } catch { if (useTransaction && scope.IsActive) scope.Cancel(); // SQLAnywhere needs explicit call to rollback transaction throw; } _stopWatch.Stop(); _announcer.Say(string.Format("{0} reverted", name)); _announcer.ElapsedTime(_stopWatch.ElapsedTime()); } } public void Rollback(int steps) { Rollback(steps, true); } public void Rollback(int steps, bool useAutomaticTransactionManagement) { var availableMigrations = MigrationLoader.LoadMigrations(); var migrationsToRollback = new List<IMigrationInfo>(); foreach (long version in VersionLoader.VersionInfo.AppliedMigrations()) { IMigrationInfo migrationInfo; if (availableMigrations.TryGetValue(version, out migrationInfo)) migrationsToRollback.Add(migrationInfo); } using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { try { foreach (IMigrationInfo migrationInfo in migrationsToRollback.Take(steps)) { ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default); } scope.Complete(); } catch { if (scope.IsActive) scope.Cancel(); // SQLAnywhere needs explicit call to rollback transaction throw; } } VersionLoader.LoadVersionInfo(); if (!VersionLoader.VersionInfo.AppliedMigrations().Any()) VersionLoader.RemoveVersionTable(); } public void RollbackToVersion(long version) { RollbackToVersion(version, true); } public void RollbackToVersion(long version, bool useAutomaticTransactionManagement) { var availableMigrations = MigrationLoader.LoadMigrations(); var migrationsToRollback = new List<IMigrationInfo>(); foreach (long appliedVersion in VersionLoader.VersionInfo.AppliedMigrations()) { IMigrationInfo migrationInfo; if (availableMigrations.TryGetValue(appliedVersion, out migrationInfo)) migrationsToRollback.Add(migrationInfo); } using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession)) { try { foreach (IMigrationInfo migrationInfo in migrationsToRollback) { if (version >= migrationInfo.Version) continue; ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default); } scope.Complete(); } catch { if (scope.IsActive) scope.Cancel(); // SQLAnywhere needs explicit call to rollback transaction throw; } } VersionLoader.LoadVersionInfo(); if (version == 0 && !VersionLoader.VersionInfo.AppliedMigrations().Any()) VersionLoader.RemoveVersionTable(); } public IAssemblyCollection MigrationAssemblies { get { return _migrationAssemblies; } } public void Up(IMigration migration) { var migrationInfoAdapter = new NonAttributedMigrationToMigrationInfoAdapter(migration); ApplyMigrationUp(migrationInfoAdapter, true); } private void ExecuteMigration(IMigration migration, Action<IMigration, IMigrationContext> getExpressions) { CaughtExceptions = new List<Exception>(); var context = new MigrationContext(Conventions, Processor, MigrationAssemblies, RunnerContext.ApplicationContext, Processor.ConnectionString); getExpressions(migration, context); _migrationValidator.ApplyConventionsToAndValidateExpressions(migration, context.Expressions); ExecuteExpressions(context.Expressions); } public void Down(IMigration migration) { var migrationInfoAdapter = new NonAttributedMigrationToMigrationInfoAdapter(migration); ApplyMigrationDown(migrationInfoAdapter, true); } /// <summary> /// execute each migration expression in the expression collection /// </summary> /// <param name="expressions"></param> protected void ExecuteExpressions(ICollection<IMigrationExpression> expressions) { long insertTicks = 0; int insertCount = 0; foreach (IMigrationExpression expression in expressions) { try { if (expression is InsertDataExpression) { insertTicks += _stopWatch.Time(() => expression.ExecuteWith(Processor)).Ticks; insertCount++; } else { AnnounceTime(expression.ToString(), () => expression.ExecuteWith(Processor)); } } catch (Exception er) { _announcer.Error(er); //catch the error and move onto the next expression if (SilentlyFail) { CaughtExceptions.Add(er); continue; } throw; } } if (insertCount > 0) { var avg = new TimeSpan(insertTicks / insertCount); var msg = string.Format("-> {0} Insert operations completed in {1} taking an average of {2}", insertCount, new TimeSpan(insertTicks), avg); _announcer.Say(msg); } } private void AnnounceTime(string message, Action action) { _announcer.Say(message); _announcer.ElapsedTime(_stopWatch.Time(action)); } public void ValidateVersionOrder() { var unappliedVersions = MigrationLoader.LoadMigrations().Where(kvp => MigrationVersionLessThanGreatestAppliedMigration(kvp.Key)).ToList(); if (unappliedVersions.Any()) throw new VersionOrderInvalidException(unappliedVersions); _announcer.Say("Version ordering valid."); } public void ListMigrations() { IVersionInfo currentVersionInfo = this.VersionLoader.VersionInfo; long currentVersion = currentVersionInfo.Latest(); _announcer.Heading("Migrations"); foreach(KeyValuePair<long, IMigrationInfo> migration in MigrationLoader.LoadMigrations()) { string migrationName = migration.Value.GetName(); bool isCurrent = migration.Key == currentVersion; string message = string.Format("{0}{1}", migrationName, isCurrent ? " (current)" : string.Empty); if(isCurrent) _announcer.Emphasize(message); else _announcer.Say(message); } } private bool MigrationVersionLessThanGreatestAppliedMigration(long version) { return !VersionLoader.VersionInfo.HasAppliedMigration(version) && version < VersionLoader.VersionInfo.Latest(); } public IMigrationScope BeginScope() { return _migrationScopeHandler.BeginScope(); } } }
// Created by Paul Gonzalez Becerra using System; namespace Saserdote.DataSystems { public class FList<T>:IFList { #region --- Field Variables --- // Variables public T[] items; #endregion // Field Variables #region --- Constructors --- public FList() { items= new T[0]; } public FList(int listSize) { items= new T[listSize]; } public FList(params T[] pmItems) { if(pmItems!= null) items= pmItems; else items= new T[0]; } #endregion // Constructors #region --- Properties --- // Gets and sets the items of the list public T this[int index] { get { return items[index]; } set { items[index]= value; } } #endregion // Properties #region --- Inherited Properties --- // Gets the size of the items contained public int size { get { return items.Length; } } #endregion // Inherited Properties #region --- Methods --- // Gets the array of items public T[] toArray() { return items; } // Gets the array of items by reference public void toArray(out T[] outArray) { outArray= items; } // Adds in an item into the list public bool add(T item) { // Variables T[] temp= new T[size+1]; for(int i= 0; i< size; i++) temp[i]= items[i]; temp[size]= item; items= temp; return true; } // Adds in a range of items public bool addRange(params T[] range) { // Variables T[] temp= new T[size+range.Length]; int k= 0; for(int i= 0; i< size; i++) temp[i]= items[i]; for(int h= size; h< temp.Length; h++) temp[h]= range[k++]; items= temp; return true; } // Finds if the given item exists inside the list public bool contains(T item, int startIndex) { for(int i= startIndex; i< size; i++) { if(items[i].Equals(item)) return true; } return false; } public bool contains(T item) { return contains(item, 0); } // Gets the index of the given item public int getIndex(T item, int startIndex) { for(int i= startIndex; i< size; i++) { if(items[i].Equals(item)) return i; } return -1; } public int getIndex(T item) { return getIndex(item, 0); } // Removes the item from the given item public bool remove(T item, int startIndex) { return removeAt(getIndex(item, startIndex)); } public bool remove(T item) { return remove(item, 0); } // Inserts the item into the given index slot public void insert(T item, int index) { if(index< 0) index= 0; else if(index>= size) { add(item); return; } // Variables T[] temp= new T[size+1]; int k= index; for(int i= 0; i< index; i++) temp[i]= items[i]; temp[index]= item; for(int h= index+1; h< temp.Length; h++) temp[h]= items[k++]; items= temp; } // Finds if the two lists are equal public bool equals(FList<T> list) { if(size!= list.size) return false; // Variables int trues= 0; for(int h= 0; h< size; h++) { for(int k= 0; k< size; k++) { if(items[h].Equals(list[k])) trues++; } } return (trues== size); } // Shuffles the list public void shuffle(Random rng) { for(int i= size; i>= 0; i--) swap(i, rng.Next(0, i)); } public void shuffle() { shuffle(new Random()); } #endregion // Methods #region --- Inherited Methods --- // Removes all the items in the list public void clear() { items= new T[0]; } // Adds an item to the list public bool add(object item) { if(item is T) return add((T)item); return false; } // Adds a range of items to the list public bool addRange(params object[] range) { if(range.GetType()== typeof(T)) { // Variables T[] temp= new T[range.Length]; for(int i= 0; i< range.Length; i++) temp[i]= (T)range[i]; return addRange(temp); } return false; } // Finds if the item is contained in the list public bool contains(object item) { if(item is T) return contains((T)item); return false; } // Gets the index of the given item public int getIndex(object item, int startIndex) { if(item is T) return getIndex((T)item, startIndex); return -1; } public int getIndex(object item) { return getIndex(item, 0); } // Inserts the item into the list public void insert(object item, int index) { if(item is T) insert((T)item, index); } // Removes the item from the list public bool remove(object item, int startIndex) { if(item is T) return remove((T)item, startIndex); return false; } public bool remove(object item) { return remove(item, 0); } // Removes the item from the list with the given index public bool removeAt(int index) { if(index< 0 || index>= size) return false; // Variables T[] temp= new T[size-1]; int k= index+1; for(int i= 0; i< index; i++) temp[i]= items[i]; if(k>= size) k= size-1; for(int h= index; h< temp.Length; h++) temp[h]= items[k++]; items= temp; return true; } // Reverses the order of the list public void reverseOrder() { // Variables T[] temp= new T[size]; int k= size-1; for(int h= 0; h< size; h++) temp[h]= items[k--]; items= temp; } // Switches the two given indices around public bool swap(int fIndex, int sIndex) { if(fIndex== sIndex) return false; if(fIndex< 0 || fIndex>= size) return false; if(sIndex< 0 || sIndex>= size) return false; // Variables T temp= items[fIndex]; items[fIndex]= items[sIndex]; items[sIndex]= temp; return true; } // Gets the object within the list public object get(int index) { if(index< 0 || index>= size) throw new Exception("Index out of range"); return items[index]; } // Finds if the given object is equal to the list public override bool Equals(object obj) { if(obj== null) return false; if(obj is FList<T>) return equals((FList<T>)obj); return false; } // Gets the hash code public override int GetHashCode() { // Variables int hashcode= 0; for(int i= 0; i< size; i++) hashcode+= items[i].GetHashCode(); return hashcode; } // Prints out all the contents of the list public override string ToString() { // Variables string str= "List of "+typeof(T)+"\n"; str+= "{\n"; for(int i= 0; i< size; i++) { if(i!= size-1) str+= "\t"+items[i].ToString()+",\n"; else str+= "\t"+items[i].ToString()+"\n"; } str+= "}"; return str; } #endregion // Inherited Methods #region --- Operators --- // Equality operators public static bool operator ==(FList<T> left, FList<T> right) { return left.Equals(right); } // Inequality operators public static bool operator !=(FList<T> left, FList<T> right) { return !left.Equals(right); } // Conversion operators // [FList to T[]] public static implicit operator T[](FList<T> castee) { return castee.toArray(); } // [T[] to FList] public static implicit operator FList<T>(T[] castee) { return new FList<T>(castee); } #endregion // Operators } } // End of File
/* * Anarres C Preprocessor * Copyright (c) 2007-2008, Shevek * * 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 boolean = System.Boolean; namespace CppNet { /** * An input to the Preprocessor. * * Inputs may come from Files, Strings or other sources. The * preprocessor maintains a stack of Sources. Operations such as * file inclusion or token pasting will push a new source onto * the Preprocessor stack. Sources pop from the stack when they * are exhausted; this may be transparent or explicit. * * BUG: Error messages are not handled properly. */ public abstract class Source : Iterable<Token>, Closeable { private Source parent; private boolean autopop; private PreprocessorListenerBase listener; private boolean active; private boolean werror; /* LineNumberReader */ /* // We can't do this, since we would lose the LexerException private class Itr implements Iterator { private Token next = null; private void advance() { try { if (next != null) next = token(); } catch (IOException e) { throw new UnsupportedOperationException( "Failed to advance token iterator: " + e.getMessage() ); } } public boolean hasNext() { return next.getType() != EOF; } public Token next() { advance(); Token t = next; next = null; return t; } public void remove() { throw new UnsupportedOperationException( "Cannot remove tokens from a Source." ); } } */ public Source() { this.parent = null; this.autopop = false; this.listener = null; this.active = true; this.werror = false; } /** * Sets the parent source of this source. * * Sources form a singly linked list. */ internal void setParent(Source parent, boolean autopop) { this.parent = parent; this.autopop = autopop; } /** * Returns the parent source of this source. * * Sources form a singly linked list. */ internal Source getParent() { return parent; } // @OverrideMustInvoke internal virtual void init(Preprocessor pp) { setListener(pp.getListener()); this.werror = pp.getWarnings().HasFlag(Warning.ERROR); } /** * Sets the listener for this Source. * * Normally this is set by the Preprocessor when a Source is * used, but if you are using a Source as a standalone object, * you may wish to call this. */ public void setListener(PreprocessorListenerBase pl) { this.listener = pl; } /** * Returns the File currently being lexed. * * If this Source is not a {@link FileLexerSource}, then * it will ask the parent Source, and so forth recursively. * If no Source on the stack is a FileLexerSource, returns null. */ internal virtual String getPath() { Source parent = getParent(); if(parent != null) return parent.getPath(); return null; } /** * Returns the human-readable name of the current Source. */ internal virtual String getName() { Source parent = getParent(); if(parent != null) return parent.getName(); return null; } /** * Returns the current line number within this Source. */ public virtual int getLine() { Source parent = getParent(); if(parent == null) return 0; return parent.getLine(); } /** * Returns the current column number within this Source. */ public virtual int getColumn() { Source parent = getParent(); if(parent == null) return 0; return parent.getColumn(); } /** * Returns true if this Source is expanding the given macro. * * This is used to prevent macro recursion. */ internal virtual boolean isExpanding(Macro m) { Source parent = getParent(); if(parent != null) return parent.isExpanding(m); return false; } /** * Returns true if this Source should be transparently popped * from the input stack. * * Examples of such sources are macro expansions. */ internal boolean isAutopop() { return autopop; } /** * Returns true if this source has line numbers. */ internal virtual boolean isNumbered() { return false; } /* This is an incredibly lazy way of disabling warnings when * the source is not active. */ internal void setActive(boolean b) { this.active = b; } internal boolean isActive() { return active; } /** * Returns the next Token parsed from this input stream. * * @see Token */ public abstract Token token(); /** * Returns a token iterator for this Source. */ public Iterator<Token> iterator() { return new SourceIterator(this); } /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ public Token skipline(boolean white) { for(; ; ) { Token tok = token(); switch(tok.getType()) { case Token.EOF: /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning(tok.getLine(), tok.getColumn(), "No newline before end of file"); return new Token(Token.NL, tok.getLine(), tok.getColumn(), "\n"); // return tok; case Token.NL: /* This may contain one or more newlines. */ return tok; case Token.CCOMMENT: case Token.CPPCOMMENT: case Token.WHITESPACE: break; default: /* XXX Check white, if required. */ if(white) warning(tok.getLine(), tok.getColumn(), "Unexpected nonwhite token"); break; } } } protected void error(int line, int column, String msg) { if(listener != null) listener.handleError(this, line, column, msg); else throw new LexerException("Error at " + line + ":" + column + ": " + msg); } protected void warning(int line, int column, String msg) { if(werror) error(line, column, msg); else if(listener != null) listener.handleWarning(this, line, column, msg); else throw new LexerException("Warning at " + line + ":" + column + ": " + msg); } public virtual void close() { } } }
using System; using UnityEngine; namespace UnityEditor { public class StandardShaderVCGUI : ShaderGUI { private enum WorkflowMode { Specular, Metallic, Dielectric } public enum BlendMode { Opaque, Cutout, Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply } private static class Styles { public static GUIStyle optionsButton = "PaneOptions"; public static GUIContent uvSetLabel = new GUIContent("UV Set"); public static GUIContent[] uvSetOptions = new GUIContent[] { new GUIContent("UV channel 0"), new GUIContent("UV channel 1") }; public static string emptyTootip = ""; public static GUIContent albedoText = new GUIContent("Albedo", "Albedo (RGB) and Transparency (A)"); public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff"); public static GUIContent specularMapText = new GUIContent("Specular", "Specular (RGB) and Smoothness (A)"); public static GUIContent metallicMapText = new GUIContent("Metallic", "Metallic (R) and Smoothness (A)"); public static GUIContent smoothnessText = new GUIContent("Smoothness", ""); public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map"); public static GUIContent heightMapText = new GUIContent("Height Map", "Height Map (G)"); public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (G)"); public static GUIContent emissionText = new GUIContent("Emission", "Emission (RGB)"); public static GUIContent detailMaskText = new GUIContent("Detail Mask", "Mask for Secondary Maps (A)"); public static GUIContent detailAlbedoText = new GUIContent("Detail Albedo x2", "Albedo (RGB) multiplied by 2"); public static GUIContent detailNormalMapText = new GUIContent("Normal Map", "Normal Map"); public static string whiteSpaceString = " "; public static string primaryMapsText = "Main Maps"; public static string secondaryMapsText = "Secondary Maps"; public static string renderingMode = "Rendering Mode"; public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive."); public static GUIContent emissiveColorWarning = new GUIContent("Ensure emissive color is non-black for emission to have effect."); public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode)); public static GUIContent vcLabel = new GUIContent("Vertex Color", "Vertex Color Intensity"); } MaterialProperty blendMode = null; MaterialProperty albedoMap = null; MaterialProperty albedoColor = null; MaterialProperty alphaCutoff = null; MaterialProperty specularMap = null; MaterialProperty specularColor = null; MaterialProperty metallicMap = null; MaterialProperty metallic = null; MaterialProperty smoothness = null; MaterialProperty bumpScale = null; MaterialProperty bumpMap = null; MaterialProperty occlusionStrength = null; MaterialProperty occlusionMap = null; MaterialProperty heigtMapScale = null; MaterialProperty heightMap = null; MaterialProperty emissionScaleUI = null; MaterialProperty emissionColorUI = null; MaterialProperty emissionColorForRendering = null; MaterialProperty emissionMap = null; MaterialProperty detailMask = null; MaterialProperty detailAlbedoMap = null; MaterialProperty detailNormalMapScale = null; MaterialProperty detailNormalMap = null; MaterialProperty uvSetSecondary = null; MaterialProperty vertexColor = null; MaterialEditor m_MaterialEditor; WorkflowMode m_WorkflowMode = WorkflowMode.Specular; bool m_FirstTimeApply = true; public void FindProperties(MaterialProperty[] props) { blendMode = FindProperty("_Mode", props); albedoMap = FindProperty("_MainTex", props); albedoColor = FindProperty("_Color", props); alphaCutoff = FindProperty("_Cutoff", props); specularMap = FindProperty("_SpecGlossMap", props, false); specularColor = FindProperty("_SpecColor", props, false); metallicMap = FindProperty("_MetallicGlossMap", props, false); metallic = FindProperty("_Metallic", props, false); if (specularMap != null && specularColor != null) m_WorkflowMode = WorkflowMode.Specular; else if (metallicMap != null && metallic != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; smoothness = FindProperty("_Glossiness", props); bumpScale = FindProperty("_BumpScale", props); bumpMap = FindProperty("_BumpMap", props); heigtMapScale = FindProperty("_Parallax", props); heightMap = FindProperty("_ParallaxMap", props); occlusionStrength = FindProperty("_OcclusionStrength", props); occlusionMap = FindProperty("_OcclusionMap", props); emissionScaleUI = FindProperty("_EmissionScaleUI", props); emissionColorUI = FindProperty("_EmissionColorUI", props); emissionColorForRendering = FindProperty("_EmissionColor", props); emissionMap = FindProperty("_EmissionMap", props); detailMask = FindProperty("_DetailMask", props); detailAlbedoMap = FindProperty("_DetailAlbedoMap", props); detailNormalMapScale = FindProperty("_DetailNormalMapScale", props); detailNormalMap = FindProperty("_DetailNormalMap", props); uvSetSecondary = FindProperty("_UVSec", props); vertexColor = FindProperty("_IntensityVC", props); } public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) { FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly m_MaterialEditor = materialEditor; Material material = materialEditor.target as Material; ShaderPropertiesGUI(material); // Make sure that needed keywords are set up if we're switching some existing // material to a standard shader. if (m_FirstTimeApply) { SetMaterialKeywords(material, m_WorkflowMode); m_FirstTimeApply = false; } } public void ShaderPropertiesGUI(Material material) { // Use default labelWidth EditorGUIUtility.labelWidth = 0f; // Detect any changes to the material EditorGUI.BeginChangeCheck(); { BlendModePopup(); // Primary properties GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel); DoAlbedoArea(material); DoSpecularMetallicArea(); m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap, heightMap.textureValue != null ? heigtMapScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null); DoEmissionArea(material); m_MaterialEditor.TexturePropertySingleLine(Styles.detailMaskText, detailMask); EditorGUI.BeginChangeCheck(); m_MaterialEditor.TextureScaleOffsetProperty(albedoMap); if (EditorGUI.EndChangeCheck()) emissionMap.textureScaleAndOffset = albedoMap.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake EditorGUILayout.Space(); // Secondary properties GUILayout.Label(Styles.secondaryMapsText, EditorStyles.boldLabel); m_MaterialEditor.TexturePropertySingleLine(Styles.detailAlbedoText, detailAlbedoMap); m_MaterialEditor.TexturePropertySingleLine(Styles.detailNormalMapText, detailNormalMap, detailNormalMapScale); m_MaterialEditor.TextureScaleOffsetProperty(detailAlbedoMap); m_MaterialEditor.ShaderProperty(uvSetSecondary, Styles.uvSetLabel.text); EditorGUILayout.Space(); m_MaterialEditor.ShaderProperty(vertexColor, "Vertex Color"); } if (EditorGUI.EndChangeCheck()) { foreach (var obj in blendMode.targets) MaterialChanged((Material)obj, m_WorkflowMode); } } internal void DetermineWorkflow(MaterialProperty[] props) { if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null) m_WorkflowMode = WorkflowMode.Specular; else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null) m_WorkflowMode = WorkflowMode.Metallic; else m_WorkflowMode = WorkflowMode.Dielectric; } void BlendModePopup() { EditorGUI.showMixedValue = blendMode.hasMixedValue; var mode = (BlendMode)blendMode.floatValue; EditorGUI.BeginChangeCheck(); mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode"); blendMode.floatValue = (float)mode; } EditorGUI.showMixedValue = false; } void DoAlbedoArea(Material material) { m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor); if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout)) { m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1); } } void DoEmissionArea(Material material) { bool showEmissionColorAndGIControls = emissionScaleUI.floatValue > 0f; bool hadEmissionTexture = emissionMap.textureValue != null; // Do controls m_MaterialEditor.TexturePropertySingleLine(Styles.emissionText, emissionMap, showEmissionColorAndGIControls ? emissionColorUI : null, emissionScaleUI); // Set default emissionScaleUI if texture was assigned if (emissionMap.textureValue != null && !hadEmissionTexture && emissionScaleUI.floatValue <= 0f) emissionScaleUI.floatValue = 1.0f; // Dynamic Lightmapping mode if (showEmissionColorAndGIControls) { bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled(EvalFinalEmissionColor(material)); EditorGUI.BeginDisabledGroup(!shouldEmissionBeEnabled); m_MaterialEditor.LightmapEmissionProperty(MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1); EditorGUI.EndDisabledGroup(); } if (!HasValidEmissiveKeyword(material)) { EditorGUILayout.HelpBox(Styles.emissiveWarning.text, MessageType.Warning); } } void DoSpecularMetallicArea() { if (m_WorkflowMode == WorkflowMode.Specular) { if (specularMap.textureValue == null) m_MaterialEditor.TexturePropertyTwoLines(Styles.specularMapText, specularMap, specularColor, Styles.smoothnessText, smoothness); else m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap); } else if (m_WorkflowMode == WorkflowMode.Metallic) { if (metallicMap.textureValue == null) m_MaterialEditor.TexturePropertyTwoLines(Styles.metallicMapText, metallicMap, metallic, Styles.smoothnessText, smoothness); else m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap); } } public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode) { switch (blendMode) { case BlendMode.Opaque: material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; break; case BlendMode.Cutout: material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 2450; break; case BlendMode.Fade: material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 3000; break; case BlendMode.Transparent: material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 3000; break; } } // Calculate final HDR _EmissionColor (gamma space) from _EmissionColorUI (LDR, gamma) & _EmissionScaleUI (gamma) static Color EvalFinalEmissionColor(Material material) { return material.GetColor("_EmissionColorUI") * material.GetFloat("_EmissionScaleUI"); } static bool ShouldEmissionBeEnabled(Color color) { return color.grayscale > (0.1f / 255.0f); } static void SetMaterialKeywords(Material material, WorkflowMode workflowMode) { // Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation // (MaterialProperty value might come from renderer material property block) SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap") || material.GetTexture("_DetailNormalMap")); if (workflowMode == WorkflowMode.Specular) SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap")); else if (workflowMode == WorkflowMode.Metallic) SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap")); SetKeyword(material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap")); SetKeyword(material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap")); bool shouldEmissionBeEnabled = ShouldEmissionBeEnabled(material.GetColor("_EmissionColor")); SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled); // Setup lightmap emissive flags MaterialGlobalIlluminationFlags flags = material.globalIlluminationFlags; if ((flags & (MaterialGlobalIlluminationFlags.BakedEmissive | MaterialGlobalIlluminationFlags.RealtimeEmissive)) != 0) { flags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; if (!shouldEmissionBeEnabled) flags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack; material.globalIlluminationFlags = flags; } float intensity = material.GetFloat("_IntensityVC"); if (intensity <= 0f) { SetKeyword(material, "_VERTEXCOLOR_LERP", false); SetKeyword(material, "_VERTEXCOLOR", false); } else if (intensity > 0f && intensity < 1f) { SetKeyword(material, "_VERTEXCOLOR_LERP", true); SetKeyword(material, "_VERTEXCOLOR", false); } else { SetKeyword(material, "_VERTEXCOLOR_LERP", false); SetKeyword(material, "_VERTEXCOLOR", true); } //SetKeyword(material, intensity < 1f?"_VERTEXCOLOR_LERP":"_VERTEXCOLOR", intensity > 0f); } bool HasValidEmissiveKeyword(Material material) { // Material animation might be out of sync with the material keyword. // So if the emission support is disabled on the material, but the property blocks have a value that requires it, then we need to show a warning. // (note: (Renderer MaterialPropertyBlock applies its values to emissionColorForRendering)) bool hasEmissionKeyword = material.IsKeywordEnabled("_EMISSION"); if (!hasEmissionKeyword && ShouldEmissionBeEnabled(emissionColorForRendering.colorValue)) return false; else return true; } static void MaterialChanged(Material material, WorkflowMode workflowMode) { // Clamp EmissionScale to always positive if (material.GetFloat("_EmissionScaleUI") < 0.0f) material.SetFloat("_EmissionScaleUI", 0.0f); // Apply combined emission value Color emissionColorOut = EvalFinalEmissionColor(material); material.SetColor("_EmissionColor", emissionColorOut); // Handle Blending modes SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode")); SetMaterialKeywords(material, workflowMode); } static void SetKeyword(Material m, string keyword, bool state) { if (state) m.EnableKeyword(keyword); else m.DisableKeyword(keyword); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.IO { /// <summary>Provides an implementation of FileSystem for Unix systems.</summary> internal sealed partial class UnixFileSystem : FileSystem { public override int MaxPath { get { return Interop.libc.MaxPath; } } public override int MaxDirectoryPath { get { return Interop.libc.MaxPath; } } public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent); } public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { // Note: we could consider using sendfile here, but it isn't part of the POSIX spec, and // has varying degrees of support on different systems. // The destination path may just be a directory into which the file should be copied. // If it is, append the filename from the source onto the destination directory if (DirectoryExists(destFullPath)) { destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath)); } // Copy the contents of the file from the source to the destination, creating the destination in the process const int bufferSize = FileStream.DefaultBufferSize; const bool useAsync = false; using (Stream src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync)) using (Stream dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync)) { src.CopyTo(dst); } // Now copy over relevant read/write/execute permissions from the source to the destination Interop.Sys.FileStatus status; while (Interop.CheckIo(Interop.Sys.Stat(sourceFullPath, out status), sourceFullPath)) ; int newMode = status.Mode & (int)Interop.Sys.Permissions.Mask; while (Interop.CheckIo(Interop.Sys.ChMod(destFullPath, newMode), destFullPath)) ; } public override void MoveFile(string sourceFullPath, string destFullPath) { // The desired behavior for Move(source, dest) is to not overwrite the destination file // if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists, // link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move // as a Creation and Deletion instead of a Rename and thus differ from Windows. while (Interop.Sys.Link(sourceFullPath, destFullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EINTR) // interrupted; try again { continue; } else if (errorInfo.Error == Interop.Error.EXDEV) // rename fails across devices / mount points { CopyFile(sourceFullPath, destFullPath, overwrite: false); break; } else if (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(destFullPath))) // The parent directory of destFile can't be found { // Windows distinguishes between whether the directory or the file isn't found, // and throws a different exception in these cases. We attempt to approximate that // here; there is a race condition here, where something could change between // when the error occurs and our checks, but it's the best we can do, and the // worst case in such a race condition (which could occur if the file system is // being manipulated concurrently with these checks) is that we throw a // FileNotFoundException instead of DirectoryNotFoundexception. throw Interop.GetExceptionForIoErrno(errorInfo, destFullPath, isDirectory: true); } else { throw Interop.GetExceptionForIoErrno(errorInfo); } } DeleteFile(sourceFullPath); } public override void DeleteFile(string fullPath) { while (Interop.Sys.Unlink(fullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EINTR) // interrupted; try again { continue; } else if (errorInfo.Error == Interop.Error.ENOENT) // already doesn't exist; nop { break; } else { if (errorInfo.Error == Interop.Error.EISDIR) errorInfo = Interop.Error.EACCES.Info(); throw Interop.GetExceptionForIoErrno(errorInfo, fullPath); } } } public override void CreateDirectory(string fullPath) { // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory. int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) { length--; } // For paths that are only // or /// if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1])) { throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath)); } // We can save a bunch of work if the directory we want to create already exists. if (DirectoryExists(fullPath)) { return; } // Attempt to figure out which directories don't exist, and only create the ones we need. bool somepathexists = false; Stack<string> stackDir = new Stack<string>(); int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { int i = length - 1; while (i >= lengthRoot && !somepathexists) { string dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing { stackDir.Push(dir); } else { somepathexists = true; } while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) { i--; } i--; } } int count = stackDir.Count; if (count == 0 && !somepathexists) { string root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) { throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true); } return; } // Create all the directories int result = 0; Interop.ErrorInfo firstError = default(Interop.ErrorInfo); string errorString = fullPath; while (stackDir.Count > 0) { string name = stackDir.Pop(); if (name.Length >= MaxDirectoryPath) { throw new PathTooLongException(SR.IO_PathTooLong); } Interop.ErrorInfo errorInfo = default(Interop.ErrorInfo); while ((result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.S_IRWXU)) < 0 && (errorInfo = Interop.Sys.GetLastErrorInfo()).Error == Interop.Error.EINTR) ; if (result < 0 && firstError.Error == 0) { // While we tried to avoid creating directories that don't // exist above, there are a few cases that can fail, e.g. // a race condition where another process or thread creates // the directory first, or there's a file at the location. if (errorInfo.Error != Interop.Error.EEXIST) { firstError = errorInfo; } else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES)) { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. firstError = errorInfo; errorString = name; } } } // Only throw an exception if creating the exact directory we wanted failed to work correctly. if (result < 0 && firstError.Error != 0) { throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true); } } public override void MoveDirectory(string sourceFullPath, string destFullPath) { while (Interop.libc.rename(sourceFullPath, destFullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EINTR: // interrupted; try again continue; case Interop.Error.EACCES: // match Win32 exception throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno); default: throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true); } } } public override void RemoveDirectory(string fullPath, bool recursive) { if (!DirectoryExists(fullPath)) { throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true); } RemoveDirectoryInternal(fullPath, recursive, throwOnTopLevelDirectoryNotFound: true); } private void RemoveDirectoryInternal(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound) { Exception firstException = null; if (recursive) { try { foreach (string item in EnumeratePaths(fullPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both)) { if (!ShouldIgnoreDirectory(Path.GetFileName(item))) { try { if (DirectoryExists(item)) { RemoveDirectoryInternal(item, recursive, throwOnTopLevelDirectoryNotFound: false); } else { DeleteFile(item); } } catch (Exception exc) { if (firstException != null) { firstException = exc; } } } } } catch (Exception exc) { if (firstException != null) { firstException = exc; } } if (firstException != null) { throw firstException; } } while (Interop.libc.rmdir(fullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EINTR: // interrupted; try again continue; case Interop.Error.EACCES: case Interop.Error.EPERM: case Interop.Error.EROFS: case Interop.Error.EISDIR: throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // match Win32 exception case Interop.Error.ENOENT: if (!throwOnTopLevelDirectoryNotFound) { return; } goto default; default: throw Interop.GetExceptionForIoErrno(errorInfo, fullPath, isDirectory: true); } } } public override bool DirectoryExists(string fullPath) { Interop.ErrorInfo ignored; return DirectoryExists(fullPath, out ignored); } private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo) { return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo); } public override bool FileExists(string fullPath) { Interop.ErrorInfo ignored; return FileExists(fullPath, Interop.Sys.FileTypes.S_IFREG, out ignored); } private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo) { Interop.Sys.FileStatus fileinfo; while (true) { errorInfo = default(Interop.ErrorInfo); int result = Interop.Sys.Stat(fullPath, out fileinfo); if (result < 0) { errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EINTR) { continue; } return false; } return (fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == fileType; } } public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Files: return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => new FileInfo(path, null)); case SearchTarget.Directories: return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => new DirectoryInfo(path, null)); default: return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ? (FileSystemInfo)new DirectoryInfo(path, null) : (FileSystemInfo)new FileInfo(path, null)); } } private sealed class FileSystemEnumerable<T> : IEnumerable<T> { private readonly PathPair _initialDirectory; private readonly string _searchPattern; private readonly SearchOption _searchOption; private readonly bool _includeFiles; private readonly bool _includeDirectories; private readonly Func<string, bool, T> _translateResult; private IEnumerator<T> _firstEnumerator; internal FileSystemEnumerable( string userPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget, Func<string, bool, T> translateResult) { // Basic validation of the input path if (userPath == null) { throw new ArgumentNullException("path"); } if (string.IsNullOrWhiteSpace(userPath)) { throw new ArgumentException(SR.Argument_EmptyPath, "path"); } // Validate and normalize the search pattern. If after doing so it's empty, // matching Win32 behavior we can skip all additional validation and effectively // return an empty enumerable. searchPattern = NormalizeSearchPattern(searchPattern); if (searchPattern.Length > 0) { PathHelpers.CheckSearchPattern(searchPattern); PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern); // If the search pattern contains any paths, make sure we factor those into // the user path, and then trim them off. int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar); if (lastSlash >= 0) { if (lastSlash >= 1) { userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash)); } searchPattern = searchPattern.Substring(lastSlash + 1); } string fullPath = Path.GetFullPath(userPath); // Store everything for the enumerator _initialDirectory = new PathPair(userPath, fullPath); _searchPattern = searchPattern; _searchOption = searchOption; _includeFiles = (searchTarget & SearchTarget.Files) != 0; _includeDirectories = (searchTarget & SearchTarget.Directories) != 0; _translateResult = translateResult; } // Open the first enumerator so that any errors are propagated synchronously. _firstEnumerator = Enumerate(); } public IEnumerator<T> GetEnumerator() { return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private IEnumerator<T> Enumerate() { return Enumerate( _initialDirectory.FullPath != null ? OpenDirectory(_initialDirectory.FullPath) : null); } private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle) { if (dirHandle == null) { // Empty search yield break; } Debug.Assert(!dirHandle.IsInvalid); Debug.Assert(!dirHandle.IsClosed); // Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories // Lazily-initialized only if we find subdirectories that will be explored. Stack<PathPair> toExplore = null; PathPair dirPath = _initialDirectory; while (dirHandle != null) { try { // Read each entry from the enumerator Interop.Sys.DirectoryEntry dirent; while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0) { // Get from the dir entry whether the entry is a file or directory. // We classify everything as a file unless we know it to be a directory. bool isDir; if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR) { // We know it's a directory. isDir = true; } else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN) { // It's a symlink or unknown: stat to it to see if we can resolve it to a directory. // If we can't (e.g.symlink to a file, broken symlink, etc.), we'll just treat it as a file. Interop.ErrorInfo errnoIgnored; isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored); } else { // Otherwise, treat it as a file. This includes regular files, FIFOs, etc. isDir = false; } // Yield the result if the user has asked for it. In the case of directories, // always explore it by pushing it onto the stack, regardless of whether // we're returning directories. if (isDir) { if (!ShouldIgnoreDirectory(dirent.InodeName)) { string userPath = null; if (_searchOption == SearchOption.AllDirectories) { if (toExplore == null) { toExplore = new Stack<PathPair>(); } userPath = Path.Combine(dirPath.UserPath, dirent.InodeName); toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName))); } if (_includeDirectories && Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0) { yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true); } } } else if (_includeFiles && Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0) { yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false); } } } finally { // Close the directory enumerator dirHandle.Dispose(); dirHandle = null; } if (toExplore != null && toExplore.Count > 0) { // Open the next directory. dirPath = toExplore.Pop(); dirHandle = OpenDirectory(dirPath.FullPath); } } } private static string NormalizeSearchPattern(string searchPattern) { if (searchPattern == "." || searchPattern == "*.*") { searchPattern = "*"; } else if (PathHelpers.EndsInDirectorySeparator(searchPattern)) { searchPattern += "*"; } return searchPattern; } private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath) { Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath); if (handle.IsInvalid) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true); } return handle; } } /// <summary>Determines whether the specified directory name should be ignored.</summary> /// <param name="name">The name to evaluate.</param> /// <returns>true if the name is "." or ".."; otherwise, false.</returns> private static bool ShouldIgnoreDirectory(string name) { return name == "." || name == ".."; } public override string GetCurrentDirectory() { return Interop.libc.getcwd(); } public override void SetCurrentDirectory(string fullPath) { while (Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath)) ; } public override FileAttributes GetAttributes(string fullPath) { return new FileInfo(fullPath, null).Attributes; } public override void SetAttributes(string fullPath, FileAttributes attributes) { new FileInfo(fullPath, null).Attributes = attributes; } public override DateTimeOffset GetCreationTime(string fullPath) { return new FileInfo(fullPath, null).CreationTime; } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.CreationTime = time; } public override DateTimeOffset GetLastAccessTime(string fullPath) { return new FileInfo(fullPath, null).LastAccessTime; } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.LastAccessTime = time; } public override DateTimeOffset GetLastWriteTime(string fullPath) { return new FileInfo(fullPath, null).LastWriteTime; } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.LastWriteTime = time; } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Recognizer.HMM { public class NBestList { #region NBestResult Inner Class public class NBestResult : IComparable { public static NBestResult Empty = new NBestResult(String.Empty, -1d, -1d, 0d); private string _name; private double _score; private double _distance; private double _angle; // constructor public NBestResult(string name, double score, double distance, double angle) { _name = name; _score = score; _distance = distance; _angle = angle; } public string Name { get { return _name; } } public double Score { get { return _score; } } public double Distance { get { return _distance; } } public double Angle { get { return _angle; } } public bool IsEmpty { get { return _score == -1d; } } // sorts in descending order of Score public int CompareTo(object obj) { if (obj is NBestResult) { NBestResult r = (NBestResult) obj; if (_score < r._score) return 1; else if (_score > r._score) return -1; return 0; } else throw new ArgumentException("object is not a NBestResult"); } } #endregion #region Fields public static NBestList Empty = new NBestList(); private ArrayList _nBestList; #endregion #region Constructor & Methods public NBestList() { _nBestList = new ArrayList(); } public bool IsEmpty { get { return _nBestList.Count == 0; } } public void AddResult(string name, double score, double distance, double angle) { NBestResult r = new NBestResult(name, score, distance, angle); _nBestList.Add(r); } public void SortDescending() { _nBestList.Sort(); } #endregion #region Top Result /// <summary> /// Gets the gesture name of the top result of the NBestList. /// </summary> public string Name { get { if (_nBestList.Count > 0) { NBestResult r = (NBestResult) _nBestList[0]; return r.Name; } return String.Empty; } } /// <summary> /// Gets the [0..1] matching score of the top result of the NBestList. /// </summary> public double Score { get { if (_nBestList.Count > 0) { NBestResult r = (NBestResult) _nBestList[0]; return r.Score; } return -1.0; } } /// <summary> /// Gets the average pixel distance of the top result of the NBestList. /// </summary> public double Distance { get { if (_nBestList.Count > 0) { NBestResult r = (NBestResult) _nBestList[0]; return r.Distance; } return -1.0; } } /// <summary> /// Gets the average pixel distance of the top result of the NBestList. /// </summary> public double Angle { get { if (_nBestList.Count > 0) { NBestResult r = (NBestResult) _nBestList[0]; return r.Angle; } return 0.0; } } #endregion #region All Results public NBestResult this[int index] { get { if (0 <= index && index < _nBestList.Count) { return (NBestResult) _nBestList[index]; } return null; } } public string[] Names { get { string[] s = new string[_nBestList.Count]; if (_nBestList.Count > 0) { for (int i = 0; i < s.Length; i++) { s[i] = ((NBestResult) _nBestList[i]).Name; } } return s; } } public string NamesString { get { string s = String.Empty; if (_nBestList.Count > 0) { foreach (NBestResult r in _nBestList) { s += String.Format("{0},", r.Name); } } return s.TrimEnd(new char[1] { ',' }); } } public double[] Scores { get { double[] s = new double[_nBestList.Count]; if (_nBestList.Count > 0) { for (int i = 0; i < s.Length; i++) { s[i] = ((NBestResult) _nBestList[i]).Score; } } return s; } } public string ScoresString { get { string s = String.Empty; if (_nBestList.Count > 0) { foreach (NBestResult r in _nBestList) { s += String.Format("{0:F3},", Math.Round(r.Score, 3)); } } return s.TrimEnd(new char[1] { ',' }); } } #endregion } }
// 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.Collections.ObjectModel; using System.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Controls.UnitTests { public class TabControlTests { [Fact] public void First_Tab_Should_Be_Selected_By_Default() { TabItem selected; var target = new TabControl { Template = new FuncControlTemplate<TabControl>(CreateTabControlTemplate), Items = new[] { (selected = new TabItem { Name = "first", Content = "foo", }), new TabItem { Name = "second", Content = "bar", }, } }; target.ApplyTemplate(); Assert.Equal(0, target.SelectedIndex); Assert.Equal(selected, target.SelectedItem); } [Fact] public void Logical_Children_Should_Be_TabItems() { var items = new[] { new TabItem { Content = "foo" }, new TabItem { Content = "bar" }, }; var target = new TabControl { Template = new FuncControlTemplate<TabControl>(CreateTabControlTemplate), Items = items, }; Assert.Equal(items, target.GetLogicalChildren()); target.ApplyTemplate(); Assert.Equal(items, target.GetLogicalChildren()); } [Fact] public void Removal_Should_Set_Next_Tab() { var collection = new ObservableCollection<TabItem>() { new TabItem { Name = "first", Content = "foo", }, new TabItem { Name = "second", Content = "bar", }, new TabItem { Name = "3rd", Content = "barf", }, }; var target = new TabControl { Template = new FuncControlTemplate<TabControl>(CreateTabControlTemplate), Items = collection, }; target.ApplyTemplate(); target.SelectedItem = collection[1]; collection.RemoveAt(1); // compare with former [2] now [1] == "3rd" Assert.Same(collection[1], target.SelectedItem); } [Fact] public void TabItem_Templates_Should_Be_Set_Before_TabItem_ApplyTemplate() { var collection = new[] { new TabItem { Name = "first", Content = "foo", }, new TabItem { Name = "second", Content = "bar", }, new TabItem { Name = "3rd", Content = "barf", }, }; var template = new FuncControlTemplate<TabItem>(x => new Decorator()); using (UnitTestApplication.Start(TestServices.RealStyler)) { var root = new TestRoot { Styles = new Styles { new Style(x => x.OfType<TabItem>()) { Setters = new[] { new Setter(TemplatedControl.TemplateProperty, template) } } }, Child = new TabControl { Template = new FuncControlTemplate<TabControl>(CreateTabControlTemplate), Items = collection, } }; } Assert.Same(collection[0].Template, template); Assert.Same(collection[1].Template, template); Assert.Same(collection[2].Template, template); } [Fact] public void DataContexts_Should_Be_Correctly_Set() { var items = new object[] { "Foo", new Item("Bar"), new TextBlock { Text = "Baz" }, new TabItem { Content = "Qux" }, new TabItem { Content = new TextBlock { Text = "Bob" } } }; var target = new TabControl { Template = new FuncControlTemplate<TabControl>(CreateTabControlTemplate), DataContext = "Base", DataTemplates = new DataTemplates { new FuncDataTemplate<Item>(x => new Button { Content = x }) }, Items = items, }; ApplyTemplate(target); var carousel = (Carousel)target.Pages; var container = (ContentPresenter)carousel.Presenter.Panel.Children.Single(); container.UpdateChild(); var dataContext = ((TextBlock)container.Child).DataContext; Assert.Equal(items[0], dataContext); target.SelectedIndex = 1; container = (ContentPresenter)carousel.Presenter.Panel.Children.Single(); container.UpdateChild(); dataContext = ((Button)container.Child).DataContext; Assert.Equal(items[1], dataContext); target.SelectedIndex = 2; dataContext = ((TextBlock)carousel.Presenter.Panel.Children.Single()).DataContext; Assert.Equal("Base", dataContext); target.SelectedIndex = 3; container = (ContentPresenter)carousel.Presenter.Panel.Children[0]; container.UpdateChild(); dataContext = ((TextBlock)container.Child).DataContext; Assert.Equal("Qux", dataContext); target.SelectedIndex = 4; dataContext = ((TextBlock)carousel.Presenter.Panel.Children.Single()).DataContext; Assert.Equal("Base", dataContext); } /// <summary> /// Non-headered control items should result in TabStripItems with empty content. /// </summary> /// <remarks> /// If a TabStrip is created with non IHeadered controls as its items, don't try to /// display the control in the TabStripItem: if the TabStrip is part of a TabControl /// then *that* will also try to display the control, resulting in dual-parentage /// breakage. /// </remarks> [Fact] public void Non_IHeadered_Control_Items_Should_Be_Ignored() { var items = new[] { new TextBlock { Text = "foo" }, new TextBlock { Text = "bar" }, }; var target = new TabControl { Template = new FuncControlTemplate<TabControl>(CreateTabControlTemplate), Items = items, }; ApplyTemplate(target); var result = target.TabStrip.GetLogicalChildren() .OfType<TabStripItem>() .Select(x => x.Content) .ToList(); Assert.Equal(new object[] { string.Empty, string.Empty }, result); } [Fact] public void Should_Handle_Changing_To_TabItem_With_Null_Content() { TabControl target = new TabControl { Template = new FuncControlTemplate<TabControl>(CreateTabControlTemplate), Items = new[] { new TabItem { Header = "Foo" }, new TabItem { Header = "Foo", Content = new Decorator() }, new TabItem { Header = "Baz" }, }, }; ApplyTemplate(target); target.SelectedIndex = 2; var carousel = (Carousel)target.Pages; var page = (TabItem)carousel.SelectedItem; Assert.Null(page.Content); } private Control CreateTabControlTemplate(TabControl parent) { return new StackPanel { Children = new Controls { new TabStrip { Name = "PART_TabStrip", Template = new FuncControlTemplate<TabStrip>(CreateTabStripTemplate), MemberSelector = TabControl.HeaderSelector, [!TabStrip.ItemsProperty] = parent[!TabControl.ItemsProperty], [!!TabStrip.SelectedIndexProperty] = parent[!!TabControl.SelectedIndexProperty] }, new Carousel { Name = "PART_Content", Template = new FuncControlTemplate<Carousel>(CreateCarouselTemplate), MemberSelector = TabControl.ContentSelector, [!Carousel.ItemsProperty] = parent[!TabControl.ItemsProperty], [!Carousel.SelectedItemProperty] = parent[!TabControl.SelectedItemProperty], } } }; } private Control CreateTabStripTemplate(TabStrip parent) { return new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty], [!CarouselPresenter.MemberSelectorProperty] = parent[!ItemsControl.MemberSelectorProperty], }; } private Control CreateCarouselTemplate(Carousel control) { return new CarouselPresenter { Name = "PART_ItemsPresenter", [!CarouselPresenter.ItemsProperty] = control[!ItemsControl.ItemsProperty], [!CarouselPresenter.ItemsPanelProperty] = control[!ItemsControl.ItemsPanelProperty], [!CarouselPresenter.MemberSelectorProperty] = control[!ItemsControl.MemberSelectorProperty], [!CarouselPresenter.SelectedIndexProperty] = control[!SelectingItemsControl.SelectedIndexProperty], [~CarouselPresenter.TransitionProperty] = control[~Carousel.TransitionProperty], }; } private void ApplyTemplate(TabControl target) { target.ApplyTemplate(); var carousel = (Carousel)target.Pages; carousel.ApplyTemplate(); carousel.Presenter.ApplyTemplate(); var tabStrip = (TabStrip)target.TabStrip; tabStrip.ApplyTemplate(); tabStrip.Presenter.ApplyTemplate(); } private class Item { public Item(string value) { Value = value; } public string Value { get; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; namespace HFATest { public struct Config { public const string hfaType = "simple"; public const string dllType = "native_cpp"; public const string floatType = "f32"; public const string DllName = "hfa" + "_" + hfaType + "_" + floatType + "_" + dllType; } public class TestMan { //--------------------------------------------- // Init Methods // --------------------------------------------------- [DllImport(Config.DllName, EntryPoint = "init_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern void Init_HFA01(out HFA01 hfa); [DllImport(Config.DllName, EntryPoint = "init_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern void Init_HFA02(out HFA02 hfa); [DllImport(Config.DllName, EntryPoint = "init_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern void Init_HFA03(out HFA03 hfa); [DllImport(Config.DllName, EntryPoint = "init_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern void Init_HFA05(out HFA05 hfa); [DllImport(Config.DllName, EntryPoint = "init_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern void Init_HFA08(out HFA08 hfa); [DllImport(Config.DllName, EntryPoint = "init_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern void Init_HFA11(out HFA11 hfa); [DllImport(Config.DllName, EntryPoint = "init_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern void Init_HFA19(out HFA19 hfa); // --------------------------------------------------- // Identity Methods // --------------------------------------------------- [DllImport(Config.DllName, EntryPoint = "identity_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern HFA01 Identity_HFA01(HFA01 hfa); [DllImport(Config.DllName, EntryPoint = "identity_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern HFA02 Identity_HFA02(HFA02 hfa); [DllImport(Config.DllName, EntryPoint = "identity_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern HFA03 Identity_HFA03(HFA03 hfa); [DllImport(Config.DllName, EntryPoint = "identity_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern HFA05 Identity_HFA05(HFA05 hfa); [DllImport(Config.DllName, EntryPoint = "identity_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern HFA08 Identity_HFA08(HFA08 hfa); [DllImport(Config.DllName, EntryPoint = "identity_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern HFA11 Identity_HFA11(HFA11 hfa); [DllImport(Config.DllName, EntryPoint = "identity_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern HFA19 Identity_HFA19(HFA19 hfa); // --------------------------------------------------- // Get Methods // --------------------------------------------------- [DllImport(Config.DllName, EntryPoint = "get_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern HFA01 Get_HFA01(); [DllImport(Config.DllName, EntryPoint = "get_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern HFA02 Get_HFA02(); [DllImport(Config.DllName, EntryPoint = "get_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern HFA03 Get_HFA03(); [DllImport(Config.DllName, EntryPoint = "get_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern HFA05 Get_HFA05(); [DllImport(Config.DllName, EntryPoint = "get_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern HFA08 Get_HFA08(); [DllImport(Config.DllName, EntryPoint = "get_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern HFA11 Get_HFA11(); [DllImport(Config.DllName, EntryPoint = "get_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern HFA19 Get_HFA19(); public static readonly float EXPECTED_SUM_HFA01 = Get_EXPECTED_SUM_HFA01(); public static readonly float EXPECTED_SUM_HFA02 = Get_EXPECTED_SUM_HFA02(); public static readonly float EXPECTED_SUM_HFA03 = Get_EXPECTED_SUM_HFA03(); public static readonly float EXPECTED_SUM_HFA05 = Get_EXPECTED_SUM_HFA05(); public static readonly float EXPECTED_SUM_HFA08 = Get_EXPECTED_SUM_HFA08(); public static readonly float EXPECTED_SUM_HFA11 = Get_EXPECTED_SUM_HFA11(); public static readonly float EXPECTED_SUM_HFA19 = Get_EXPECTED_SUM_HFA19(); [DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Get_EXPECTED_SUM_HFA01(); [DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Get_EXPECTED_SUM_HFA02(); [DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Get_EXPECTED_SUM_HFA03(); [DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Get_EXPECTED_SUM_HFA05(); [DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Get_EXPECTED_SUM_HFA08(); [DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Get_EXPECTED_SUM_HFA11(); [DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Get_EXPECTED_SUM_HFA19(); [DllImport(Config.DllName, EntryPoint = "sum_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum_HFA01(HFA01 hfa); [DllImport(Config.DllName, EntryPoint = "sum_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum_HFA02(HFA02 hfa); [DllImport(Config.DllName, EntryPoint = "sum_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum_HFA03(HFA03 hfa); [DllImport(Config.DllName, EntryPoint = "sum_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum_HFA05(HFA05 hfa); [DllImport(Config.DllName, EntryPoint = "sum_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum_HFA08(HFA08 hfa); [DllImport(Config.DllName, EntryPoint = "sum_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum_HFA11(HFA11 hfa); [DllImport(Config.DllName, EntryPoint = "sum_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum_HFA19(HFA19 hfa); [DllImport(Config.DllName, EntryPoint = "sum3_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum3_HFA01(float v1, long v2, HFA01 hfa); [DllImport(Config.DllName, EntryPoint = "sum3_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum3_HFA02(float v1, long v2, HFA02 hfa); [DllImport(Config.DllName, EntryPoint = "sum3_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum3_HFA03(float v1, long v2, HFA03 hfa); [DllImport(Config.DllName, EntryPoint = "sum3_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum3_HFA05(float v1, long v2, HFA05 hfa); [DllImport(Config.DllName, EntryPoint = "sum3_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum3_HFA08(float v1, long v2, HFA08 hfa); [DllImport(Config.DllName, EntryPoint = "sum3_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum3_HFA11(float v1, long v2, HFA11 hfa); [DllImport(Config.DllName, EntryPoint = "sum3_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum3_HFA19(float v1, long v2, HFA19 hfa); [DllImport(Config.DllName, EntryPoint = "sum5_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum5_HFA01(long v1, double v2, int v3, sbyte v4, HFA01 hfa); [DllImport(Config.DllName, EntryPoint = "sum5_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum5_HFA02(long v1, double v2, int v3, sbyte v4, HFA02 hfa); [DllImport(Config.DllName, EntryPoint = "sum5_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum5_HFA03(long v1, double v2, int v3, sbyte v4, HFA03 hfa); [DllImport(Config.DllName, EntryPoint = "sum5_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum5_HFA05(long v1, double v2, int v3, sbyte v4, HFA05 hfa); [DllImport(Config.DllName, EntryPoint = "sum5_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum5_HFA08(long v1, double v2, int v3, sbyte v4, HFA08 hfa); [DllImport(Config.DllName, EntryPoint = "sum5_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum5_HFA11(long v1, double v2, int v3, sbyte v4, HFA11 hfa); [DllImport(Config.DllName, EntryPoint = "sum5_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum5_HFA19(long v1, double v2, int v3, sbyte v4, HFA19 hfa); [DllImport(Config.DllName, EntryPoint = "sum8_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum8_HFA01(float v1, double v2, long v3, sbyte v4, double v5, HFA01 hfa); [DllImport(Config.DllName, EntryPoint = "sum8_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum8_HFA02(float v1, double v2, long v3, sbyte v4, double v5, HFA02 hfa); [DllImport(Config.DllName, EntryPoint = "sum8_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum8_HFA03(float v1, double v2, long v3, sbyte v4, double v5, HFA03 hfa); [DllImport(Config.DllName, EntryPoint = "sum8_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum8_HFA05(float v1, double v2, long v3, sbyte v4, double v5, HFA05 hfa); [DllImport(Config.DllName, EntryPoint = "sum8_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum8_HFA08(float v1, double v2, long v3, sbyte v4, double v5, HFA08 hfa); [DllImport(Config.DllName, EntryPoint = "sum8_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum8_HFA11(float v1, double v2, long v3, sbyte v4, double v5, HFA11 hfa); [DllImport(Config.DllName, EntryPoint = "sum8_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum8_HFA19(float v1, double v2, long v3, sbyte v4, double v5, HFA19 hfa); [DllImport(Config.DllName, EntryPoint = "sum11_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum11_HFA01(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA01 hfa); [DllImport(Config.DllName, EntryPoint = "sum11_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum11_HFA02(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA02 hfa); [DllImport(Config.DllName, EntryPoint = "sum11_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum11_HFA03(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA03 hfa); [DllImport(Config.DllName, EntryPoint = "sum11_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum11_HFA05(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA05 hfa); [DllImport(Config.DllName, EntryPoint = "sum11_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum11_HFA08(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA08 hfa); [DllImport(Config.DllName, EntryPoint = "sum11_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum11_HFA11(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA11 hfa); [DllImport(Config.DllName, EntryPoint = "sum11_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum11_HFA19(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA19 hfa); [DllImport(Config.DllName, EntryPoint = "sum19_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum19_HFA01(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA01 hfa); [DllImport(Config.DllName, EntryPoint = "sum19_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum19_HFA02(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA02 hfa); [DllImport(Config.DllName, EntryPoint = "sum19_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum19_HFA03(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA03 hfa); [DllImport(Config.DllName, EntryPoint = "sum19_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum19_HFA05(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA05 hfa); [DllImport(Config.DllName, EntryPoint = "sum19_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum19_HFA08(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA08 hfa); [DllImport(Config.DllName, EntryPoint = "sum19_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum19_HFA11(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA11 hfa); [DllImport(Config.DllName, EntryPoint = "sum19_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Sum19_HFA19(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA19 hfa); // --------------------------------------------------- // Average Methods // --------------------------------------------------- [DllImport(Config.DllName, EntryPoint = "average_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Average_HFA01(HFA01 hfa); [DllImport(Config.DllName, EntryPoint = "average_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Average_HFA02(HFA02 hfa); [DllImport(Config.DllName, EntryPoint = "average_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Average_HFA03(HFA03 hfa); [DllImport(Config.DllName, EntryPoint = "average_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Average_HFA05(HFA05 hfa); [DllImport(Config.DllName, EntryPoint = "average_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Average_HFA08(HFA08 hfa); [DllImport(Config.DllName, EntryPoint = "average_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Average_HFA11(HFA11 hfa); [DllImport(Config.DllName, EntryPoint = "average_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Average_HFA19(HFA19 hfa); [DllImport(Config.DllName, EntryPoint = "average3_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Average3_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3); [DllImport(Config.DllName, EntryPoint = "average3_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Average3_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3); [DllImport(Config.DllName, EntryPoint = "average3_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Average3_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3); [DllImport(Config.DllName, EntryPoint = "average3_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Average3_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3); [DllImport(Config.DllName, EntryPoint = "average3_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Average3_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3); [DllImport(Config.DllName, EntryPoint = "average3_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Average3_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3); [DllImport(Config.DllName, EntryPoint = "average3_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Average3_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3); [DllImport(Config.DllName, EntryPoint = "average5_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Average5_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3, HFA01 hfa4, HFA01 hfa5); [DllImport(Config.DllName, EntryPoint = "average5_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Average5_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3, HFA02 hfa4, HFA02 hfa5); [DllImport(Config.DllName, EntryPoint = "average5_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Average5_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3, HFA03 hfa4, HFA03 hfa5); [DllImport(Config.DllName, EntryPoint = "average5_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Average5_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3, HFA05 hfa4, HFA05 hfa5); [DllImport(Config.DllName, EntryPoint = "average5_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Average5_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3, HFA08 hfa4, HFA08 hfa5); [DllImport(Config.DllName, EntryPoint = "average5_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Average5_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3, HFA11 hfa4, HFA11 hfa5); [DllImport(Config.DllName, EntryPoint = "average5_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Average5_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3, HFA19 hfa4, HFA19 hfa5); [DllImport(Config.DllName, EntryPoint = "average8_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Average8_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3, HFA01 hfa4, HFA01 hfa5, HFA01 hfa6, HFA01 hfa7, HFA01 hfa8); [DllImport(Config.DllName, EntryPoint = "average8_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Average8_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3, HFA02 hfa4, HFA02 hfa5, HFA02 hfa6, HFA02 hfa7, HFA02 hfa8); [DllImport(Config.DllName, EntryPoint = "average8_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Average8_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3, HFA03 hfa4, HFA03 hfa5, HFA03 hfa6, HFA03 hfa7, HFA03 hfa8); [DllImport(Config.DllName, EntryPoint = "average8_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Average8_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3, HFA05 hfa4, HFA05 hfa5, HFA05 hfa6, HFA05 hfa7, HFA05 hfa8); [DllImport(Config.DllName, EntryPoint = "average8_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Average8_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3, HFA08 hfa4, HFA08 hfa5, HFA08 hfa6, HFA08 hfa7, HFA08 hfa8); [DllImport(Config.DllName, EntryPoint = "average8_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Average8_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3, HFA11 hfa4, HFA11 hfa5, HFA11 hfa6, HFA11 hfa7, HFA11 hfa8); [DllImport(Config.DllName, EntryPoint = "average8_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Average8_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3, HFA19 hfa4, HFA19 hfa5, HFA19 hfa6, HFA19 hfa7, HFA19 hfa8); [DllImport(Config.DllName, EntryPoint = "average11_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Average11_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3, HFA01 hfa4, HFA01 hfa5, HFA01 hfa6, HFA01 hfa7, HFA01 hfa8, HFA01 hfa9, HFA01 hfa10, HFA01 hfa11); [DllImport(Config.DllName, EntryPoint = "average11_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Average11_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3, HFA02 hfa4, HFA02 hfa5, HFA02 hfa6, HFA02 hfa7, HFA02 hfa8, HFA02 hfa9, HFA02 hfa10, HFA02 hfa11); [DllImport(Config.DllName, EntryPoint = "average11_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Average11_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3, HFA03 hfa4, HFA03 hfa5, HFA03 hfa6, HFA03 hfa7, HFA03 hfa8, HFA03 hfa9, HFA03 hfa10, HFA03 hfa11); [DllImport(Config.DllName, EntryPoint = "average11_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Average11_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3, HFA05 hfa4, HFA05 hfa5, HFA05 hfa6, HFA05 hfa7, HFA05 hfa8, HFA05 hfa9, HFA05 hfa10, HFA05 hfa11); [DllImport(Config.DllName, EntryPoint = "average11_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Average11_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3, HFA08 hfa4, HFA08 hfa5, HFA08 hfa6, HFA08 hfa7, HFA08 hfa8, HFA08 hfa9, HFA08 hfa10, HFA08 hfa11); [DllImport(Config.DllName, EntryPoint = "average11_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Average11_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3, HFA11 hfa4, HFA11 hfa5, HFA11 hfa6, HFA11 hfa7, HFA11 hfa8, HFA11 hfa9, HFA11 hfa10, HFA11 hfa11); [DllImport(Config.DllName, EntryPoint = "average11_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Average11_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3, HFA19 hfa4, HFA19 hfa5, HFA19 hfa6, HFA19 hfa7, HFA19 hfa8, HFA19 hfa9, HFA19 hfa10, HFA19 hfa11); [DllImport(Config.DllName, EntryPoint = "average19_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Average19_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3, HFA01 hfa4, HFA01 hfa5, HFA01 hfa6, HFA01 hfa7, HFA01 hfa8, HFA01 hfa9, HFA01 hfa10, HFA01 hfa11, HFA01 hfa12, HFA01 hfa13, HFA01 hfa14, HFA01 hfa15, HFA01 hfa16, HFA01 hfa17, HFA01 hfa18, HFA01 hfa19); [DllImport(Config.DllName, EntryPoint = "average19_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Average19_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3, HFA02 hfa4, HFA02 hfa5, HFA02 hfa6, HFA02 hfa7, HFA02 hfa8, HFA02 hfa9, HFA02 hfa10, HFA02 hfa11, HFA02 hfa12, HFA02 hfa13, HFA02 hfa14, HFA02 hfa15, HFA02 hfa16, HFA02 hfa17, HFA02 hfa18, HFA02 hfa19); [DllImport(Config.DllName, EntryPoint = "average19_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Average19_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3, HFA03 hfa4, HFA03 hfa5, HFA03 hfa6, HFA03 hfa7, HFA03 hfa8, HFA03 hfa9, HFA03 hfa10, HFA03 hfa11, HFA03 hfa12, HFA03 hfa13, HFA03 hfa14, HFA03 hfa15, HFA03 hfa16, HFA03 hfa17, HFA03 hfa18, HFA03 hfa19); [DllImport(Config.DllName, EntryPoint = "average19_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Average19_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3, HFA05 hfa4, HFA05 hfa5, HFA05 hfa6, HFA05 hfa7, HFA05 hfa8, HFA05 hfa9, HFA05 hfa10, HFA05 hfa11, HFA05 hfa12, HFA05 hfa13, HFA05 hfa14, HFA05 hfa15, HFA05 hfa16, HFA05 hfa17, HFA05 hfa18, HFA05 hfa19); [DllImport(Config.DllName, EntryPoint = "average19_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Average19_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3, HFA08 hfa4, HFA08 hfa5, HFA08 hfa6, HFA08 hfa7, HFA08 hfa8, HFA08 hfa9, HFA08 hfa10, HFA08 hfa11, HFA08 hfa12, HFA08 hfa13, HFA08 hfa14, HFA08 hfa15, HFA08 hfa16, HFA08 hfa17, HFA08 hfa18, HFA08 hfa19); [DllImport(Config.DllName, EntryPoint = "average19_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Average19_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3, HFA11 hfa4, HFA11 hfa5, HFA11 hfa6, HFA11 hfa7, HFA11 hfa8, HFA11 hfa9, HFA11 hfa10, HFA11 hfa11, HFA11 hfa12, HFA11 hfa13, HFA11 hfa14, HFA11 hfa15, HFA11 hfa16, HFA11 hfa17, HFA11 hfa18, HFA11 hfa19); [DllImport(Config.DllName, EntryPoint = "average19_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Average19_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3, HFA19 hfa4, HFA19 hfa5, HFA19 hfa6, HFA19 hfa7, HFA19 hfa8, HFA19 hfa9, HFA19 hfa10, HFA19 hfa11, HFA19 hfa12, HFA19 hfa13, HFA19 hfa14, HFA19 hfa15, HFA19 hfa16, HFA19 hfa17, HFA19 hfa18, HFA19 hfa19); // --------------------------------------------------- // Add Methods // --------------------------------------------------- [DllImport(Config.DllName, EntryPoint = "add01_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Add01_HFA01(HFA01 hfa1, float v1, HFA01 hfa2, int v2, HFA01 hfa3, short v3, double v4, HFA01 hfa4, HFA01 hfa5, float v5, long v6, float v7, HFA01 hfa6, float v8, HFA01 hfa7); [DllImport(Config.DllName, EntryPoint = "add01_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Add01_HFA02(HFA02 hfa1, float v1, HFA02 hfa2, int v2, HFA02 hfa3, short v3, double v4, HFA02 hfa4, HFA02 hfa5, float v5, long v6, float v7, HFA02 hfa6, float v8, HFA02 hfa7); [DllImport(Config.DllName, EntryPoint = "add01_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Add01_HFA03(HFA03 hfa1, float v1, HFA03 hfa2, int v2, HFA03 hfa3, short v3, double v4, HFA03 hfa4, HFA03 hfa5, float v5, long v6, float v7, HFA03 hfa6, float v8, HFA03 hfa7); [DllImport(Config.DllName, EntryPoint = "add01_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Add01_HFA05(HFA05 hfa1, float v1, HFA05 hfa2, int v2, HFA05 hfa3, short v3, double v4, HFA05 hfa4, HFA05 hfa5, float v5, long v6, float v7, HFA05 hfa6, float v8, HFA05 hfa7); [DllImport(Config.DllName, EntryPoint = "add01_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Add01_HFA08(HFA08 hfa1, float v1, HFA08 hfa2, int v2, HFA08 hfa3, short v3, double v4, HFA08 hfa4, HFA08 hfa5, float v5, long v6, float v7, HFA08 hfa6, float v8, HFA08 hfa7); [DllImport(Config.DllName, EntryPoint = "add01_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Add01_HFA11(HFA11 hfa1, float v1, HFA11 hfa2, int v2, HFA11 hfa3, short v3, double v4, HFA11 hfa4, HFA11 hfa5, float v5, long v6, float v7, HFA11 hfa6, float v8, HFA11 hfa7); [DllImport(Config.DllName, EntryPoint = "add01_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Add01_HFA19(HFA19 hfa1, float v1, HFA19 hfa2, int v2, HFA19 hfa3, short v3, double v4, HFA19 hfa4, HFA19 hfa5, float v5, long v6, float v7, HFA19 hfa6, float v8, HFA19 hfa7); [DllImport(Config.DllName, EntryPoint = "add01_HFA00", CallingConvention = CallingConvention.Cdecl)] public static extern float Add01_HFA00(HFA03 hfa1, float v1, HFA02 hfa2, int v2, HFA19 hfa3, short v3, double v4, HFA05 hfa4, HFA08 hfa5, float v5, long v6, float v7, HFA11 hfa6, float v8, HFA01 hfa7); [DllImport(Config.DllName, EntryPoint = "add02_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Add02_HFA01(HFA01 hfa1, HFA01 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA01 hfa3, double v7, float v8, HFA01 hfa4, short v9, HFA01 hfa5, float v10, HFA01 hfa6, HFA01 hfa7); [DllImport(Config.DllName, EntryPoint = "add02_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Add02_HFA02(HFA02 hfa1, HFA02 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA02 hfa3, double v7, float v8, HFA02 hfa4, short v9, HFA02 hfa5, float v10, HFA02 hfa6, HFA02 hfa7); [DllImport(Config.DllName, EntryPoint = "add02_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Add02_HFA03(HFA03 hfa1, HFA03 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA03 hfa3, double v7, float v8, HFA03 hfa4, short v9, HFA03 hfa5, float v10, HFA03 hfa6, HFA03 hfa7); [DllImport(Config.DllName, EntryPoint = "add02_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Add02_HFA05(HFA05 hfa1, HFA05 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA05 hfa3, double v7, float v8, HFA05 hfa4, short v9, HFA05 hfa5, float v10, HFA05 hfa6, HFA05 hfa7); [DllImport(Config.DllName, EntryPoint = "add02_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Add02_HFA08(HFA08 hfa1, HFA08 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA08 hfa3, double v7, float v8, HFA08 hfa4, short v9, HFA08 hfa5, float v10, HFA08 hfa6, HFA08 hfa7); [DllImport(Config.DllName, EntryPoint = "add02_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Add02_HFA11(HFA11 hfa1, HFA11 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA11 hfa3, double v7, float v8, HFA11 hfa4, short v9, HFA11 hfa5, float v10, HFA11 hfa6, HFA11 hfa7); [DllImport(Config.DllName, EntryPoint = "add02_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Add02_HFA19(HFA19 hfa1, HFA19 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA19 hfa3, double v7, float v8, HFA19 hfa4, short v9, HFA19 hfa5, float v10, HFA19 hfa6, HFA19 hfa7); [DllImport(Config.DllName, EntryPoint = "add02_HFA00", CallingConvention = CallingConvention.Cdecl)] public static extern float Add02_HFA00(HFA01 hfa1, HFA05 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA03 hfa3, double v7, float v8, HFA11 hfa4, short v9, HFA19 hfa5, float v10, HFA08 hfa6, HFA02 hfa7); [DllImport(Config.DllName, EntryPoint = "add03_HFA01", CallingConvention = CallingConvention.Cdecl)] public static extern float Add03_HFA01(float v1, sbyte v2, HFA01 hfa1, double v3, sbyte v4, HFA01 hfa2, long v5, short v6, int v7, HFA01 hfa3, HFA01 hfa4, float v8, HFA01 hfa5, float v9, HFA01 hfa6, float v10, HFA01 hfa7); [DllImport(Config.DllName, EntryPoint = "add03_HFA02", CallingConvention = CallingConvention.Cdecl)] public static extern float Add03_HFA02(float v1, sbyte v2, HFA02 hfa1, double v3, sbyte v4, HFA02 hfa2, long v5, short v6, int v7, HFA02 hfa3, HFA02 hfa4, float v8, HFA02 hfa5, float v9, HFA02 hfa6, float v10, HFA02 hfa7); [DllImport(Config.DllName, EntryPoint = "add03_HFA03", CallingConvention = CallingConvention.Cdecl)] public static extern float Add03_HFA03(float v1, sbyte v2, HFA03 hfa1, double v3, sbyte v4, HFA03 hfa2, long v5, short v6, int v7, HFA03 hfa3, HFA03 hfa4, float v8, HFA03 hfa5, float v9, HFA03 hfa6, float v10, HFA03 hfa7); [DllImport(Config.DllName, EntryPoint = "add03_HFA05", CallingConvention = CallingConvention.Cdecl)] public static extern float Add03_HFA05(float v1, sbyte v2, HFA05 hfa1, double v3, sbyte v4, HFA05 hfa2, long v5, short v6, int v7, HFA05 hfa3, HFA05 hfa4, float v8, HFA05 hfa5, float v9, HFA05 hfa6, float v10, HFA05 hfa7); [DllImport(Config.DllName, EntryPoint = "add03_HFA08", CallingConvention = CallingConvention.Cdecl)] public static extern float Add03_HFA08(float v1, sbyte v2, HFA08 hfa1, double v3, sbyte v4, HFA08 hfa2, long v5, short v6, int v7, HFA08 hfa3, HFA08 hfa4, float v8, HFA08 hfa5, float v9, HFA08 hfa6, float v10, HFA08 hfa7); [DllImport(Config.DllName, EntryPoint = "add03_HFA11", CallingConvention = CallingConvention.Cdecl)] public static extern float Add03_HFA11(float v1, sbyte v2, HFA11 hfa1, double v3, sbyte v4, HFA11 hfa2, long v5, short v6, int v7, HFA11 hfa3, HFA11 hfa4, float v8, HFA11 hfa5, float v9, HFA11 hfa6, float v10, HFA11 hfa7); [DllImport(Config.DllName, EntryPoint = "add03_HFA19", CallingConvention = CallingConvention.Cdecl)] public static extern float Add03_HFA19(float v1, sbyte v2, HFA19 hfa1, double v3, sbyte v4, HFA19 hfa2, long v5, short v6, int v7, HFA19 hfa3, HFA19 hfa4, float v8, HFA19 hfa5, float v9, HFA19 hfa6, float v10, HFA19 hfa7); [DllImport(Config.DllName, EntryPoint = "add03_HFA00", CallingConvention = CallingConvention.Cdecl)] public static extern float Add03_HFA00(float v1, sbyte v2, HFA08 hfa1, double v3, sbyte v4, HFA19 hfa2, long v5, short v6, int v7, HFA03 hfa3, HFA01 hfa4, float v8, HFA11 hfa5, float v9, HFA02 hfa6, float v10, HFA05 hfa7); } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.3.7.3. Information about underwater acoustic emmissions. This requires manual cleanup. The beam data records should ALL be a the finish, rather than attached to each emitter system. UNFINISHED /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(EntityID))] [XmlInclude(typeof(EventID))] [XmlInclude(typeof(ShaftRPMs))] [XmlInclude(typeof(ApaData))] [XmlInclude(typeof(AcousticEmitterSystemData))] public partial class UaPdu : DistributedEmissionsFamilyPdu, IEquatable<UaPdu> { /// <summary> /// ID of the entity that is the source of the emission /// </summary> private EntityID _emittingEntityID = new EntityID(); /// <summary> /// ID of event /// </summary> private EventID _eventID = new EventID(); /// <summary> /// This field shall be used to indicate whether the data in the UA PDU represent a state update or data that have changed since issuance of the last UA PDU /// </summary> private byte _stateChangeIndicator; /// <summary> /// padding /// </summary> private byte _pad; /// <summary> /// This field indicates which database record (or file) shall be used in the definition of passive signature (unintentional) emissions of the entity. The indicated database record (or file) shall define all noise generated as a function of propulsion plant configurations and associated auxiliaries. /// </summary> private ushort _passiveParameterIndex; /// <summary> /// This field shall specify the entity propulsion plant configuration. This field is used to determine the passive signature characteristics of an entity. /// </summary> private byte _propulsionPlantConfiguration; /// <summary> /// This field shall represent the number of shafts on a platform /// </summary> private byte _numberOfShafts; /// <summary> /// This field shall indicate the number of APAs described in the current UA PDU /// </summary> private byte _numberOfAPAs; /// <summary> /// This field shall specify the number of UA emitter systems being described in the current UA PDU /// </summary> private byte _numberOfUAEmitterSystems; /// <summary> /// shaft RPM values /// </summary> private List<ShaftRPMs> _shaftRPMs = new List<ShaftRPMs>(); /// <summary> /// apaData /// </summary> private List<ApaData> _apaData = new List<ApaData>(); private List<AcousticEmitterSystemData> _emitterSystems = new List<AcousticEmitterSystemData>(); /// <summary> /// Initializes a new instance of the <see cref="UaPdu"/> class. /// </summary> public UaPdu() { PduType = (byte)29; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(UaPdu left, UaPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(UaPdu left, UaPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += this._emittingEntityID.GetMarshalledSize(); // this._emittingEntityID marshalSize += this._eventID.GetMarshalledSize(); // this._eventID marshalSize += 1; // this._stateChangeIndicator marshalSize += 1; // this._pad marshalSize += 2; // this._passiveParameterIndex marshalSize += 1; // this._propulsionPlantConfiguration marshalSize += 1; // this._numberOfShafts marshalSize += 1; // this._numberOfAPAs marshalSize += 1; // this._numberOfUAEmitterSystems for (int idx = 0; idx < this._shaftRPMs.Count; idx++) { ShaftRPMs listElement = (ShaftRPMs)this._shaftRPMs[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._apaData.Count; idx++) { ApaData listElement = (ApaData)this._apaData[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._emitterSystems.Count; idx++) { AcousticEmitterSystemData listElement = (AcousticEmitterSystemData)this._emitterSystems[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the ID of the entity that is the source of the emission /// </summary> [XmlElement(Type = typeof(EntityID), ElementName = "emittingEntityID")] public EntityID EmittingEntityID { get { return this._emittingEntityID; } set { this._emittingEntityID = value; } } /// <summary> /// Gets or sets the ID of event /// </summary> [XmlElement(Type = typeof(EventID), ElementName = "eventID")] public EventID EventID { get { return this._eventID; } set { this._eventID = value; } } /// <summary> /// Gets or sets the This field shall be used to indicate whether the data in the UA PDU represent a state update or data that have changed since issuance of the last UA PDU /// </summary> [XmlElement(Type = typeof(byte), ElementName = "stateChangeIndicator")] public byte StateChangeIndicator { get { return this._stateChangeIndicator; } set { this._stateChangeIndicator = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(byte), ElementName = "pad")] public byte Pad { get { return this._pad; } set { this._pad = value; } } /// <summary> /// Gets or sets the This field indicates which database record (or file) shall be used in the definition of passive signature (unintentional) emissions of the entity. The indicated database record (or file) shall define all noise generated as a function of propulsion plant configurations and associated auxiliaries. /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "passiveParameterIndex")] public ushort PassiveParameterIndex { get { return this._passiveParameterIndex; } set { this._passiveParameterIndex = value; } } /// <summary> /// Gets or sets the This field shall specify the entity propulsion plant configuration. This field is used to determine the passive signature characteristics of an entity. /// </summary> [XmlElement(Type = typeof(byte), ElementName = "propulsionPlantConfiguration")] public byte PropulsionPlantConfiguration { get { return this._propulsionPlantConfiguration; } set { this._propulsionPlantConfiguration = value; } } /// <summary> /// Gets or sets the This field shall represent the number of shafts on a platform /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfShafts method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(byte), ElementName = "numberOfShafts")] public byte NumberOfShafts { get { return this._numberOfShafts; } set { this._numberOfShafts = value; } } /// <summary> /// Gets or sets the This field shall indicate the number of APAs described in the current UA PDU /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfAPAs method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(byte), ElementName = "numberOfAPAs")] public byte NumberOfAPAs { get { return this._numberOfAPAs; } set { this._numberOfAPAs = value; } } /// <summary> /// Gets or sets the This field shall specify the number of UA emitter systems being described in the current UA PDU /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfUAEmitterSystems method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(byte), ElementName = "numberOfUAEmitterSystems")] public byte NumberOfUAEmitterSystems { get { return this._numberOfUAEmitterSystems; } set { this._numberOfUAEmitterSystems = value; } } /// <summary> /// Gets the shaft RPM values /// </summary> [XmlElement(ElementName = "shaftRPMsList", Type = typeof(List<ShaftRPMs>))] public List<ShaftRPMs> ShaftRPMs { get { return this._shaftRPMs; } } /// <summary> /// Gets the apaData /// </summary> [XmlElement(ElementName = "apaDataList", Type = typeof(List<ApaData>))] public List<ApaData> ApaData { get { return this._apaData; } } /// <summary> /// Gets the emitterSystems /// </summary> [XmlElement(ElementName = "emitterSystemsList", Type = typeof(List<AcousticEmitterSystemData>))] public List<AcousticEmitterSystemData> EmitterSystems { get { return this._emitterSystems; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { this._emittingEntityID.Marshal(dos); this._eventID.Marshal(dos); dos.WriteByte((byte)this._stateChangeIndicator); dos.WriteByte((byte)this._pad); dos.WriteUnsignedShort((ushort)this._passiveParameterIndex); dos.WriteUnsignedByte((byte)this._propulsionPlantConfiguration); dos.WriteUnsignedByte((byte)this._shaftRPMs.Count); dos.WriteUnsignedByte((byte)this._apaData.Count); dos.WriteUnsignedByte((byte)this._emitterSystems.Count); for (int idx = 0; idx < this._shaftRPMs.Count; idx++) { ShaftRPMs aShaftRPMs = (ShaftRPMs)this._shaftRPMs[idx]; aShaftRPMs.Marshal(dos); } for (int idx = 0; idx < this._apaData.Count; idx++) { ApaData aApaData = (ApaData)this._apaData[idx]; aApaData.Marshal(dos); } for (int idx = 0; idx < this._emitterSystems.Count; idx++) { AcousticEmitterSystemData aAcousticEmitterSystemData = (AcousticEmitterSystemData)this._emitterSystems[idx]; aAcousticEmitterSystemData.Marshal(dos); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._emittingEntityID.Unmarshal(dis); this._eventID.Unmarshal(dis); this._stateChangeIndicator = dis.ReadByte(); this._pad = dis.ReadByte(); this._passiveParameterIndex = dis.ReadUnsignedShort(); this._propulsionPlantConfiguration = dis.ReadUnsignedByte(); this._numberOfShafts = dis.ReadUnsignedByte(); this._numberOfAPAs = dis.ReadUnsignedByte(); this._numberOfUAEmitterSystems = dis.ReadUnsignedByte(); for (int idx = 0; idx < this.NumberOfShafts; idx++) { ShaftRPMs anX = new ShaftRPMs(); anX.Unmarshal(dis); this._shaftRPMs.Add(anX); } for (int idx = 0; idx < this.NumberOfAPAs; idx++) { ApaData anX = new ApaData(); anX.Unmarshal(dis); this._apaData.Add(anX); } for (int idx = 0; idx < this.NumberOfUAEmitterSystems; idx++) { AcousticEmitterSystemData anX = new AcousticEmitterSystemData(); anX.Unmarshal(dis); this._emitterSystems.Add(anX); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<UaPdu>"); base.Reflection(sb); try { sb.AppendLine("<emittingEntityID>"); this._emittingEntityID.Reflection(sb); sb.AppendLine("</emittingEntityID>"); sb.AppendLine("<eventID>"); this._eventID.Reflection(sb); sb.AppendLine("</eventID>"); sb.AppendLine("<stateChangeIndicator type=\"byte\">" + this._stateChangeIndicator.ToString(CultureInfo.InvariantCulture) + "</stateChangeIndicator>"); sb.AppendLine("<pad type=\"byte\">" + this._pad.ToString(CultureInfo.InvariantCulture) + "</pad>"); sb.AppendLine("<passiveParameterIndex type=\"ushort\">" + this._passiveParameterIndex.ToString(CultureInfo.InvariantCulture) + "</passiveParameterIndex>"); sb.AppendLine("<propulsionPlantConfiguration type=\"byte\">" + this._propulsionPlantConfiguration.ToString(CultureInfo.InvariantCulture) + "</propulsionPlantConfiguration>"); sb.AppendLine("<shaftRPMs type=\"byte\">" + this._shaftRPMs.Count.ToString(CultureInfo.InvariantCulture) + "</shaftRPMs>"); sb.AppendLine("<apaData type=\"byte\">" + this._apaData.Count.ToString(CultureInfo.InvariantCulture) + "</apaData>"); sb.AppendLine("<emitterSystems type=\"byte\">" + this._emitterSystems.Count.ToString(CultureInfo.InvariantCulture) + "</emitterSystems>"); for (int idx = 0; idx < this._shaftRPMs.Count; idx++) { sb.AppendLine("<shaftRPMs" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"ShaftRPMs\">"); ShaftRPMs aShaftRPMs = (ShaftRPMs)this._shaftRPMs[idx]; aShaftRPMs.Reflection(sb); sb.AppendLine("</shaftRPMs" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._apaData.Count; idx++) { sb.AppendLine("<apaData" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"ApaData\">"); ApaData aApaData = (ApaData)this._apaData[idx]; aApaData.Reflection(sb); sb.AppendLine("</apaData" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._emitterSystems.Count; idx++) { sb.AppendLine("<emitterSystems" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"AcousticEmitterSystemData\">"); AcousticEmitterSystemData aAcousticEmitterSystemData = (AcousticEmitterSystemData)this._emitterSystems[idx]; aAcousticEmitterSystemData.Reflection(sb); sb.AppendLine("</emitterSystems" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</UaPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as UaPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(UaPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (!this._emittingEntityID.Equals(obj._emittingEntityID)) { ivarsEqual = false; } if (!this._eventID.Equals(obj._eventID)) { ivarsEqual = false; } if (this._stateChangeIndicator != obj._stateChangeIndicator) { ivarsEqual = false; } if (this._pad != obj._pad) { ivarsEqual = false; } if (this._passiveParameterIndex != obj._passiveParameterIndex) { ivarsEqual = false; } if (this._propulsionPlantConfiguration != obj._propulsionPlantConfiguration) { ivarsEqual = false; } if (this._numberOfShafts != obj._numberOfShafts) { ivarsEqual = false; } if (this._numberOfAPAs != obj._numberOfAPAs) { ivarsEqual = false; } if (this._numberOfUAEmitterSystems != obj._numberOfUAEmitterSystems) { ivarsEqual = false; } if (this._shaftRPMs.Count != obj._shaftRPMs.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._shaftRPMs.Count; idx++) { if (!this._shaftRPMs[idx].Equals(obj._shaftRPMs[idx])) { ivarsEqual = false; } } } if (this._apaData.Count != obj._apaData.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._apaData.Count; idx++) { if (!this._apaData[idx].Equals(obj._apaData[idx])) { ivarsEqual = false; } } } if (this._emitterSystems.Count != obj._emitterSystems.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._emitterSystems.Count; idx++) { if (!this._emitterSystems[idx].Equals(obj._emitterSystems[idx])) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._emittingEntityID.GetHashCode(); result = GenerateHash(result) ^ this._eventID.GetHashCode(); result = GenerateHash(result) ^ this._stateChangeIndicator.GetHashCode(); result = GenerateHash(result) ^ this._pad.GetHashCode(); result = GenerateHash(result) ^ this._passiveParameterIndex.GetHashCode(); result = GenerateHash(result) ^ this._propulsionPlantConfiguration.GetHashCode(); result = GenerateHash(result) ^ this._numberOfShafts.GetHashCode(); result = GenerateHash(result) ^ this._numberOfAPAs.GetHashCode(); result = GenerateHash(result) ^ this._numberOfUAEmitterSystems.GetHashCode(); if (this._shaftRPMs.Count > 0) { for (int idx = 0; idx < this._shaftRPMs.Count; idx++) { result = GenerateHash(result) ^ this._shaftRPMs[idx].GetHashCode(); } } if (this._apaData.Count > 0) { for (int idx = 0; idx < this._apaData.Count; idx++) { result = GenerateHash(result) ^ this._apaData[idx].GetHashCode(); } } if (this._emitterSystems.Count > 0) { for (int idx = 0; idx < this._emitterSystems.Count; idx++) { result = GenerateHash(result) ^ this._emitterSystems[idx].GetHashCode(); } } return result; } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using VSLangProj; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// All public properties on Nodeproperties or derived classes are assumed to be used by Automation by default. /// Set this attribute to false on Properties that should not be visible for Automation. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class AutomationBrowsableAttribute : System.Attribute { public AutomationBrowsableAttribute(bool browsable) { this.browsable = browsable; } public bool Browsable { get { return this.browsable; } } private bool browsable; } /// <summary> /// This attribute is used to mark properties that shouldn't be serialized. Marking properties with this will /// result in them not being serialized and not being bold in the properties pane. /// </summary> [AttributeUsage(AttributeTargets.Property)] internal sealed class AlwaysSerializedAttribute : Attribute { public AlwaysSerializedAttribute() { } } /// <summary> /// To create your own localizable node properties, subclass this and add public properties /// decorated with your own localized display name, category and description attributes. /// </summary> [ComVisible(true)] public class NodeProperties : LocalizableProperties, ISpecifyPropertyPages, IVsGetCfgProvider, IVsSpecifyProjectDesignerPages, IVsBrowseObject { #region fields private HierarchyNode node; #endregion #region properties [Browsable(false)] [AutomationBrowsable(true)] public object Node { get { return this.node; } } internal HierarchyNode HierarchyNode { get { return this.node; } } /// <summary> /// Used by Property Pages Frame to set it's title bar. The Caption of the Hierarchy Node is returned. /// </summary> [Browsable(false)] [AutomationBrowsable(false)] public virtual string Name { get { return this.node.Caption; } } #endregion #region ctors internal NodeProperties(HierarchyNode node) { Utilities.ArgumentNotNull("node", node); this.node = node; } #endregion #region ISpecifyPropertyPages methods public virtual void GetPages(CAUUID[] pages) { this.GetCommonPropertyPages(pages); } #endregion #region IVsSpecifyProjectDesignerPages /// <summary> /// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration independent. /// </summary> /// <param name="pages">The pages to return.</param> /// <returns></returns> public virtual int GetProjectDesignerPages(CAUUID[] pages) { this.GetCommonPropertyPages(pages); return VSConstants.S_OK; } #endregion #region IVsGetCfgProvider methods public virtual int GetCfgProvider(out IVsCfgProvider p) { p = null; return VSConstants.E_NOTIMPL; } #endregion #region IVsBrowseObject methods /// <summary> /// Maps back to the hierarchy or project item object corresponding to the browse object. /// </summary> /// <param name="hier">Reference to the hierarchy object.</param> /// <param name="itemid">Reference to the project item.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid) { Utilities.CheckNotNull(node); hier = node.ProjectMgr.GetOuterInterface<IVsHierarchy>(); itemid = this.node.ID; return VSConstants.S_OK; } #endregion #region overridden methods /// <summary> /// Get the Caption of the Hierarchy Node instance. If Caption is null or empty we delegate to base /// </summary> /// <returns>Caption of Hierarchy node instance</returns> public override string GetComponentName() { string caption = this.HierarchyNode.Caption; if (string.IsNullOrEmpty(caption)) { return base.GetComponentName(); } else { return caption; } } #endregion #region helper methods protected string GetProperty(string name, string def) { string a = this.HierarchyNode.ItemNode.GetMetadata(name); return (a == null) ? def : a; } protected void SetProperty(string name, string value) { this.HierarchyNode.ItemNode.SetMetadata(name, value); } /// <summary> /// Retrieves the common property pages. The NodeProperties is the BrowseObject and that will be called to support /// configuration independent properties. /// </summary> /// <param name="pages">The pages to return.</param> private void GetCommonPropertyPages(CAUUID[] pages) { // We do not check whether the supportsProjectDesigner is set to false on the ProjectNode. // We rely that the caller knows what to call on us. Utilities.ArgumentNotNull("pages", pages); if (pages.Length == 0) { throw new ArgumentException(SR.GetString(SR.InvalidParameter), "pages"); } // Only the project should show the property page the rest should show the project properties. if (this.node != null && (this.node is ProjectNode)) { // Retrieve the list of guids from hierarchy properties. // Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy string guidsList = String.Empty; IVsHierarchy hierarchy = HierarchyNode.ProjectMgr.GetOuterInterface<IVsHierarchy>(); object variant = null; ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList, out variant)); guidsList = (string)variant; Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList); if (guids == null || guids.Length == 0) { pages[0] = new CAUUID(); pages[0].cElems = 0; } else { pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids); } } else { pages[0] = new CAUUID(); pages[0].cElems = 0; } } #endregion #region ExtenderSupport [Browsable(false)] public virtual string ExtenderCATID { get { Guid catid = this.HierarchyNode.ProjectMgr.GetCATIDForType(this.GetType()); if (Guid.Empty.CompareTo(catid) == 0) { return null; } return catid.ToString("B"); } } [Browsable(false)] public object ExtenderNames() { EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.HierarchyNode.GetService(typeof(EnvDTE.ObjectExtenders)); Utilities.CheckNotNull(extenderService, "Could not get the ObjectExtenders object from the services exposed by this property object"); return extenderService.GetExtenderNames(this.ExtenderCATID, this); } public object Extender(string extenderName) { EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.HierarchyNode.GetService(typeof(EnvDTE.ObjectExtenders)); Utilities.CheckNotNull(extenderService, "Could not get the ObjectExtenders object from the services exposed by this property object"); return extenderService.GetExtender(this.ExtenderCATID, extenderName, this); } #endregion } [ComVisible(true)] public class FileNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] [AlwaysSerialized] public virtual string FileName { get { return this.HierarchyNode.Caption; } set { this.HierarchyNode.SetEditLabel(value); } } [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public string FullPath { get { return this.HierarchyNode.Url; } } #region non-browsable properties - used for automation only [Browsable(false)] public string URL { get { return this.HierarchyNode.Url; } } [Browsable(false)] public string Extension { get { return Path.GetExtension(this.HierarchyNode.Caption); } } [Browsable(false)] public bool IsLinkFile { get { return HierarchyNode.IsLinkFile; } } #endregion #endregion #region ctors internal FileNodeProperties(HierarchyNode node) : base(node) { } #endregion public override string GetClassName() { return SR.GetString(SR.FileProperties); } } [ComVisible(true)] public class ExcludedFileNodeProperties : FileNodeProperties { internal ExcludedFileNodeProperties(HierarchyNode node) : base(node) { } [SRCategoryAttribute(SR.Advanced)] [SRDisplayName(SR.BuildAction)] [SRDescriptionAttribute(SR.BuildActionDescription)] [TypeConverter(typeof(BuildActionTypeConverter))] public prjBuildAction BuildAction { get { return prjBuildAction.prjBuildActionNone; } } } [ComVisible(true)] public class IncludedFileNodeProperties : FileNodeProperties { internal IncludedFileNodeProperties(HierarchyNode node) : base(node) { } /// <summary> /// Specifies the build action as a string so the user can configure it to any value. /// </summary> [SRCategoryAttribute(SR.Advanced)] [SRDisplayName(SR.BuildAction)] [SRDescriptionAttribute(SR.BuildActionDescription)] [AlwaysSerialized] [TypeConverter(typeof(BuildActionStringConverter))] public string ItemType { get { return HierarchyNode.ItemNode.ItemTypeName; } set { HierarchyNode.ItemNode.ItemTypeName = value; } } /// <summary> /// Specifies the build action as a projBuildAction so that automation can get the /// expected enum value. /// </summary> [Browsable(false)] public prjBuildAction BuildAction { get { var res = BuildActionTypeConverter.Instance.ConvertFromString(HierarchyNode.ItemNode.ItemTypeName); if (res is prjBuildAction) { return (prjBuildAction)res; } return prjBuildAction.prjBuildActionContent; } set { this.HierarchyNode.ItemNode.ItemTypeName = BuildActionTypeConverter.Instance.ConvertToString(value); } } [SRCategoryAttribute(SR.Advanced)] [SRDisplayName(SR.Publish)] [SRDescriptionAttribute(SR.PublishDescription)] public bool Publish { get { var publish = this.HierarchyNode.ItemNode.GetMetadata("Publish"); if (String.IsNullOrEmpty(publish)) { if (this.HierarchyNode.ItemNode.ItemTypeName == ProjectFileConstants.Compile) { return true; } return false; } return Convert.ToBoolean(publish); } set { this.HierarchyNode.ItemNode.SetMetadata("Publish", value.ToString()); } } [Browsable(false)] public bool ShouldSerializePublish() { // If compile, default should be true, else the default is false. if (HierarchyNode.ItemNode.ItemTypeName == ProjectFileConstants.Compile) { return !Publish; } return Publish; } [Browsable(false)] public void ResetPublish() { // If compile, default should be true, else the default is false. if (HierarchyNode.ItemNode.ItemTypeName == ProjectFileConstants.Compile) { Publish = true; } Publish = false; } [Browsable(false)] public string SourceControlStatus { get { // remove STATEICON_ and return rest of enum return HierarchyNode.StateIconIndex.ToString().Substring(10); } } [Browsable(false)] public string SubType { get { return this.HierarchyNode.ItemNode.GetMetadata("SubType"); } set { this.HierarchyNode.ItemNode.SetMetadata("SubType", value.ToString()); } } } [ComVisible(true)] public class LinkFileNodeProperties : FileNodeProperties { internal LinkFileNodeProperties(HierarchyNode node) : base(node) { } /// <summary> /// Specifies the build action as a string so the user can configure it to any value. /// </summary> [SRCategoryAttribute(SR.Advanced)] [SRDisplayName(SR.BuildAction)] [SRDescriptionAttribute(SR.BuildActionDescription)] [AlwaysSerialized] [TypeConverter(typeof(BuildActionStringConverter))] public string ItemType { get { return HierarchyNode.ItemNode.ItemTypeName; } set { HierarchyNode.ItemNode.ItemTypeName = value; } } [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] [ReadOnly(true)] public override string FileName { get { return this.HierarchyNode.Caption; } set { throw new InvalidOperationException(); } } } [ComVisible(true)] public class DependentFileNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] public virtual string FileName { get { return this.HierarchyNode.Caption; } } [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public string FullPath { get { return this.HierarchyNode.Url; } } #endregion #region ctors internal DependentFileNodeProperties(HierarchyNode node) : base(node) { } #endregion public override string GetClassName() { return SR.GetString(SR.FileProperties); } } class BuildActionTypeConverter : StringConverter { internal static readonly BuildActionTypeConverter Instance = new BuildActionTypeConverter(); public BuildActionTypeConverter() { } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { switch ((prjBuildAction)value) { case prjBuildAction.prjBuildActionCompile: return ProjectFileConstants.Compile; case prjBuildAction.prjBuildActionContent: return ProjectFileConstants.Content; case prjBuildAction.prjBuildActionNone: return ProjectFileConstants.None; } } return base.ConvertTo(context, culture, value, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string strVal = (string)value; if (strVal.Equals(ProjectFileConstants.Compile, StringComparison.OrdinalIgnoreCase)) { return prjBuildAction.prjBuildActionCompile; } else if (strVal.Equals(ProjectFileConstants.Content, StringComparison.OrdinalIgnoreCase)) { return prjBuildAction.prjBuildActionContent; } else if (strVal.Equals(ProjectFileConstants.None, StringComparison.OrdinalIgnoreCase)) { return prjBuildAction.prjBuildActionNone; } } return base.ConvertFrom(context, culture, value); } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new[] { prjBuildAction.prjBuildActionNone, prjBuildAction.prjBuildActionCompile, prjBuildAction.prjBuildActionContent }); } } /// <summary> /// This type converter doesn't really do any conversions, but allows us to provide /// a list of standard values for the build action. /// </summary> class BuildActionStringConverter : StringConverter { internal static readonly BuildActionStringConverter Instance = new BuildActionStringConverter(); public BuildActionStringConverter() { } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { return value; } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { return value; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { FileNodeProperties nodeProps = context.Instance as FileNodeProperties; IEnumerable<string> itemNames; if (nodeProps != null) { itemNames = nodeProps.HierarchyNode.ProjectMgr.GetAvailableItemNames(); } else { itemNames = new[] { ProjectFileConstants.None, ProjectFileConstants.Compile, ProjectFileConstants.Content }; } return new StandardValuesCollection(itemNames.ToArray()); } } [ComVisible(true)] public class ProjectNodeProperties : NodeProperties, EnvDTE80.IInternalExtenderProvider { #region properties [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.ProjectFolder)] [SRDescriptionAttribute(SR.ProjectFolderDescription)] [AutomationBrowsable(false)] public string ProjectFolder { get { return this.Node.ProjectMgr.ProjectFolder; } } [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.ProjectFile)] [SRDescriptionAttribute(SR.ProjectFileDescription)] [AutomationBrowsable(false)] public string ProjectFile { get { return this.Node.ProjectMgr.ProjectFile; } set { this.Node.ProjectMgr.ProjectFile = value; } } #region non-browsable properties - used for automation only [Browsable(false)] public string Guid { get { return this.Node.ProjectMgr.ProjectIDGuid.ToString(); } } [Browsable(false)] public string FileName { get { return this.Node.ProjectMgr.ProjectFile; } set { this.Node.ProjectMgr.ProjectFile = value; } } [Browsable(false)] public string FullPath { get { return CommonUtils.NormalizeDirectoryPath(this.Node.ProjectMgr.ProjectFolder); } } #endregion #endregion #region ctors internal ProjectNodeProperties(ProjectNode node) : base(node) { } internal new ProjectNode Node { get { return (ProjectNode)base.Node; } } #endregion #region overridden methods /// <summary> /// ICustomTypeDescriptor.GetEditor /// To enable the "Property Pages" button on the properties browser /// the browse object (project properties) need to be unmanaged /// or it needs to provide an editor of type ComponentEditor. /// </summary> /// <param name="editorBaseType">Type of the editor</param> /// <returns>Editor</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The service provider is used by the PropertiesEditorLauncher")] public override object GetEditor(Type editorBaseType) { // Override the scenario where we are asked for a ComponentEditor // as this is how the Properties Browser calls us if (editorBaseType == typeof(ComponentEditor)) { IOleServiceProvider sp; ErrorHandler.ThrowOnFailure(Node.ProjectMgr.GetSite(out sp)); return new PropertiesEditorLauncher(new ServiceProvider(sp)); } return base.GetEditor(editorBaseType); } public override int GetCfgProvider(out IVsCfgProvider p) { if (this.Node != null && this.Node.ProjectMgr != null) { return this.Node.ProjectMgr.GetCfgProvider(out p); } return base.GetCfgProvider(out p); } public override string GetClassName() { return SR.GetString(SR.ProjectProperties); } #endregion #region IInternalExtenderProvider Members bool EnvDTE80.IInternalExtenderProvider.CanExtend(string extenderCATID, string extenderName, object extendeeObject) { EnvDTE80.IInternalExtenderProvider outerHierarchy = Node.GetOuterInterface<EnvDTE80.IInternalExtenderProvider>(); if (outerHierarchy != null) { return outerHierarchy.CanExtend(extenderCATID, extenderName, extendeeObject); } return false; } object EnvDTE80.IInternalExtenderProvider.GetExtender(string extenderCATID, string extenderName, object extendeeObject, EnvDTE.IExtenderSite extenderSite, int cookie) { EnvDTE80.IInternalExtenderProvider outerHierarchy = Node.GetOuterInterface<EnvDTE80.IInternalExtenderProvider>(); if (outerHierarchy != null) { return outerHierarchy.GetExtender(extenderCATID, extenderName, extendeeObject, extenderSite, cookie); } return null; } object EnvDTE80.IInternalExtenderProvider.GetExtenderNames(string extenderCATID, object extendeeObject) { return null; } #endregion } [ComVisible(true)] public class FolderNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.FolderName)] [SRDescriptionAttribute(SR.FolderNameDescription)] public string FolderName { get { return this.HierarchyNode.Caption; } set { HierarchyNode.ProjectMgr.Site.GetUIThread().Invoke(() => { this.HierarchyNode.SetEditLabel(value); this.HierarchyNode.ProjectMgr.ReDrawNode(HierarchyNode, UIHierarchyElement.Caption); }); } } #region properties - used for automation only [Browsable(false)] [AutomationBrowsable(true)] public string FileName { get { return this.HierarchyNode.Caption; } set { HierarchyNode.ProjectMgr.Site.GetUIThread().Invoke(() => { this.HierarchyNode.SetEditLabel(value); this.HierarchyNode.ProjectMgr.ReDrawNode(HierarchyNode, UIHierarchyElement.Caption); }); } } [Browsable(true)] [AutomationBrowsable(true)] [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public string FullPath { get { return CommonUtils.NormalizeDirectoryPath(this.HierarchyNode.GetMkDocument()); } } #endregion #endregion #region ctors internal FolderNodeProperties(HierarchyNode node) : base(node) { } #endregion public override string GetClassName() { return SR.GetString(SR.FolderProperties); } } [CLSCompliant(false), ComVisible(true)] public class ReferenceNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.RefName)] [SRDescriptionAttribute(SR.RefNameDescription)] [Browsable(true)] [AutomationBrowsable(true)] public override string Name { get { return this.HierarchyNode.Caption; } } [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.CopyToLocal)] [SRDescriptionAttribute(SR.CopyToLocalDescription)] public bool CopyToLocal { get { string copyLocal = this.GetProperty(ProjectFileConstants.Private, "False"); if (copyLocal == null || copyLocal.Length == 0) return true; return bool.Parse(copyLocal); } set { this.SetProperty(ProjectFileConstants.Private, value.ToString()); } } [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public virtual string FullPath { get { return this.HierarchyNode.Url; } } #endregion #region ctors internal ReferenceNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.ReferenceProperties); } #endregion } [ComVisible(true)] public class ProjectReferencesProperties : ReferenceNodeProperties { #region ctors internal ProjectReferencesProperties(ProjectReferenceNode node) : base(node) { } #endregion #region overriden methods public override string FullPath { get { return ((ProjectReferenceNode)Node).ReferencedProjectOutputPath; } } #endregion } }
using System; using System.IO; using Org.BouncyCastle.Bcpg.Sig; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Bcpg.OpenPgp { /// <remarks>Generator for PGP signatures.</remarks> // TODO Should be able to implement ISigner? public class PgpSignatureGenerator { private static readonly ISignatureSubpacket[] _emptySignatureSubpackets = new ISignatureSubpacket[0]; private readonly PublicKeyAlgorithmTag _keyAlgorithm; private readonly HashAlgorithmTag _hashAlgorithm; private IPgpPrivateKey _privKey; private readonly ISigner _sig; private readonly IDigest _dig; private int _signatureType; private byte _lastb; private ISignatureSubpacket[] _unhashed = _emptySignatureSubpackets; private ISignatureSubpacket[] _hashed = _emptySignatureSubpackets; /// <summary>Create a generator for the passed in keyAlgorithm and hashAlgorithm codes.</summary> public PgpSignatureGenerator(PublicKeyAlgorithmTag keyAlgorithm, HashAlgorithmTag hashAlgorithm) { _keyAlgorithm = keyAlgorithm; _hashAlgorithm = hashAlgorithm; _dig = DigestUtilities.GetDigest(PgpUtilities.GetDigestName(hashAlgorithm)); _sig = SignerUtilities.GetSigner(PgpUtilities.GetSignatureName(keyAlgorithm, hashAlgorithm)); } /// <summary>Initialise the generator for signing.</summary> public void InitSign(int sigType, IPgpPrivateKey key) { InitSign(sigType, key, null); } /// <summary>Initialise the generator for signing.</summary> public void InitSign(int sigType, IPgpPrivateKey key, ISecureRandom random) { _privKey = key; _signatureType = sigType; try { ICipherParameters cp = key.Key; if (random != null) { cp = new ParametersWithRandom(key.Key, random); } _sig.Init(true, cp); } catch (InvalidKeyException e) { throw new PgpException("invalid key.", e); } _dig.Reset(); _lastb = 0; } public void Update(byte b) { if (_signatureType == PgpSignature.CanonicalTextDocument) { DoCanonicalUpdateByte(b); } else { DoUpdateByte(b); } } private void DoCanonicalUpdateByte( byte b) { if (b == '\r') { DoUpdateCrlf(); } else if (b == '\n') { if (_lastb != '\r') { DoUpdateCrlf(); } } else { DoUpdateByte(b); } _lastb = b; } private void DoUpdateCrlf() { DoUpdateByte((byte)'\r'); DoUpdateByte((byte)'\n'); } private void DoUpdateByte( byte b) { _sig.Update(b); _dig.Update(b); } public void Update(params byte[] b) { Update(b, 0, b.Length); } public void Update(byte[] b, int off, int len) { if (_signatureType == PgpSignature.CanonicalTextDocument) { var finish = off + len; for (var i = off; i != finish; i++) { DoCanonicalUpdateByte(b[i]); } } else { _sig.BlockUpdate(b, off, len); _dig.BlockUpdate(b, off, len); } } public void SetHashedSubpackets(IPgpSignatureSubpacketVector hashedPackets) { _hashed = hashedPackets == null ? _emptySignatureSubpackets : hashedPackets.ToSubpacketArray(); } public void SetUnhashedSubpackets(IPgpSignatureSubpacketVector unhashedPackets) { _unhashed = unhashedPackets == null ? _emptySignatureSubpackets : unhashedPackets.ToSubpacketArray(); } /// <summary>Return the one pass header associated with the current signature.</summary> public PgpOnePassSignature GenerateOnePassVersion(bool isNested) { return new PgpOnePassSignature(new OnePassSignaturePacket( _signatureType, _hashAlgorithm, _keyAlgorithm, _privKey.KeyId, isNested)); } /// <summary>Return a signature object containing the current signature state.</summary> public PgpSignature Generate() { ISignatureSubpacket[] hPkts = _hashed, unhPkts = _unhashed; if (!PacketPresent(_hashed, SignatureSubpacketTag.CreationTime)) { hPkts = InsertSubpacket(hPkts, new SignatureCreationTime(false, DateTime.UtcNow)); } if (!PacketPresent(_hashed, SignatureSubpacketTag.IssuerKeyId) && !PacketPresent(_unhashed, SignatureSubpacketTag.IssuerKeyId)) { unhPkts = InsertSubpacket(unhPkts, new IssuerKeyId(false, _privKey.KeyId)); } const int version = 4; byte[] hData; try { using (var hOut = new MemoryStream()) { for (var i = 0; i != hPkts.Length; i++) { hPkts[i].Encode(hOut); } var data = hOut.ToArray(); using (var sOut = new MemoryStream(data.Length + 6)) { sOut.WriteByte(version); sOut.WriteByte((byte)_signatureType); sOut.WriteByte((byte)_keyAlgorithm); sOut.WriteByte((byte)_hashAlgorithm); sOut.WriteByte((byte)(data.Length >> 8)); sOut.WriteByte((byte)data.Length); sOut.Write(data, 0, data.Length); hData = sOut.ToArray(); } } } catch (IOException e) { throw new PgpException("exception encoding hashed data.", e); } _sig.BlockUpdate(hData, 0, hData.Length); _dig.BlockUpdate(hData, 0, hData.Length); hData = new byte[] { version, 0xff, (byte)(hData.Length >> 24), (byte)(hData.Length >> 16), (byte)(hData.Length >> 8), (byte) hData.Length }; _sig.BlockUpdate(hData, 0, hData.Length); _dig.BlockUpdate(hData, 0, hData.Length); var sigBytes = _sig.GenerateSignature(); var digest = DigestUtilities.DoFinal(_dig); var fingerPrint = new[] { digest[0], digest[1] }; // an RSA signature var isRsa = _keyAlgorithm == PublicKeyAlgorithmTag.RsaSign || _keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral; var sigValues = isRsa ? PgpUtilities.RsaSigToMpi(sigBytes) : PgpUtilities.DsaSigToMpi(sigBytes); return new PgpSignature(new SignaturePacket(_signatureType, _privKey.KeyId, _keyAlgorithm, _hashAlgorithm, hPkts, unhPkts, fingerPrint, sigValues)); } /// <summary> /// Generate a certification for the passed in ID and key. /// </summary> /// <param name="id">The ID we are certifying against the public key.</param> /// <param name="pubKey">The key we are certifying against the ID.</param> /// <returns> /// The certification. /// </returns> public PgpSignature GenerateCertification(string id, IPgpPublicKey pubKey) { UpdateWithPublicKey(pubKey); // // hash in the id // UpdateWithIdData(0xb4, Strings.ToByteArray(id)); return Generate(); } /// <summary> /// Generate a certification for the passed in userAttributes. /// </summary> /// <param name="userAttributes">The ID we are certifying against the public key.</param> /// <param name="pubKey">The key we are certifying against the ID.</param> /// <returns> /// The certification. /// </returns> /// <exception cref="PgpException">cannot encode subpacket array</exception> public PgpSignature GenerateCertification(PgpUserAttributeSubpacketVector userAttributes, IPgpPublicKey pubKey) { UpdateWithPublicKey(pubKey); // // hash in the attributes // try { using (var bOut = new MemoryStream()) { foreach (var packet in userAttributes.ToSubpacketArray()) { packet.Encode(bOut); } UpdateWithIdData(0xd1, bOut.ToArray()); } } catch (IOException e) { throw new PgpException("cannot encode subpacket array", e); } return this.Generate(); } /// <summary> /// Generate a certification for the passed in key against the passed in master key. /// </summary> /// <param name="masterKey">The key we are certifying against.</param> /// <param name="pubKey">The key we are certifying.</param> /// <returns> /// The certification. /// </returns> public PgpSignature GenerateCertification( IPgpPublicKey masterKey, IPgpPublicKey pubKey) { UpdateWithPublicKey(masterKey); UpdateWithPublicKey(pubKey); return Generate(); } /// <summary> /// Generate a certification, such as a revocation, for the passed in key. /// </summary> /// <param name="pubKey">The key we are certifying.</param> /// <returns> /// The certification. /// </returns> public PgpSignature GenerateCertification(IPgpPublicKey pubKey) { UpdateWithPublicKey(pubKey); return Generate(); } /// <summary> /// Gets the encoded public key. /// </summary> /// <param name="pubKey">The pub key.</param> /// <returns></returns> /// <exception cref="PgpException">exception preparing key.</exception> private static byte[] GetEncodedPublicKey(IPgpPublicKey pubKey) { try { return pubKey.PublicKeyPacket.GetEncodedContents(); } catch (IOException e) { throw new PgpException("exception preparing key.", e); } } /// <summary> /// Packets the present. /// </summary> /// <param name="packets">The packets.</param> /// <param name="type">The type.</param> /// <returns></returns> private static bool PacketPresent(ISignatureSubpacket[] packets, SignatureSubpacketTag type) { for (var i = 0; i != packets.Length; i++) { if (packets[i].SubpacketType == type) { return true; } } return false; } /// <summary> /// Inserts the subpacket. /// </summary> /// <param name="packets">The packets.</param> /// <param name="subpacket">The subpacket.</param> /// <returns></returns> private static SignatureSubpacket[] InsertSubpacket(ISignatureSubpacket[] packets, SignatureSubpacket subpacket) { var tmp = new SignatureSubpacket[packets.Length + 1]; tmp[0] = subpacket; packets.CopyTo(tmp, 1); return tmp; } private void UpdateWithIdData(int header, byte[] idBytes) { this.Update( (byte)header, (byte)(idBytes.Length >> 24), (byte)(idBytes.Length >> 16), (byte)(idBytes.Length >> 8), (byte)(idBytes.Length)); this.Update(idBytes); } private void UpdateWithPublicKey(IPgpPublicKey key) { var keyBytes = GetEncodedPublicKey(key); this.Update( (byte)0x99, (byte)(keyBytes.Length >> 8), (byte)(keyBytes.Length)); this.Update(keyBytes); } } }
// DeflateStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009-2010 Dino Chiesa. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-July-31 14:48:11> // // ------------------------------------------------------------------ // // This module defines the DeflateStream class, which can be used as a replacement for // the System.IO.Compression.DeflateStream class in the .NET BCL. // // ------------------------------------------------------------------ using System; namespace Ionic.Zlib { /// <summary> /// A class for compressing and decompressing streams using the Deflate algorithm. /// </summary> /// /// <remarks> /// /// <para> /// The DeflateStream is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see /// cref="System.IO.Stream"/>. It adds DEFLATE compression or decompression to any /// stream. /// </para> /// /// <para> /// Using this stream, applications can compress or decompress data via stream /// <c>Read</c> and <c>Write</c> operations. Either compresssion or decompression /// can occur through either reading or writing. The compression format used is /// DEFLATE, which is documented in <see /// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE /// Compressed Data Format Specification version 1.3.". /// </para> /// /// <para> /// This class is similar to <see cref="ZlibStream"/>, except that /// <c>ZlibStream</c> adds the <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC /// 1950 - ZLIB</see> framing bytes to a compressed stream when compressing, or /// expects the RFC1950 framing bytes when decompressing. The <c>DeflateStream</c> /// does not. /// </para> /// /// </remarks> /// /// <seealso cref="ZlibStream" /> /// <seealso cref="GZipStream" /> internal class DeflateStream : System.IO.Stream { internal ZlibBaseStream _baseStream; internal System.IO.Stream _innerStream; bool _disposed; /// <summary> /// Create a DeflateStream using the specified CompressionMode. /// </summary> /// /// <remarks> /// When mode is <c>CompressionMode.Compress</c>, the DeflateStream will use /// the default compression level. The "captive" stream will be closed when /// the DeflateStream is closed. /// </remarks> /// /// <example> /// This example uses a DeflateStream to compress data from a file, and writes /// the compressed data to another file. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".deflated")) /// { /// using (Stream compressor = new DeflateStream(raw, CompressionMode.Compress)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".deflated") /// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param> public DeflateStream(System.IO.Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { } /// <summary> /// Create a DeflateStream using the specified CompressionMode and the specified CompressionLevel. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is /// ignored. The "captive" stream will be closed when the DeflateStream is /// closed. /// </para> /// /// </remarks> /// /// <example> /// /// This example uses a DeflateStream to compress data from a file, and writes /// the compressed data to another file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".deflated")) /// { /// using (Stream compressor = new DeflateStream(raw, /// CompressionMode.Compress, /// CompressionLevel.BestCompression)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n= -1; /// while (n != 0) /// { /// if (n &gt; 0) /// compressor.Write(buffer, 0, n); /// n= input.Read(buffer, 0, buffer.Length); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".deflated") /// Using compressor As Stream = New DeflateStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream to be read or written while deflating or inflating.</param> /// <param name="mode">Indicates whether the <c>DeflateStream</c> will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { } /// <summary> /// Create a <c>DeflateStream</c> using the specified /// <c>CompressionMode</c>, and explicitly specify whether the /// stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// memory stream that will be re-read after compression. Specify true for /// the <paramref name="leaveOpen"/> parameter to leave the stream open. /// </para> /// /// <para> /// The <c>DeflateStream</c> will use the default compression level. /// </para> /// /// <para> /// See the other overloads of this constructor for example code. /// </para> /// </remarks> /// /// <param name="stream"> /// The stream which will be read or written. This is called the /// "captive" stream in other places in this documentation. /// </param> /// /// <param name="mode"> /// Indicates whether the <c>DeflateStream</c> will compress or decompress. /// </param> /// /// <param name="leaveOpen">true if the application would like the stream to /// remain open after inflation/deflation.</param> public DeflateStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } /// <summary> /// Create a <c>DeflateStream</c> using the specified <c>CompressionMode</c> /// and the specified <c>CompressionLevel</c>, and explicitly specify whether /// the stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored. /// </para> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// <see cref="System.IO.MemoryStream"/> that will be re-read after /// compression. Specify true for the <paramref name="leaveOpen"/> parameter /// to leave the stream open. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a <c>DeflateStream</c> to compress data from /// a file, and store the compressed data into another file. /// /// <code> /// using (var output = System.IO.File.Create(fileToCompress + ".deflated")) /// { /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (Stream compressor = new DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n= -1; /// while (n != 0) /// { /// if (n &gt; 0) /// compressor.Write(buffer, 0, n); /// n= input.Read(buffer, 0, buffer.Length); /// } /// } /// } /// // can write additional data to the output stream here /// } /// </code> /// /// <code lang="VB"> /// Using output As FileStream = File.Create(fileToCompress &amp; ".deflated") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using compressor As Stream = New DeflateStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// ' can write additional data to the output stream here. /// End Using /// </code> /// </example> /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the DeflateStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public DeflateStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _innerStream = stream; _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.DEFLATE, leaveOpen); } #region Zlib properties /// <summary> /// This property sets the flush behavior on the stream. /// </summary> /// <remarks> See the ZLIB documentation for the meaning of the flush behavior. /// </remarks> public virtual FlushType FlushMode { get { return (this._baseStream._flushMode); } set { if (_disposed) throw new ObjectDisposedException("DeflateStream"); this._baseStream._flushMode = value; } } /// <summary> /// The size of the working buffer for the compression codec. /// </summary> /// /// <remarks> /// <para> /// The working buffer is used for all stream operations. The default size is /// 1024 bytes. The minimum size is 128 bytes. You may get better performance /// with a larger buffer. Then again, you might not. You would have to test /// it. /// </para> /// /// <para> /// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the /// stream. If you try to set it afterwards, it will throw. /// </para> /// </remarks> public int BufferSize { get { return this._baseStream._bufferSize; } set { if (_disposed) throw new ObjectDisposedException("DeflateStream"); if (this._baseStream._workingBuffer != null) throw new ZlibException("The working buffer is already set."); if (value < ZlibConstants.WorkingBufferSizeMin) throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin)); this._baseStream._bufferSize = value; } } /// <summary> /// The ZLIB strategy to be used during compression. /// </summary> /// /// <remarks> /// By tweaking this parameter, you may be able to optimize the compression for /// data with particular characteristics. /// </remarks> public CompressionStrategy Strategy { get { return this._baseStream.Strategy; } set { if (_disposed) throw new ObjectDisposedException("DeflateStream"); this._baseStream.Strategy = value; } } /// <summary> Returns the total number of bytes input so far.</summary> public virtual long TotalIn { get { return this._baseStream._z.TotalBytesIn; } } /// <summary> Returns the total number of bytes output so far.</summary> public virtual long TotalOut { get { return this._baseStream._z.TotalBytesOut; } } #endregion #region System.IO.Stream methods /// <summary> /// Dispose the stream. /// </summary> /// <remarks> /// <para> /// This may or may not result in a <c>Close()</c> call on the captive /// stream. See the constructors that have a <c>leaveOpen</c> parameter /// for more information. /// </para> /// <para> /// Application code won't call this code directly. This method may be /// invoked in two distinct scenarios. If disposing == true, the method /// has been called directly or indirectly by a user's code, for example /// via the public Dispose() method. In this case, both managed and /// unmanaged resources can be referenced and disposed. If disposing == /// false, the method has been called by the runtime from inside the /// object finalizer and this method should not reference other objects; /// in that case only unmanaged resources must be referenced or /// disposed. /// </para> /// </remarks> /// <param name="disposing"> /// true if the Dispose method was invoked by user code. /// </param> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (this._baseStream != null)) this._baseStream.Dispose(); _disposed = true; } } finally { base.Dispose(disposing); } } /// <summary> /// Indicates whether the stream can be read. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports reading. /// </remarks> public override bool CanRead { get { if (_disposed) throw new ObjectDisposedException("DeflateStream"); return _baseStream._stream.CanRead; } } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream can be written. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports writing. /// </remarks> public override bool CanWrite { get { if (_disposed) throw new ObjectDisposedException("DeflateStream"); return _baseStream._stream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_disposed) throw new ObjectDisposedException("DeflateStream"); _baseStream.Flush(); } /// <summary> /// Reading this property always throws a <see cref="NotImplementedException"/>. /// </summary> public override long Length { get { throw new NotImplementedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotImplementedException"/>. Reading will return the total bytes /// written out, if used in writing, or the total bytes read in, if used in /// reading. The count may refer to compressed bytes or uncompressed bytes, /// depending on how you've used the stream. /// </remarks> public override long Position { get { if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Writer) return this._baseStream._z.TotalBytesOut; if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader) return this._baseStream._z.TotalBytesIn; return 0; } set { throw new NotImplementedException(); } } /// <summary> /// Read data from the stream. /// </summary> /// <remarks> /// /// <para> /// If you wish to use the <c>DeflateStream</c> to compress data while /// reading, you can create a <c>DeflateStream</c> with /// <c>CompressionMode.Compress</c>, providing an uncompressed data stream. /// Then call Read() on that <c>DeflateStream</c>, and the data read will be /// compressed as you read. If you wish to use the <c>DeflateStream</c> to /// decompress data while reading, you can create a <c>DeflateStream</c> with /// <c>CompressionMode.Decompress</c>, providing a readable compressed data /// stream. Then call Read() on that <c>DeflateStream</c>, and the data read /// will be decompressed as you read. /// </para> /// /// <para> /// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both. /// </para> /// /// </remarks> /// <param name="buffer">The buffer into which the read data should be placed.</param> /// <param name="offset">the offset within that data array to put the first byte read.</param> /// <param name="count">the number of bytes to read.</param> /// <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("DeflateStream"); return _baseStream.Read(buffer, offset, count); } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="offset">this is irrelevant, since it will always throw!</param> /// <param name="origin">this is irrelevant, since it will always throw!</param> /// <returns>irrelevant!</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotImplementedException(); } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="value">this is irrelevant, since it will always throw!</param> public override void SetLength(long value) { throw new NotImplementedException(); } /// <summary> /// Write data to the stream. /// </summary> /// <remarks> /// /// <para> /// If you wish to use the <c>DeflateStream</c> to compress data while /// writing, you can create a <c>DeflateStream</c> with /// <c>CompressionMode.Compress</c>, and a writable output stream. Then call /// <c>Write()</c> on that <c>DeflateStream</c>, providing uncompressed data /// as input. The data sent to the output stream will be the compressed form /// of the data written. If you wish to use the <c>DeflateStream</c> to /// decompress data while writing, you can create a <c>DeflateStream</c> with /// <c>CompressionMode.Decompress</c>, and a writable output stream. Then /// call <c>Write()</c> on that stream, providing previously compressed /// data. The data sent to the output stream will be the decompressed form of /// the data written. /// </para> /// /// <para> /// A <c>DeflateStream</c> can be used for <c>Read()</c> or <c>Write()</c>, /// but not both. /// </para> /// /// </remarks> /// /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("DeflateStream"); _baseStream.Write(buffer, offset, count); } #endregion /// <summary> /// Compress a string into a byte array using DEFLATE (RFC 1951). /// </summary> /// /// <remarks> /// Uncompress it with <see cref="DeflateStream.UncompressString(byte[])"/>. /// </remarks> /// /// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso> /// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso> /// <seealso cref="GZipStream.CompressString(string)">GZipStream.CompressString(string)</seealso> /// <seealso cref="ZlibStream.CompressString(string)">ZlibStream.CompressString(string)</seealso> /// /// <param name="s"> /// A string to compress. The string will first be encoded /// using UTF8, then compressed. /// </param> /// /// <returns>The string in compressed form</returns> public static byte[] CompressString(String s) { using (var ms = new System.IO.MemoryStream()) { System.IO.Stream compressor = new DeflateStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return ms.ToArray(); } } /// <summary> /// Compress a byte array into a new byte array using DEFLATE. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="DeflateStream.UncompressBuffer(byte[])"/>. /// </remarks> /// /// <seealso cref="DeflateStream.CompressString(string)">DeflateStream.CompressString(string)</seealso> /// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso> /// <seealso cref="GZipStream.CompressBuffer(byte[])">GZipStream.CompressBuffer(byte[])</seealso> /// <seealso cref="ZlibStream.CompressBuffer(byte[])">ZlibStream.CompressBuffer(byte[])</seealso> /// /// <param name="b"> /// A buffer to compress. /// </param> /// /// <returns>The data in compressed form</returns> public static byte[] CompressBuffer(byte[] b) { using (var ms = new System.IO.MemoryStream()) { System.IO.Stream compressor = new DeflateStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression ); ZlibBaseStream.CompressBuffer(b, compressor); return ms.ToArray(); } } /// <summary> /// Uncompress a DEFLATE'd byte array into a single string. /// </summary> /// /// <seealso cref="DeflateStream.CompressString(String)">DeflateStream.CompressString(String)</seealso> /// <seealso cref="DeflateStream.UncompressBuffer(byte[])">DeflateStream.UncompressBuffer(byte[])</seealso> /// <seealso cref="GZipStream.UncompressString(byte[])">GZipStream.UncompressString(byte[])</seealso> /// <seealso cref="ZlibStream.UncompressString(byte[])">ZlibStream.UncompressString(byte[])</seealso> /// /// <param name="compressed"> /// A buffer containing DEFLATE-compressed data. /// </param> /// /// <returns>The uncompressed string</returns> public static String UncompressString(byte[] compressed) { using (var input = new System.IO.MemoryStream(compressed)) { System.IO.Stream decompressor = new DeflateStream(input, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } } /// <summary> /// Uncompress a DEFLATE'd byte array into a byte array. /// </summary> /// /// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso> /// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso> /// <seealso cref="GZipStream.UncompressBuffer(byte[])">GZipStream.UncompressBuffer(byte[])</seealso> /// <seealso cref="ZlibStream.UncompressBuffer(byte[])">ZlibStream.UncompressBuffer(byte[])</seealso> /// /// <param name="compressed"> /// A buffer containing data that has been compressed with DEFLATE. /// </param> /// /// <returns>The data in uncompressed form</returns> public static byte[] UncompressBuffer(byte[] compressed) { using (var input = new System.IO.MemoryStream(compressed)) { System.IO.Stream decompressor = new DeflateStream( input, CompressionMode.Decompress ); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcnv = Google.Cloud.Notebooks.V1Beta1; using sys = System; namespace Google.Cloud.Notebooks.V1Beta1 { /// <summary>Resource name for the <c>Instance</c> resource.</summary> public sealed partial class InstanceName : gax::IResourceName, sys::IEquatable<InstanceName> { /// <summary>The possible contents of <see cref="InstanceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/instances/{instance}</c>.</summary> ProjectInstance = 1, } private static gax::PathTemplate s_projectInstance = new gax::PathTemplate("projects/{project}/instances/{instance}"); /// <summary>Creates a <see cref="InstanceName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="InstanceName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static InstanceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new InstanceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="InstanceName"/> with the pattern <c>projects/{project}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="InstanceName"/> constructed from the provided ids.</returns> public static InstanceName FromProjectInstance(string projectId, string instanceId) => new InstanceName(ResourceNameType.ProjectInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/instances/{instance}</c>. /// </returns> public static string Format(string projectId, string instanceId) => FormatProjectInstance(projectId, instanceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/instances/{instance}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="InstanceName"/> with pattern /// <c>projects/{project}/instances/{instance}</c>. /// </returns> public static string FormatProjectInstance(string projectId, string instanceId) => s_projectInstance.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))); /// <summary>Parses the given resource name string into a new <see cref="InstanceName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName) => Parse(instanceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="InstanceName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="InstanceName"/> if successful.</returns> public static InstanceName Parse(string instanceName, bool allowUnparsed) => TryParse(instanceName, allowUnparsed, out InstanceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/instances/{instance}</c></description></item> /// </list> /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, out InstanceName result) => TryParse(instanceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="InstanceName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/instances/{instance}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="instanceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="InstanceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string instanceName, bool allowUnparsed, out InstanceName result) { gax::GaxPreconditions.CheckNotNull(instanceName, nameof(instanceName)); gax::TemplatedResourceName resourceName; if (s_projectInstance.TryParseName(instanceName, out resourceName)) { result = FromProjectInstance(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(instanceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private InstanceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string instanceId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; InstanceId = instanceId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="InstanceName"/> class from the component parts of pattern /// <c>projects/{project}/instances/{instance}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> public InstanceName(string projectId, string instanceId) : this(ResourceNameType.ProjectInstance, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string InstanceId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectInstance: return s_projectInstance.Expand(ProjectId, InstanceId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as InstanceName); /// <inheritdoc/> public bool Equals(InstanceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(InstanceName a, InstanceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(InstanceName a, InstanceName b) => !(a == b); } public partial class Instance { /// <summary> /// <see cref="gcnv::InstanceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcnv::InstanceName InstanceName { get => string.IsNullOrEmpty(Name) ? null : gcnv::InstanceName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
namespace Nancy { using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Nancy.Cookies; using Nancy.Responses.Negotiation; /// <summary> /// Provides strongly-typed access to HTTP request headers. /// </summary> public class RequestHeaders : IEnumerable<KeyValuePair<string, IEnumerable<string>>> { private readonly IDictionary<string, IEnumerable<string>> headers; private readonly ConcurrentDictionary<string, IEnumerable<Tuple<string, decimal>>> cache; /// <summary> /// Initializes a new instance of the <see cref="RequestHeaders"/> class. /// </summary> /// <param name="headers">The headers.</param> public RequestHeaders(IDictionary<string, IEnumerable<string>> headers) { this.headers = new Dictionary<string, IEnumerable<string>>(headers, StringComparer.OrdinalIgnoreCase); this.cache = new ConcurrentDictionary<string, IEnumerable<Tuple<string, decimal>>>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Content-types that are acceptable. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value> public IEnumerable<Tuple<string, decimal>> Accept { get { return this.GetWeightedValues("Accept"); } set { this.SetHeaderValues("Accept", value, GetWeightedValuesAsStrings); } } /// <summary> /// Character sets that are acceptable. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value> public IEnumerable<Tuple<string, decimal>> AcceptCharset { get { return this.GetWeightedValues("Accept-Charset"); } set { this.SetHeaderValues("Accept-Charset", value, GetWeightedValuesAsStrings); } } /// <summary> /// Acceptable encodings. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value> public IEnumerable<string> AcceptEncoding { get { return this.GetSplitValues("Accept-Encoding"); } set { this.SetHeaderValues("Accept-Encoding", value, x => x); } } /// <summary> /// Acceptable languages for response. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value> public IEnumerable<Tuple<string, decimal>> AcceptLanguage { get { return this.GetWeightedValues("Accept-Language"); } set { this.SetHeaderValues("Accept-Language", value, GetWeightedValuesAsStrings); } } /// <summary> /// Authorization header value for request. /// </summary> /// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value> public string Authorization { get { return this.GetValue("Authorization", x => x.First(), string.Empty); } set { this.SetHeaderValues("Authorization", value, x => new[] { x }); } } /// <summary> /// Used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value> public IEnumerable<string> CacheControl { get { return this.GetValue("Cache-Control"); } set { this.SetHeaderValues("Cache-Control", value, x => x); } } /// <summary> /// Contains name/value pairs of information stored for that URL. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> that contains <see cref="INancyCookie"/> instances if they are available; otherwise it will be empty.</value> public IEnumerable<INancyCookie> Cookie { get { return this.GetValue("Cookie", GetNancyCookies, Enumerable.Empty<INancyCookie>()); } } /// <summary> /// What type of connection the user-agent would prefer. /// </summary> /// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value> public string Connection { get { return this.GetValue("Connection", x => x.First(), string.Empty); } set { this.SetHeaderValues("Connection", value, x => new[] { x }); } } /// <summary> /// The length of the request body in octets (8-bit bytes). /// </summary> /// <value>The length of the contents if it is available; otherwise 0.</value> public long ContentLength { get { return this.GetValue("Content-Length", x => Convert.ToInt64(x.First()), 0); } set { this.SetHeaderValues("Content-Length", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); } } /// <summary> /// The mime type of the body of the request (used with POST and PUT requests). /// </summary> /// <value>A <see cref="MediaRange"/> containing the header value if it is available; otherwise <see langword="null"/>.</value> public MediaRange ContentType { get { return this.GetValue("Content-Type", x => new MediaRange(x.First()), null); } set { this.SetHeaderValues("Content-Type", value, x => new[] { x.ToString() }); } } /// <summary> /// The date and time that the message was sent. /// </summary> /// <value>A <see cref="DateTime"/> instance that specifies when the message was sent. If not available then <see langword="null"/> will be returned.</value> public DateTime? Date { get { return this.GetValue("Date", x => ParseDateTime(x.First()), null); } set { this.SetHeaderValues("Date", value, x => new[] { GetDateAsString(value) }); } } /// <summary> /// The domain name of the server (for virtual hosting), mandatory since HTTP/1.1 /// </summary> /// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value> public string Host { get { return this.GetValue("Host", x => x.First(), string.Empty); } set { this.SetHeaderValues("Host", value, x => new[] { x }); } } /// <summary> /// Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for methods like PUT to only update a resource if it has not been modified since the user last updated it. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value> public IEnumerable<string> IfMatch { get { return this.GetValue("If-Match"); } set { this.SetHeaderValues("If-Match", value, x => x); } } /// <summary> /// Allows a 304 Not Modified to be returned if content is unchanged /// </summary> /// <value>A <see cref="DateTime"/> instance that specifies when the requested resource must have been changed since. If not available then <see langword="null"/> will be returned.</value> public DateTime? IfModifiedSince { get { return this.GetValue("If-Modified-Since", x => ParseDateTime(x.First()), null); } set { this.SetHeaderValues("If-Modified-Since", value, x => new[] { GetDateAsString(value) }); } } /// <summary> /// Allows a 304 Not Modified to be returned if content is unchanged /// </summary> /// <value>An <see cref="IEnumerable{T}"/> that contains the header values if they are available; otherwise it will be empty.</value> public IEnumerable<string> IfNoneMatch { get { return this.GetValue("If-None-Match"); } set { this.SetHeaderValues("If-None-Match", value, x => x); } } /// <summary> /// If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity. /// </summary> /// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value> public string IfRange { get { return this.GetValue("If-Range", x => x.First(), string.Empty); } set { this.SetHeaderValues("If-Range", value, x => new[] { x }); } } /// <summary> /// Only send the response if the entity has not been modified since a specific time. /// </summary> /// <value>A <see cref="DateTime"/> instance that specifies when the requested resource may not have been changed since. If not available then <see langword="null"/> will be returned.</value> public DateTime? IfUnmodifiedSince { get { return this.GetValue("If-Unmodified-Since", x => ParseDateTime(x.First()), null); } set { this.SetHeaderValues("If-Unmodified-Since", value, x => new[] { GetDateAsString(value) }); } } /// <summary> /// Gets the names of the available request headers. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> containing the names of the headers.</value> public IEnumerable<string> Keys { get { return this.headers.Keys; } } /// <summary> /// Limit the number of times the message can be forwarded through proxies or gateways. /// </summary> /// <value>The number of the maximum allowed number of forwards if it is available; otherwise 0.</value> public int MaxForwards { get { return this.GetValue("Max-Forwards", x => Convert.ToInt32(x.First()), 0); } set { this.SetHeaderValues("Max-Forwards", value, x => new[] { x.ToString(CultureInfo.InvariantCulture) }); } } /// <summary> /// This is the address of the previous web page from which a link to the currently requested page was followed. /// </summary> /// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value> public string Referrer { get { return this.GetValue("Referer", x => x.First(), string.Empty); } set { this.SetHeaderValues("Referer", value, x => new[] { x }); } } /// <summary> /// The user agent string of the user agent /// </summary> /// <value>A <see cref="string"/> containing the header value if it is available; otherwise <see cref="string.Empty"/>.</value> public string UserAgent { get { return this.GetValue("User-Agent", x => x.First(), string.Empty); } set { this.SetHeaderValues("User-Agent", value, x => new[] { x }); } } /// <summary> /// Gets all the header values. /// </summary> /// <value>An <see cref="IEnumerable{T}"/> that contains all the header values.</value> public IEnumerable<IEnumerable<string>> Values { get { return this.headers.Values; } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns>A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.</returns> public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator() { return this.headers.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Gets the values for the header identified by the <paramref name="name"/> parameter. /// </summary> /// <param name="name">The name of the header to return the values for.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains the values for the header. If the header is not defined then <see cref="Enumerable.Empty{TResult}"/> is returned.</returns> public IEnumerable<string> this[string name] { get { return (this.headers.ContainsKey(name)) ? this.headers[name] : Enumerable.Empty<string>(); } } private static string GetDateAsString(DateTime? value) { return !value.HasValue ? null : value.Value.ToString("R", CultureInfo.InvariantCulture); } private IEnumerable<string> GetSplitValues(string header) { var values = this.GetValue(header); return values .SelectMany(x => x.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) .Select(x => x.Trim()) .ToList(); } private IEnumerable<Tuple<string, decimal>> GetWeightedValues(string headerName) { return this.cache.GetOrAdd(headerName, r => { var values = this.GetValue(r); var result = new List<Tuple<string, decimal>>(); foreach (var header in values) { var buffer = string.Empty; var name = string.Empty; var quality = string.Empty; var isReadingQuality = false; var isInQuotedSection = false; for (var index = 0; index < header.Length; index++) { var character = header[index]; if (character.Equals(' ') && (index != header.Length - 1) && !isInQuotedSection) { continue; } if (character.Equals('"')) { isInQuotedSection = !isInQuotedSection; } if (isInQuotedSection) { buffer += character; if (index != header.Length - 1) { continue; ; } } if (character.Equals(';') || character.Equals(',') || (index == header.Length - 1)) { if (!(character.Equals(';') || character.Equals(','))) { buffer += character; } if (isReadingQuality) { quality = buffer; } else { if (name.Length > 0) { name += ';'; } name += buffer; } buffer = string.Empty; isReadingQuality = false; isInQuotedSection = false; } if (character.Equals(';')) { continue; } if ((character.Equals('q') || character.Equals('Q')) && (index != header.Length - 1)) { if (header[index + 1].Equals('=')) { isReadingQuality = true; continue; } } if (isReadingQuality && character.Equals('=')) { continue; } if (character.Equals(',') || (index == header.Length - 1)) { var actualQuality = 1m; decimal temp; if (decimal.TryParse(quality, NumberStyles.Number, CultureInfo.InvariantCulture, out temp)) { actualQuality = temp; } result.Add(new Tuple<string, decimal>(name, actualQuality)); name = string.Empty; quality = string.Empty; buffer = string.Empty; isReadingQuality = false; continue; } buffer += character; } } return result.OrderByDescending(x => x.Item2); }); } private static IEnumerable<INancyCookie> GetNancyCookies(IEnumerable<string> cookies) { if (cookies == null) { yield break; } foreach (var cookie in cookies) { var cookieStrings = cookie.Split(';'); foreach (var cookieString in cookieStrings) { var equalPos = cookieString.IndexOf('='); if (equalPos >= 0) { yield return new NancyCookie(cookieString.Substring(0, equalPos).TrimStart(), cookieString.Substring(equalPos+1).TrimEnd()); } } } } private IEnumerable<string> GetValue(string name) { return this.GetValue(name, x => x, new string[] {}); } private T GetValue<T>(string name, Func<IEnumerable<string>, T> converter, T defaultValue) { IEnumerable<string> values; if (!this.headers.TryGetValue(name, out values)) { return defaultValue; } return converter.Invoke(values); } private static IEnumerable<string> GetWeightedValuesAsStrings(IEnumerable<Tuple<string, decimal>> values) { return values.Select(x => string.Concat(x.Item1, ";q=", x.Item2.ToString(CultureInfo.InvariantCulture))); } private static DateTime? ParseDateTime(string value) { DateTime result; // note CultureInfo.InvariantCulture is ignored if (DateTime.TryParseExact(value, "R", CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) { return result; } return null; } private void SetHeaderValues<T>(string header, T value, Func<T, IEnumerable<string>> valueTransformer) { this.InvalidateCacheEntry(header); if (EqualityComparer<T>.Default.Equals(value, default(T))) { if (this.headers.ContainsKey(header)) { this.headers.Remove(header); } } else { this.headers[header] = valueTransformer.Invoke(value); } } private void InvalidateCacheEntry(string header) { IEnumerable<Tuple<string, decimal>> values; this.cache.TryRemove(header, out values); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using IdentityServer.UnitTests.Common; using IdentityServer4.Configuration; using IdentityServer4.Models; using IdentityServer4.ResponseHandling; using IdentityServer4.Services; using IdentityServer4.Services.Default; using IdentityServer4.Stores; using IdentityServer4.Validation; using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace IdentityServer.UnitTests.ResponseHandling { public class DeviceAuthorizationResponseGeneratorTests { private readonly List<IdentityResource> identityResources = new List<IdentityResource> {new IdentityResources.OpenId(), new IdentityResources.Profile()}; private readonly List<ApiResource> apiResources = new List<ApiResource> {new ApiResource("resource") {Scopes = new List<Scope> {new Scope("api1")}}}; private readonly FakeUserCodeGenerator fakeUserCodeGenerator = new FakeUserCodeGenerator(); private readonly IDeviceFlowCodeService deviceFlowCodeService = new DefaultDeviceFlowCodeService(new InMemoryDeviceFlowStore(), new StubHandleGenerationService()); private readonly IdentityServerOptions options = new IdentityServerOptions(); private readonly StubClock clock = new StubClock(); private readonly DeviceAuthorizationResponseGenerator generator; private readonly DeviceAuthorizationRequestValidationResult testResult; private const string TestBaseUrl = "http://localhost:5000/"; public DeviceAuthorizationResponseGeneratorTests() { var resourceStore = new InMemoryResourcesStore(identityResources, apiResources); var scopeValidator = new ScopeValidator(resourceStore, new NullLogger<ScopeValidator>()); testResult = new DeviceAuthorizationRequestValidationResult(new ValidatedDeviceAuthorizationRequest { Client = new Client {ClientId = Guid.NewGuid().ToString()}, IsOpenIdRequest = true, ValidatedScopes = scopeValidator }); generator = new DeviceAuthorizationResponseGenerator( options, new DefaultUserCodeService(new IUserCodeGenerator[] {new NumericUserCodeGenerator(), fakeUserCodeGenerator }), deviceFlowCodeService, clock, new NullLogger<DeviceAuthorizationResponseGenerator>()); } [Fact] public void ProcessAsync_when_valiationresult_null_exect_exception() { Func<Task> act = () => generator.ProcessAsync(null, TestBaseUrl); act.Should().Throw<ArgumentNullException>(); } [Fact] public void ProcessAsync_when_valiationresult_client_null_exect_exception() { var validationResult = new DeviceAuthorizationRequestValidationResult(new ValidatedDeviceAuthorizationRequest()); Func <Task> act = () => generator.ProcessAsync(validationResult, TestBaseUrl); act.Should().Throw<ArgumentNullException>(); } [Fact] public void ProcessAsync_when_baseurl_null_exect_exception() { Func<Task> act = () => generator.ProcessAsync(testResult, null); act.Should().Throw<ArgumentException>(); } [Fact] public async Task ProcessAsync_when_user_code_collision_expect_retry() { var creationTime = DateTime.UtcNow; clock.UtcNowFunc = () => creationTime; testResult.ValidatedRequest.Client.UserCodeType = FakeUserCodeGenerator.UserCodeTypeValue; await deviceFlowCodeService.StoreDeviceAuthorizationAsync(FakeUserCodeGenerator.TestCollisionUserCode, new DeviceCode()); var response = await generator.ProcessAsync(testResult, TestBaseUrl); response.UserCode.Should().Be(FakeUserCodeGenerator.TestUniqueUserCode); } [Fact] public async Task ProcessAsync_when_user_code_collision_retry_limit_reached_expect_error() { var creationTime = DateTime.UtcNow; clock.UtcNowFunc = () => creationTime; fakeUserCodeGenerator.RetryLimit = 1; testResult.ValidatedRequest.Client.UserCodeType = FakeUserCodeGenerator.UserCodeTypeValue; await deviceFlowCodeService.StoreDeviceAuthorizationAsync(FakeUserCodeGenerator.TestCollisionUserCode, new DeviceCode()); await Assert.ThrowsAsync<InvalidOperationException>(() => generator.ProcessAsync(testResult, TestBaseUrl)); } [Fact] public async Task ProcessAsync_when_generated_expect_user_code_stored() { var creationTime = DateTime.UtcNow; clock.UtcNowFunc = () => creationTime; testResult.ValidatedRequest.RequestedScopes = new List<string> { "openid", "resource" }; var response = await generator.ProcessAsync(testResult, TestBaseUrl); response.UserCode.Should().NotBeNullOrWhiteSpace(); var userCode = await deviceFlowCodeService.FindByUserCodeAsync(response.UserCode); userCode.Should().NotBeNull(); userCode.ClientId.Should().Be(testResult.ValidatedRequest.Client.ClientId); userCode.Lifetime.Should().Be(testResult.ValidatedRequest.Client.DeviceCodeLifetime); userCode.CreationTime.Should().Be(creationTime); userCode.Subject.Should().BeNull(); userCode.AuthorizedScopes.Should().BeNull(); userCode.RequestedScopes.Should().Contain(testResult.ValidatedRequest.RequestedScopes); } [Fact] public async Task ProcessAsync_when_generated_expect_device_code_stored() { var creationTime = DateTime.UtcNow; clock.UtcNowFunc = () => creationTime; var response = await generator.ProcessAsync(testResult, TestBaseUrl); response.DeviceCode.Should().NotBeNullOrWhiteSpace(); response.Interval.Should().Be(options.DeviceFlow.Interval); var deviceCode = await deviceFlowCodeService.FindByDeviceCodeAsync(response.DeviceCode); deviceCode.Should().NotBeNull(); deviceCode.ClientId.Should().Be(testResult.ValidatedRequest.Client.ClientId); deviceCode.IsOpenId.Should().Be(testResult.ValidatedRequest.IsOpenIdRequest); deviceCode.Lifetime.Should().Be(testResult.ValidatedRequest.Client.DeviceCodeLifetime); deviceCode.CreationTime.Should().Be(creationTime); deviceCode.Subject.Should().BeNull(); deviceCode.AuthorizedScopes.Should().BeNull(); response.DeviceCodeLifetime.Should().Be(deviceCode.Lifetime); } [Fact] public async Task ProcessAsync_when_DeviceVerificationUrl_is_relative_uri_expect_correct_VerificationUris() { const string baseUrl = "http://localhost:5000/"; options.UserInteraction.DeviceVerificationUrl = "/device"; options.UserInteraction.DeviceVerificationUserCodeParameter = "userCode"; var response = await generator.ProcessAsync(testResult, baseUrl); response.VerificationUri.Should().Be("http://localhost:5000/device"); response.VerificationUriComplete.Should().StartWith("http://localhost:5000/device?userCode="); } [Fact] public async Task ProcessAsync_when_DeviceVerificationUrl_is_absolute_uri_expect_correct_VerificationUris() { const string baseUrl = "http://localhost:5000/"; options.UserInteraction.DeviceVerificationUrl = "http://short/device"; options.UserInteraction.DeviceVerificationUserCodeParameter = "userCode"; var response = await generator.ProcessAsync(testResult, baseUrl); response.VerificationUri.Should().Be("http://short/device"); response.VerificationUriComplete.Should().StartWith("http://short/device?userCode="); } } internal class FakeUserCodeGenerator : IUserCodeGenerator { public const string UserCodeTypeValue = "Collider"; public const string TestUniqueUserCode = "123"; public const string TestCollisionUserCode = "321"; private int tryCount = 0; private int retryLimit = 2; public string UserCodeType => UserCodeTypeValue; public int RetryLimit { get => retryLimit; set => retryLimit = value; } public Task<string> GenerateAsync() { if (tryCount == 0) { tryCount++; return Task.FromResult(TestCollisionUserCode); } tryCount++; return Task.FromResult(TestUniqueUserCode); } } }
// Copyright (c) 2010-2013 SharpDoc - 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.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using SharpDoc.Logging; using SharpDoc.Model; using SharpRazor; namespace SharpDoc { /// <summary> /// Template context used by all templates. /// </summary> public class TemplateContext { private const string StyleDirectory = "Styles"; private List<TagExpandItem> _regexItems; private MsdnRegistry _msnRegistry; private bool assembliesProcessed; private bool topicsProcessed; /// <summary> /// Initializes a new instance of the <see cref="TemplateContext"/> class. /// </summary> public TemplateContext(Razorizer razorizer) { this.Razorizer = razorizer; StyleDirectories = new List<string>(); _regexItems = new List<TagExpandItem>(); _msnRegistry = new MsdnRegistry(); Param = new DynamicParam(); Style = new DynamicParam(); Indents = new Stack<int>(); razorizer.TemplateResolver += TemplateResolver; } /// <summary> /// Finds a <see cref="IModelReference"/> from an id. /// </summary> /// <param name="id">The id.</param> /// <returns> /// A registered reference or null if it's an external or invalid reference /// </returns> private IModelReference FindLocalReference(string id) { return Registry.FindById(id); } public Razorizer Razorizer { get; private set; } /// <summary> /// Gets the param dynamic properties. /// </summary> /// <value>The param dynamic properties.</value> public dynamic Param { get; private set; } /// <summary> /// Gets the style dynamic properties. /// </summary> /// <value>The style dynamic properties.</value> public dynamic Style { get; private set; } /// <summary> /// Gets or sets the style manager. /// </summary> /// <value>The style manager.</value> public StyleManager StyleManager { get; set; } /// <summary> /// Gets or sets the registry. /// </summary> /// <value>The registry.</value> public MemberRegistry Registry { get; set; } /// <summary> /// Gets or sets the topics. /// </summary> /// <value>The topics.</value> public NTopic RootTopic { get; set; } /// <summary> /// Gets or sets the search topic. /// </summary> /// <value>The search topic.</value> public NTopic SearchTopic { get; set;} /// <summary> /// Gets or sets the class library topic. /// </summary> /// <value> /// The class library topic. /// </value> public NTopic ClassLibraryTopic { get; set; } /// <summary> /// Gets or sets the assemblies. /// </summary> /// <value>The assemblies.</value> public List<NNamespace> Namespaces { get; set; } /// <summary> /// Gets or sets the current topic. /// </summary> /// <value>The current topic.</value> public NTopic Topic { get; set; } /// <summary> /// Gets or sets the current assembly being processed. /// </summary> /// <value>The current assembly being processed.</value> public NAssembly Assembly { get; set; } /// <summary> /// Gets or sets the current namespace being processed. /// </summary> /// <value>The current namespace being processed.</value> public NNamespace Namespace { get; set; } /// <summary> /// Gets or sets the current type being processed. /// </summary> /// <value>The current type being processed.</value> public NType Type { get; set; } /// <summary> /// Gets or sets the current member being processed. /// </summary> /// <value>The current member.</value> public NMember Member { get; set; } /// <summary> /// Gets or sets the style directories. /// </summary> /// <value>The style directories.</value> private List<string> StyleDirectories {get; set;} /// <summary> /// Gets or sets the output directory. /// </summary> /// <value>The output directory.</value> public string OutputDirectory { get; set; } /// <summary> /// Gets or sets the link resolver. /// </summary> /// <value>The link resolver.</value> public Func<LinkDescriptor, string> LinkResolver { get; set; } /// <summary> /// Gets or sets the page id function. /// </summary> /// <value> /// The page id function. /// </value> public Func<IModelReference, string> PageIdFunction { get; set; } /// <summary> /// Gets or sets the write to function. /// </summary> /// <value> /// The write to function. /// </value> public Action<IModelReference, string> WriteTo { get; set; } /// <summary> /// Gets or sets the index file. /// </summary> /// <value> /// The index file. /// </value> public TextWriter IndexFile { get; set; } /// <summary> /// Gets or sets the function that get the content of a page of the extern documentation site. /// </summary> /// <value> /// The function that get the content of a page of the extern documentation site. /// </value> public Func<XmlNode, bool, string> GetWebDocContent { get; set; } public Action<IModelReference> BuildTopic { get; set; } /// <summary> /// Gets or sets the web documentation. /// </summary> /// <value>The web documentation.</value> public WebDocumentation WebDocumentation { get; set; } /// <summary> /// Gets or sets the name of the current style. /// </summary> /// <value> /// The name of the current style. /// </value> public string CurrentStyleName { get; set; } /// <summary> /// Gets or sets the config. /// </summary> /// <value> /// The config. /// </value> public Config Config { get; set; } public Stack<int> Indents { get; private set; } private ModelProcessor modelProcessor; private TopicBuilder topicBuilder; /// <summary> /// Initializes this instance. /// </summary> public void Initialize() { Config.FilePath = Config.FilePath ?? Path.Combine(Environment.CurrentDirectory, "unknown.xml"); OutputDirectory = Config.AbsoluteOutputDirectory; // Set title Param.Title = Config.Title; // Add parameters if (Config.Parameters.Count > 0) { var dictionary = (DynamicParam)Param; foreach (var configParam in Config.Parameters) { dictionary.Properties.Remove(configParam.Name); dictionary.Properties.Add(configParam.Name, configParam.value); } } // Add styles if (Config.StyleParameters.Count > 0) { var dictionary = (IDictionary<string, object>)Style; foreach (var configParam in Config.StyleParameters) { dictionary.Remove(configParam.Name); dictionary.Add(configParam.Name, configParam.value); } } } /// <summary> /// Processes the assemblies. /// </summary> public void ProcessAssemblies() { if (!assembliesProcessed) { // Process the assemblies modelProcessor = new ModelProcessor { AssemblyManager = new MonoCecilAssemblyManager(), ModelBuilder = new MonoCecilModelBuilder(), PageIdFunction = PageIdFunction }; modelProcessor.Run(Config); if (Logger.HasErrors) Logger.Fatal("Too many errors in config file. Check previous message."); Namespaces = new List<NNamespace>(modelProcessor.Namespaces); Registry = modelProcessor.Registry; assembliesProcessed = true; } } /// <summary> /// Processes the topics. /// </summary> public void ProcessTopics() { if (!topicsProcessed) { // Build the topics topicBuilder = new TopicBuilder() { Namespaces = modelProcessor.Namespaces, Registry = modelProcessor.Registry }; topicBuilder.Run(Config, PageIdFunction, BuildTopic); if (Logger.HasErrors) Logger.Fatal("Too many errors in config file. Check previous message."); RootTopic = topicBuilder.RootTopic; SearchTopic = topicBuilder.SearchTopic; ClassLibraryTopic = topicBuilder.ClassLibraryTopic; topicsProcessed = true; } } /// <summary> /// Finds the topic by id. /// </summary> /// <param name="topicId">The topic id.</param> /// <returns></returns> public NTopic FindTopicById(string topicId) { if (RootTopic == null) return null; return RootTopic.FindTopicById(topicId); } /// <summary> /// Gets the current context. /// </summary> /// <value>The current context.</value> public IModelReference CurrentContext { get { if (Type != null) return Type; if (Namespace != null) return Namespace; if (Assembly != null) return Assembly; if (Topic != null) return Topic; return null; } } /// <summary> /// Resolve a local element Id (i.e. "T:System.Object") to a URL. /// </summary> /// <param name="reference">The reference.</param> /// <param name="linkName">Name of the link.</param> /// <param name="forceLocal">if set to <c>true</c> [force local].</param> /// <param name="attributes">The attributes.</param> /// <param name="useSelf">if set to <c>true</c> [use self when possible].</param> /// <returns></returns> public string ToUrl(IModelReference reference, string linkName = null, bool forceLocal = false, string attributes = null, bool useSelf = true) { return ToUrl(reference.Id, linkName, forceLocal, attributes, reference, useSelf); } /// <summary> /// Resolve a document Id (i.e. "T:System.Object") to an URL. /// </summary> /// <param name="id">The id.</param> /// <param name="linkName">Name of the link.</param> /// <param name="forceLocal">if set to <c>true</c> [force local].</param> /// <param name="attributes">The attributes.</param> /// <param name="localReference">The local reference.</param> /// <param name="useSelf"></param> /// <returns></returns> public string ToUrl(string id, string linkName = null, bool forceLocal = false, string attributes = null, IModelReference localReference = null, bool useSelf = true) { if (string.IsNullOrWhiteSpace(id)) return "#"; id = id.Trim(); if (id.StartsWith("!:")) id = id.Substring(2); if (id.Length == 0 || id == "#") return linkName ?? id; var linkDescriptor = new LinkDescriptor { Type = LinkType.None, Index = -1 }; var typeReference = localReference as INTypeReference; INTypeReference genericInstance = null; bool isGenericInstance = typeReference != null && typeReference.IsGenericInstance; bool isGenericParameter = typeReference != null && typeReference.IsGenericParameter; if (isGenericInstance) { var elementType = typeReference.ElementType; id = elementType.Id; genericInstance = typeReference; linkName = elementType.Name.Substring(0, elementType.Name.IndexOf('<')); } // Starting with a #? It's a self link if (id.StartsWith("#")) id = CurrentContext.Id + id; string anchor = null; linkDescriptor.LocalReference = FindLocalReference(id); if (linkDescriptor.LocalReference == null) { // Try to query again with the part before # (for anchor support) var indexSharp = id.IndexOf('#'); if (indexSharp != -1) { var idBeforeSharp = id.Substring(0, indexSharp); linkDescriptor.LocalReference = FindLocalReference(idBeforeSharp); if (linkDescriptor.LocalReference != null) { // If it's a match, use it for resolution anchor = id.Substring(indexSharp); id = idBeforeSharp; } } } if (isGenericParameter) { linkDescriptor.Name = typeReference.Name; } else if (linkDescriptor.LocalReference != null) { // For local references, use short name var method = linkDescriptor.LocalReference as NMethod; if (method != null) linkDescriptor.Name = method.Signature; else linkDescriptor.Name = linkDescriptor.LocalReference.Name; linkDescriptor.PageId = linkDescriptor.LocalReference.PageId; linkDescriptor.Type = LinkType.Local; linkDescriptor.Index = linkDescriptor.LocalReference.Index; if (!forceLocal && CurrentContext != null && linkDescriptor.LocalReference is NMember) { var declaringType = ((NMember) linkDescriptor.LocalReference).DeclaringType; // If link is self referencing the current context, then use a self link if ((id == CurrentContext.Id || (declaringType != null && declaringType.Id == CurrentContext.Id && (!id.StartsWith("T:") && !declaringType.Id.StartsWith("T:")))) && useSelf) { linkDescriptor.Type = LinkType.Self; } } } else { linkDescriptor.Type = LinkType.External; if (id.StartsWith("http:") || id.StartsWith("https:")) { linkDescriptor.Location = id; } else { // Try to resolve to MSDN linkDescriptor.Location = _msnRegistry.FindUrl(id); var reference = TextReferenceUtility.CreateReference(id); if (linkDescriptor.Location != null) { linkDescriptor.Name = reference.FullName; // Open MSDN documentation to a new window attributes = (attributes ?? "") + " target='_blank'"; } else { linkDescriptor.Name = reference.Name; } } } if (LinkResolver == null) { Logger.Warning("Model.LinkResolver must be set"); return id; } if (linkName != null) linkDescriptor.Name = linkName; linkDescriptor.Id = id; linkDescriptor.Attributes = attributes; linkDescriptor.Anchor = anchor; var urlBuilder = new StringBuilder(); urlBuilder.Append(LinkResolver(linkDescriptor)); // Handle URL for generic instance if (genericInstance != null) { urlBuilder.Append("&lt;"); for (int i = 0; i < genericInstance.GenericArguments.Count; i++) { if (i > 0) urlBuilder.Append(", "); var genericArgument = genericInstance.GenericArguments[i]; // Recursive call here urlBuilder.Append(ToUrl(genericArgument)); } urlBuilder.Append("&gt;"); } return urlBuilder.ToString(); } /// <summary> /// Uses the style. /// </summary> /// <param name="styleName">Name of the style.</param> /// <returns></returns> internal void UseStyle(string styleName) { if (!StyleManager.StyleExist(styleName)) Logger.Fatal("Cannot us style [{0}]. Style doesn't exist", styleName); CurrentStyleName = styleName; StyleDirectories.Clear(); var includeBaseStyle = new List<string>(); var styles = StyleManager.AvailableStyles; includeBaseStyle.Add(styleName); bool isNotComplete = true; // Compute directories to look, by following // In the same order they are declared while (isNotComplete) { isNotComplete = false; // Build directories to look for this specific style and all its base style); var toRemove = new List<StyleDefinition>(); foreach (var style in styles) { // Apply parameter inherited from style if (style.Name == styleName) { foreach (var parameter in style.Parameters) { ((DynamicParam)Param).Properties.Remove(parameter.Name); ((DynamicParam)Param).Properties.Add(parameter.Name, parameter.value); } } if (includeBaseStyle.Contains(style.Name)) { toRemove.Add(style); StyleDirectories.Add(style.DirectoryPath); isNotComplete = true; if (style.HasBaseStyle) includeBaseStyle.Add(style.BaseStyle); } } // Remove the style that was processed by the previous loop foreach (var styleDefinition in toRemove) styles.Remove(styleDefinition); } foreach (var styleDirectory in StyleDirectories) { Logger.Message("Using Style Directory [{0}]", styleDirectory); } } /// <summary> /// Resolves a path from template directories. /// </summary> /// <param name="path">The path.</param> /// <returns>The path to the file or directory</returns> public string ResolvePath(string path) { for (int i = 0; i < StyleDirectories.Count; i++) { string filePath = Path.Combine(StyleDirectories[i], path); if (File.Exists(filePath)) return filePath; } return null; } /// <summary> /// Resolves and load a file from template directories. /// </summary> /// <param name="file">The file.</param> /// <returns>The content of the file</returns> public string Loadfile(string file) { string filePath = ResolvePath(file); if (filePath == null) { Logger.Fatal("Cannot find file [{0}] from the following Template Directories [{1}]", file, string.Join(",", StyleDirectories)); // Fatal is stopping the process return ""; } return File.ReadAllText(filePath); } /// <summary> /// Gets the template. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public string GetTemplate(string name, out string location) { location = ResolvePath(name + ".cshtml"); if (location == null) location = ResolvePath(Path.Combine("html", name + ".cshtml")); if (location == null) { Logger.Fatal("Cannot find template [{0}] from the following Template Directories [{1}]", name, string.Join(",", StyleDirectories)); // Fatal is stopping the process return ""; } return File.ReadAllText(location); } /// <summary> /// Copies the content of the directory from all template directories. /// using inheritance directory. /// </summary> /// <param name="directoryName">Name of the directory.</param> public void CopyStyleContent(string directoryName) { for (int i = StyleDirectories.Count - 1; i >=0; i--) { var templateDirectory = StyleDirectories[i]; string filePath = Path.Combine(templateDirectory, directoryName); if (Directory.Exists(filePath)) { CopyDirectory(filePath, OutputDirectory, true); } } } /// <summary> /// Copies the content of a local directory to the destination html directory. /// </summary> /// <param name="directoryNameOrFile">Name of the source directory.</param> /// <param name="toDirectory">Name of the destination directory.</param> public void CopyLocalContent(string directoryNameOrFile, string toDirectory) { var fileOrDir = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Config.FilePath), directoryNameOrFile)); var absoulteDirectory = Path.Combine(Config.AbsoluteOutputDirectory, toDirectory); if (File.Exists(fileOrDir)) { Logger.Message("Copying file from [{0}] to [{1}]", directoryNameOrFile, toDirectory); File.Copy(fileOrDir, absoulteDirectory, true); } else { CopyDirectory(fileOrDir, absoulteDirectory, true); } } public void CopyDirectory(string from, string to, bool includeFromDir = false) { // string source, destination; - folder paths int basePathIndex = (includeFromDir ? from.Trim('/','\\').LastIndexOf('\\') : from.Length) + 1; foreach (string filePath in Directory.GetFiles(from, "*.*", SearchOption.AllDirectories)) { string subPath = filePath.Substring(basePathIndex); string newpath = Path.Combine(to, subPath); string dirPath = Path.GetDirectoryName(newpath); if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); Logger.Message("Copying file from [{0}] to [{1}]", subPath, newpath); File.Copy(filePath, newpath, true); } } // private List<> private class TagExpandItem { public TagExpandItem(Regex expression, string replaceString, bool isOnlyForHtmlContent) { Expression = expression; ReplaceString = replaceString; IsOnlyForHtmlContent = isOnlyForHtmlContent; } public TagExpandItem(Regex expression, MatchEvaluator replaceEvaluator, bool isOnlyForHtmlContent) { Expression = expression; ReplaceEvaluator = replaceEvaluator; IsOnlyForHtmlContent = isOnlyForHtmlContent; } public readonly bool IsOnlyForHtmlContent; Regex Expression; string ReplaceString; MatchEvaluator ReplaceEvaluator; public string Replace(string content) { if (content == null) return null; if (ReplaceString != null) return Expression.Replace(content, ReplaceString); return Expression.Replace(content, ReplaceEvaluator); } } /// <summary> /// Add regular expression for TagExpand function. /// </summary> /// <param name="regexp">The regexp.</param> /// <param name="substitution">The substitution.</param> /// <param name="isOnlyForHtmlContent">if set to <c>true</c> [is only for HTML content].</param> public void RegisterTagResolver(string regexp, string substitution, bool isOnlyForHtmlContent = false) { _regexItems.Add(new TagExpandItem(new Regex(regexp, RegexOptions.Singleline), substitution, isOnlyForHtmlContent)); } /// <summary> /// Add regular expression for RegexExpand function. /// </summary> /// <param name="regexp">The regexp.</param> /// <param name="evaluator">The evaluator.</param> /// <param name="isOnlyForHtmlContent">if set to <c>true</c> [is only for HTML content].</param> public void RegisterTagResolver(string regexp, MatchEvaluator evaluator, bool isOnlyForHtmlContent = false) { _regexItems.Add(new TagExpandItem(new Regex(regexp, RegexOptions.Singleline), evaluator, isOnlyForHtmlContent)); } /// <summary> /// Perform regular expression expansion. /// </summary> /// <param name="content">The content to replace.</param> /// <param name="isOnlyForHtmlContent">if set to <c>true</c> [is only for HTML content].</param> /// <returns>The content replaced</returns> public string TagExpand(string content, bool isOnlyForHtmlContent = false) { foreach (var regexItem in _regexItems) { //if (regexItem.IsOnlyForHtmlContent == isOnlyForHtmlContent) { content = regexItem.Replace(content); } } return content; } /// <summary> /// Parses the specified template name. /// </summary> /// <param name="templateName">Name of the template.</param> /// <returns></returns> public string Parse(string templateName) { string location = null; try { var template = Razorizer.FindTemplate(templateName); template.Model = this; return template.Run(); } catch (TemplateCompilationException ex) { foreach (var compilerError in ex.Errors) { Logger.PushLocation(location, compilerError.Line, compilerError.Column); if (compilerError.IsWarning) { Logger.Warning("{0}: {1}", compilerError.ErrorNumber, compilerError.ErrorText); } else { Logger.Error("{0}: {1}", compilerError.ErrorNumber, compilerError.ErrorText); } Logger.PopLocation(); } Logger.PopLocation(); Logger.Fatal("Error when compiling template [{0}]", templateName); } catch (TemplateParsingException ex) { foreach (var parserError in ex.Errors) { Logger.PushLocation(ex.Location, parserError.Location.LineIndex, parserError.Location.CharacterIndex); Logger.Error("{0}: {1}", "R0000", parserError.Message); Logger.PopLocation(); } Logger.PopLocation(); Logger.Fatal("Error when compiling template [{0}]", templateName); } catch (Exception ex) { Logger.PushLocation(location); Logger.Error("Unexpected exception", ex); Logger.PopLocation(); throw; } return ""; } private PageTemplate TemplateResolver(string templateName) { string location = null; string templateContent = GetTemplate(templateName, out location); var template = Razorizer.Compile(templateName, templateContent, location); template.Model = this; return template; } public void debug() {var i = 1;} public void debug2() {var i = 2;} } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Security.Cryptography; using DiscUtils.Streams; namespace DiscUtils.Xva { #if NETCORE internal class HashStreamCore : Stream { private readonly IncrementalHash _hashAlg; private readonly Ownership _ownWrapped; private long _hashPos; private Stream _wrapped; public HashStreamCore(Stream wrapped, Ownership ownsWrapped, IncrementalHash hashAlg) { _wrapped = wrapped; _ownWrapped = ownsWrapped; _hashAlg = hashAlg; } public override bool CanRead { get { return _wrapped.CanRead; } } public override bool CanSeek { get { return _wrapped.CanSeek; } } public override bool CanWrite { get { return _wrapped.CanWrite; } } public override long Length { get { return _wrapped.Length; } } public override long Position { get { return _wrapped.Position; } set { _wrapped.Position = value; } } public override void Flush() { _wrapped.Flush(); } public override int Read(byte[] buffer, int offset, int count) { if (Position != _hashPos) { throw new InvalidOperationException("Reads must be contiguous"); } int numRead = _wrapped.Read(buffer, offset, count); _hashAlg.AppendData(buffer, offset, numRead); _hashPos += numRead; return numRead; } public override long Seek(long offset, SeekOrigin origin) { return _wrapped.Seek(offset, origin); } public override void SetLength(long value) { _wrapped.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { _wrapped.Write(buffer, offset, count); } protected override void Dispose(bool disposing) { try { if (disposing && _ownWrapped == Ownership.Dispose && _wrapped != null) { _wrapped.Dispose(); _wrapped = null; } } finally { base.Dispose(disposing); } } } #else internal class HashStreamDotnet : Stream { private Stream _wrapped; private Ownership _ownWrapped; private HashAlgorithm _hashAlg; private long _hashPos; public HashStreamDotnet(Stream wrapped, Ownership ownsWrapped, HashAlgorithm hashAlg) { _wrapped = wrapped; _ownWrapped = ownsWrapped; _hashAlg = hashAlg; } public override bool CanRead { get { return _wrapped.CanRead; } } public override bool CanSeek { get { return _wrapped.CanSeek; } } public override bool CanWrite { get { return _wrapped.CanWrite; } } public override long Length { get { return _wrapped.Length; } } public override long Position { get { return _wrapped.Position; } set { _wrapped.Position = value; } } public override void Flush() { _wrapped.Flush(); } public override int Read(byte[] buffer, int offset, int count) { if (Position != _hashPos) { throw new InvalidOperationException("Reads must be contiguous"); } int numRead = _wrapped.Read(buffer, offset, count); _hashAlg.TransformBlock(buffer, offset, numRead, buffer, offset); _hashPos += numRead; return numRead; } public override long Seek(long offset, SeekOrigin origin) { return _wrapped.Seek(offset, origin); } public override void SetLength(long value) { _wrapped.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { _wrapped.Write(buffer, offset, count); } protected override void Dispose(bool disposing) { try { if (disposing && _ownWrapped == Ownership.Dispose && _wrapped != null) { _wrapped.Dispose(); _wrapped = null; } } finally { base.Dispose(disposing); } } } #endif }
namespace java.net { [global::MonoJavaBridge.JavaClass(typeof(global::java.net.URLConnection_))] public abstract partial class URLConnection : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected URLConnection(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.net.URLConnection.staticClass, "toString", "()Ljava/lang/String;", ref global::java.net.URLConnection._m0) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m1; public virtual global::java.net.URL getURL() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.net.URL>(this, global::java.net.URLConnection.staticClass, "getURL", "()Ljava/net/URL;", ref global::java.net.URLConnection._m1) as java.net.URL; } private static global::MonoJavaBridge.MethodId _m2; public virtual global::java.lang.Object getContent(java.lang.Class[] arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.URLConnection.staticClass, "getContent", "([Ljava/lang/Class;)Ljava/lang/Object;", ref global::java.net.URLConnection._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m3; public virtual global::java.lang.Object getContent() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.URLConnection.staticClass, "getContent", "()Ljava/lang/Object;", ref global::java.net.URLConnection._m3) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m4; public virtual global::java.io.InputStream getInputStream() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.URLConnection.staticClass, "getInputStream", "()Ljava/io/InputStream;", ref global::java.net.URLConnection._m4) as java.io.InputStream; } private static global::MonoJavaBridge.MethodId _m5; public virtual global::java.security.Permission getPermission() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.URLConnection.staticClass, "getPermission", "()Ljava/security/Permission;", ref global::java.net.URLConnection._m5) as java.security.Permission; } private static global::MonoJavaBridge.MethodId _m6; public abstract void connect(); private static global::MonoJavaBridge.MethodId _m7; public virtual void setRequestProperty(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V", ref global::java.net.URLConnection._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m8; public virtual long getDate() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.net.URLConnection.staticClass, "getDate", "()J", ref global::java.net.URLConnection._m8); } private static global::MonoJavaBridge.MethodId _m9; public virtual global::java.lang.String getContentType() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.net.URLConnection.staticClass, "getContentType", "()Ljava/lang/String;", ref global::java.net.URLConnection._m9) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m10; public virtual int getContentLength() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.URLConnection.staticClass, "getContentLength", "()I", ref global::java.net.URLConnection._m10); } private static global::MonoJavaBridge.MethodId _m11; public virtual global::java.lang.String getHeaderField(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.net.URLConnection.staticClass, "getHeaderField", "(Ljava/lang/String;)Ljava/lang/String;", ref global::java.net.URLConnection._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m12; public virtual global::java.lang.String getHeaderField(int arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.net.URLConnection.staticClass, "getHeaderField", "(I)Ljava/lang/String;", ref global::java.net.URLConnection._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m13; public virtual global::java.lang.String getHeaderFieldKey(int arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.net.URLConnection.staticClass, "getHeaderFieldKey", "(I)Ljava/lang/String;", ref global::java.net.URLConnection._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m14; public virtual long getLastModified() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.net.URLConnection.staticClass, "getLastModified", "()J", ref global::java.net.URLConnection._m14); } private static global::MonoJavaBridge.MethodId _m15; public static global::java.net.FileNameMap getFileNameMap() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m15.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m15 = @__env.GetStaticMethodIDNoThrow(global::java.net.URLConnection.staticClass, "getFileNameMap", "()Ljava/net/FileNameMap;"); return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.net.FileNameMap>(@__env.CallStaticObjectMethod(java.net.URLConnection.staticClass, global::java.net.URLConnection._m15)) as java.net.FileNameMap; } private static global::MonoJavaBridge.MethodId _m16; public virtual void addRequestProperty(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "addRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V", ref global::java.net.URLConnection._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m17; public virtual global::java.lang.String getRequestProperty(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.net.URLConnection.staticClass, "getRequestProperty", "(Ljava/lang/String;)Ljava/lang/String;", ref global::java.net.URLConnection._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m18; public virtual global::java.util.Map getRequestProperties() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Map>(this, global::java.net.URLConnection.staticClass, "getRequestProperties", "()Ljava/util/Map;", ref global::java.net.URLConnection._m18) as java.util.Map; } private static global::MonoJavaBridge.MethodId _m19; public static global::java.lang.String guessContentTypeFromStream(java.io.InputStream arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m19.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m19 = @__env.GetStaticMethodIDNoThrow(global::java.net.URLConnection.staticClass, "guessContentTypeFromStream", "(Ljava/io/InputStream;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.net.URLConnection.staticClass, global::java.net.URLConnection._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m20; public static global::java.lang.String guessContentTypeFromName(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m20.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m20 = @__env.GetStaticMethodIDNoThrow(global::java.net.URLConnection.staticClass, "guessContentTypeFromName", "(Ljava/lang/String;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.net.URLConnection.staticClass, global::java.net.URLConnection._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m21; public static void setFileNameMap(java.net.FileNameMap arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m21.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m21 = @__env.GetStaticMethodIDNoThrow(global::java.net.URLConnection.staticClass, "setFileNameMap", "(Ljava/net/FileNameMap;)V"); @__env.CallStaticVoidMethod(java.net.URLConnection.staticClass, global::java.net.URLConnection._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; public virtual void setConnectTimeout(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "setConnectTimeout", "(I)V", ref global::java.net.URLConnection._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m23; public virtual int getConnectTimeout() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.URLConnection.staticClass, "getConnectTimeout", "()I", ref global::java.net.URLConnection._m23); } private static global::MonoJavaBridge.MethodId _m24; public virtual void setReadTimeout(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "setReadTimeout", "(I)V", ref global::java.net.URLConnection._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m25; public virtual int getReadTimeout() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.URLConnection.staticClass, "getReadTimeout", "()I", ref global::java.net.URLConnection._m25); } private static global::MonoJavaBridge.MethodId _m26; public virtual global::java.lang.String getContentEncoding() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.net.URLConnection.staticClass, "getContentEncoding", "()Ljava/lang/String;", ref global::java.net.URLConnection._m26) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m27; public virtual long getExpiration() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.net.URLConnection.staticClass, "getExpiration", "()J", ref global::java.net.URLConnection._m27); } private static global::MonoJavaBridge.MethodId _m28; public virtual global::java.util.Map getHeaderFields() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Map>(this, global::java.net.URLConnection.staticClass, "getHeaderFields", "()Ljava/util/Map;", ref global::java.net.URLConnection._m28) as java.util.Map; } private static global::MonoJavaBridge.MethodId _m29; public virtual int getHeaderFieldInt(java.lang.String arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.URLConnection.staticClass, "getHeaderFieldInt", "(Ljava/lang/String;I)I", ref global::java.net.URLConnection._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m30; public virtual long getHeaderFieldDate(java.lang.String arg0, long arg1) { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.net.URLConnection.staticClass, "getHeaderFieldDate", "(Ljava/lang/String;J)J", ref global::java.net.URLConnection._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m31; public virtual global::java.io.OutputStream getOutputStream() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.URLConnection.staticClass, "getOutputStream", "()Ljava/io/OutputStream;", ref global::java.net.URLConnection._m31) as java.io.OutputStream; } private static global::MonoJavaBridge.MethodId _m32; public virtual void setDoInput(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "setDoInput", "(Z)V", ref global::java.net.URLConnection._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m33; public virtual bool getDoInput() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.URLConnection.staticClass, "getDoInput", "()Z", ref global::java.net.URLConnection._m33); } private static global::MonoJavaBridge.MethodId _m34; public virtual void setDoOutput(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "setDoOutput", "(Z)V", ref global::java.net.URLConnection._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m35; public virtual bool getDoOutput() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.URLConnection.staticClass, "getDoOutput", "()Z", ref global::java.net.URLConnection._m35); } private static global::MonoJavaBridge.MethodId _m36; public virtual void setAllowUserInteraction(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "setAllowUserInteraction", "(Z)V", ref global::java.net.URLConnection._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m37; public virtual bool getAllowUserInteraction() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.URLConnection.staticClass, "getAllowUserInteraction", "()Z", ref global::java.net.URLConnection._m37); } private static global::MonoJavaBridge.MethodId _m38; public static void setDefaultAllowUserInteraction(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m38.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m38 = @__env.GetStaticMethodIDNoThrow(global::java.net.URLConnection.staticClass, "setDefaultAllowUserInteraction", "(Z)V"); @__env.CallStaticVoidMethod(java.net.URLConnection.staticClass, global::java.net.URLConnection._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m39; public static bool getDefaultAllowUserInteraction() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m39.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m39 = @__env.GetStaticMethodIDNoThrow(global::java.net.URLConnection.staticClass, "getDefaultAllowUserInteraction", "()Z"); return @__env.CallStaticBooleanMethod(java.net.URLConnection.staticClass, global::java.net.URLConnection._m39); } private static global::MonoJavaBridge.MethodId _m40; public virtual void setUseCaches(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "setUseCaches", "(Z)V", ref global::java.net.URLConnection._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m41; public virtual bool getUseCaches() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.URLConnection.staticClass, "getUseCaches", "()Z", ref global::java.net.URLConnection._m41); } private static global::MonoJavaBridge.MethodId _m42; public virtual void setIfModifiedSince(long arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "setIfModifiedSince", "(J)V", ref global::java.net.URLConnection._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m43; public virtual long getIfModifiedSince() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::java.net.URLConnection.staticClass, "getIfModifiedSince", "()J", ref global::java.net.URLConnection._m43); } private static global::MonoJavaBridge.MethodId _m44; public virtual bool getDefaultUseCaches() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.URLConnection.staticClass, "getDefaultUseCaches", "()Z", ref global::java.net.URLConnection._m44); } private static global::MonoJavaBridge.MethodId _m45; public virtual void setDefaultUseCaches(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection.staticClass, "setDefaultUseCaches", "(Z)V", ref global::java.net.URLConnection._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m46; public static void setDefaultRequestProperty(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m46.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m46 = @__env.GetStaticMethodIDNoThrow(global::java.net.URLConnection.staticClass, "setDefaultRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); @__env.CallStaticVoidMethod(java.net.URLConnection.staticClass, global::java.net.URLConnection._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m47; public static global::java.lang.String getDefaultRequestProperty(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m47.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m47 = @__env.GetStaticMethodIDNoThrow(global::java.net.URLConnection.staticClass, "getDefaultRequestProperty", "(Ljava/lang/String;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.net.URLConnection.staticClass, global::java.net.URLConnection._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m48; public static void setContentHandlerFactory(java.net.ContentHandlerFactory arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m48.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m48 = @__env.GetStaticMethodIDNoThrow(global::java.net.URLConnection.staticClass, "setContentHandlerFactory", "(Ljava/net/ContentHandlerFactory;)V"); @__env.CallStaticVoidMethod(java.net.URLConnection.staticClass, global::java.net.URLConnection._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m49; protected URLConnection(java.net.URL arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.URLConnection._m49.native == global::System.IntPtr.Zero) global::java.net.URLConnection._m49 = @__env.GetMethodIDNoThrow(global::java.net.URLConnection.staticClass, "<init>", "(Ljava/net/URL;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.URLConnection.staticClass, global::java.net.URLConnection._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static URLConnection() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.net.URLConnection.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/net/URLConnection")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.net.URLConnection))] internal sealed partial class URLConnection_ : java.net.URLConnection { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal URLConnection_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override void connect() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.URLConnection_.staticClass, "connect", "()V", ref global::java.net.URLConnection_._m0); } static URLConnection_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.net.URLConnection_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/net/URLConnection")); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>LandingPageView</c> resource.</summary> public sealed partial class LandingPageViewName : gax::IResourceName, sys::IEquatable<LandingPageViewName> { /// <summary>The possible contents of <see cref="LandingPageViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c>. /// </summary> CustomerUnexpandedFinalUrlFingerprint = 1, } private static gax::PathTemplate s_customerUnexpandedFinalUrlFingerprint = new gax::PathTemplate("customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}"); /// <summary>Creates a <see cref="LandingPageViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="LandingPageViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static LandingPageViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new LandingPageViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="LandingPageViewName"/> with the pattern /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="unexpandedFinalUrlFingerprintId"> /// The <c>UnexpandedFinalUrlFingerprint</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns>A new instance of <see cref="LandingPageViewName"/> constructed from the provided ids.</returns> public static LandingPageViewName FromCustomerUnexpandedFinalUrlFingerprint(string customerId, string unexpandedFinalUrlFingerprintId) => new LandingPageViewName(ResourceNameType.CustomerUnexpandedFinalUrlFingerprint, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), unexpandedFinalUrlFingerprintId: gax::GaxPreconditions.CheckNotNullOrEmpty(unexpandedFinalUrlFingerprintId, nameof(unexpandedFinalUrlFingerprintId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="LandingPageViewName"/> with pattern /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="unexpandedFinalUrlFingerprintId"> /// The <c>UnexpandedFinalUrlFingerprint</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="LandingPageViewName"/> with pattern /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c>. /// </returns> public static string Format(string customerId, string unexpandedFinalUrlFingerprintId) => FormatCustomerUnexpandedFinalUrlFingerprint(customerId, unexpandedFinalUrlFingerprintId); /// <summary> /// Formats the IDs into the string representation of this <see cref="LandingPageViewName"/> with pattern /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="unexpandedFinalUrlFingerprintId"> /// The <c>UnexpandedFinalUrlFingerprint</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="LandingPageViewName"/> with pattern /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c>. /// </returns> public static string FormatCustomerUnexpandedFinalUrlFingerprint(string customerId, string unexpandedFinalUrlFingerprintId) => s_customerUnexpandedFinalUrlFingerprint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(unexpandedFinalUrlFingerprintId, nameof(unexpandedFinalUrlFingerprintId))); /// <summary> /// Parses the given resource name string into a new <see cref="LandingPageViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="landingPageViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="LandingPageViewName"/> if successful.</returns> public static LandingPageViewName Parse(string landingPageViewName) => Parse(landingPageViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="LandingPageViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="landingPageViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="LandingPageViewName"/> if successful.</returns> public static LandingPageViewName Parse(string landingPageViewName, bool allowUnparsed) => TryParse(landingPageViewName, allowUnparsed, out LandingPageViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="LandingPageViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="landingPageViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="LandingPageViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string landingPageViewName, out LandingPageViewName result) => TryParse(landingPageViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="LandingPageViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="landingPageViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="LandingPageViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string landingPageViewName, bool allowUnparsed, out LandingPageViewName result) { gax::GaxPreconditions.CheckNotNull(landingPageViewName, nameof(landingPageViewName)); gax::TemplatedResourceName resourceName; if (s_customerUnexpandedFinalUrlFingerprint.TryParseName(landingPageViewName, out resourceName)) { result = FromCustomerUnexpandedFinalUrlFingerprint(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(landingPageViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private LandingPageViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string unexpandedFinalUrlFingerprintId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; UnexpandedFinalUrlFingerprintId = unexpandedFinalUrlFingerprintId; } /// <summary> /// Constructs a new instance of a <see cref="LandingPageViewName"/> class from the component parts of pattern /// <c>customers/{customer_id}/landingPageViews/{unexpanded_final_url_fingerprint}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="unexpandedFinalUrlFingerprintId"> /// The <c>UnexpandedFinalUrlFingerprint</c> ID. Must not be <c>null</c> or empty. /// </param> public LandingPageViewName(string customerId, string unexpandedFinalUrlFingerprintId) : this(ResourceNameType.CustomerUnexpandedFinalUrlFingerprint, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), unexpandedFinalUrlFingerprintId: gax::GaxPreconditions.CheckNotNullOrEmpty(unexpandedFinalUrlFingerprintId, nameof(unexpandedFinalUrlFingerprintId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>UnexpandedFinalUrlFingerprint</c> ID. Will not be <c>null</c>, unless this instance contains an /// unparsed resource name. /// </summary> public string UnexpandedFinalUrlFingerprintId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerUnexpandedFinalUrlFingerprint: return s_customerUnexpandedFinalUrlFingerprint.Expand(CustomerId, UnexpandedFinalUrlFingerprintId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as LandingPageViewName); /// <inheritdoc/> public bool Equals(LandingPageViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(LandingPageViewName a, LandingPageViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(LandingPageViewName a, LandingPageViewName b) => !(a == b); } public partial class LandingPageView { /// <summary> /// <see cref="LandingPageViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal LandingPageViewName ResourceNameAsLandingPageViewName { get => string.IsNullOrEmpty(ResourceName) ? null : LandingPageViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
namespace Microsoft.Protocols.TestSuites.MS_ASCMD { using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.Common.Response; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// This scenario is designed to test the FolderCreate command. /// </summary> [TestClass] public class S02_FolderCreate : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test Cases /// <summary> /// This test case is used to verify if the FolderCreate command request is successful, ServerId element should be returned. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S02_TC01_FolderCreate_Success() { #region Call method FolderCreate to create a new folder as a child folder of the specified parent folder. FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse(this.LastFolderSyncKey, (byte)FolderType.UserCreatedMail, Common.GenerateResourceName(Site, "FolderCreate"), "0"); Site.Assert.AreEqual<int>(1, int.Parse(folderCreateResponse.ResponseData.Status), "If the FolderCreate command executes successfully, the Status in response should be 1."); // Record created folder collectionID. TestSuiteBase.RecordCaseRelativeFolders(this.User1Information, folderCreateResponse.ResponseData.ServerId); #endregion #region Call method FolderSync to synchronize the collection hierarchy. FolderSyncResponse folderSyncResponse = this.FolderSync(); bool folderAddSuccess = false; foreach (FolderSyncChangesAdd add in folderSyncResponse.ResponseData.Changes.Add) { if (add.ServerId == folderCreateResponse.ResponseData.ServerId) { folderAddSuccess = true; break; } } #endregion #region Capture FolderCreate command success related requirements // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4011"); // If the serverId of Add element equal with the serverId specified in the response of FolderCreate command, it indicates the FolderCreate command completed successfully. // Verify MS-ASCMD requirement: MS-ASCMD_R4011 Site.CaptureRequirementIfIsTrue( folderAddSuccess, 4011, @"[In Status(FolderCreate)] [When the scope is Global], [the cause of the status value 1 is] Server successfully completed command."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R79"); // If the serverId of Add element equal with the serverId specified in the response of FolderCreate command, it indicates the FolderCreate command completed successfully. // Verify MS-ASCMD requirement: MS-ASCMD_R79 Site.CaptureRequirementIfIsTrue( folderAddSuccess, 79, @"[In FolderCreate] The FolderCreate command creates a new folder as a child folder of the specified parent folder."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3903"); // Folder has been created successfully, server returns a non-null ServerId. Site.CaptureRequirementIfIsNotNull( folderCreateResponse.ResponseData.ServerId, 3903, @"[In ServerId(FolderCreate)] The ServerId element MUST be returned if the FolderCreate command request was successful."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4569"); // Folder has been created successfully, server must send a synchronization key to the client in a response. Site.CaptureRequirementIfIsNotNull( folderCreateResponse.ResponseData.SyncKey, 4569, @"[In SyncKey(FolderCreate, FolderDelete, and FolderUpdate)] After a successful FolderCreate command (section 2.2.2.2) [, FolderDelete command (section 2.2.2.3), or FolderUpdate command (section 2.2.2.5)], the server MUST send a synchronization key to the client in a response."); #endregion } /// <summary> /// This test case is used to verify if the FolderCreate command request fails, ServerId element should not be returned. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S02_TC02_FolderCreate_Fail() { // Call method FolderCreate to create a new folder as a child folder of the specified parent folder without DisplayName element value. FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse(this.LastFolderSyncKey, (byte)FolderType.UserCreatedMail, string.Empty, "0"); Site.Assert.IsNotNull(folderCreateResponse.ResponseData.Status, "The Status element should be return."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3904"); // If the FolderCreate command request fails, server returns a null ServerId. Site.CaptureRequirementIfIsNull( folderCreateResponse.ResponseData.ServerId, 3904, @"[In ServerId(FolderCreate)] the element MUST NOT be returned if the FolderCreate command request fails."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4570"); // If the FolderCreate command request fails, server returns a null SyncKey. Site.CaptureRequirementIfIsNull( folderCreateResponse.ResponseData.SyncKey, 4570, @"[In SyncKey(FolderCreate, FolderDelete, and FolderUpdate)] If the FolderCreate command [, FolderDelete command, or FolderUpdate command] is not successful, the server MUST NOT return a SyncKey element."); } /// <summary> /// This test case is used to verify FolderCreate command, if the folder name already exists, the status should be equal to 2. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S02_TC03_FolderCreate_Status2() { #region Call method FolderCreate to create a new folder as a child folder of the mailbox Root folder. string folderName = Common.GenerateResourceName(Site, "FolderCreate", 1); FolderCreateRequest folderCreateRequest = Common.CreateFolderCreateRequest(this.LastFolderSyncKey, (byte)FolderType.UserCreatedMail, folderName, "0"); FolderCreateResponse folderCreateResponse = this.CMDAdapter.FolderCreate(folderCreateRequest); Site.Assert.AreEqual<int>(1, int.Parse(folderCreateResponse.ResponseData.Status), "If the FolderCreate command executes successfully, the Status in response should be 1."); TestSuiteBase.RecordCaseRelativeFolders(this.User1Information, folderCreateResponse.ResponseData.ServerId); #endregion #region Call method FolderCreate to create another new folder with same name as a child folder of the mailbox Root folder. folderCreateRequest = Common.CreateFolderCreateRequest(folderCreateResponse.ResponseData.SyncKey, (byte)FolderType.UserCreatedMail, folderName, "0"); folderCreateResponse = this.CMDAdapter.FolderCreate(folderCreateRequest); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4013"); // Verify MS-ASCMD requirement: MS-ASCMD_R4013 Site.CaptureRequirementIfAreEqual<int>( 2, int.Parse(folderCreateResponse.ResponseData.Status), 4013, @"[In Status(FolderCreate)] [When the scope is Item], [the cause of the status value 2 is] The parent folder already contains a folder that has this name."); #endregion } /// <summary> /// This test case is used to verify FolderCreate command, if the parentId doesn't exist, the status should be equal to 5. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S02_TC04_FolderCreate_Status5() { // Set a parentFolderID that doesn't exist in request. FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse(this.LastFolderSyncKey, (byte)FolderType.UserCreatedMail, Common.GenerateResourceName(Site, "FolderCreate"), "InvalidParentId"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4019"); // If the parent folder does not exist on the server, the value of the Status element should be 5. // Verify MS-ASCMD requirement: MS-ASCMD_R4019 Site.CaptureRequirementIfAreEqual<int>( 5, int.Parse(folderCreateResponse.ResponseData.Status), 4019, @"[In Status(FolderCreate)] [When the scope is Item], [the cause of the status value 5 is] The parent folder does not exist on the server, possibly because it has been deleted or renamed."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4018"); // If the parent folder does not exist on the server, the value of the Status element should be 5. // Verify MS-ASCMD requirement: MS-ASCMD_R4018 Site.CaptureRequirementIfAreEqual<int>( 5, int.Parse(folderCreateResponse.ResponseData.Status), 4018, @"[In Status(FolderCreate)] [When the scope is] Item, [the meaning of the status value] 5 [is] The specified parent folder was not found."); } /// <summary> /// This test case is used to verify FolderCreate command, if the SyncKey is invalid, the status should be equal to 9. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S02_TC05_FolderCreate_Status9() { // Call method FolderCreate to create a new folder with invalid folder SyncKey. FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse("InvalidFolderSyncKey", (byte)FolderType.UserCreatedMail, Common.GenerateResourceName(Site, "FolderCreate"), "0"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4032"); // If the client sent a malformed or mismatched synchronization key in FolderCreate request, the value of the Status element should be 9. // Verify MS-ASCMD requirement: MS-ASCMD_R4032 Site.CaptureRequirementIfAreEqual<int>( 9, int.Parse(folderCreateResponse.ResponseData.Status), 4032, @"[In Status(FolderCreate)] [When the scope is Global], [the cause of the status value 9 is] The client sent a malformed or mismatched synchronization key, or the synchronization state is corrupted on the server."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4573"); // If the client sent a malformed or mismatched synchronization key in FolderCreate request, the value of the Status element should be 9. // Verify MS-ASCMD requirement: MS-ASCMD_R4573 Site.CaptureRequirementIfAreEqual<int>( 9, int.Parse(folderCreateResponse.ResponseData.Status), 4573, @"[In SyncKey(FolderCreate, FolderDelete, and FolderUpdate)] The server MUST return a Status element (section 2.2.3.162.4) value of 9 if the value of the SyncKey element does not match the value of the synchronization key on the server."); } /// <summary> /// This test case is used to verify FolderCreate command, if the request contains a semantic error, the status should be equal to 10. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S02_TC06_FolderCreate_Status10() { // Call method FolderCreate to create a new folder as a child folder of the specified parent folder without folder SyncKey. FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse(null, (byte)FolderType.UserCreatedMail, Common.GenerateResourceName(Site, "FolderCreate"), "0"); Site.Assert.AreEqual<int>(10, int.Parse(folderCreateResponse.ResponseData.Status), "If the request contains a semantic error, the status should be equal to 10."); folderCreateResponse = this.GetFolderCreateResponse(this.LastFolderSyncKey, (byte)FolderType.Inbox, Common.GenerateResourceName(this.Site, "FolderCreate"), "0"); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4035"); // Verify MS-ASCMD requirement: MS-ASCMD_R4035 Site.CaptureRequirementIfAreEqual<int>( 10, int.Parse(folderCreateResponse.ResponseData.Status), 4035, @"[In Status(FolderCreate)] [When the scope is Global], [the cause of the status value 10 is] The client sent a FolderCreate command request (section 2.2.2.2) that contains a semantic error, or the client attempted to create a default folder, such as the Inbox folder, Outbox folder, or Contacts folder."); } /// <summary> /// This test case is used to verify FolderCreate command, if the specified parent folder is the recipient information cache, the status should be equal to 3. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S02_TC07_FolderCreate_Status3() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The recipient information cache is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); // Set the specified parent folder is the recipient information cache FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse(this.LastFolderSyncKey, (byte)FolderType.UserCreatedMail, Common.GenerateResourceName(Site, "FolderCreate"), User1Information.RecipientInformationCacheCollectionId); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "MS-ASCMD_R4016"); // Verify MS-ASCMD requirement: MS-ASCMD_R4016 Site.CaptureRequirementIfAreEqual<int>( 3, int.Parse(folderCreateResponse.ResponseData.Status), 4016, @"[In Status(FolderCreate)] [When the scope is Item], [the cause of the status value 3 is] The specified parent folder is the Recipient information folder."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "MS-ASCMD_R5769"); // Since server return status 3, the FolderCreate command cannot be used to update a recipient information cache. // Verify MS-ASCMD requirement: MS-ASCMD_R5769 Site.CaptureRequirement( 5769, @"[In FolderCreate] The FolderCreate command cannot be used to create [a recipient information cache or] a subfolder of a recipient information cache."); } /// <summary> /// This test case is used to verify FolderCreate command, if create a recipient information cache, the status should be equal to 3. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S02_TC08_FolderCreate_RecipientInformationCache_Status3() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The recipient information cache is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); // Set the specified parent folder is the recipient information cache FolderCreateResponse folderCreateResponse = this.GetFolderCreateResponse(this.LastFolderSyncKey, (byte)FolderType.RecipientInformationCache, Common.GenerateResourceName(Site, "FolderCreate"), User1Information.InboxCollectionId); Site.Assert.AreEqual<int>(3, int.Parse(folderCreateResponse.ResponseData.Status), "The status should be equal to 3 when the FolderCreate is used to create a recipient information cache."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "MS-ASCMD_R81"); // Since server return status 3, the FolderCreate command cannot be used to update a recipient information cache. // Verify MS-ASCMD requirement: MS-ASCMD_R81 Site.CaptureRequirement( 81, @"[In FolderCreate] The FolderCreate command cannot be used to create a recipient information cache [or a subfolder of a recipient information cache]."); } #endregion } }
using System.Collections.Generic; using System.IO; using System.Text; using UnityEditor; namespace ResourceFormat { public class ModelOverviewReport { [MenuItem(OverviewConfig.ModelReportMenu)] public static void GenerateRportByConfig() { List<ModelInfo> modelInfoList = ModelInfo.GetModelInfoByDirectory(OverviewConfig.RootPath); GenerateReport(OverviewConfig.ModelReportPath, modelInfoList); } public static void GenerateReport(string filePath, List<ModelInfo> modelInfoList) { UnityEngine.Debug.Log("Begin ModelOverviewReport Generate."); EditorCommon.EditorTool.CreateDirectory(filePath); FileStream fs = File.Open(filePath, FileMode.Create, FileAccess.Write, FileShare.Read); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8); sw.WriteLine("##Model Total Info Report"); sw.WriteLine(GenerateReadWriteData(modelInfoList)); sw.WriteLine(GenerateImportMaterialData(modelInfoList)); sw.WriteLine(GenerateOptimizeMeshData(modelInfoList)); sw.WriteLine(GenerateMeshVerticesData(modelInfoList)); sw.WriteLine(GenerateMeshCompressData(modelInfoList)); sw.WriteLine(GenerateMeshVertexCountData(modelInfoList)); sw.WriteLine(GenerateMeshTriangleCountData(modelInfoList)); sw.Flush(); sw.Close(); UnityEngine.Debug.Log("End ModelOverviewReport Generate."); } private static string GenerateReadWriteData(List<ModelInfo> modelInfoList) { Dictionary<bool, KeyValuePair<int, long>> dict = new Dictionary<bool, KeyValuePair<int, long>>(); for (int i = 0; i < modelInfoList.Count; ++i) { var key = modelInfoList[i].ReadWriteEnable; var value = modelInfoList[i].MemSize; if (!dict.ContainsKey(key)) { dict.Add(key, new KeyValuePair<int, long>()); } KeyValuePair<int, long> rwData = dict[key]; dict[key] = new KeyValuePair<int, long>(rwData.Key + 1, rwData.Value + value); } StringBuilder sb = new StringBuilder(); sb.AppendLine("####Read/Write Enable"); sb.AppendLine("|Read/Write Enable|Count|Size|"); sb.AppendLine("|-|-|-|"); for (int i = 0; i < 2; ++i) { KeyValuePair<int, long> itor; if (!dict.TryGetValue(i == 1, out itor)) continue; sb.Append(i == 1 ? "|True|" : "|False|"); sb.AppendFormat("{0}|{1}|", itor.Key, EditorUtility.FormatBytes(itor.Value)); sb.AppendLine(); } return sb.ToString(); } private static string GenerateImportMaterialData(List<ModelInfo> modelInfoList) { Dictionary<bool, KeyValuePair<int, long>> dict = new Dictionary<bool, KeyValuePair<int, long>>(); for (int i = 0; i < modelInfoList.Count; ++i) { var key = modelInfoList[i].ImportMaterials; var value = modelInfoList[i].MemSize; if (!dict.ContainsKey(key)) { dict.Add(key, new KeyValuePair<int, long>()); } KeyValuePair<int, long> rwData = dict[key]; dict[key] = new KeyValuePair<int, long>(rwData.Key + 1, rwData.Value + value); } StringBuilder sb = new StringBuilder(); sb.AppendLine("####Import Material"); sb.AppendLine("|Importer|Count|Size|"); sb.AppendLine("|-|-|-|"); for (int i = 0; i < 2; ++i) { KeyValuePair<int, long> itor; if (!dict.TryGetValue(i == 1, out itor)) continue; sb.Append(i == 1 ? "|True|" : "|False|"); sb.AppendFormat("{0}|{1}|", itor.Key, EditorUtility.FormatBytes(itor.Value)); sb.AppendLine(); } return sb.ToString(); } private static string GenerateOptimizeMeshData(List<ModelInfo> modelInfoList) { Dictionary<bool, KeyValuePair<int, long>> dict = new Dictionary<bool, KeyValuePair<int, long>>(); for (int i = 0; i < modelInfoList.Count; ++i) { var key = modelInfoList[i].OptimizeMesh; var value = modelInfoList[i].MemSize; if (!dict.ContainsKey(key)) { dict.Add(key, new KeyValuePair<int, long>()); } KeyValuePair<int, long> rwData = dict[key]; dict[key] = new KeyValuePair<int, long>(rwData.Key + 1, rwData.Value + value); } StringBuilder sb = new StringBuilder(); sb.AppendLine("####Optimize Mesh"); sb.AppendLine("|optimizeMesh|Count|Size|"); sb.AppendLine("|-|-|-|"); for (int i = 0; i < 2; ++i) { KeyValuePair<int, long> itor; if (!dict.TryGetValue(i == 1, out itor)) continue; sb.Append(i == 1 ? "|True|" : "|False|"); sb.AppendFormat("{0}|{1}|", itor.Key, EditorUtility.FormatBytes(itor.Value)); sb.AppendLine(); } return sb.ToString(); } private static string GenerateMeshVerticesData(List<ModelInfo> modelInfoList) { Dictionary<int, KeyValuePair<int, long>> dict = new Dictionary<int, KeyValuePair<int, long>>(); for (int i = 0; i < modelInfoList.Count; ++i) { ModelInfo mInfo = modelInfoList[i]; var key = mInfo.GetMeshDataID(); var value = modelInfoList[i].MemSize; if (!dict.ContainsKey(key)) { dict.Add(key, new KeyValuePair<int, long>()); } KeyValuePair<int, long> rwData = dict[key]; dict[key] = new KeyValuePair<int, long>(rwData.Key + 1, rwData.Value + value); } List<KeyValuePair<int, KeyValuePair<int, long>>> list = new List<KeyValuePair<int, KeyValuePair<int, long>>>(dict); list.Sort((x, y) => { return y.Value.Key.CompareTo(x.Value.Key); }); StringBuilder sb = new StringBuilder(); sb.AppendLine("####Mesh Data"); sb.AppendLine("|Data|Count|Size|"); sb.AppendLine("|-|-|-|"); foreach (var itor in list) { int key = itor.Key; sb.AppendFormat("|{0}|", ModelInfo.GetMeshDataStr(key)); sb.AppendFormat("{0}|{1}|", itor.Value.Key, EditorUtility.FormatBytes(itor.Value.Value)); sb.AppendLine(); } return sb.ToString(); } private static string GenerateMeshCompressData(List<ModelInfo> modelInfoList) { Dictionary<ModelImporterMeshCompression, KeyValuePair<int, long>> dict = new Dictionary<ModelImporterMeshCompression, KeyValuePair<int, long>>(); for (int i = 0; i < modelInfoList.Count; ++i) { var key = modelInfoList[i].MeshCompression; var value = modelInfoList[i].MemSize; if (!dict.ContainsKey(key)) { dict.Add(key, new KeyValuePair<int, long>()); } KeyValuePair<int, long> rwData = dict[key]; dict[key] = new KeyValuePair<int, long>(rwData.Key + 1, rwData.Value + value); } List<KeyValuePair<ModelImporterMeshCompression, KeyValuePair<int, long>>> list = new List<KeyValuePair<ModelImporterMeshCompression, KeyValuePair<int, long>>>(dict); list.Sort((x, y) => { return y.Value.Value.CompareTo(x.Value.Value); }); StringBuilder sb = new StringBuilder(); sb.AppendLine("####Mesh Compress"); sb.AppendLine("|Compression|Count|Size|"); sb.AppendLine("|-|-|-|"); foreach (var itor in list) { sb.AppendFormat("|{0}|", itor.Key); sb.AppendFormat("{0}|{1}|", itor.Value.Key, EditorUtility.FormatBytes(itor.Value.Value)); sb.AppendLine(); } return sb.ToString(); } private static string GenerateMeshVertexCountData(List<ModelInfo> modelInfoList) { int verTexMod = OverviewTableConst.VertexCountMod; Dictionary<int, KeyValuePair<int, long>> dict = new Dictionary<int, KeyValuePair<int, long>>(); for (int i = 0; i < modelInfoList.Count; ++i) { var key = modelInfoList[i].vertexCount / verTexMod; var value = modelInfoList[i].MemSize; if (!dict.ContainsKey(key)) { dict.Add(key, new KeyValuePair<int, long>()); } KeyValuePair<int, long> rwData = dict[key]; dict[key] = new KeyValuePair<int, long>(rwData.Key + 1, rwData.Value + value); } List<KeyValuePair<int, KeyValuePair<int, long>>> list = new List<KeyValuePair<int, KeyValuePair<int, long>>>(dict); list.Sort((x, y) => { return y.Value.Value.CompareTo(x.Value.Value); }); StringBuilder sb = new StringBuilder(); sb.AppendLine("####Vertex Count"); sb.AppendLine("|VertexCount|Count|Size|"); sb.AppendLine("|-|-|-|"); foreach (var itor in list) { sb.AppendFormat("|{0}-{1}|", itor.Key * verTexMod, (itor.Key + 1) * verTexMod - 1); sb.AppendFormat("{0}|{1}|", itor.Value.Key, EditorUtility.FormatBytes(itor.Value.Value)); sb.AppendLine(); } return sb.ToString(); } private static string GenerateMeshTriangleCountData(List<ModelInfo> modelInfoList) { int triTexMod = OverviewTableConst.TriangleCountMod; Dictionary<int, KeyValuePair<int, long>> dict = new Dictionary<int, KeyValuePair<int, long>>(); for (int i = 0; i < modelInfoList.Count; ++i) { var key = modelInfoList[i].triangleCount / triTexMod; var value = modelInfoList[i].MemSize; if (!dict.ContainsKey(key)) { dict.Add(key, new KeyValuePair<int, long>()); } KeyValuePair<int, long> rwData = dict[key]; dict[key] = new KeyValuePair<int, long>(rwData.Key + 1, rwData.Value + value); } List<KeyValuePair<int, KeyValuePair<int, long>>> list = new List<KeyValuePair<int, KeyValuePair<int, long>>>(dict); list.Sort((x, y) => { return y.Value.Value.CompareTo(x.Value.Value); }); StringBuilder sb = new StringBuilder(); sb.AppendLine("####Triangle Count"); sb.AppendLine("|TriangleCount|Count|Size|"); sb.AppendLine("|-|-|-|"); foreach (var itor in list) { sb.AppendFormat("|{0}-{1}|", itor.Key * triTexMod, (itor.Key + 1) * triTexMod - 1); sb.AppendFormat("{0}|{1}|", itor.Value.Key, EditorUtility.FormatBytes(itor.Value.Value)); sb.AppendLine(); } return sb.ToString(); } } }
// dnlib: See LICENSE.txt for more info namespace dnlib.DotNet { /// <summary> /// See CorHdr.h/CorElementType /// </summary> public enum ElementType : byte { /// <summary/> End = 0x00, /// <summary>System.Void</summary> Void = 0x01, /// <summary>System.Boolean</summary> Boolean = 0x02, /// <summary>System.Char</summary> Char = 0x03, /// <summary>System.SByte</summary> I1 = 0x04, /// <summary>System.Byte</summary> U1 = 0x05, /// <summary>System.Int16</summary> I2 = 0x06, /// <summary>System.UInt16</summary> U2 = 0x07, /// <summary>System.Int32</summary> I4 = 0x08, /// <summary>System.UInt32</summary> U4 = 0x09, /// <summary>System.Int64</summary> I8 = 0x0A, /// <summary>System.UInt64</summary> U8 = 0x0B, /// <summary>System.Single</summary> R4 = 0x0C, /// <summary>System.Double</summary> R8 = 0x0D, /// <summary>System.String</summary> String = 0x0E, /// <summary>Pointer type (*)</summary> Ptr = 0x0F, /// <summary>ByRef type (&amp;)</summary> ByRef = 0x10, /// <summary>Value type</summary> ValueType = 0x11, /// <summary>Reference type</summary> Class = 0x12, /// <summary>Type generic parameter</summary> Var = 0x13, /// <summary>Multidimensional array ([*], [,], [,,], ...)</summary> Array = 0x14, /// <summary>Generic instance type</summary> GenericInst = 0x15, /// <summary>Typed byref</summary> TypedByRef = 0x16, /// <summary>Value array (don't use)</summary> ValueArray = 0x17, /// <summary>System.IntPtr</summary> I = 0x18, /// <summary>System.UIntPtr</summary> U = 0x19, /// <summary>native real (don't use)</summary> R = 0x1A, /// <summary>Function pointer</summary> FnPtr = 0x1B, /// <summary>System.Object</summary> Object = 0x1C, /// <summary>Single-dimension, zero lower bound array ([])</summary> SZArray = 0x1D, /// <summary>Method generic parameter</summary> MVar = 0x1E, /// <summary>Required C modifier</summary> CModReqd = 0x1F, /// <summary>Optional C modifier</summary> CModOpt = 0x20, /// <summary>Used internally by the CLR (don't use)</summary> Internal = 0x21, /// <summary>Module (don't use)</summary> Module = 0x3F, /// <summary>Sentinel (method sigs only)</summary> Sentinel = 0x41, /// <summary>Pinned type (locals only)</summary> Pinned = 0x45, } public static partial class Extensions { /// <summary> /// Returns <c>true</c> if it's an integer or a floating point type /// </summary> /// <param name="etype">Element type</param> /// <returns></returns> public static bool IsPrimitive(this ElementType etype) { switch (etype) { case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.I: case ElementType.U: case ElementType.R: return true; default: return false; } } /// <summary> /// Returns the size of the element type in bytes or <c>-1</c> if it's unknown /// </summary> /// <param name="etype">Element type</param> /// <param name="ptrSize">Size of a pointer</param> /// <returns></returns> public static int GetPrimitiveSize(this ElementType etype, int ptrSize = -1) { switch (etype) { case ElementType.Boolean: case ElementType.I1: case ElementType.U1: return 1; case ElementType.Char: case ElementType.I2: case ElementType.U2: return 2; case ElementType.I4: case ElementType.U4: case ElementType.R4: return 4; case ElementType.I8: case ElementType.U8: case ElementType.R8: return 8; case ElementType.Ptr: case ElementType.FnPtr: case ElementType.I: case ElementType.U: return ptrSize; default: return -1; } } /// <summary> /// Checks whether it's a value type /// </summary> /// <param name="etype">this</param> /// <returns><c>true</c> if it's a value type, <c>false</c> if it's not a value type or /// if we couldn't determine whether it's a value type. Eg., it could be a generic /// instance type.</returns> public static bool IsValueType(this ElementType etype) { switch (etype) { case ElementType.Void: case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.ValueType: case ElementType.TypedByRef: case ElementType.ValueArray: case ElementType.I: case ElementType.U: case ElementType.R: return true; case ElementType.GenericInst: // We don't have enough info to determine whether this is a value type return false; case ElementType.End: case ElementType.String: case ElementType.Ptr: case ElementType.ByRef: case ElementType.Class: case ElementType.Var: case ElementType.Array: case ElementType.FnPtr: case ElementType.Object: case ElementType.SZArray: case ElementType.MVar: case ElementType.CModReqd: case ElementType.CModOpt: case ElementType.Internal: case ElementType.Module: case ElementType.Sentinel: case ElementType.Pinned: default: return false; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 gagve = Google.Ads.GoogleAds.V8.Enums; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="InvoiceServiceClient"/> instances.</summary> public sealed partial class InvoiceServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="InvoiceServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="InvoiceServiceSettings"/>.</returns> public static InvoiceServiceSettings GetDefault() => new InvoiceServiceSettings(); /// <summary>Constructs a new <see cref="InvoiceServiceSettings"/> object with default settings.</summary> public InvoiceServiceSettings() { } private InvoiceServiceSettings(InvoiceServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListInvoicesSettings = existing.ListInvoicesSettings; OnCopy(existing); } partial void OnCopy(InvoiceServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>InvoiceServiceClient.ListInvoices</c> and <c>InvoiceServiceClient.ListInvoicesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListInvoicesSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="InvoiceServiceSettings"/> object.</returns> public InvoiceServiceSettings Clone() => new InvoiceServiceSettings(this); } /// <summary> /// Builder class for <see cref="InvoiceServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class InvoiceServiceClientBuilder : gaxgrpc::ClientBuilderBase<InvoiceServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public InvoiceServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public InvoiceServiceClientBuilder() { UseJwtAccessWithScopes = InvoiceServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref InvoiceServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<InvoiceServiceClient> task); /// <summary>Builds the resulting client.</summary> public override InvoiceServiceClient Build() { InvoiceServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<InvoiceServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<InvoiceServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private InvoiceServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return InvoiceServiceClient.Create(callInvoker, Settings); } private async stt::Task<InvoiceServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return InvoiceServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => InvoiceServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => InvoiceServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => InvoiceServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>InvoiceService client wrapper, for convenient use.</summary> /// <remarks> /// A service to fetch invoices issued for a billing setup during a given month. /// </remarks> public abstract partial class InvoiceServiceClient { /// <summary> /// The default endpoint for the InvoiceService service, which is a host of "googleads.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default InvoiceService scopes.</summary> /// <remarks> /// The default InvoiceService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="InvoiceServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="InvoiceServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="InvoiceServiceClient"/>.</returns> public static stt::Task<InvoiceServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new InvoiceServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="InvoiceServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="InvoiceServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="InvoiceServiceClient"/>.</returns> public static InvoiceServiceClient Create() => new InvoiceServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="InvoiceServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="InvoiceServiceSettings"/>.</param> /// <returns>The created <see cref="InvoiceServiceClient"/>.</returns> internal static InvoiceServiceClient Create(grpccore::CallInvoker callInvoker, InvoiceServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } InvoiceService.InvoiceServiceClient grpcClient = new InvoiceService.InvoiceServiceClient(callInvoker); return new InvoiceServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC InvoiceService client</summary> public virtual InvoiceService.InvoiceServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns all invoices associated with a billing setup, for a given month. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [InvoiceError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListInvoicesResponse ListInvoices(ListInvoicesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns all invoices associated with a billing setup, for a given month. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [InvoiceError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListInvoicesResponse> ListInvoicesAsync(ListInvoicesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns all invoices associated with a billing setup, for a given month. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [InvoiceError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListInvoicesResponse> ListInvoicesAsync(ListInvoicesRequest request, st::CancellationToken cancellationToken) => ListInvoicesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns all invoices associated with a billing setup, for a given month. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [InvoiceError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer to fetch invoices for. /// </param> /// <param name="billingSetup"> /// Required. The billing setup resource name of the requested invoices. /// /// `customers/{customer_id}/billingSetups/{billing_setup_id}` /// </param> /// <param name="issueYear"> /// Required. The issue year to retrieve invoices, in yyyy format. Only /// invoices issued in 2019 or later can be retrieved. /// </param> /// <param name="issueMonth"> /// Required. The issue month to retrieve invoices. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListInvoicesResponse ListInvoices(string customerId, string billingSetup, string issueYear, gagve::MonthOfYearEnum.Types.MonthOfYear issueMonth, gaxgrpc::CallSettings callSettings = null) => ListInvoices(new ListInvoicesRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), BillingSetup = gax::GaxPreconditions.CheckNotNullOrEmpty(billingSetup, nameof(billingSetup)), IssueYear = gax::GaxPreconditions.CheckNotNullOrEmpty(issueYear, nameof(issueYear)), IssueMonth = issueMonth, }, callSettings); /// <summary> /// Returns all invoices associated with a billing setup, for a given month. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [InvoiceError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer to fetch invoices for. /// </param> /// <param name="billingSetup"> /// Required. The billing setup resource name of the requested invoices. /// /// `customers/{customer_id}/billingSetups/{billing_setup_id}` /// </param> /// <param name="issueYear"> /// Required. The issue year to retrieve invoices, in yyyy format. Only /// invoices issued in 2019 or later can be retrieved. /// </param> /// <param name="issueMonth"> /// Required. The issue month to retrieve invoices. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListInvoicesResponse> ListInvoicesAsync(string customerId, string billingSetup, string issueYear, gagve::MonthOfYearEnum.Types.MonthOfYear issueMonth, gaxgrpc::CallSettings callSettings = null) => ListInvoicesAsync(new ListInvoicesRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), BillingSetup = gax::GaxPreconditions.CheckNotNullOrEmpty(billingSetup, nameof(billingSetup)), IssueYear = gax::GaxPreconditions.CheckNotNullOrEmpty(issueYear, nameof(issueYear)), IssueMonth = issueMonth, }, callSettings); /// <summary> /// Returns all invoices associated with a billing setup, for a given month. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [InvoiceError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer to fetch invoices for. /// </param> /// <param name="billingSetup"> /// Required. The billing setup resource name of the requested invoices. /// /// `customers/{customer_id}/billingSetups/{billing_setup_id}` /// </param> /// <param name="issueYear"> /// Required. The issue year to retrieve invoices, in yyyy format. Only /// invoices issued in 2019 or later can be retrieved. /// </param> /// <param name="issueMonth"> /// Required. The issue month to retrieve invoices. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ListInvoicesResponse> ListInvoicesAsync(string customerId, string billingSetup, string issueYear, gagve::MonthOfYearEnum.Types.MonthOfYear issueMonth, st::CancellationToken cancellationToken) => ListInvoicesAsync(customerId, billingSetup, issueYear, issueMonth, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>InvoiceService client wrapper implementation, for convenient use.</summary> /// <remarks> /// A service to fetch invoices issued for a billing setup during a given month. /// </remarks> public sealed partial class InvoiceServiceClientImpl : InvoiceServiceClient { private readonly gaxgrpc::ApiCall<ListInvoicesRequest, ListInvoicesResponse> _callListInvoices; /// <summary> /// Constructs a client wrapper for the InvoiceService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="InvoiceServiceSettings"/> used within this client.</param> public InvoiceServiceClientImpl(InvoiceService.InvoiceServiceClient grpcClient, InvoiceServiceSettings settings) { GrpcClient = grpcClient; InvoiceServiceSettings effectiveSettings = settings ?? InvoiceServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListInvoices = clientHelper.BuildApiCall<ListInvoicesRequest, ListInvoicesResponse>(grpcClient.ListInvoicesAsync, grpcClient.ListInvoices, effectiveSettings.ListInvoicesSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callListInvoices); Modify_ListInvoicesApiCall(ref _callListInvoices); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ListInvoicesApiCall(ref gaxgrpc::ApiCall<ListInvoicesRequest, ListInvoicesResponse> call); partial void OnConstruction(InvoiceService.InvoiceServiceClient grpcClient, InvoiceServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC InvoiceService client</summary> public override InvoiceService.InvoiceServiceClient GrpcClient { get; } partial void Modify_ListInvoicesRequest(ref ListInvoicesRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns all invoices associated with a billing setup, for a given month. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [InvoiceError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ListInvoicesResponse ListInvoices(ListInvoicesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListInvoicesRequest(ref request, ref callSettings); return _callListInvoices.Sync(request, callSettings); } /// <summary> /// Returns all invoices associated with a billing setup, for a given month. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [InvoiceError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ListInvoicesResponse> ListInvoicesAsync(ListInvoicesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListInvoicesRequest(ref request, ref callSettings); return _callListInvoices.Async(request, callSettings); } } }
using Microsoft.Diagnostics.Utilities; using System; using System.Diagnostics; using System.Text; #pragma warning disable 1591 // disable warnings on XML comments not being present // This code was automatically generated by the TraceParserGen tool, which converts // an ETW event manifest into strongly typed C# classes. namespace Microsoft.Diagnostics.Tracing.Parsers { using Microsoft.Diagnostics.Tracing.Parsers.MicrosoftWindowsNDISPacketCapture; [System.CodeDom.Compiler.GeneratedCode("traceparsergen", "2.0")] public sealed class MicrosoftWindowsNDISPacketCaptureTraceEventParser : TraceEventParser { public static string ProviderName = "Microsoft-Windows-NDIS-PacketCapture"; public static Guid ProviderGuid = new Guid(unchecked((int)0x2ed6006e), unchecked((short)0x4729), unchecked((short)0x4609), 0xb4, 0x23, 0x3e, 0xe7, 0xbc, 0xd6, 0x78, 0xef); public enum Keywords : long { Ethernet8023 = 0x1, Wirelesswan = 0x200, Tunnel = 0x8000, StringkeywordNative80211 = 0x10000, Vmswitch = 0x1000000, Packettruncated = 0x2000000, Packetstart = 0x40000000, Packetend = 0x80000000, Utsendpath = 0x100000000, Utreceivepath = 0x200000000, Utl3connectpath = 0x400000000, Utl2connectpath = 0x800000000, Utclosepath = 0x1000000000, Utauthentication = 0x2000000000, Utconfiguration = 0x4000000000, Utglobal = 0x8000000000, }; public MicrosoftWindowsNDISPacketCaptureTraceEventParser(TraceEventSource source) : base(source) { } public event Action<PacketFragmentArgs> PacketFragment { add { source.RegisterEventTemplate(PacketFragmentTemplate(value, State)); } remove { source.UnregisterEventTemplate(value, 1001, ProviderGuid); } } public event Action<PacketMetaDataArgs> PacketMetaData { add { source.RegisterEventTemplate(PacketMetaDataTemplate(value, State)); } remove { source.UnregisterEventTemplate(value, 1002, ProviderGuid); } } #region private protected override string GetProviderName() { return ProviderName; } static private PacketFragmentArgs PacketFragmentTemplate(Action<PacketFragmentArgs> action, MicrosoftWindowsNDISPacketCaptureTraceEventParserState state) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName // TODO FIX NOW HACK return new PacketFragmentArgs(action, 1001, 0, "PacketFragment", Guid.Empty, 0, "", ProviderGuid, ProviderName, state); } static private PacketMetaDataArgs PacketMetaDataTemplate(Action<PacketMetaDataArgs> action, MicrosoftWindowsNDISPacketCaptureTraceEventParserState state) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName // TODO FIX NOW HACK return new PacketMetaDataArgs(action, 1002, 0, "PacketMetaData", Guid.Empty, 0, "", ProviderGuid, ProviderName, state); } static private volatile TraceEvent[] s_templates; protected override void EnumerateTemplates(Func<string, string, EventFilterResponse> eventsToObserve, Action<TraceEvent> callback) { if (s_templates == null) { var templates = new TraceEvent[2]; templates[0] = PacketFragmentTemplate(null, null); templates[1] = PacketMetaDataTemplate(null, null); s_templates = templates; } foreach (var template in s_templates) if (eventsToObserve == null || eventsToObserve(template.ProviderName, template.EventName) == EventFilterResponse.AcceptEvent) callback(template); } MicrosoftWindowsNDISPacketCaptureTraceEventParserState State { get { MicrosoftWindowsNDISPacketCaptureTraceEventParserState ret = (MicrosoftWindowsNDISPacketCaptureTraceEventParserState)StateObject; if (ret == null) { ret = new MicrosoftWindowsNDISPacketCaptureTraceEventParserState(); StateObject = ret; } return ret; } } #endregion } #region internal classes internal unsafe class MicrosoftWindowsNDISPacketCaptureTraceEventParserState { public MicrosoftWindowsNDISPacketCaptureTraceEventParserState() { m_FragmentEventIndex = EventIndex.Invalid; } internal Guid m_FragmentActivity; internal EventIndex m_FragmentEventIndex; internal bool m_TCPHeaderInPreviousFragment; internal byte* m_TCPHeader; internal byte* m_TCPHeaderEnd; internal int m_TCPHeaderMax; ~MicrosoftWindowsNDISPacketCaptureTraceEventParserState() { if (m_TCPHeader != null) { System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)m_TCPHeader); m_TCPHeader = null; } } } #endregion } namespace Microsoft.Diagnostics.Tracing.Parsers.MicrosoftWindowsNDISPacketCapture { public sealed class PacketFragmentArgs : TraceEvent { public int MiniportIfIndex { get { return GetInt32At(0); } } public int LowerIfIndex { get { return GetInt32At(4); } } public int FragmentSize { get { return GetInt32At(8); } } public unsafe byte* Fragment { get { return (byte*)DataStart + 12; } } public unsafe string ParsedPacket { get { byte* frag = Fragment; byte* fragEnd = frag + FragmentSize; // TODO FIX NOW This is probably a hack if (m_state == null) { m_state = new MicrosoftWindowsNDISPacketCaptureTraceEventParserState(); } bool TCPHeaderInPreviousFragment = m_state.m_TCPHeaderInPreviousFragment; m_state.m_TCPHeaderInPreviousFragment = false; // If we have a remembered header, use that. byte* packetStart = null; bool isContinuationFragment = false; if (m_state.m_FragmentEventIndex + 1 == EventIndex && m_state.m_FragmentActivity == ActivityID) { isContinuationFragment = true; if (TCPHeaderInPreviousFragment) { packetStart = m_state.m_TCPHeader; fragEnd = m_state.m_TCPHeaderEnd; } } m_state.m_FragmentActivity = ActivityID; m_state.m_FragmentEventIndex = EventIndex; if (packetStart == null) { packetStart = FindIPHeader(frag, fragEnd); } if (packetStart != null) { StringBuilder sb = new StringBuilder(); if (isContinuationFragment) { sb.Append("CONT ").Append(ActivityID.ToString().Substring(6, 2)).Append(" "); } IPHeader ip = new IPHeader(packetStart); sb.Append("IP"); sb.Append(" Source=").Append(ip.SourceAddress); sb.Append(" Dest=").Append(ip.DestinationAddress); if (ip.Protocol == 6) // TCP-IP { TCPHeader tcp = new TCPHeader(packetStart + ip.IPHeaderSize); sb.Append(" TCP"); // Create a connection ID. This is the source IP/port dest IP/port hashed int connetionIDHash = ip.SourceAddress.GetHashCode() + ip.DestinationAddress.GetHashCode() + tcp.SourcePort + tcp.DestPort; int connectionID = (ushort)(((uint)connetionIDHash >> 16) + connetionIDHash); // Suffix it with a > or < to indicate direction char suffix = tcp.SourcePort >= tcp.DestPort ? '>' : '<'; sb.Append(" ConnID=").Append(connectionID.ToString("x")).Append(suffix); sb.Append(" SPort=").Append(tcp.SourcePort); sb.Append(" DPort=").Append(tcp.DestPort); if (tcp.Cwr) { sb.Append(" CWR"); } if (tcp.Ece) { sb.Append(" ECE"); } if (tcp.Urg) { sb.Append(" URG"); } if (tcp.Ack) { sb.Append(" ACK"); } if (tcp.Psh) { sb.Append(" PSH"); } if (tcp.Rst) { sb.Append(" RST"); } if (tcp.Syn) { sb.Append(" SYN"); } if (tcp.Fin) { sb.Append(" FIN"); } if (tcp.AnyOptions) { var scale = tcp.WindowScale; if (0 <= scale) { sb.Append(" WindowScale=").Append(scale); } var maxSeg = tcp.MaximumSegmentSize; if (0 <= maxSeg) { sb.Append(" MaxSeg=").Append(maxSeg); } if (tcp.SelectivAckAllowed) { sb.Append(" SelectiveAck"); } sb.Append(" TcpHdrLen=").Append(tcp.TCPHeaderSize); } sb.Append(" Ack=0x").Append(tcp.AckNumber.ToString("x")); sb.Append(" Seq=0x").Append(tcp.SequenceNumber.ToString("x")); sb.Append(" Window=").Append(tcp.WindowSize); sb.Append(" Len=").Append(ip.Length - ip.IPHeaderSize - tcp.TCPHeaderSize); if (tcp.DestPort == 80 || tcp.SourcePort == 80) // HTTP { byte* httpBase = packetStart + ip.IPHeaderSize + tcp.TCPHeaderSize; if (TCPHeaderInPreviousFragment) { httpBase = Fragment; fragEnd = httpBase + FragmentSize; } else if (httpBase == fragEnd) { m_state.m_TCPHeaderInPreviousFragment = true; // Copy the bytes. var headerSize = ip.IPHeaderSize + tcp.TCPHeaderSize; if (m_state.m_TCPHeaderMax < headerSize) { if (m_state.m_TCPHeader != null) { System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)m_state.m_TCPHeader); } m_state.m_TCPHeaderMax = headerSize + 16; m_state.m_TCPHeader = (byte*)System.Runtime.InteropServices.Marshal.AllocHGlobal(m_state.m_TCPHeaderMax); } m_state.m_TCPHeaderEnd = m_state.m_TCPHeader + headerSize; var ptr = packetStart; for (int i = 0; i < headerSize; i++) { m_state.m_TCPHeader[i] = *ptr++; } } sb.Append(" HTTP"); if (httpBase < fragEnd) { AppendPrintable(httpBase, fragEnd, sb, " Stream=", 16); } } } else { sb.Append(" Len=").Append(ip.Length - ip.IPHeaderSize); if (ip.Protocol == 17) // UDP { sb.Append(" UDP"); } else { sb.Append("IP(").Append(ip.Protocol.ToString()).Append(")"); } } return sb.ToString(); } else if (isContinuationFragment) { return "CONTINUATION FRAGMENT " + ActivityID.ToString().Substring(6, 2) + " SIZE=" + FragmentSize; } else { return "NON-IP FRAGMENT " + ActivityID.ToString().Substring(6, 2) + " SIZE=" + FragmentSize; } } } public unsafe string TcpStreamSample { get { string sample = FindPrintableTcpStream(Fragment, FragmentSize, 128, true); if (sample == null) { return ""; } return sample.Replace("\r\n", " "); } } #region Private /// <summary> /// Sees if up to 'max' bytes of frag-fragend is a printable string and if so prints it to 'sb' with /// 'prefix' before it. /// </summary> private static unsafe void AppendPrintable(byte* frag, byte* fragEnd, StringBuilder sb, string prefix, int max) { var limit = frag + max; if (limit < fragEnd) { fragEnd = limit; } if (!IsPrintable(frag, fragEnd)) { return; } // Then print it sb.Append(prefix); for (byte* ptr = frag; ptr < fragEnd; ptr++) { if ((byte)' ' <= *ptr) { sb.Append((char)*ptr); } else { sb.Append(' '); } } sb.Append("..."); } private static unsafe bool IsPrintable(byte* frag, byte* fragEnd) { // is the complete string printable? for (byte* ptr = frag; ptr < fragEnd; ptr++) { if (!((byte)'\n' <= *ptr && *ptr < 128)) { return false; } } return true; } private unsafe struct IPHeader { public IPHeader(byte* address) { this.address = address; } public int IPHeaderSize { get { return (address[0] & 0xF) * 4; } } public int Length { get { return (address[2] << 8) + address[3]; } } public System.Net.IPAddress SourceAddress { get { return new System.Net.IPAddress(*((uint*)&address[12])); } } public System.Net.IPAddress DestinationAddress { get { return new System.Net.IPAddress(*((uint*)&address[16])); } } public byte Protocol { get { return address[9]; } } public int CheckSum { get { return (address[10] << 8) + address[11]; } } private byte* address; } private unsafe struct TCPHeader { public TCPHeader(byte* address) { this.address = address; } public int SourcePort { get { return (address[0] << 8) + address[1]; } } public int DestPort { get { return (address[2] << 8) + address[3]; } } public int SequenceNumber { get { return (((((address[4] << 8) + address[5]) << 8) + address[6]) << 8) + address[7]; } } public int AckNumber { get { return (((((address[8] << 8) + address[9]) << 8) + address[10]) << 8) + address[11]; } } public int TCPHeaderSize { get { return (address[12] >> 4) * 4; } } public bool Ns { get { return (address[12] & 0x1) != 0; } } public bool Cwr { get { return (address[13] & 0x80) != 0; } } public bool Ece { get { return (address[13] & 0x40) != 0; } } public bool Urg { get { return (address[13] & 0x20) != 0; } } public bool Ack { get { return (address[13] & 0x10) != 0; } } public bool Psh { get { return (address[13] & 0x8) != 0; } } public bool Rst { get { return (address[13] & 0x4) != 0; } } public bool Syn { get { return (address[13] & 0x2) != 0; } } public bool Fin { get { return (address[13] & 0x1) != 0; } } public int WindowSize { get { return (address[14] << 8) + address[15]; } } public int CheckSum { get { return (address[16] << 8) + address[17]; } } public int UrgentPointer { get { return (address[18] << 8) + address[19]; } } // Returns -1 if not present; public int WindowScale { get { return GetOption(3); } } public bool SelectivAckAllowed { get { return GetOption(4) == 0; } } public int MaximumSegmentSize { get { return GetOption(2); } } public bool AnyOptions { get { return 20 < TCPHeaderSize; } } #region private private int GetOption(int optionID) { byte* optionsEnd = address + TCPHeaderSize; byte* optionPtr = address + 20; while (optionPtr < optionsEnd) { if (*optionPtr == 0) { break; } if (*optionPtr == 1) { optionPtr++; } else { var len = optionPtr[1]; if (len < 2 || 10 < len) // protect against errors. { break; } if (*optionPtr == optionID) { if (len == 2) { return 0; } if (len == 3) { return optionPtr[2]; } if (len == 4) { return (optionPtr[2] << 8) + optionPtr[3]; } break; } optionPtr += len; } } return -1; } private byte* address; #endregion } private static unsafe byte* FindIPHeader(byte* frag, byte* fragEnd) { fragEnd -= 30; // // Only search out at most 50 bytes. if (&frag[50] < fragEnd) { fragEnd = &frag[50]; } byte* bestSoFar = null; while (frag < fragEnd) { if (*frag == 0x45) { // Compute the header checksum uint checkSum = 0; ushort* ptr = (ushort*)frag; for (int i = 0; i < 10; i++) { checkSum += *ptr++; } checkSum = (ushort)checkSum + (checkSum >> 16); if (checkSum == 0xFFFF) { return frag; } var ip = new IPHeader(frag); if (ip.CheckSum == 0 && bestSoFar == null) { bestSoFar = frag; } } frag++; } return bestSoFar; } internal PacketFragmentArgs(Action<PacketFragmentArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName, MicrosoftWindowsNDISPacketCaptureTraceEventParserState state) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; m_state = state; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != FragmentSize + 12)); Debug.Assert(!(Version > 0 && EventDataLength < FragmentSize + 12)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<PacketFragmentArgs>)value; } } public override unsafe StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "MiniportIfIndex", MiniportIfIndex); XmlAttrib(sb, "LowerIfIndex", LowerIfIndex); XmlAttrib(sb, "FragmentSize", FragmentSize).AppendLine(); XmlAttrib(sb, "ParsedPacket", ParsedPacket); string httpHeader = FindPrintableTcpStream(Fragment, FragmentSize, int.MaxValue); if (httpHeader != null) { sb.AppendLine(">"); sb.AppendLine(" <Printable>"); var printHttpHheader = " " + httpHeader.Replace("\n", "\n "); // indent it. sb.AppendLine(XmlUtilities.XmlEscape(printHttpHheader)); sb.AppendLine(" </Printable>"); sb.Append("</Event>"); } else { sb.Append("/>"); } return sb; } private unsafe string FindPrintableTcpStream(byte* fragment, int fragmentSize, int maxLength, bool oneLine = false) { if (fragmentSize < 16) { return null; } byte* fragmentEnd = fragment + fragmentSize; if (!IsPrintable(fragment, fragment + 16)) { byte* ipStart = FindIPHeader(fragment, fragmentEnd); if (ipStart == null) { return null; } IPHeader ip = new IPHeader(ipStart); if (ip.Protocol != 6) // TCP { return null; } TCPHeader tcp = new TCPHeader(ipStart + ip.IPHeaderSize); var streamStart = tcp.TCPHeaderSize + ip.IPHeaderSize + ipStart; if (fragmentEnd - streamStart < 16) { return null; } if (!IsPrintable(streamStart, streamStart + 16)) { return null; } fragment = streamStart; } StringBuilder sb = new StringBuilder(); if (maxLength < fragmentEnd - fragment) { fragmentEnd = fragment + maxLength; } // As this point the fragment points at printable characters. Keep going until it becomes unprintable while (fragment < fragmentEnd) { byte b = *fragment; if (!((byte)'\n' <= b && b < 128)) { break; } if (oneLine && (b == '\r' || b == '\n')) { break; } sb.Append((char)b); fragment++; } return sb.ToString(); } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "MiniportIfIndex", "LowerIfIndex", "FragmentSize", "ParsedPacket", "TcpStreamSample" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return MiniportIfIndex; case 1: return LowerIfIndex; case 2: return FragmentSize; case 3: return ParsedPacket; case 4: return TcpStreamSample; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<PacketFragmentArgs> m_target; protected override void SetState(object newState) { m_state = (MicrosoftWindowsNDISPacketCaptureTraceEventParserState)newState; } private MicrosoftWindowsNDISPacketCaptureTraceEventParserState m_state; #endregion } public sealed class PacketMetaDataArgs : TraceEvent { public int MiniportIfIndex { get { return GetInt32At(0); } } public int LowerIfIndex { get { return GetInt32At(4); } } public int MetadataSize { get { return GetInt32At(8); } } public unsafe byte* Metadata { get { return (byte*)DataStart + 12; } } #region Private internal PacketMetaDataArgs(Action<PacketMetaDataArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName, MicrosoftWindowsNDISPacketCaptureTraceEventParserState state) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { m_target = target; m_state = state; } protected override void Dispatch() { m_target(this); } protected override void Validate() { Debug.Assert(!(Version == 0 && EventDataLength != MetadataSize + 12)); Debug.Assert(!(Version > 0 && EventDataLength < MetadataSize + 12)); } protected override Delegate Target { get { return m_target; } set { m_target = (Action<PacketMetaDataArgs>)value; } } public override StringBuilder ToXml(StringBuilder sb) { Prefix(sb); XmlAttrib(sb, "MiniportIfIndex", MiniportIfIndex); XmlAttrib(sb, "LowerIfIndex", LowerIfIndex); XmlAttrib(sb, "MetadataSize", MetadataSize); sb.Append("/>"); return sb; } public override string[] PayloadNames { get { if (payloadNames == null) { payloadNames = new string[] { "MiniportIfIndex", "LowerIfIndex", "MetadataSize" }; } return payloadNames; } } public override object PayloadValue(int index) { switch (index) { case 0: return MiniportIfIndex; case 1: return LowerIfIndex; case 2: return MetadataSize; default: Debug.Assert(false, "Bad field index"); return null; } } private event Action<PacketMetaDataArgs> m_target; protected override void SetState(object newState) { m_state = (MicrosoftWindowsNDISPacketCaptureTraceEventParserState)newState; } private MicrosoftWindowsNDISPacketCaptureTraceEventParserState m_state; #endregion } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Linq; using System.Threading; using Cassandra.IntegrationTests.TestBase; namespace Cassandra.IntegrationTests.TestClusterManagement { public class CcmBridge : IDisposable { public DirectoryInfo CcmDir { get; private set; } public const int DefaultCmdTimeout = 90 * 1000; public string Name { get; private set; } public string IpPrefix { get; private set; } public CcmBridge(string name, string ipPrefix) { Name = name; IpPrefix = ipPrefix; CcmDir = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); } public void Dispose() { } public void Create(string version, bool useSsl) { var sslParams = ""; if (useSsl) { var sslPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "ssl"); if (!File.Exists(Path.Combine(sslPath, "keystore.jks"))) { throw new Exception(string.Format("In order to use SSL with CCM you must provide have the keystore.jks and cassandra.crt files located in your {0} folder", sslPath)); } sslParams = "--ssl " + sslPath; } ExecuteCcm(string.Format("create {0} -i {1} -v {2} {3}", Name, IpPrefix, version, sslParams)); } public void Start(string[] jvmArgs) { var parameters = new List<string> { "start", "--wait-for-binary-proto" }; if (TestUtils.IsWin) { parameters.Add("--quiet-windows"); } if (jvmArgs != null) { foreach (var arg in jvmArgs) { parameters.Add("--jvm_arg"); parameters.Add(arg); } } ExecuteCcm(string.Join(" ", parameters)); } public void Populate(int dc1NodeLength, int dc2NodeLength, bool useVNodes) { var parameters = new List<string> { "populate", "-n", dc1NodeLength + (dc2NodeLength > 0 ? ":" + dc2NodeLength : null) }; if (useVNodes) { parameters.Add("--vnodes"); } ExecuteCcm(string.Join(" ", parameters)); } public void SwitchToThis() { string switchCmd = "switch " + Name; ExecuteCcm(switchCmd, DefaultCmdTimeout, false); } public void List() { ExecuteCcm("list"); } public void Stop() { ExecuteCcm("stop"); } public void StopForce() { ExecuteCcm("stop --not-gently"); } public void Start(int n, string additionalArgs = null) { string quietWindows = null; if (TestUtils.IsWin) { quietWindows = "--quiet-windows"; } ExecuteCcm(string.Format("node{0} start --wait-for-binary-proto {1} {2}", n, additionalArgs, quietWindows)); } public void Stop(int n) { ExecuteCcm(string.Format("node{0} stop", n)); } public void StopForce(int n) { ExecuteCcm(string.Format("node{0} stop --not-gently", n)); } public void Remove() { ExecuteCcm("remove"); } public void BootstrapNode(int n) { BootstrapNode(n, null); } public void BootstrapNode(int n, string dc) { ExecuteCcm(string.Format("add node{0} -i {1}{2} -j {3} -b -s {4}", n, IpPrefix, n, 7000 + 100 * n, dc != null ? "-d " + dc : null)); Start(n); } public void DecommissionNode(int n) { ExecuteCcm(string.Format("node{0} decommission", n)); } public static ProcessOutput ExecuteCcm(string args, int timeout = DefaultCmdTimeout, bool throwOnProcessError = true) { var executable = "/usr/local/bin/ccm"; if (TestUtils.IsWin) { executable = "cmd.exe"; args = "/c ccm " + args; } Trace.TraceInformation(executable + " " + args); var output = ExecuteProcess(executable, args, timeout); if (throwOnProcessError) { ValidateOutput(output); } return output; } private static void ValidateOutput(ProcessOutput output) { if (output.ExitCode != 0) { throw new TestInfrastructureException(string.Format("Process exited in error {0}", output.ToString())); } } /// <summary> /// Spawns a new process (platform independent) /// </summary> public static ProcessOutput ExecuteProcess(string processName, string args, int timeout = DefaultCmdTimeout) { var output = new ProcessOutput(); using (var process = new Process()) { process.StartInfo.FileName = processName; process.StartInfo.Arguments = args; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; //Hide the python window if possible process.StartInfo.UseShellExecute = false; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.CreateNoWindow = true; using (var outputWaitHandle = new AutoResetEvent(false)) using (var errorWaitHandle = new AutoResetEvent(false)) { process.OutputDataReceived += (sender, e) => { if (e.Data == null) { try { outputWaitHandle.Set(); } catch { //probably is already disposed } } else { output.OutputText.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { try { errorWaitHandle.Set(); } catch { //probably is already disposed } } else { output.OutputText.AppendLine(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout)) { // Process completed. output.ExitCode = process.ExitCode; } else { // Timed out. output.ExitCode = -1; } } } return output; } } }
using System; using System.Reflection; using Orleans.GrainDirectory; using System.Linq; namespace Orleans { namespace Concurrency { /// <summary> /// The ReadOnly attribute is used to mark methods that do not modify the state of a grain. /// <para> /// Marking methods as ReadOnly allows the run-time system to perform a number of optimizations /// that may significantly improve the performance of your application. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Method)] internal sealed class ReadOnlyAttribute : Attribute { } /// <summary> /// The Reentrant attribute is used to mark grain implementation classes that allow request interleaving within a task. /// <para> /// This is an advanced feature and should not be used unless the implications are fully understood. /// That said, allowing request interleaving allows the run-time system to perform a number of optimizations /// that may significantly improve the performance of your application. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class ReentrantAttribute : Attribute { } /// <summary> /// The Unordered attribute is used to mark grain interface in which the delivery order of /// messages is not significant. /// </summary> [AttributeUsage(AttributeTargets.Interface)] public sealed class UnorderedAttribute : Attribute { } /// <summary> /// The StatelessWorker attribute is used to mark grain class in which there is no expectation /// of preservation of grain state between requests and where multiple activations of the same grain are allowed to be created by the runtime. /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class StatelessWorkerAttribute : Attribute { /// <summary> /// Maximal number of local StatelessWorkers in a single silo. /// </summary> public int MaxLocalWorkers { get; private set; } public StatelessWorkerAttribute(int maxLocalWorkers) { MaxLocalWorkers = maxLocalWorkers; } public StatelessWorkerAttribute() { MaxLocalWorkers = -1; } } /// <summary> /// The AlwaysInterleaveAttribute attribute is used to mark methods that can interleave with any other method type, including write (non ReadOnly) requests. /// </summary> /// <remarks> /// Note that this attribute is applied to method declaration in the grain interface, /// and not to the method in the implementation class itself. /// </remarks> [AttributeUsage(AttributeTargets.Method)] public sealed class AlwaysInterleaveAttribute : Attribute { } /// <summary> /// The Immutable attribute indicates that instances of the marked class or struct are never modified /// after they are created. /// </summary> /// <remarks> /// Note that this implies that sub-objects are also not modified after the instance is created. /// </remarks> [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class)] public sealed class ImmutableAttribute : Attribute { } } namespace MultiCluster { /// <summary> /// base class for multi cluster registration strategies. /// </summary> [AttributeUsage(AttributeTargets.Class)] public abstract class RegistrationAttribute : Attribute { internal MultiClusterRegistrationStrategy RegistrationStrategy { get; private set; } internal RegistrationAttribute(MultiClusterRegistrationStrategy strategy) { RegistrationStrategy = strategy ?? MultiClusterRegistrationStrategy.GetDefault(); } } /// <summary> /// This attribute indicates that instances of the marked grain class /// will have an independent instance for each cluster with /// no coordination. /// </summary> public class OneInstancePerClusterAttribute : RegistrationAttribute { public OneInstancePerClusterAttribute() : base(ClusterLocalRegistration.Singleton) { } } } namespace Placement { using Orleans.Runtime; /// <summary> /// Base for all placement policy marker attributes. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public abstract class PlacementAttribute : Attribute { internal PlacementStrategy PlacementStrategy { get; private set; } internal PlacementAttribute(PlacementStrategy placement) { PlacementStrategy = placement ?? PlacementStrategy.GetDefault(); } } /// <summary> /// Marks a grain class as using the <c>RandomPlacement</c> policy. /// </summary> /// <remarks> /// This is the default placement policy, so this attribute does not need to be used for normal grains. /// </remarks> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class RandomPlacementAttribute : PlacementAttribute { public RandomPlacementAttribute() : base(RandomPlacement.Singleton) { } } /// <summary> /// Marks a grain class as using the <c>PreferLocalPlacement</c> policy. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false) ] public sealed class PreferLocalPlacementAttribute : PlacementAttribute { public PreferLocalPlacementAttribute() : base(PreferLocalPlacement.Singleton) { } } /// <summary> /// Marks a grain class as using the <c>ActivationCountBasedPlacement</c> policy. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class ActivationCountBasedPlacementAttribute : PlacementAttribute { public ActivationCountBasedPlacementAttribute() : base(ActivationCountBasedPlacement.Singleton) { } } } namespace CodeGeneration { /// <summary> /// The TypeCodeOverrideAttribute attribute allows to specify the grain interface ID or the grain class type code /// to override the default ones to avoid hash collisions /// </summary> [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class)] public sealed class TypeCodeOverrideAttribute : Attribute { /// <summary> /// Use a specific grain interface ID or grain class type code (e.g. to avoid hash collisions) /// </summary> public int TypeCode { get; private set; } public TypeCodeOverrideAttribute(int typeCode) { TypeCode = typeCode; } } /// <summary> /// Used to mark a method as providing a copier function for that type. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class CopierMethodAttribute : Attribute { } /// <summary> /// Used to mark a method as providinga serializer function for that type. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class SerializerMethodAttribute : Attribute { } /// <summary> /// Used to mark a method as providing a deserializer function for that type. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class DeserializerMethodAttribute : Attribute { } /// <summary> /// Used to make a class for auto-registration as a serialization helper. /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class RegisterSerializerAttribute : Attribute { } } namespace Providers { /// <summary> /// The [Orleans.Providers.StorageProvider] attribute is used to define which storage provider to use for persistence of grain state. /// <para> /// Specifying [Orleans.Providers.StorageProvider] property is recommended for all grains which extend Grain&lt;T&gt;. /// If no [Orleans.Providers.StorageProvider] attribute is specified, then a "Default" strorage provider will be used. /// If a suitable storage provider cannot be located for this grain, then the grain will fail to load into the Silo. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class StorageProviderAttribute : Attribute { public StorageProviderAttribute() { ProviderName = Runtime.Constants.DEFAULT_STORAGE_PROVIDER_NAME; } /// <summary> /// The name of the storage provider to ne used for persisting state for this grain. /// </summary> public string ProviderName { get; set; } } } [AttributeUsage(AttributeTargets.Interface)] internal sealed class FactoryAttribute : Attribute { public enum FactoryTypes { Grain, ClientObject, Both }; private readonly FactoryTypes factoryType; public FactoryAttribute(FactoryTypes factoryType) { this.factoryType = factoryType; } internal static FactoryTypes CollectFactoryTypesSpecified(Type type) { var attribs = type.GetTypeInfo().GetCustomAttributes(typeof(FactoryAttribute), inherit: true).ToArray(); // if no attributes are specified, we default to FactoryTypes.Grain. if (0 == attribs.Length) return FactoryTypes.Grain; // otherwise, we'll consider all of them and aggregate the specifications // like flags. FactoryTypes? result = null; foreach (var i in attribs) { var a = (FactoryAttribute)i; if (result.HasValue) { if (a.factoryType == FactoryTypes.Both) result = a.factoryType; else if (a.factoryType != result.Value) result = FactoryTypes.Both; } else result = a.factoryType; } if (result.Value == FactoryTypes.Both) { throw new NotSupportedException( "Orleans doesn't currently support generating both a grain and a client object factory but we really want to!"); } return result.Value; } public static FactoryTypes CollectFactoryTypesSpecified<T>() { return CollectFactoryTypesSpecified(typeof(T)); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple=true)] public sealed class ImplicitStreamSubscriptionAttribute : Attribute { public string Namespace { get; private set; } // We have not yet come to an agreement whether the provider should be specified as well. public ImplicitStreamSubscriptionAttribute(string streamNamespace) { Namespace = streamNamespace; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Data.SqlTypes; using System.Globalization; using System.Text; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class SqlTypeTest { private static string[] s_sampleString = new string[] { "In", "its", "first", "month", "on", "the", "market,", "Microsoft\u2019s", "new", "search", "engine", "Bing", "Yahoo\u2019s", "Wednesday", "from", "tracker", "comScore", "8.4% of queries", "Earlier, Microsoft said that unique visitors to Bing", "rose 8% in June compared to the previous month. ", "The company also touted the search engine\u2019s success with advertisers, saying electronics", "retailer TigerDirect increased its marketing spend on", "Bing \u201Cby twofold.\u201D", "\u3072\u3089\u304C\u306A", "\u304B\u305F\u304B\u306A", "\u30AB\u30BF\u30AB\u30CA", "\uFF2C\uFF4F\uFF52\uFF45\uFF4D\u3000\uFF49\uFF50\uFF53\uFF55\uFF4D\u3000\uFF44\uFF4F\uFF4C\uFF4F\uFF52\u3000\uFF53\uFF49\uFF54\u3000\uFF41\uFF4D\uFF45\uFF54", "\uFF8C\uFF67\uFF7D\uFF9E\uFF65\uFF77\uFF9E\uFF80\uFF70", "\u30D5\u30A1\u30BA\u30FB\u30AE\u30BF\u30FC", "eNGine", new string(new char[] {'I', 'n', '\uD800', '\uDC00', 'z'}), // surrogate pair new string(new char[] {'\uD800', '\uDC00', '\uD800', '\uDCCC', '\uDBFF', '\uDFCC', '\uDBFF', '\uDFFF'}) // surrogate pairs }; private static string[,] s_specialMatchingString = new string[4, 2] {{"Lorem ipsum dolor sit amet", "\uFF2C\uFF4F\uFF52\uFF45\uFF4D\u3000\uFF49\uFF50\uFF53\uFF55\uFF4D\u3000\uFF44\uFF4F\uFF4C\uFF4F\uFF52\u3000\uFF53\uFF49\uFF54\u3000\uFF41\uFF4D\uFF45\uFF54"}, {"\u304B\u305F\u304B\u306A", "\u30AB\u30BF\u30AB\u30CA"}, {"\uFF8C\uFF67\uFF7D\uFF9E\uFF65\uFF77\uFF9E\uFF80\uFF70", "\u30D5\u30A1\u30BA\u30FB\u30AE\u30BF\u30FC"}, {"engine", "eNGine"}}; private static SqlCompareOptions s_defaultCompareOption = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth; private static SqlCompareOptions[] s_compareOptions = new SqlCompareOptions[] { SqlCompareOptions.None, SqlCompareOptions.BinarySort, SqlCompareOptions.BinarySort2, s_defaultCompareOption}; private static int s_sampleStringCount = s_sampleString.Length - 1; private static CultureInfo[] s_cultureInfo = { new CultureInfo("ar-SA"), // Arabic - Saudi Arabia new CultureInfo("ja-JP"), // Japanese - Japan new CultureInfo("de-DE"), // German - Germany new CultureInfo("hi-IN"), // Hindi - India new CultureInfo("tr-TR"), // Turkish - Turkey new CultureInfo("th-TH"), // Thai - Thailand new CultureInfo("el-GR"), // Greek - Greece new CultureInfo("ru-RU"), // Russian - Russia new CultureInfo("he-IL"), // Hebrew - Israel new CultureInfo("cs-CZ"), // Czech - Czech Republic new CultureInfo("fr-CH"), // French - Switzerland new CultureInfo("en-US") // English - United States }; private static int[] s_cultureLocaleIDs = { 0x0401, // Arabic - Saudi Arabia 0x0411, // Japanese - Japan 0x0407, // German - Germany 0x0439, // Hindi - India 0x041f, // Turkish - Turkey 0x041e, // Thai - Thailand 0x0408, // Greek - Greece 0x0419, // Russian - Russia 0x040d, // Hebrew - Israel 0x0405, // Czech - Czech Republic 0x100c, // French - Switzerland 0x0409 // English - United States }; private static UnicodeEncoding s_unicodeEncoding = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); [Fact] public static void SqlStringValidComparisonTest() { for (int j = 0; j < s_cultureInfo.Length; ++j) { SqlStringDefaultCompareOptionTest(s_cultureLocaleIDs[j]); for (int i = 0; i < s_compareOptions.Length; ++i) { SqlStringCompareTest(200, s_compareOptions[i], s_cultureInfo[j], s_cultureLocaleIDs[j]); } } } [Fact] public static void SqlStringNullComparisonTest() { SqlString nullSqlString = new SqlString(null); SqlString nonNullSqlString = new SqlString("abc "); Assert.True( (bool)(nullSqlString < nonNullSqlString || nonNullSqlString >= nullSqlString || nullSqlString.CompareTo(nonNullSqlString) < 0 || nonNullSqlString.CompareTo(nullSqlString) >= 0), "FAILED: (SqlString Null Comparison): Null SqlString not equal to null"); Assert.True((nullSqlString == null && nullSqlString.CompareTo(null) == 0).IsNull, "FAILED: (SqlString Null Comparison): Null SqlString not equal to null"); } // Special characters matching test for default option (SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth) private static void SqlStringDefaultCompareOptionTest(int localeID) { SqlString str1; SqlString str2; for (int i = 0; i < s_specialMatchingString.GetLength(0); ++i) { // SqlString(string) creates instance with the default comparison options str1 = new SqlString(s_specialMatchingString[i, 0], localeID); str2 = new SqlString(s_specialMatchingString[i, 1], localeID); // Per default option, each set contains two string which should be matched as equal per default option Assert.True((bool)(str1 == str2), string.Format("Error (Default Comparison Option with Operator): {0} and {1} should be equal", s_specialMatchingString[i, 0], s_specialMatchingString[i, 1])); Assert.True(str1.CompareTo(str2) == 0, string.Format("FAILED: (Default Comparison Option with CompareTo): {0} and {1} should be equal", s_specialMatchingString[i, 0], s_specialMatchingString[i, 1])); } } private static void SqlStringCompareTest(int numberOfItems, SqlCompareOptions compareOption, CultureInfo cInfo, int localeID) { SortedList<SqlString, SqlString> items = CreateSortedSqlStringList(numberOfItems, compareOption, cInfo, localeID); VerifySortedSqlStringList(items, compareOption, cInfo); } private static SortedList<SqlString, SqlString> CreateSortedSqlStringList(int numberOfItems, SqlCompareOptions compareOption, CultureInfo cInfo, int localeID) { SortedList<SqlString, SqlString> items = new SortedList<SqlString, SqlString>(numberOfItems); // // Generate list of SqlString // Random rand = new Random(500); int numberOfWords; StringBuilder builder = new StringBuilder(); SqlString word; for (int i = 0; i < numberOfItems; ++i) { do { builder.Clear(); numberOfWords = rand.Next(10) + 1; for (int j = 0; j < numberOfWords; ++j) { builder.Append(s_sampleString[rand.Next(s_sampleStringCount)]); builder.Append(" "); } if (numberOfWords % 2 == 1) { for (int k = 0; k < rand.Next(100); ++k) { builder.Append(' '); } } word = new SqlString(builder.ToString(), localeID, compareOption); } while (items.ContainsKey(word)); items.Add(word, word); } return items; } private static void VerifySortedSqlStringList(SortedList<SqlString, SqlString> items, SqlCompareOptions compareOption, CultureInfo cInfo) { // // Verify the list is in order // IList<SqlString> keyList = items.Keys; for (int i = 0; i < items.Count - 1; ++i) { SqlString currentString = keyList[i]; SqlString nextString = keyList[i + 1]; Assert.True((bool)((currentString < nextString) && (nextString >= currentString)), "FAILED: (SqlString Operator Comparison): SqlStrings are out of order"); Assert.True((currentString.CompareTo(nextString) < 0) && (nextString.CompareTo(currentString) > 0), "FAILED: (SqlString.CompareTo): SqlStrings are out of order"); switch (compareOption) { case SqlCompareOptions.BinarySort: Assert.True(CompareBinary(currentString.Value, nextString.Value) < 0, "FAILED: (SqlString BinarySort Comparison): SqlStrings are out of order"); break; case SqlCompareOptions.BinarySort2: Assert.True(string.CompareOrdinal(currentString.Value.TrimEnd(), nextString.Value.TrimEnd()) < 0, "FAILED: (SqlString BinarySort2 Comparison): SqlStrings are out of order"); break; default: CompareInfo cmpInfo = cInfo.CompareInfo; CompareOptions cmpOptions = SqlString.CompareOptionsFromSqlCompareOptions(nextString.SqlCompareOptions); Assert.True(cmpInfo.Compare(currentString.Value.TrimEnd(), nextString.Value.TrimEnd(), cmpOptions) < 0, "FAILED: (SqlString Comparison): SqlStrings are out of order"); break; } } } // Wide-character string comparison for Binary Unicode Collation (for SqlCompareOptions.BinarySort) // Return values: // -1 : wstr1 < wstr2 // 0 : wstr1 = wstr2 // 1 : wstr1 > wstr2 // // Does a memory comparison. // NOTE: This comparison algorightm is different from BinraySory2. The algorithm is copied fro SqlString implementation private static int CompareBinary(string x, string y) { byte[] rgDataX = s_unicodeEncoding.GetBytes(x); byte[] rgDataY = s_unicodeEncoding.GetBytes(y); int cbX = rgDataX.Length; int cbY = rgDataY.Length; int cbMin = cbX < cbY ? cbX : cbY; int i; for (i = 0; i < cbMin; i++) { if (rgDataX[i] < rgDataY[i]) return -1; else if (rgDataX[i] > rgDataY[i]) return 1; } i = cbMin; int iCh; int iSpace = (int)' '; if (cbX < cbY) { for (; i < cbY; i += 2) { iCh = ((int)rgDataY[i + 1]) << 8 + rgDataY[i]; if (iCh != iSpace) return (iSpace > iCh) ? 1 : -1; } } else { for (; i < cbX; i += 2) { iCh = ((int)rgDataX[i + 1]) << 8 + rgDataX[i]; if (iCh != iSpace) return (iCh > iSpace) ? 1 : -1; } } return 0; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using QuantConnect.Orders.Fills; using QuantConnect.Securities; using static QuantConnect.StringExtensions; namespace QuantConnect.Orders.Fees { /// <summary> /// Provides the default implementation of <see cref="IFeeModel"/> /// </summary> public class InteractiveBrokersFeeModel : FeeModel { private readonly decimal _forexCommissionRate; private readonly decimal _forexMinimumOrderFee; // option commission function takes number of contracts and the size of the option premium and returns total commission private readonly Dictionary<string, Func<decimal, decimal, CashAmount>> _optionFee = new Dictionary<string, Func<decimal, decimal, CashAmount>>(); private readonly Dictionary<string, CashAmount> _futureFee = // IB fee + exchange fee new Dictionary<string, CashAmount> { { Market.USA, new CashAmount(0.85m + 1, "USD") } }; /// <summary> /// Initializes a new instance of the <see cref="ImmediateFillModel"/> /// </summary> /// <param name="monthlyForexTradeAmountInUSDollars">Monthly FX dollar volume traded</param> /// <param name="monthlyOptionsTradeAmountInContracts">Monthly options contracts traded</param> public InteractiveBrokersFeeModel(decimal monthlyForexTradeAmountInUSDollars = 0, decimal monthlyOptionsTradeAmountInContracts = 0) { ProcessForexRateSchedule(monthlyForexTradeAmountInUSDollars, out _forexCommissionRate, out _forexMinimumOrderFee); Func<decimal, decimal, CashAmount> optionsCommissionFunc; ProcessOptionsRateSchedule(monthlyOptionsTradeAmountInContracts, out optionsCommissionFunc); // only USA for now _optionFee.Add(Market.USA, optionsCommissionFunc); } /// <summary> /// Gets the order fee associated with the specified order. This returns the cost /// of the transaction in the account currency /// </summary> /// <param name="parameters">A <see cref="OrderFeeParameters"/> object /// containing the security and order</param> /// <returns>The cost of the order in units of the account currency</returns> public override OrderFee GetOrderFee(OrderFeeParameters parameters) { var order = parameters.Order; var security = parameters.Security; // Option exercise for equity options is free of charge if (order.Type == OrderType.OptionExercise) { var optionOrder = (OptionExerciseOrder)order; // For Futures Options, contracts are charged the standard commission at expiration of the contract. // Read more here: https://www1.interactivebrokers.com/en/index.php?f=14718#trading-related-fees if (optionOrder.Symbol.ID.SecurityType == SecurityType.Option) { return OrderFee.Zero; } } decimal feeResult; string feeCurrency; var market = security.Symbol.ID.Market; switch (security.Type) { case SecurityType.Forex: // get the total order value in the account currency var totalOrderValue = order.GetValue(security); var fee = Math.Abs(_forexCommissionRate*totalOrderValue); feeResult = Math.Max(_forexMinimumOrderFee, fee); // IB Forex fees are all in USD feeCurrency = Currencies.USD; break; case SecurityType.Option: case SecurityType.IndexOption: Func<decimal, decimal, CashAmount> optionsCommissionFunc; if (!_optionFee.TryGetValue(market, out optionsCommissionFunc)) { throw new KeyNotFoundException($"InteractiveBrokersFeeModel(): unexpected option Market {market}"); } // applying commission function to the order var optionFee = optionsCommissionFunc(order.AbsoluteQuantity, order.Price); feeResult = optionFee.Amount; feeCurrency = optionFee.Currency; break; case SecurityType.Future: case SecurityType.FutureOption: // The futures options fee model is exactly the same as futures' fees on IB. if (market == Market.Globex || market == Market.NYMEX || market == Market.CBOT || market == Market.ICE || market == Market.CFE || market == Market.COMEX || market == Market.CME) { // just in case... market = Market.USA; } CashAmount feeRatePerContract; if (!_futureFee.TryGetValue(market, out feeRatePerContract)) { throw new KeyNotFoundException($"InteractiveBrokersFeeModel(): unexpected future Market {market}"); } feeResult = order.AbsoluteQuantity * feeRatePerContract.Amount; feeCurrency = feeRatePerContract.Currency; break; case SecurityType.Equity: EquityFee equityFee; switch (market) { case Market.USA: equityFee = new EquityFee("USD", feePerShare: 0.005m, minimumFee: 1, maximumFeeRate: 0.005m); break; default: throw new KeyNotFoundException($"InteractiveBrokersFeeModel(): unexpected equity Market {market}"); } var tradeValue = Math.Abs(order.GetValue(security)); //Per share fees var tradeFee = equityFee.FeePerShare * order.AbsoluteQuantity; //Maximum Per Order: equityFee.MaximumFeeRate //Minimum per order. $equityFee.MinimumFee var maximumPerOrder = equityFee.MaximumFeeRate * tradeValue; if (tradeFee < equityFee.MinimumFee) { tradeFee = equityFee.MinimumFee; } else if (tradeFee > maximumPerOrder) { tradeFee = maximumPerOrder; } feeCurrency = equityFee.Currency; //Always return a positive fee. feeResult = Math.Abs(tradeFee); break; default: // unsupported security type throw new ArgumentException(Invariant($"Unsupported security type: {security.Type}")); } return new OrderFee(new CashAmount( feeResult, feeCurrency)); } /// <summary> /// Determines which tier an account falls into based on the monthly trading volume /// </summary> private static void ProcessForexRateSchedule(decimal monthlyForexTradeAmountInUSDollars, out decimal commissionRate, out decimal minimumOrderFee) { const decimal bp = 0.0001m; if (monthlyForexTradeAmountInUSDollars <= 1000000000) // 1 billion { commissionRate = 0.20m * bp; minimumOrderFee = 2.00m; } else if (monthlyForexTradeAmountInUSDollars <= 2000000000) // 2 billion { commissionRate = 0.15m * bp; minimumOrderFee = 1.50m; } else if (monthlyForexTradeAmountInUSDollars <= 5000000000) // 5 billion { commissionRate = 0.10m * bp; minimumOrderFee = 1.25m; } else { commissionRate = 0.08m * bp; minimumOrderFee = 1.00m; } } /// <summary> /// Determines which tier an account falls into based on the monthly trading volume /// </summary> private static void ProcessOptionsRateSchedule(decimal monthlyOptionsTradeAmountInContracts, out Func<decimal, decimal, CashAmount> optionsCommissionFunc) { if (monthlyOptionsTradeAmountInContracts <= 10000) { optionsCommissionFunc = (orderSize, premium) => { var commissionRate = premium >= 0.1m ? 0.7m : (0.05m <= premium && premium < 0.1m ? 0.5m : 0.25m); return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD); }; } else if (monthlyOptionsTradeAmountInContracts <= 50000) { optionsCommissionFunc = (orderSize, premium) => { var commissionRate = premium >= 0.05m ? 0.5m : 0.25m; return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD); }; } else if (monthlyOptionsTradeAmountInContracts <= 100000) { optionsCommissionFunc = (orderSize, premium) => { var commissionRate = 0.25m; return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD); }; } else { optionsCommissionFunc = (orderSize, premium) => { var commissionRate = 0.15m; return new CashAmount(Math.Max(orderSize * commissionRate, 1.0m), Currencies.USD); }; } } /// <summary> /// Helper class to handle IB Equity fees /// </summary> private class EquityFee { public string Currency { get; } public decimal FeePerShare { get; } public decimal MinimumFee { get; } public decimal MaximumFeeRate { get; } public EquityFee(string currency, decimal feePerShare, decimal minimumFee, decimal maximumFeeRate) { Currency = currency; FeePerShare = feePerShare; MinimumFee = minimumFee; MaximumFeeRate = maximumFeeRate; } } } }
using IglooCastle.Core; using IglooCastle.Core.Elements; using IglooCastle.Core.Printers; using IglooCastle.Demo; using IglooCastle.Samples; using NUnit.Framework; using System; namespace IglooCastle.Tests { [TestFixture] public class TypeElementTest : TestBase { [Test] public void TestName() { var typeElement = Documentation.Find(typeof(TypeElement)); Assert.IsNotNull(typeElement); Assert.AreEqual("TypeElement", typeElement.Name); } [Test] public void TestNameOfGenericDefinition() { var typeElement = Documentation.Find(typeof(DocumentationElement<>)); Assert.AreEqual("DocumentationElement`1", typeElement.Name); } [Test] public void TestShortNameGenericDefinition() { var typeElement = Documentation.Find(typeof(DocumentationElement<>)); Assert.AreEqual("DocumentationElement&lt;TMember&gt;", typeElement.ToString("s")); } [Test] public void TestFullNameGenericDefinition() { var typeElement = Documentation.Find(typeof(DocumentationElement<>)); Assert.AreEqual("IglooCastle.Core.Elements.DocumentationElement&lt;TMember&gt;", typeElement.ToString("f")); } [Test] public void TestShortNameNestedClass() { var typeElement = Documentation.Find(typeof(Sample.NestedSample)); Assert.AreEqual("Sample.NestedSample", typeElement.ToString("s")); } [Test] public void TestShortNameSecondLevelNestedClass() { var typeElement = Documentation.Find(typeof(Sample.NestedSample.SecondLevelNest)); Assert.AreEqual("Sample.NestedSample.SecondLevelNest", typeElement.ToString("s")); } [Test] public void TestFullNameSecondLevelNestedClass() { var typeElement = Documentation.Find(typeof(Sample.NestedSample.SecondLevelNest)); Assert.AreEqual( "IglooCastle.Samples.Sample.NestedSample.SecondLevelNest", typeElement.ToString("f")); } [Test] public void TestHtmlSystemString() { const string expected = "<a href=\"http://msdn.microsoft.com/en-us/library/system.string%28v=vs.110%29.aspx\">string</a>"; Assert.AreEqual(expected, Documentation.Find(typeof(string)).ToHtml()); } [Test] public void TestHtmlSystemType() { const string expected = "<a href=\"http://msdn.microsoft.com/en-us/library/system.type%28v=vs.110%29.aspx\">Type</a>"; Assert.AreEqual(expected, Documentation.Find(typeof(Type)).ToHtml()); } [Test] public void TestHtmlSystemObjectByRef() { const string expected = "<a href=\"http://msdn.microsoft.com/en-us/library/system.object%28v=vs.110%29.aspx\">object</a>"; Assert.AreEqual(expected, Documentation.Find(typeof(object).MakeByRefType()).ToHtml()); } [Test] public void TestHtml_GenericContainerIsNotLocalType_GenericArgumentIsLocalType() { // public ICollection<PropertyElement> Properties const string expected = "System.Collections.Generic.ICollection&lt;" + "<a href=\"T_IglooCastle.Core.Elements.PropertyElement.html\">PropertyElement</a>" + "&gt;"; TypeElement targetTypeElement = Documentation.Find(typeof(TypeElement)); PropertyElement targetProperty = targetTypeElement.GetProperty("Properties"); Assert.AreEqual(expected, targetProperty.PropertyType.ToHtml()); } [Test] public void TestHtmlArray() { const string expected = "<a href=\"T_IglooCastle.Core.Elements.NamespaceElement.html\">NamespaceElement</a>[]"; Assert.AreEqual(expected, Documentation.Find(typeof(NamespaceElement[])).ToHtml()); } [Test] public void TestHtmlGenericArgument() { const string expected = "TMember"; TypeElement targetTypeElement = Documentation.Find(typeof(DocumentationElement<>)); PropertyElement targetProperty = targetTypeElement.GetProperty("Member"); Assert.AreEqual(expected, targetProperty.PropertyType.ToHtml()); } [Test] public void TestHtmlNestedClass() { const string expected = "<a href=\"T_IglooCastle.Demo.NestingDemo+NestedDemo.html\">NestingDemo.NestedDemo</a>"; Assert.AreEqual(expected, Documentation.Find(typeof(NestingDemo.NestedDemo)).ToHtml()); } [Test] public void TestHtmlGenericTypeDefinition() { const string expected = "<a href=\"T_IglooCastle.Core.Elements.MethodBaseElement%601.html\">MethodBaseElement</a>&lt;T&gt;"; Assert.AreEqual(expected, Documentation.Find(typeof(MethodBaseElement<>)).ToHtml()); } [Test] public void TestHtmlCompleteGenericType() { const string expected = "<a href=\"T_IglooCastle.Core.Elements.DocumentationElement%601.html\">DocumentationElement</a>&lt;" + "<a href=\"T_IglooCastle.Core.Elements.PropertyElement.html\">PropertyElement</a>" + "&gt;"; Assert.AreEqual(expected, Documentation.Find(typeof(DocumentationElement<PropertyElement>)).ToHtml()); } [Test] public void TestSyntaxWithLinksClass() { const string expected = "public class Documentation : <a href=\"T_IglooCastle.Core.Elements.ITypeContainer.html\">ITypeContainer</a>"; Assert.AreEqual(expected, Documentation.Find(typeof(Documentation)).ToSyntax()); } [Test] public void TestSyntaxWithLinksInterface() { const string expected = "public interface ITypeContainer"; Assert.AreEqual(expected, Documentation.Find(typeof(ITypeContainer)).ToSyntax()); } [Test] public void TestSyntaxWithLinksStaticClass() { const string expected = "public static class XmlCommentExtensions"; Assert.AreEqual(expected, Documentation.Find(typeof(XmlCommentExtensions)).ToSyntax()); } [Test] public void TestSyntaxWithLinksSealedClass() { const string expected = "public sealed class FilenameProvider"; Assert.AreEqual(expected, Documentation.Find(typeof(FilenameProvider)).ToSyntax()); } [Test] public void TestSyntaxWithLinksAbstractClass() { string actual = Documentation.Find(typeof(DocumentationElement<>)).ToSyntax(); StringAssert.Contains("public abstract class DocumentationElement&lt;TMember&gt; : <a", actual); StringAssert.Contains("<a href=\"T_IglooCastle.Core.Elements.IDocumentationElement.html\">IDocumentationElement</a>", actual); } [Test] public void TestSyntaxWithLinksDerivedClass() { string actual = Documentation.Find(typeof(TypeElement)).ToSyntax(); StringAssert.Contains("public class TypeElement : <a", actual); StringAssert.Contains("<a href=\"T_IglooCastle.Core.Elements.ReflectedElement%601.html\">ReflectedElement</a>&lt;<a href=\"http://msdn.microsoft.com/en-us/library/system.type%28v=vs.110%29.aspx\">Type</a>&gt;", actual); StringAssert.Contains("<a href=\"T_IglooCastle.Core.Elements.IDocumentationElement.html\">IDocumentationElement</a>", actual); } [Test] public void TestSyntaxCovariance() { const string expected = "public interface IVariance&lt;in T1, out T2&gt;"; Assert.AreEqual(expected, Documentation.Find(typeof(IVariance<,>)).ToSyntax()); } [Test] public void TestSyntaxWithLinksAnnotatedDemo() { const string expected = "[<a href=\"T_IglooCastle.Demo.DemoAttribute.html\">Demo</a>] public class AnnotatedDemo"; Assert.AreEqual(expected, Documentation.Find(typeof(AnnotatedDemo)).ToSyntax()); } [Test] public void TestGetDescendantTypes() { var typeElement = Documentation.Find(typeof(DocumentationElement<>)); var result = typeElement.GetDescendantTypes(); Assert.IsNotNull(result); CollectionAssert.AreEquivalent(new TypeElement[] { Documentation.Find(typeof(AttributeElement)), Documentation.Find(typeof(ConstructorElement)), Documentation.Find(typeof(CustomAttributeDataElement)), Documentation.Find(typeof(EnumMemberElement)), Documentation.Find(typeof(MethodBaseElement<>)), Documentation.Find(typeof(MethodElement)), Documentation.Find(typeof(NamespaceElement)), Documentation.Find(typeof(ParameterInfoElement)), Documentation.Find(typeof(PropertyElement)), Documentation.Find(typeof(ReflectedElement<>)), Documentation.Find(typeof(TypeElement)), Documentation.Find(typeof(TypeMemberElement<>)), }, result); } [Test] public void TestGetChildTypes() { var typeElement = Documentation.Find(typeof(DocumentationElement<>)); var result = typeElement.GetChildTypes(); Assert.IsNotNull(result); CollectionAssert.AreEquivalent(new TypeElement[] { Documentation.Find(typeof(AttributeElement)), Documentation.Find(typeof(CustomAttributeDataElement)), Documentation.Find(typeof(NamespaceElement)), Documentation.Find(typeof(ParameterInfoElement)), Documentation.Find(typeof(ReflectedElement<>)), }, result); } [Test] public void TestSyntaxOfStruct() { var typeElement = Documentation.Find(typeof(DemoStruct)); Assert.AreEqual("public struct DemoStruct", typeElement.ToSyntax()); } } }
//----------------------------------------------------------------------- // <copyright file="TangoARScreen.cs" company="Google"> // // Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System.Collections; using Tango; using UnityEngine; /// <summary> /// TangoARScreen takes the YUV image from the API, resize the image plane and passes /// the YUV data and vertices data to the YUV2RGB shader to produce a properly /// sized RGBA image. /// /// Please note that all the YUV to RGB conversion is done through the YUV2RGB /// shader, no computation is in this class, this class only passes the data to /// shader. /// </summary> [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public class TangoARScreen : MonoBehaviour, ITangoLifecycle, IExperimentalTangoVideoOverlay { /// <summary> /// If set, m_updatePointsMesh in PointCloud also gets set. Then PointCloud material's renderqueue is set to /// background-1 so that PointCloud data gets written to Z buffer for Depth test with virtual /// objects in scene. Note 1: This is a very rudimentary way of doing occlusion and limited by the capabilities of /// depth camera. Note 2: To enable occlusion TangoPointCloud prefab must be present in the scene as well. /// </summary> public bool m_enableOcclusion; /// <summary> /// Set this to the AR Screen material. /// </summary> public Material m_screenMaterial; /// <summary> /// The most recent time (in seconds) the screen was updated. /// </summary> [HideInInspector] public double m_screenUpdateTime; /// <summary> /// The Background renderqueue's number. /// </summary> private const int BACKGROUND_RENDER_QUEUE = 1000; /// <summary> /// Point size of PointCloud data when projected on to image plane. /// </summary> private const int POINTCLOUD_SPLATTER_UPSAMPLE_SIZE = 30; /// <summary> /// Script that manages the postprocess distortiotn of the camera image. /// </summary> private ARCameraPostProcess m_arCameraPostProcess; /// <summary> /// U texture coordinate amount that the color camera image is being clipped on each side. /// /// Ranges from 0 (no clipping) to 0.5 (full clipping). /// </summary> private float m_uOffset; /// <summary> /// V texture coordinate amount that the color camera image is being clipped on each side. /// /// Ranges from 0 (no clipping) to 0.5 (full clipping). /// </summary> private float m_vOffset; /// <summary> /// Converts a normalized Unity viewport position into its corresponding normalized position on the color camera /// image. /// </summary> /// <returns>Normalized position for the color camera.</returns> /// <param name="pos">Normalized position for the 3D viewport.</param> public Vector2 ViewportPointToCameraImagePoint(Vector2 pos) { return new Vector2(Mathf.Lerp(m_uOffset, 1 - m_uOffset, pos.x), Mathf.Lerp(m_vOffset, 1 - m_vOffset, pos.y)); } /// <summary> /// Converts a color camera position into its corresponding normalized Unity viewport position. /// image. /// </summary> /// <returns>Normalized position for the color camera.</returns> /// <param name="pos">Normalized position for the 3D viewport.</param> public Vector2 CameraImagePointToViewportPoint(Vector2 pos) { return new Vector2((pos.x - m_uOffset) / (1 - (2 * m_uOffset)), (pos.y - m_vOffset) / (1 - (2 * m_vOffset))); } /// @cond /// <summary> /// Initialize the AR Screen. /// </summary> public void Start() { TangoApplication tangoApplication = FindObjectOfType<TangoApplication>(); m_arCameraPostProcess = gameObject.GetComponent<ARCameraPostProcess>(); if (tangoApplication != null) { tangoApplication.Register(this); // If already connected to a service, then do initialization now. if (tangoApplication.IsServiceConnected) { OnTangoServiceConnected(); } // Pass YUV textures to shader for process. YUVTexture textures = tangoApplication.GetVideoOverlayTextureYUV(); m_screenMaterial.SetTexture("_YTex", textures.m_videoOverlayTextureY); m_screenMaterial.SetTexture("_UTex", textures.m_videoOverlayTextureCb); m_screenMaterial.SetTexture("_VTex", textures.m_videoOverlayTextureCr); } if (m_enableOcclusion) { TangoPointCloud pointCloud = FindObjectOfType<TangoPointCloud>(); if (pointCloud != null) { Renderer renderer = pointCloud.GetComponent<Renderer>(); renderer.enabled = true; // Set the renderpass as background renderqueue's number minus one. YUV2RGB shader executes in // Background queue which is 1000. // But since we want to write depth data to Z buffer before YUV2RGB shader executes so that YUV2RGB // data ignores Ztest from the depth data we set renderqueue of PointCloud as 999. renderer.material.renderQueue = BACKGROUND_RENDER_QUEUE - 1; renderer.material.SetFloat("point_size", POINTCLOUD_SPLATTER_UPSAMPLE_SIZE); pointCloud.m_updatePointsMesh = true; } else { Debug.Log("Point Cloud data is not available, occlusion is not possible."); } } } /// <summary> /// This is called when the permission granting process is finished. /// </summary> /// <param name="permissionsGranted"><c>true</c> if permissions were granted, otherwise <c>false</c>.</param> public void OnTangoPermissions(bool permissionsGranted) { } /// <summary> /// This is called when succesfully connected to the Tango service. /// </summary> public void OnTangoServiceConnected() { // Set up the size of ARScreen based on camera intrinsics. TangoCameraIntrinsics intrinsics = new TangoCameraIntrinsics(); VideoOverlayProvider.GetIntrinsics(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, intrinsics); if (intrinsics.width != 0 && intrinsics.height != 0) { Camera camera = GetComponent<Camera>(); if (camera != null) { // If this script is attached to a camera, then the camera is an Augmented Reality camera. The color // camera image then must fill the viewport. That means we must clip the color camera image to make // its ratio the same as the Unity camera. If we don't do this the color camera image will be // stretched non-uniformly, making a circle into an ellipse. float widthRatio = (float)camera.pixelWidth / (float)intrinsics.width; float heightRatio = (float)camera.pixelHeight / (float)intrinsics.height; if (widthRatio >= heightRatio) { m_uOffset = 0; m_vOffset = (1 - (heightRatio / widthRatio)) / 2; } else { m_uOffset = (1 - (widthRatio / heightRatio)) / 2; m_vOffset = 0; } m_arCameraPostProcess.SetupIntrinsic(intrinsics); _MeshUpdateForIntrinsics(GetComponent<MeshFilter>().mesh, m_uOffset, m_vOffset); _CameraUpdateForIntrinsics(camera, intrinsics, m_uOffset, m_vOffset); } } else { m_uOffset = 0; m_vOffset = 0; m_arCameraPostProcess.enabled = false; } } /// <summary> /// This is called when disconnected from the Tango service. /// </summary> public void OnTangoServiceDisconnected() { } /// <summary> /// This will be called when a new frame is available from the camera. /// /// The first scan-line of the color image is reserved for metadata instead of image pixels. /// </summary> /// <param name="cameraId">Camera identifier.</param> public void OnExperimentalTangoImageAvailable(TangoEnums.TangoCameraId cameraId) { if (cameraId == TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR) { m_screenUpdateTime = VideoOverlayProvider.RenderLatestFrame(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR); // Rendering the latest frame changes a bunch of OpenGL state. Ensure Unity knows the current OpenGL state. GL.InvalidateState(); } } /// @endcond /// <summary> /// Update a mesh so it can be used for the Video Overlay image plane. /// /// The image plane is drawn without any projection or view matrix transforms, so it must line up exactly with /// normalized screen space. The texture coordinates of the mesh are adjusted so it properly clips the image /// plane. /// </summary> /// <param name="mesh">Mesh to update.</param> /// <param name="uOffset">U texture coordinate clipping.</param> /// <param name="vOffset">V texture coordinate clipping.</param> private static void _MeshUpdateForIntrinsics(Mesh mesh, float uOffset, float vOffset) { // Set the vertices base on the offset, note that the offset is used to compensate // the ratio differences between the camera image and device screen. Vector3[] verts = new Vector3[4]; verts[0] = new Vector3(-1, -1, 1); verts[1] = new Vector3(-1, +1, 1); verts[2] = new Vector3(+1, +1, 1); verts[3] = new Vector3(+1, -1, 1); // Set indices. int[] indices = new int[6]; indices[0] = 0; indices[1] = 2; indices[2] = 3; indices[3] = 1; indices[4] = 2; indices[5] = 0; // Set UVs. Vector2[] uvs = new Vector2[4]; uvs[0] = new Vector2(0 + uOffset, 0 + vOffset); uvs[1] = new Vector2(0 + uOffset, 1 - vOffset); uvs[2] = new Vector2(1 - uOffset, 1 - vOffset); uvs[3] = new Vector2(1 - uOffset, 0 + vOffset); mesh.Clear(); mesh.vertices = verts; mesh.triangles = indices; mesh.uv = uvs; // Make this mesh never fail the occlusion cull mesh.bounds = new Bounds(Vector3.zero, new Vector3(float.MaxValue, float.MaxValue, float.MaxValue)); } /// <summary> /// Update a camera so its perspective lines up with the color camera's perspective. /// </summary> /// <param name="cam">Camera to update.</param> /// <param name="intrinsics">Tango camera intrinsics for the color camera.</param> /// <param name="uOffset">U texture coordinate clipping.</param> /// <param name="vOffset">V texture coordinate clipping.</param> private static void _CameraUpdateForIntrinsics(Camera cam, TangoCameraIntrinsics intrinsics, float uOffset, float vOffset) { float cx = (float)intrinsics.cx; float cy = (float)intrinsics.cy; float width = (float)intrinsics.width; float height = (float)intrinsics.height; float xscale = cam.nearClipPlane / (float)intrinsics.fx; float yscale = cam.nearClipPlane / (float)intrinsics.fy; float pixelLeft = -cx + (uOffset * width); float pixelRight = width - cx - (uOffset * width); // OpenGL coordinates has y pointing downwards so we negate this term. float pixelBottom = -height + cy + (vOffset * height); float pixelTop = cy - (vOffset * height); cam.projectionMatrix = _Frustum(pixelLeft * xscale, pixelRight * xscale, pixelBottom * yscale, pixelTop * yscale, cam.nearClipPlane, cam.farClipPlane); } /// <summary> /// Compute a projection matrix for a frustum. /// /// This function's implementation is same as glFrustum. /// </summary> /// <returns>Projection matrix.</returns> /// <param name="left">Specify the coordinates for the left vertical clipping planes.</param> /// <param name="right">Specify the coordinates for the right vertical clipping planes.</param> /// <param name="bottom">Specify the coordinates for the bottom horizontal clipping planes.</param> /// <param name="top">Specify the coordinates for the top horizontal clipping planes.</param> /// <param name="zNear">Specify the distances to the near depth clipping planes. Both distances must be positive.</param> /// <param name="zFar">Specify the distances to the far depth clipping planes. Both distances must be positive.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "*", Justification = "Matrix visibility is more important.")] private static Matrix4x4 _Frustum(float left, float right, float bottom, float top, float zNear, float zFar) { Matrix4x4 m = new Matrix4x4(); m.SetRow(0, new Vector4(2.0f * zNear / (right - left), 0.0f, (right + left) / (right - left) , 0.0f)); m.SetRow(1, new Vector4(0.0f, 2.0f * zNear / (top - bottom), (top + bottom) / (top - bottom) , 0.0f)); m.SetRow(2, new Vector4(0.0f, 0.0f, -(zFar + zNear) / (zFar - zNear), -(2 * zFar * zNear) / (zFar - zNear))); m.SetRow(3, new Vector4(0.0f, 0.0f, -1.0f, 0.0f)); return m; } }
// ------------------------------------------------------------------------ // ======================================================================== // THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR // ======================================================================== // Template: ViewModel.tt using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Input; using Controls=WPAppStudio.Controls; using Entities=WPAppStudio.Entities; using EntitiesBase=WPAppStudio.Entities.Base; using IServices=WPAppStudio.Services.Interfaces; using IViewModels=WPAppStudio.ViewModel.Interfaces; using Localization=WPAppStudio.Localization; using Repositories=WPAppStudio.Repositories; using Services=WPAppStudio.Services; using ViewModelsBase=WPAppStudio.ViewModel.Base; using WPAppStudio; using WPAppStudio.Shared; namespace WPAppStudio.ViewModel { /// <summary> /// Implementation of moments_Detail ViewModel. /// </summary> [CompilerGenerated] [GeneratedCode("Radarc", "4.0")] public partial class moments_DetailViewModel : ViewModelsBase.VMBase, IViewModels.Imoments_DetailViewModel, ViewModelsBase.INavigable { private readonly Repositories.moments_momentsCollection _moments_momentsCollection; private readonly IServices.IDialogService _dialogService; private readonly IServices.INavigationService _navigationService; private readonly IServices.ISpeechService _speechService; private readonly IServices.IShareService _shareService; private readonly IServices.ILiveTileService _liveTileService; /// <summary> /// Initializes a new instance of the <see cref="moments_DetailViewModel" /> class. /// </summary> /// <param name="moments_momentsCollection">The Moments_moments Collection.</param> /// <param name="dialogService">The Dialog Service.</param> /// <param name="navigationService">The Navigation Service.</param> /// <param name="speechService">The Speech Service.</param> /// <param name="shareService">The Share Service.</param> /// <param name="liveTileService">The Live Tile Service.</param> public moments_DetailViewModel(Repositories.moments_momentsCollection moments_momentsCollection, IServices.IDialogService dialogService, IServices.INavigationService navigationService, IServices.ISpeechService speechService, IServices.IShareService shareService, IServices.ILiveTileService liveTileService) { _moments_momentsCollection = moments_momentsCollection; _dialogService = dialogService; _navigationService = navigationService; _speechService = speechService; _shareService = shareService; _liveTileService = liveTileService; } private Entities.momentsSchema _currentmomentsSchema; /// <summary> /// CurrentmomentsSchema property. /// </summary> public Entities.momentsSchema CurrentmomentsSchema { get { return _currentmomentsSchema; } set { SetProperty(ref _currentmomentsSchema, value); } } private bool _hasNextpanoramamoments_Detail0; /// <summary> /// HasNextpanoramamoments_Detail0 property. /// </summary> public bool HasNextpanoramamoments_Detail0 { get { return _hasNextpanoramamoments_Detail0; } set { SetProperty(ref _hasNextpanoramamoments_Detail0, value); } } private bool _hasPreviouspanoramamoments_Detail0; /// <summary> /// HasPreviouspanoramamoments_Detail0 property. /// </summary> public bool HasPreviouspanoramamoments_Detail0 { get { return _hasPreviouspanoramamoments_Detail0; } set { SetProperty(ref _hasPreviouspanoramamoments_Detail0, value); } } /// <summary> /// Delegate method for the TextToSpeechmoments_DetailStaticControlCommand command. /// </summary> public void TextToSpeechmoments_DetailStaticControlCommandDelegate() { _speechService.TextToSpeech(CurrentmomentsSchema.Subtitle + " " + CurrentmomentsSchema.Description); } private ICommand _textToSpeechmoments_DetailStaticControlCommand; /// <summary> /// Gets the TextToSpeechmoments_DetailStaticControlCommand command. /// </summary> public ICommand TextToSpeechmoments_DetailStaticControlCommand { get { return _textToSpeechmoments_DetailStaticControlCommand = _textToSpeechmoments_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(TextToSpeechmoments_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the Sharemoments_DetailStaticControlCommand command. /// </summary> public void Sharemoments_DetailStaticControlCommandDelegate() { _shareService.Share(CurrentmomentsSchema.Subtitle, CurrentmomentsSchema.Description, "", CurrentmomentsSchema.Image); } private ICommand _sharemoments_DetailStaticControlCommand; /// <summary> /// Gets the Sharemoments_DetailStaticControlCommand command. /// </summary> public ICommand Sharemoments_DetailStaticControlCommand { get { return _sharemoments_DetailStaticControlCommand = _sharemoments_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(Sharemoments_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the PinToStartmoments_DetailStaticControlCommand command. /// </summary> public void PinToStartmoments_DetailStaticControlCommandDelegate() { _liveTileService.PinToStart(typeof(IViewModels.Imoments_DetailViewModel), CreateTileInfomoments_DetailStaticControl()); } private ICommand _pinToStartmoments_DetailStaticControlCommand; /// <summary> /// Gets the PinToStartmoments_DetailStaticControlCommand command. /// </summary> public ICommand PinToStartmoments_DetailStaticControlCommand { get { return _pinToStartmoments_DetailStaticControlCommand = _pinToStartmoments_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(PinToStartmoments_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the Nextpanoramamoments_Detail0 command. /// </summary> public async void Nextpanoramamoments_Detail0Delegate() { LoadingCurrentmomentsSchema = true; var next = await _moments_momentsCollection.Next(CurrentmomentsSchema); if(next != null) CurrentmomentsSchema = next; RefreshHasPrevNext(); } private bool _loadingCurrentmomentsSchema; public bool LoadingCurrentmomentsSchema { get { return _loadingCurrentmomentsSchema; } set { SetProperty(ref _loadingCurrentmomentsSchema, value); } } private ICommand _nextpanoramamoments_Detail0; /// <summary> /// Gets the Nextpanoramamoments_Detail0 command. /// </summary> public ICommand Nextpanoramamoments_Detail0 { get { return _nextpanoramamoments_Detail0 = _nextpanoramamoments_Detail0 ?? new ViewModelsBase.DelegateCommand(Nextpanoramamoments_Detail0Delegate); } } /// <summary> /// Delegate method for the Previouspanoramamoments_Detail0 command. /// </summary> public void Previouspanoramamoments_Detail0Delegate() { var prev = _moments_momentsCollection.Previous(CurrentmomentsSchema); if(prev != null) CurrentmomentsSchema = prev; RefreshHasPrevNext(); } private ICommand _previouspanoramamoments_Detail0; /// <summary> /// Gets the Previouspanoramamoments_Detail0 command. /// </summary> public ICommand Previouspanoramamoments_Detail0 { get { return _previouspanoramamoments_Detail0 = _previouspanoramamoments_Detail0 ?? new ViewModelsBase.DelegateCommand(Previouspanoramamoments_Detail0Delegate); } } private async void RefreshHasPrevNext() { HasPreviouspanoramamoments_Detail0 = _moments_momentsCollection.HasPrevious(CurrentmomentsSchema); HasNextpanoramamoments_Detail0 = await _moments_momentsCollection.HasNext(CurrentmomentsSchema); LoadingCurrentmomentsSchema = false; } public object NavigationContext { set { if (!(value is Entities.momentsSchema)) { return; } CurrentmomentsSchema = value as Entities.momentsSchema; RefreshHasPrevNext(); } } /// <summary> /// Initializes a <see cref="Services.TileInfo" /> object for the moments_DetailStaticControl control. /// </summary> /// <returns>A <see cref="Services.TileInfo" /> object.</returns> public Services.TileInfo CreateTileInfomoments_DetailStaticControl() { var tileInfo = new Services.TileInfo { CurrentId = CurrentmomentsSchema.Subtitle, Title = CurrentmomentsSchema.Subtitle, BackTitle = CurrentmomentsSchema.Subtitle, BackContent = CurrentmomentsSchema.Description, Count = 0, BackgroundImagePath = CurrentmomentsSchema.Image, BackBackgroundImagePath = CurrentmomentsSchema.Image, LogoPath = "Logo-89401204-353b-44fd-86c0-eeff17be5801.png" }; return tileInfo; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using DesertOctopus.MammothCache.Common; using Polly; using Polly.Retry; using StackExchange.Redis; namespace DesertOctopus.MammothCache.Redis { /// <summary> /// Wrap StackExchange.Redis to add retry policy /// </summary> public sealed class RedisConnection : IRedisConnection, ISecondLevelCache, IDisposable { private readonly ConnectionMultiplexer _multiplexer; private readonly RetryPolicy _retryPolicy; private readonly RetryPolicy _retryPolicyAsync; private readonly string _instanceId = Guid.NewGuid().ToString(); private readonly string _setKeyChannel; private readonly string _removeAllItemsChannel = "RemoveAllItems"; private readonly PolicyBuilder _baseRetryPolicy; private bool _isDisposed = false; private ISubscriber _subscriber; /// <inheritdoc/> public event ItemEvictedFromCacheEventHandler OnItemRemovedFromCache; /// <inheritdoc/> public event RemoveAllItemsEventHandler OnRemoveAllItems; /// <summary> /// Initializes a new instance of the <see cref="RedisConnection"/> class. /// </summary> /// <param name="connectionString">Connection string to Redis</param> /// <param name="redisRetryPolicy">Retry policy</param> public RedisConnection(string connectionString, IRedisRetryPolicy redisRetryPolicy) { _setKeyChannel = "~SetKey~:" + _instanceId; _baseRetryPolicy = Policy.Handle<TimeoutException>() .Or<TimeoutException>() .Or<SocketException>() .Or<IOException>(); // for async _retryPolicy = GetBaseRetryPolicyBuilder().WaitAndRetry(redisRetryPolicy.SleepDurations); _retryPolicyAsync = GetBaseRetryPolicyBuilder().WaitAndRetryAsync(redisRetryPolicy.SleepDurations); var options = ConfigurationOptions.Parse(connectionString); ConfigureIfMissing(options, "abortConnect", connectionString, o => { o.AbortOnConnectFail = false; }); ConfigureIfMissing(options, "allowAdmin", connectionString, o => { o.AllowAdmin = true; }); _multiplexer = ConnectionMultiplexer.Connect(options); _multiplexer.PreserveAsyncOrder = false; SubscribeToEvents(); } private void SubscribeToEvents() { _subscriber = _multiplexer.GetSubscriber(); GetRetryPolicy().Execute(() => _subscriber.Subscribe("__key*__:*del", OnKeyRemoveFromRedis)); GetRetryPolicy().Execute(() => _subscriber.Subscribe("__key*__:*expired", OnKeyRemoveFromRedis)); GetRetryPolicy().Execute(() => _subscriber.Subscribe("__key*__:*evicted", OnKeyRemoveFromRedis)); GetRetryPolicy().Execute(() => _subscriber.Subscribe("~SetKey~:*", OnSetKeyFromRedis)); GetRetryPolicy().Execute(() => _subscriber.Subscribe(_removeAllItemsChannel, OnRemoveAllItemsFromRedis)); } private void OnRemoveAllItemsFromRedis(RedisChannel arg1, RedisValue arg2) { var eventCopy = OnRemoveAllItems; if (eventCopy != null) { eventCopy(this, new RemoveAllItemsEventArgs()); } } private void OnSetKeyFromRedis(RedisChannel redisChannel, RedisValue redisValue) { var channel = (string)redisChannel; if (channel != _setKeyChannel) { SendOnItemRemoveFromCacheEvent(redisValue); } } private void OnKeyRemoveFromRedis(RedisChannel redisChannel, RedisValue redisValue) { SendOnItemRemoveFromCacheEvent(redisValue); } private void SendOnItemRemoveFromCacheEvent(RedisValue redisValue) { var eventCopy = OnItemRemovedFromCache; if (eventCopy != null && redisValue.HasValue) { eventCopy(this, new ItemEvictedEventArgs { Key = (string)redisValue }); } } private void ConfigureIfMissing(ConfigurationOptions options, string configOption, string connectionString, Action<ConfigurationOptions> action) { if (connectionString.IndexOf(configOption, StringComparison.InvariantCultureIgnoreCase) == -1) { action(options); } } /// <summary> /// Dispose the <see cref="RedisConnection"/> /// </summary> public void Dispose() { GuardDisposed(); GetRetryPolicy().Execute(() => _subscriber.UnsubscribeAll()); _multiplexer.Dispose(); _isDisposed = true; } private void GuardDisposed() { if (_isDisposed) { throw new ObjectDisposedException("This RedisConnection is disposed"); } } internal PolicyBuilder GetBaseRetryPolicyBuilder() { GuardDisposed(); return _baseRetryPolicy; } internal RetryPolicy GetRetryPolicy() { GuardDisposed(); return _retryPolicy; } internal RetryPolicy GetRetryPolicyAsync() { GuardDisposed(); return _retryPolicyAsync; } internal IDatabase GetDatabase() { return _multiplexer.GetDatabase(); } /// <inheritdoc/> public byte[] Get(string key) { var redisValue = GetRetryPolicy().Execute<RedisValue>(() => GetDatabase().StringGet(key)); if (redisValue.HasValue) { return redisValue; } return null; } /// <inheritdoc/> public Dictionary<CacheItemDefinition, byte[]> Get(ICollection<CacheItemDefinition> keys) { var redisResult = GetRetryPolicy().Execute<RedisResult>(() => GetDatabase().ScriptEvaluate(LuaScripts.GetMultipleGetScript(), keys: keys.Select(x => (RedisKey)x.Key).ToArray())); return CreateCacheItemDefinitionArrayFromLuaScriptResult(keys, redisResult); } private static Dictionary<CacheItemDefinition, byte[]> CreateCacheItemDefinitionArrayFromLuaScriptResult(ICollection<CacheItemDefinition> keys, RedisResult redisResult) { if (redisResult == null) { throw new InvalidOperationException("Lua script did not return anything."); } var redisValues = (RedisValue[])redisResult; if (redisValues.Length != keys.Count * 2) { throw new InvalidOperationException("Lua script did not return the expected number of records."); } var result = new Dictionary<CacheItemDefinition, byte[]>(); int cpt = 0; foreach (var key in keys) { var cid = key.Clone(); int ttl = (int)redisValues[cpt + 1]; if (ttl <= 0) { cid.TimeToLive = null; } else { cid.TimeToLive = TimeSpan.FromSeconds(ttl); } result.Add(cid, redisValues[cpt]); cpt += 2; } return result; } /// <inheritdoc/> public async Task<byte[]> GetAsync(string key) { var redisValue = await GetRetryPolicyAsync().ExecuteAsync<RedisValue>(() => GetDatabase().StringGetAsync(key)).ConfigureAwait(false); if (redisValue.HasValue) { return redisValue; } return null; } /// <inheritdoc/> public async Task<Dictionary<CacheItemDefinition, byte[]>> GetAsync(ICollection<CacheItemDefinition> keys) { var redisResult = await GetRetryPolicyAsync().ExecuteAsync<RedisResult>(() => GetDatabase().ScriptEvaluateAsync(LuaScripts.GetMultipleGetScript(), keys: keys.Select(x => (RedisKey)x.Key).ToArray())); return CreateCacheItemDefinitionArrayFromLuaScriptResult(keys, redisResult); } /// <inheritdoc/> public void Set(string key, byte[] serializedValue) { Set(key, serializedValue, null); } /// <inheritdoc/> public void Set(string key, byte[] serializedValue, TimeSpan? ttl) { GetRetryPolicy().Execute(() => GetDatabase().Publish(_setKeyChannel, key)); GetRetryPolicy().Execute(() => GetDatabase().StringSet(key, serializedValue, expiry: ttl)); } /// <inheritdoc/> public void Set(Dictionary<CacheItemDefinition, byte[]> objects) { RedisValue[] values; RedisKey[] keys; GetMultipleSetValues(objects, out keys, out values); foreach (var key in keys) { GetRetryPolicy().Execute(() => GetDatabase().Publish(_setKeyChannel, (string)key)); } GetRetryPolicy().Execute<RedisResult>(() => GetDatabase().ScriptEvaluate(LuaScripts.GetMultipleSetScript(), keys: keys, values: values)); } private static void GetMultipleSetValues(Dictionary<CacheItemDefinition, byte[]> objects, out RedisKey[] keys, out RedisValue[] values) { keys = new RedisKey[objects.Count]; values = new RedisValue[objects.Count * 2]; int cpt = 0; foreach (var kvp in objects) { keys[cpt] = kvp.Key.Key; values[cpt * 2] = kvp.Value; values[(cpt * 2) + 1] = kvp.Key.TimeToLive.HasValue ? kvp.Key.TimeToLive.Value.TotalSeconds : 0; cpt++; } } /// <inheritdoc/> public Task SetAsync(string key, byte[] serializedValue) { return SetAsync(key, serializedValue, null); } /// <inheritdoc/> public async Task SetAsync(string key, byte[] serializedValue, TimeSpan? ttl) { await GetRetryPolicyAsync().ExecuteAsync(() => GetDatabase().PublishAsync(_setKeyChannel, key)).ConfigureAwait(false); await GetRetryPolicyAsync().ExecuteAsync(() => GetDatabase().StringSetAsync(key, serializedValue, expiry: ttl)).ConfigureAwait(false); } /// <inheritdoc/> public async Task SetAsync(Dictionary<CacheItemDefinition, byte[]> objects) { RedisValue[] values; RedisKey[] keys; GetMultipleSetValues(objects, out keys, out values); foreach (var key in keys) { await GetRetryPolicyAsync().ExecuteAsync(() => GetDatabase().PublishAsync(_setKeyChannel, (string)key)).ConfigureAwait(false); } await GetRetryPolicyAsync().ExecuteAsync<RedisResult>(() => GetDatabase().ScriptEvaluateAsync(LuaScripts.GetMultipleSetScript(), keys: keys, values: values)).ConfigureAwait(false); } /// <inheritdoc/> public bool Remove(string key) { return GetRetryPolicy().Execute<bool>(() => GetDatabase().KeyDelete(key)); } /// <inheritdoc/> public Task<bool> RemoveAsync(string key) { return GetRetryPolicyAsync().ExecuteAsync<bool>(() => GetDatabase().KeyDeleteAsync(key)); } /// <inheritdoc/> public void RemoveAll() { GetRetryPolicy() .Execute(() => { var endpoints = _multiplexer.GetEndPoints(true); foreach (var endpoint in endpoints) { var server = _multiplexer.GetServer(endpoint); server.FlushAllDatabases(); } }); GetRetryPolicy().Execute(() => GetDatabase().Publish(_removeAllItemsChannel, String.Empty)); } /// <inheritdoc/> public async Task RemoveAllAsync() { await GetRetryPolicyAsync() .ExecuteAsync(async () => { var endpoints = _multiplexer.GetEndPoints(true); foreach (var endpoint in endpoints) { var server = _multiplexer.GetServer(endpoint); await server.FlushAllDatabasesAsync() .ConfigureAwait(false); } }) .ConfigureAwait(false); await GetRetryPolicyAsync().ExecuteAsync(() => GetDatabase().PublishAsync(_removeAllItemsChannel, String.Empty)).ConfigureAwait(false); } /// <inheritdoc/> public TimeToLiveResult GetTimeToLive(string key) { var redisResult = GetRetryPolicy().Execute<RedisResult>(() => GetDatabase().ScriptEvaluate(LuaScripts.GetTtlScript(), keys: new RedisKey[] { key })); return ConvertRedisResultTimeToLiveResult((int)redisResult); } /// <inheritdoc/> public async Task<TimeToLiveResult> GetTimeToLiveAsync(string key) { var redisResult = await GetRetryPolicyAsync().ExecuteAsync<RedisResult>(() => GetDatabase().ScriptEvaluateAsync(LuaScripts.GetTtlScript(), keys: new RedisKey[] { key })).ConfigureAwait(false); return ConvertRedisResultTimeToLiveResult((int)redisResult); } /// <inheritdoc/> public Dictionary<string, TimeToLiveResult> GetTimeToLives(string[] keys) { var redisResult = GetRetryPolicy().Execute<RedisResult>(() => GetDatabase().ScriptEvaluate(LuaScripts.GetTtlsScript(), keys: keys.Select(x => (RedisKey)x).ToArray())); if (redisResult == null) { throw new InvalidOperationException("Lua script did not return anything."); } return ConvertRedisResultTimeToLiveResults(keys, redisResult); } /// <inheritdoc/> public async Task<Dictionary<string, TimeToLiveResult>> GetTimeToLivesAsync(string[] keys) { var redisResult = await GetRetryPolicyAsync().ExecuteAsync<RedisResult>(() => GetDatabase().ScriptEvaluateAsync(LuaScripts.GetTtlsScript(), keys: keys.Select(x => (RedisKey)x).ToArray())).ConfigureAwait(false); if (redisResult == null) { throw new InvalidOperationException("Lua script did not return anything."); } return ConvertRedisResultTimeToLiveResults(keys, redisResult); } private static Dictionary<string, TimeToLiveResult> ConvertRedisResultTimeToLiveResults(string[] keys, RedisResult redisResult) { var redisValues = (RedisValue[])redisResult; var result = new Dictionary<string, TimeToLiveResult>(); int cpt = 0; foreach (var key in keys) { result.Add(key, ConvertRedisResultTimeToLiveResult((int)redisValues[cpt])); cpt++; } return result; } private static TimeToLiveResult ConvertRedisResultTimeToLiveResult(int ttl) { if (ttl == -2 || ttl == 0) { return new TimeToLiveResult(); } if (ttl == -1) { return new TimeToLiveResult() { KeyExists = true }; } return new TimeToLiveResult() { KeyExists = true, TimeToLive = TimeSpan.FromSeconds(ttl) }; } private IServer GetServer(ConnectionMultiplexer muxer) { EndPoint[] endpoints = _multiplexer.GetEndPoints(); IServer result = null; foreach (var endpoint in endpoints) { var server = muxer.GetServer(endpoint); if (server.IsSlave || !server.IsConnected) { continue; } if (result != null) { throw new InvalidOperationException("Requires exactly one master endpoint (found " + server.EndPoint + " and " + result.EndPoint + ")"); } result = server; } if (result == null) { throw new InvalidOperationException("Requires exactly one master endpoint (found none)"); } return result; } /// <inheritdoc/> public KeyValuePair<string, string>[] GetConfig(string pattern) { return GetRetryPolicy().Execute(() => GetServer(_multiplexer).ConfigGet(pattern)); } /// <inheritdoc/> public Task<KeyValuePair<string, string>[]> GetConfigAsync(string pattern) { return GetRetryPolicyAsync().ExecuteAsync(() => GetServer(_multiplexer).ConfigGetAsync(pattern)); } /// <inheritdoc/> public bool KeyExists(string key) { return GetRetryPolicy().Execute<bool>(() => GetDatabase().KeyExists(key)); } /// <inheritdoc/> public Task<bool> KeyExistsAsync(string key) { return GetRetryPolicyAsync().ExecuteAsync(() => GetDatabase().KeyExistsAsync(key)); } /// <inheritdoc/> public IDisposable AcquireLock(string key, TimeSpan lockExpiry, TimeSpan timeout) { return new RedisLock(this).AcquireLock(key, lockExpiry, timeout); } /// <inheritdoc/> public Task<IDisposable> AcquireLockAsync(string key, TimeSpan lockExpiry, TimeSpan timeout) { return new RedisLock(this).AcquireLockAsync(key, lockExpiry, timeout); } } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> //----------------------------------------------------------------------- #endregion using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace SharpNative.Compiler.YieldAsync { public class YieldClassGenerator { private Compilation compilation; private ClassDeclarationSyntax classDeclarationSyntax; private MemberDeclarationSyntax node; private ISymbol method; public const string isStarted = "_isStarted"; public const string isStartedLocal = "_isStartedLocal"; public YieldClassGenerator(Compilation compilation, ClassDeclarationSyntax classDeclarationSyntax, MemberDeclarationSyntax node) { this.compilation = compilation; this.classDeclarationSyntax = classDeclarationSyntax; this.node = node; method = ModelExtensions.GetDeclaredSymbol(compilation.GetSemanticModel(node.SyntaxTree), node); } public ClassDeclarationSyntax CreateEnumerator() { var members = new List<MemberDeclarationSyntax>(); FieldDeclarationSyntax thisField = null; if (!method.IsStatic) { thisField = Cs.Field(method.ContainingType.ToTypeSyntax(), "_this"); members.Add(thisField); } var stateGenerator = new YieldStateGenerator(compilation, node); stateGenerator.GenerateStates(); var states = stateGenerator.States; var isStartedField = Cs.Field(Cs.Bool(), isStarted); members.Add(isStartedField); var stateField = Cs.Field(Cs.Int(), StateGenerator.state); members.Add(stateField); ITypeSymbol elementType = null; if (method is IMethodSymbol) { elementType = ((INamedTypeSymbol) (method as IMethodSymbol).ReturnType).TypeArguments.FirstOrDefault(); } else if (method is IPropertySymbol) { elementType = ((INamedTypeSymbol) (method as IPropertySymbol).Type).TypeArguments.FirstOrDefault(); } if (elementType == null) elementType = Context.Object; var currentProperty = Cs.Property(elementType.ToTypeSyntax(), "Current"); members.Add(currentProperty); if(node is MethodDeclarationSyntax) foreach (var parameter in (node as MethodDeclarationSyntax).ParameterList.Parameters) { var parameterField = Cs.Field(parameter.Type, parameter.Identifier); members.Add(parameterField); } foreach (var variable in stateGenerator.HoistedVariables) { var variableField = Cs.Field(variable.Item2, variable.Item1); members.Add(variableField); } var className = method.GetYieldClassName(); var constructorParameters = new List<ParameterSyntax>(); if (!method.IsStatic) { constructorParameters.Add(SyntaxFactory.Parameter(SyntaxFactory.Identifier("_this")).WithType(thisField.Declaration.Type)); } if (node is MethodDeclarationSyntax) constructorParameters.AddRange((node as MethodDeclarationSyntax).ParameterList.Parameters.Select(x => SyntaxFactory.Parameter(x.Identifier).WithType(x.Type))); var constructor = SyntaxFactory.ConstructorDeclaration(className) .AddModifiers(Cs.Public()) .WithParameterList(constructorParameters.ToArray()) .WithBody( SyntaxFactory.Block( // Assign fields constructorParameters.Select(x => Cs.Express(Cs.Assign(Cs.This().Member(x.Identifier), SyntaxFactory.IdentifierName(x.Identifier)))) ) .AddStatements( Cs.Express(Cs.Assign(Cs.This().Member(StateGenerator.state), Cs.Integer(1))) ) ); members.Add(constructor); var ienumerable_g = SyntaxFactory.ParseTypeName("System.Collections.Generic.IEnumerable<" + elementType.ToDisplayString() + ">"); var ienumerator_g = SyntaxFactory.ParseTypeName("System.Collections.Generic.IEnumerator<" + elementType.ToDisplayString() + ">"); var ienumerable = SyntaxFactory.ParseTypeName("System.Collections.IEnumerable"); var ienumerator = SyntaxFactory.ParseTypeName("System.Collections.IEnumerator"); // IEnumerator IEnumerable.GetEnumerator() //{ // return GetEnumerator(); //} var iegetEnumerator = SyntaxFactory.MethodDeclaration(ienumerator, "GetEnumerator") .AddModifiers(Cs.Public()) .WithExplicitInterfaceSpecifier(SyntaxFactory.ExplicitInterfaceSpecifier(SyntaxFactory.ParseName("System.Collections.IEnumerable"))) .WithBody(Cs.Block( Cs.Return(Cs.This().Member("GetEnumerator").Invoke()))); members.Add(iegetEnumerator); // public void Dispose() //{ //} var dispose = SyntaxFactory.MethodDeclaration(Context.Void.ToTypeSyntax(), "Dispose") .AddModifiers(Cs.Public()) .WithBody(Cs.Block()); members.Add(dispose); // public void Reset() // { // throw new NotImplementedException(); // } var reset = SyntaxFactory.MethodDeclaration(Context.Void.ToTypeSyntax(), "Reset") .AddModifiers(Cs.Public()) .WithBody(Cs.Block(Cs.Throw(Cs.New(Context.Compilation.FindType("System.NotImplementedException").ToTypeSyntax())))); members.Add(reset); // object IEnumerator.Current //{ // get { return Current; } //} //IEnumerator var iecurrent = Cs.Property(Context.Object.ToTypeSyntax(), "Current", true, false, Cs.Block( Cs.Return(Cs.This().Member("Current")) )).WithExplicitInterfaceSpecifier(SyntaxFactory.ExplicitInterfaceSpecifier(SyntaxFactory.ParseName("System.Collections.IEnumerator"))); members.Add(iecurrent); // Generate the GetEnumerator method, which looks something like: // var $isStartedLocal = $isStarted; // $isStarted = true; // if ($isStartedLocal) // return this.Clone().GetEnumerator(); // else // return this; var getEnumerator = SyntaxFactory.MethodDeclaration(ienumerator_g, "GetEnumerator") .AddModifiers(Cs.Public()) .WithBody(Cs.Block( Cs.Local(isStartedLocal, SyntaxFactory.IdentifierName(isStarted)), Cs.Express(SyntaxFactory.IdentifierName(isStarted).Assign(Cs.True())), Cs.If( SyntaxFactory.IdentifierName(isStartedLocal), Cs.Return(Cs.This().Member("Clone").Invoke().Member("GetEnumerator").Invoke()), Cs.Return(Cs.This())))); members.Add(getEnumerator); // Generate the MoveNext method, which looks something like: // $top: // while (true) // { // switch (state) // { // case 0: ... // case 1: ... // } // } var moveNextBody = SyntaxFactory.LabeledStatement("_top", Cs.While(Cs.True(), Cs.Switch(Cs.This().Member(StateGenerator.state), states.Select((x, i) => Cs.Section(Cs.Integer(i), x.Statements.ToArray())).ToArray()))); var moveNext = SyntaxFactory.MethodDeclaration(Cs.Bool(), "MoveNext") .AddModifiers(Cs.Public()) .WithBody(SyntaxFactory.Block(moveNextBody, Cs.Return(SyntaxFactory.ParseExpression("false")))); members.Add(moveNext); TypeSyntax classNameWithTypeArguments = SyntaxFactory.IdentifierName(className); if(method is IMethodSymbol) if ((method as IMethodSymbol).TypeParameters.Any()) { classNameWithTypeArguments = SyntaxFactory.GenericName( SyntaxFactory.Identifier(className), SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList( (method as IMethodSymbol).TypeParameters.Select(x => SyntaxFactory.ParseTypeName(x.Name)), (method as IMethodSymbol).TypeParameters.Select(x => x).Skip(1).Select(_ => SyntaxFactory.Token(SyntaxKind.CommaToken))) )); } var cloneBody = Cs.Block( Cs.Return(classNameWithTypeArguments.New( constructorParameters.Select(x => SyntaxFactory.IdentifierName(x.Identifier)).ToArray() )) ); var clone = SyntaxFactory.MethodDeclaration(ienumerable_g, "Clone") .AddModifiers(Cs.Public()) .WithBody(SyntaxFactory.Block(cloneBody)); members.Add(clone); //IEnumerable<T>,IEnumerator<T> SimpleBaseTypeSyntax[] baseTypes = new[] { SyntaxFactory.SimpleBaseType(ienumerable_g), SyntaxFactory.SimpleBaseType(ienumerator_g) }; ClassDeclarationSyntax result = SyntaxFactory.ClassDeclaration(className).WithBaseList(baseTypes).WithMembers(members.ToArray()); if(method is IMethodSymbol) if ((method as IMethodSymbol).TypeParameters.Any()) { result = result.WithTypeParameterList((node as MethodDeclarationSyntax).TypeParameterList); } return result; } } }
using System; using System.Collections.Generic; using DTA; using Fairweather.Service; using Versioning; namespace Common { public class Sage_Access { public Sage_Access(string path, Credentials creds, int version) : this(path, creds, version, Data.Default_Machine_Name) { } public Sage_Access(string path, Credentials creds, int version, string machine) { this.Creds = creds; this.Version = version; this.Path = path; this.Machine = machine; } public string Path { get; private set; } public Credentials Creds { get; private set; } public string Username { get { return Creds.Username; } } public string Password { get { return Creds.Password; } } public Company_Number Company { get { return Creds.Company; } } public int Version { get; private set; } public string Machine { get; set; } public Sage_Connection Conn { get; private set; } public SDO_Engine Sdo { get { return Conn.sdo; } } public Work_Space WS { get { return Conn.ws; } } public IDisposable Establish_Connection() { var new_conn = new Sage_Connection(this.Username, this.Password, this.Path, this.Version, this.Machine); var old_conn = Conn; Conn = new_conn; return new On_Dispose(() => { Conn.Try_Dispose(); Conn = old_conn ?? new_conn; }); } public void Test_Connection() { if (Connected) return; var sdo = new SDO_Engine(Version); var ws = sdo.WSAdd(Data.Workspace); ws.Test_Connection(Path, Username, Password, Machine); } public bool Connected { get { var tmp = Conn; return tmp != null && tmp.Connected; } } public string Get_Last_Sage_Error() { using (Establish_Connection()) { return Sdo.Last_Error_Text; } } /* Sage Access */ public IDisposable Attempt_Transaction() { bool _; return Attempt_Transaction(out _); } public IDisposable Attempt_Transaction(out bool ok) { return Attempt_Transaction(true, out ok); } public IDisposable Attempt_Transaction(bool attempt_retry, out bool ok) { IDisposable ret = null; ok = Sage_Guard(() => ret = Establish_Connection(), attempt_retry); return ok ? ret : null; } public bool Test_And_Prompt() { return Sage_Guard(this.Test_Connection, cst_sage_guard_def_allow_retry); } public bool Test(bool allow_retry) { return Sage_Guard(this.Test_Connection, allow_retry); } // **************************** public static T Get_Value<T>(Func<T> f, T def, int? retries) { T ret = default(T); if (!Repeat_Until_Success(() => ret = f(), retries)) ret = def; return ret; } public static T Get_Value<T>(Func<T> f) { var ret = default(T); if (!Repeat_Until_Success(() => ret = f())) ret = default(T); return ret; } public static bool Repeat_Until_Success(Action act) { return Repeat_Until_Success(act, null); } public static bool Repeat_Until_Success(Action act, int? max_iters) { int ii = 0; while (true) { if (Sage_Guard(act)) return true; if (max_iters.HasValue && max_iters.Value > ii) return false; ++ii; } } const bool cst_sage_guard_def_allow_retry = true; public static bool Sage_Guard(Action act) { return Sage_Guard(act, cst_sage_guard_def_allow_retry); } public static bool Sage_Guard(Action act, bool allow_retry) { return Sage_Guard(act, ex => Exceptions.Handle_Sage_X(ex, allow_retry)); } public static bool Sage_Guard(Action act, Func<XSage, bool> handler) { while (true) { try { act(); return true; } catch (XSage ex) { if (handler != null && handler(ex)) continue; return false; } } } } }
// // // Copyright (c) Microsoft. 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. namespace Relay.Tests.ScenarioTests { using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Management.Relay; using Microsoft.Azure.Management.Relay.Models; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Relay.Tests.TestHelper; using Xunit; public partial class ScenarioTests { [Fact] public void WCFRelayCreateGetUpdateDeleteAuthorizationRules_length() { using (MockContext context = MockContext.Start(this.GetType())) { InitializeClients(context); var location = this.ResourceManagementClient.GetLocationFromProvider(); var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location); if (string.IsNullOrWhiteSpace(resourceGroup)) { resourceGroup = TestUtilities.GenerateName(RelayManagementHelper.ResourceGroupPrefix); this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup); } // Create Namespace var namespaceName = TestUtilities.GenerateName(RelayManagementHelper.NamespacePrefix); var createNamespaceResponse = this.RelayManagementClient.Namespaces.CreateOrUpdate(resourceGroup, namespaceName, new RelayNamespace() { Location = location, Tags = new Dictionary<string, string>() { {"tag1", "value1"}, {"tag2", "value2"} } }); Assert.NotNull(createNamespaceResponse); Assert.Equal(createNamespaceResponse.Name, namespaceName); Assert.Equal(2, createNamespaceResponse.Tags.Count); Assert.Equal("Microsoft.Relay/Namespaces", createNamespaceResponse.Type); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created namespace var getNamespaceResponse = RelayManagementClient.Namespaces.Get(resourceGroup, namespaceName); if (string.Compare(getNamespaceResponse.ProvisioningState.ToString(), "Succeeded", true) != 0) TestUtilities.Wait(TimeSpan.FromSeconds(5)); getNamespaceResponse = RelayManagementClient.Namespaces.Get(resourceGroup, namespaceName); Assert.NotNull(getNamespaceResponse); Assert.Equal("Succeeded", getNamespaceResponse.ProvisioningState.ToString(), StringComparer.CurrentCultureIgnoreCase); Assert.Equal(location, getNamespaceResponse.Location, StringComparer.CurrentCultureIgnoreCase); // Get all namespaces created within a resourceGroup var getAllNamespacesResponse = RelayManagementClient.Namespaces.ListByResourceGroup(resourceGroup); Assert.NotNull(getAllNamespacesResponse); Assert.True(getAllNamespacesResponse.Count() >= 1); Assert.Contains(getAllNamespacesResponse, ns => ns.Name == namespaceName); Assert.True(getAllNamespacesResponse.All(ns => ns.Id.Contains(resourceGroup))); // Get all namespaces created within the subscription irrespective of the resourceGroup getAllNamespacesResponse = RelayManagementClient.Namespaces.List(); Assert.NotNull(getAllNamespacesResponse); Assert.True(getAllNamespacesResponse.Count() >= 1); Assert.Contains(getAllNamespacesResponse, ns => ns.Name == namespaceName); // Create WCF Relay - var wcfRelayName = RelayManagementHelper.WcfPrefix + "thisisthenamewithmorethan53charschecktoverifytheremovlaof50charsnamelengthlimit"; var createdWCFRelayResponse = RelayManagementClient.WCFRelays.CreateOrUpdate(resourceGroup, namespaceName, wcfRelayName, new WcfRelay() { RelayType = Relaytype.NetTcp, RequiresClientAuthorization = true, RequiresTransportSecurity = true }); Assert.NotNull(createdWCFRelayResponse); Assert.Equal(createdWCFRelayResponse.Name, wcfRelayName); Assert.True(createdWCFRelayResponse.RequiresClientAuthorization); Assert.True(createdWCFRelayResponse.RequiresTransportSecurity); Assert.Equal(Relaytype.NetTcp, createdWCFRelayResponse.RelayType); var getWCFRelaysResponse = RelayManagementClient.WCFRelays.Get(resourceGroup, namespaceName, wcfRelayName); // Create a WCFRelay AuthorizationRule var authorizationRuleName = RelayManagementHelper.AuthorizationRulesPrefix + "thisisthenamewithmorethan53charschecktoverifytheremovlaof50charsnamelengthlimit"; string createPrimaryKey = HttpMockServer.GetVariable("CreatePrimaryKey", RelayManagementHelper.GenerateRandomKey()); var createAutorizationRuleParameter = new AuthorizationRule() { Rights = new List<AccessRights?>() { AccessRights.Listen, AccessRights.Send } }; var jsonStr = RelayManagementHelper.ConvertObjectToJSon(createAutorizationRuleParameter); var test = RelayManagementClient.WCFRelays.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, createAutorizationRuleParameter); var createNamespaceAuthorizationRuleResponse = RelayManagementClient.WCFRelays.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, createAutorizationRuleParameter); Assert.NotNull(createNamespaceAuthorizationRuleResponse); Assert.True(createNamespaceAuthorizationRuleResponse.Rights.Count == createAutorizationRuleParameter.Rights.Count); foreach (var right in createAutorizationRuleParameter.Rights) { Assert.Contains(createNamespaceAuthorizationRuleResponse.Rights, r => r == right); } // Get created WCFRelay AuthorizationRules var getNamespaceAuthorizationRulesResponse = RelayManagementClient.WCFRelays.GetAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName); Assert.NotNull(getNamespaceAuthorizationRulesResponse); Assert.True(getNamespaceAuthorizationRulesResponse.Rights.Count == createAutorizationRuleParameter.Rights.Count); foreach (var right in createAutorizationRuleParameter.Rights) { Assert.Contains(getNamespaceAuthorizationRulesResponse.Rights, r => r == right); } // Get all WCFRelay AuthorizationRules var getAllNamespaceAuthorizationRulesResponse = RelayManagementClient.WCFRelays.ListAuthorizationRules(resourceGroup, namespaceName,wcfRelayName); Assert.NotNull(getAllNamespaceAuthorizationRulesResponse); Assert.True(getAllNamespaceAuthorizationRulesResponse.Count() >= 1); Assert.Contains(getAllNamespaceAuthorizationRulesResponse, ns => ns.Name == authorizationRuleName); // Update WCFRelay authorizationRule string updatePrimaryKey = HttpMockServer.GetVariable("UpdatePrimaryKey", RelayManagementHelper.GenerateRandomKey()); AuthorizationRule updateNamespaceAuthorizationRuleParameter = new AuthorizationRule(); updateNamespaceAuthorizationRuleParameter.Rights = new List<AccessRights?>() { AccessRights.Listen }; var updateNamespaceAuthorizationRuleResponse = RelayManagementClient.WCFRelays.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, updateNamespaceAuthorizationRuleParameter); Assert.NotNull(updateNamespaceAuthorizationRuleResponse); Assert.Equal(authorizationRuleName, updateNamespaceAuthorizationRuleResponse.Name); Assert.True(updateNamespaceAuthorizationRuleResponse.Rights.Count == updateNamespaceAuthorizationRuleParameter.Rights.Count); foreach (var right in updateNamespaceAuthorizationRuleParameter.Rights) { Assert.Contains(updateNamespaceAuthorizationRuleResponse.Rights, r => r.Equals(right)); } // Get the WCFRelay namespace AuthorizationRule var getNamespaceAuthorizationRuleResponse = RelayManagementClient.WCFRelays.GetAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName); Assert.NotNull(getNamespaceAuthorizationRuleResponse); Assert.Equal(authorizationRuleName, getNamespaceAuthorizationRuleResponse.Name); Assert.True(getNamespaceAuthorizationRuleResponse.Rights.Count == updateNamespaceAuthorizationRuleParameter.Rights.Count); foreach (var right in updateNamespaceAuthorizationRuleParameter.Rights) { Assert.Contains(getNamespaceAuthorizationRuleResponse.Rights, r => r.Equals(right)); } // Get the connectionString to the WCFRelay for a Authorization rule created var listKeysResponse = RelayManagementClient.WCFRelays.ListKeys(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName); Assert.NotNull(listKeysResponse); Assert.NotNull(listKeysResponse.PrimaryConnectionString); Assert.NotNull(listKeysResponse.SecondaryConnectionString); // Regenerate AuthorizationRules var regenerateKeysParameters = new RegenerateAccessKeyParameters(); regenerateKeysParameters.KeyType = KeyType.PrimaryKey; //Primary Key var regenerateKeysPrimaryResponse = RelayManagementClient.WCFRelays.RegenerateKeys(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, regenerateKeysParameters); Assert.NotNull(regenerateKeysPrimaryResponse); Assert.NotEqual(regenerateKeysPrimaryResponse.PrimaryKey, listKeysResponse.PrimaryKey); Assert.Equal(regenerateKeysPrimaryResponse.SecondaryKey, listKeysResponse.SecondaryKey); regenerateKeysParameters.KeyType = KeyType.SecondaryKey; //Secondary Key var regenerateKeysSecondaryResponse = RelayManagementClient.WCFRelays.RegenerateKeys(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName, regenerateKeysParameters); Assert.NotNull(regenerateKeysSecondaryResponse); Assert.NotEqual(regenerateKeysSecondaryResponse.SecondaryKey, listKeysResponse.SecondaryKey); Assert.Equal(regenerateKeysSecondaryResponse.PrimaryKey, regenerateKeysPrimaryResponse.PrimaryKey); // Delete WCFRelay authorizationRule RelayManagementClient.WCFRelays.DeleteAuthorizationRule(resourceGroup, namespaceName, wcfRelayName, authorizationRuleName); try { RelayManagementClient.WCFRelays.Delete(resourceGroup, namespaceName, wcfRelayName); } catch (Exception ex) { Assert.Contains("NotFound", ex.Message); } try { // Delete namespace RelayManagementClient.Namespaces.Delete(resourceGroup, namespaceName); } catch (Exception ex) { Assert.Contains("NotFound", ex.Message); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { /// <summary> /// Named pipe server /// </summary> public sealed partial class NamedPipeServerStream : PipeStream { [SecurityCritical] private unsafe static readonly IOCompletionCallback s_WaitForConnectionCallback = new IOCompletionCallback(NamedPipeServerStream.AsyncWaitForConnectionCallback); [SecurityCritical] private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, HandleInheritability inheritability) { Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty"); Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction"); Debug.Assert(inBufferSize >= 0, "inBufferSize is negative"); Debug.Assert(outBufferSize >= 0, "outBufferSize is negative"); Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid"); Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range"); string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName); // Make sure the pipe name isn't one of our reserved names for anonymous pipes. if (String.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentOutOfRangeException("pipeName", SR.ArgumentOutOfRange_AnonymousReserved); } int openMode = ((int)direction) | (maxNumberOfServerInstances == 1 ? Interop.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) | (int)options; // We automatically set the ReadMode to match the TransmissionMode. int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1; // Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254). if (maxNumberOfServerInstances == MaxAllowedServerInstances) { maxNumberOfServerInstances = 255; } Interop.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability); SafePipeHandle handle = Interop.mincore.CreateNamedPipe(fullPipeName, openMode, pipeModes, maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs); if (handle.IsInvalid) { throw Win32Marshal.GetExceptionForLastWin32Error(); } InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0); } // This will wait until the client calls Connect(). If we return from this method, we guarantee that // the client has returned from its Connect call. The client may have done so before this method // was called (but not before this server is been created, or, if we were servicing another client, // not before we called Disconnect), in which case, there may be some buffer already in the pipe waiting // for us to read. See NamedPipeClientStream.Connect for more information. [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] public void WaitForConnection() { CheckConnectOperationsServer(); if (IsAsync) { IAsyncResult result = BeginWaitForConnection(null, null); EndWaitForConnection(result); } else { if (!Interop.mincore.ConnectNamedPipe(InternalHandle, Interop.NULL)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.ERROR_PIPE_CONNECTED) { throw Win32Marshal.GetExceptionForWin32Error(errorCode); } // pipe already connected if (errorCode == Interop.ERROR_PIPE_CONNECTED && State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } // If we reach here then a connection has been established. This can happen if a client // connects in the interval between the call to CreateNamedPipe and the call to ConnectNamedPipe. // In this situation, there is still a good connection between client and server, even though // ConnectNamedPipe returns zero. } State = PipeState.Connected; } } public Task WaitForConnectionAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (!IsAsync) { return Task.Factory.StartNew(s => ((NamedPipeServerStream)s).WaitForConnection(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } return Task.Factory.FromAsync( BeginWaitForConnection, EndWaitForConnection, cancellationToken.CanBeCanceled ? new IOCancellationHelper(cancellationToken) : null); } // Async version of WaitForConnection. See the comments above for more info. [SecurityCritical] private unsafe IAsyncResult BeginWaitForConnection(AsyncCallback callback, Object state) { CheckConnectOperationsServer(); if (!IsAsync) { throw new InvalidOperationException(SR.InvalidOperation_PipeNotAsync); } // Create and store async stream class library specific data in the // async result PipeAsyncResult asyncResult = new PipeAsyncResult(); asyncResult._handle = InternalHandle; asyncResult._userCallback = callback; asyncResult._userStateObject = state; IOCancellationHelper cancellationHelper = state as IOCancellationHelper; // Create wait handle and store in async result ManualResetEvent waitHandle = new ManualResetEvent(false); asyncResult._waitHandle = waitHandle; // Create a managed overlapped class // We will set the file offsets later Overlapped overlapped = new Overlapped(); overlapped.OffsetLow = 0; overlapped.OffsetHigh = 0; overlapped.AsyncResult = asyncResult; // Pack the Overlapped class, and store it in the async result NativeOverlapped* intOverlapped = overlapped.Pack(s_WaitForConnectionCallback, null); asyncResult._overlapped = intOverlapped; if (!Interop.mincore.ConnectNamedPipe(InternalHandle, intOverlapped)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.ERROR_IO_PENDING) { if (cancellationHelper != null) { cancellationHelper.AllowCancellation(InternalHandle, intOverlapped); } return asyncResult; } // WaitForConnectionCallback will not be called becasue we completed synchronously. // Either the pipe is already connected, or there was an error. Unpin and free the overlapped again. Overlapped.Free(intOverlapped); asyncResult._overlapped = null; // Did the client already connect to us? if (errorCode == Interop.ERROR_PIPE_CONNECTED) { if (State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } asyncResult.CallUserCallback(); return asyncResult; } throw Win32Marshal.GetExceptionForWin32Error(errorCode); } // will set state to Connected when EndWait is called if (cancellationHelper != null) { cancellationHelper.AllowCancellation(InternalHandle, intOverlapped); } return asyncResult; } // Async version of WaitForConnection. See comments for WaitForConnection for more info. [SecurityCritical] private unsafe void EndWaitForConnection(IAsyncResult asyncResult) { CheckConnectOperationsServer(); if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (!IsAsync) { throw new InvalidOperationException(SR.InvalidOperation_PipeNotAsync); } PipeAsyncResult afsar = asyncResult as PipeAsyncResult; if (afsar == null) { throw __Error.GetWrongAsyncResult(); } // Ensure we can't get into any races by doing an interlocked // CompareExchange here. Avoids corrupting memory via freeing the // NativeOverlapped class or GCHandle twice. -- if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0)) { throw __Error.GetEndWaitForConnectionCalledTwice(); } IOCancellationHelper cancellationHelper = afsar.AsyncState as IOCancellationHelper; if (cancellationHelper != null) { cancellationHelper.SetOperationCompleted(); } // Obtain the WaitHandle, but don't use public property in case we // delay initialize the manual reset event in the future. WaitHandle wh = afsar._waitHandle; if (wh != null) { // We must block to ensure that ConnectionIOCallback has completed, // and we should close the WaitHandle in here. AsyncFSCallback // and the hand-ported imitation version in COMThreadPool.cpp // are the only places that set this event. using (wh) { wh.WaitOne(); Debug.Assert(afsar._isComplete == true, "NamedPipeServerStream::EndWaitForConnection - AsyncFSCallback didn't set _isComplete to true!"); } } // We should have freed the overlapped and set it to null either in the Begin // method (if ConnectNamedPipe completed synchronously) or in AsyncWaitForConnectionCallback. // If it is not nulled out, we should not be past the above wait: Debug.Assert(afsar._overlapped == null); // Now check for any error during the read. if (afsar._errorCode != 0) { if (afsar._errorCode == Interop.ERROR_OPERATION_ABORTED) { if (cancellationHelper != null) { cancellationHelper.ThrowIOOperationAborted(); } } throw Win32Marshal.GetExceptionForWin32Error(afsar._errorCode); } // Success State = PipeState.Connected; } [SecurityCritical] public void Disconnect() { CheckDisconnectOperations(); // Disconnect the pipe. if (!Interop.mincore.DisconnectNamedPipe(InternalHandle)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } State = PipeState.Disconnected; } #if RunAs // This method calls a delegate while impersonating the client. Note that we will not have // access to the client's security token until it has written at least once to the pipe // (and has set its impersonationLevel argument appropriately). [SecurityCritical] [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)] public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker) { CheckWriteOperations(); ExecuteHelper execHelper = new ExecuteHelper(impersonationWorker, InternalHandle); RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, execHelper); // now handle win32 impersonate/revert specific errors by throwing corresponding exceptions if (execHelper._impersonateErrorCode != 0) { WinIOError(execHelper._impersonateErrorCode); } else if (execHelper._revertImpersonateErrorCode != 0) { WinIOError(execHelper._revertImpersonateErrorCode); } } // the following are needed for CER private static RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(ImpersonateAndTryCode); private static RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(RevertImpersonationOnBackout); [SecurityCritical] private static void ImpersonateAndTryCode(Object helper) { ExecuteHelper execHelper = (ExecuteHelper)helper; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (UnsafeNativeMethods.ImpersonateNamedPipeClient(execHelper._handle)) { execHelper._mustRevert = true; } else { execHelper._impersonateErrorCode = Marshal.GetLastWin32Error(); } } if (execHelper._mustRevert) { // impersonate passed so run user code execHelper._userCode(); } } [SecurityCritical] [PrePrepareMethod] private static void RevertImpersonationOnBackout(Object helper, bool exceptionThrown) { ExecuteHelper execHelper = (ExecuteHelper)helper; if (execHelper._mustRevert) { if (!UnsafeNativeMethods.RevertToSelf()) { execHelper._revertImpersonateErrorCode = Marshal.GetLastWin32Error(); } } } internal class ExecuteHelper { internal PipeStreamImpersonationWorker _userCode; internal SafePipeHandle _handle; internal bool _mustRevert; internal int _impersonateErrorCode; internal int _revertImpersonateErrorCode; [SecurityCritical] internal ExecuteHelper(PipeStreamImpersonationWorker userCode, SafePipeHandle handle) { _userCode = userCode; _handle = handle; } } #endif // Gets the username of the connected client. Not that we will not have access to the client's // username until it has written at least once to the pipe (and has set its impersonationLevel // argument appropriately). [SecurityCritical] public String GetImpersonationUserName() { CheckWriteOperations(); StringBuilder userName = new StringBuilder(Interop.CREDUI_MAX_USERNAME_LENGTH + 1); if (!Interop.mincore.GetNamedPipeHandleState(InternalHandle, Interop.NULL, Interop.NULL, Interop.NULL, Interop.NULL, userName, userName.Capacity)) { WinIOError(Marshal.GetLastWin32Error()); } return userName.ToString(); } // Callback to be called by the OS when completing the async WaitForConnection operation. [SecurityCritical] unsafe private static void AsyncWaitForConnectionCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped) { // Unpack overlapped Overlapped overlapped = Overlapped.Unpack(pOverlapped); // Extract async result from overlapped PipeAsyncResult asyncResult = (PipeAsyncResult)overlapped.AsyncResult; // Free the pinned overlapped: Debug.Assert(asyncResult._overlapped == pOverlapped); Overlapped.Free(pOverlapped); asyncResult._overlapped = null; // Special case for when the client has already connected to us. if (errorCode == Interop.ERROR_PIPE_CONNECTED) { errorCode = 0; } asyncResult._errorCode = (int)errorCode; // Call the user-provided callback. It can and often should // call EndWaitForConnection. There's no reason to use an async // delegate here - we're already on a threadpool thread. // IAsyncResult's completedSynchronously property must return // false here, saying the user callback was called on another thread. asyncResult._completedSynchronously = false; asyncResult._isComplete = true; // The OS does not signal this event. We must do it ourselves. ManualResetEvent wh = asyncResult._waitHandle; if (wh != null) { Debug.Assert(!wh.GetSafeWaitHandle().IsClosed, "ManualResetEvent already closed!"); bool r = wh.Set(); Debug.Assert(r, "ManualResetEvent::Set failed!"); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } AsyncCallback userCallback = asyncResult._userCallback; if (userCallback != null) { userCallback(asyncResult); } } } }
// 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. #if FEATURE_REGISTRY using Microsoft.Win32; #endif using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Threading; namespace System.Diagnostics { internal sealed class PerformanceCounterLib { private static string s_computerName; private PerformanceMonitor _performanceMonitor; private string _machineName; private string _perfLcid; private static Dictionary<String, PerformanceCounterLib> s_libraryTable; private Dictionary<int, string> _nameTable; private readonly object _nameTableLock = new Object(); private static Object s_internalSyncObject; internal PerformanceCounterLib(string machineName, string lcid) { _machineName = machineName; _perfLcid = lcid; } /// <internalonly/> internal static string ComputerName => LazyInitializer.EnsureInitialized(ref s_computerName, ref s_internalSyncObject, () => Interop.Kernel32.GetComputerName()); internal Dictionary<int, string> NameTable { get { if (_nameTable == null) { lock (_nameTableLock) { if (_nameTable == null) _nameTable = GetStringTable(false); } } return _nameTable; } } internal string GetCounterName(int index) { string result; return NameTable.TryGetValue(index, out result) ? result : ""; } internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture) { string lcidString = culture.Name.ToLowerInvariant(); if (machineName.CompareTo(".") == 0) machineName = ComputerName.ToLowerInvariant(); else machineName = machineName.ToLowerInvariant(); LazyInitializer.EnsureInitialized(ref s_libraryTable, ref s_internalSyncObject, () => new Dictionary<string, PerformanceCounterLib>()); string libraryKey = machineName + ":" + lcidString; PerformanceCounterLib library; if (!PerformanceCounterLib.s_libraryTable.TryGetValue(libraryKey, out library)) { library = new PerformanceCounterLib(machineName, lcidString); PerformanceCounterLib.s_libraryTable[libraryKey] = library; } return library; } internal byte[] GetPerformanceData(string item) { if (_performanceMonitor == null) { lock (LazyInitializer.EnsureInitialized(ref s_internalSyncObject)) { if (_performanceMonitor == null) _performanceMonitor = new PerformanceMonitor(_machineName); } } return _performanceMonitor.GetData(item); } private Dictionary<int, string> GetStringTable(bool isHelp) { #if FEATURE_REGISTRY Dictionary<int, string> stringTable; RegistryKey libraryKey; libraryKey = Registry.PerformanceData; try { string[] names = null; int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // In some stress situations, querying counter values from // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009 // often returns null/empty data back. We should build fault-tolerance logic to // make it more reliable because getting null back once doesn't necessarily mean // that the data is corrupted, most of the time we would get the data just fine // in subsequent tries. while (waitRetries > 0) { try { if (!isHelp) names = (string[])libraryKey.GetValue("Counter " + _perfLcid); else names = (string[])libraryKey.GetValue("Explain " + _perfLcid); if ((names == null) || (names.Length == 0)) { --waitRetries; if (waitSleep == 0) waitSleep = 10; else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } } else break; } catch (IOException) { // RegistryKey throws if it can't find the value. We want to return an empty table // and throw a different exception higher up the stack. names = null; break; } catch (InvalidCastException) { // Unable to cast object of type 'System.Byte[]' to type 'System.String[]'. // this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ names = null; break; } } if (names == null) stringTable = new Dictionary<int, string>(); else { stringTable = new Dictionary<int, string>(names.Length / 2); for (int index = 0; index < (names.Length / 2); ++index) { string nameString = names[(index * 2) + 1]; if (nameString == null) nameString = String.Empty; int key; if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key)) { if (isHelp) { // Category Help Table throw new InvalidOperationException(SR.Format(SR.CategoryHelpCorrupt, names[index * 2])); } else { // Counter Name Table throw new InvalidOperationException(SR.Format(SR.CounterNameCorrupt, names[index * 2])); } } stringTable[key] = nameString; } } } finally { libraryKey.Dispose(); } return stringTable; #else return new Dictionary<int, string>(); #endif } internal class PerformanceMonitor { #if FEATURE_REGISTRY private RegistryKey _perfDataKey = null; #endif private string _machineName; internal PerformanceMonitor(string machineName) { _machineName = machineName; Init(); } private void Init() { #if FEATURE_REGISTRY _perfDataKey = Registry.PerformanceData; #endif } // Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some // scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY, // ERROR_NOT_READY etc can be seen by other concurrent calls (which is the reason for the // wait loop and switch case below). We want to wait most certainly more than a 2min window. // The current wait time of up to 10mins takes care of the known stress deadlock issues. In most // cases we wouldn't wait for more than 2mins anyways but in worst cases how much ever time // we wait may not be sufficient if the Win32 code keeps running into this deadlock again // and again. A condition very rare but possible in theory. We would get back to the user // in this case with InvalidOperationException after the wait time expires. internal byte[] GetData(string item) { #if FEATURE_REGISTRY int waitRetries = 17; //2^16*10ms == approximately 10mins int waitSleep = 0; byte[] data = null; int error = 0; while (waitRetries > 0) { try { data = (byte[])_perfDataKey.GetValue(item); return data; } catch (IOException e) { error = e.HResult; switch (error) { case Interop.Advapi32.RPCStatus.RPC_S_CALL_FAILED: case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Advapi32.RPCStatus.RPC_S_SERVER_UNAVAILABLE: Init(); goto case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT; case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT: case Interop.Errors.ERROR_NOT_READY: case Interop.Errors.ERROR_LOCK_FAILED: case Interop.Errors.ERROR_BUSY: --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } break; default: throw new Win32Exception(error); } } catch (InvalidCastException e) { throw new InvalidOperationException(SR.Format(SR.CounterDataCorrupt, _perfDataKey.ToString()), e); } } throw new Win32Exception(error); #else return Array.Empty<byte>(); #endif } } } }
// // Copyright 2012 Clancey // // 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 MonoTouch.Dialog; using MonoTouch.UIKit; using MonoTouch.Foundation; using System.Drawing; using System.Collections.Generic; namespace ClanceysLib { public class CalendarDateTimeElement : StringElement { public enum PickerTypes { DatePicker,Calendar } public static DateTime DateTimeMin { get{return DateTime.FromFileTimeUtc(0);} } public static DateTime NSDateToDateTime(MonoTouch.Foundation.NSDate date) { var nsDateNow = (DateTime)NSDate.Now; var diff = DateTime.Now.Subtract(nsDateNow); var newDate = ((DateTime)date).Add(diff); return newDate; // return (new DateTime(2001,1,1,0,0,0)).AddSeconds(date.SecondsSinceReferenceDate); } public static NSDate DateTimeToNSDate(DateTime date) { //var nsDateNow = (DateTime)NSDate.Now; //var diff = DateTime.Now.Subtract(nsDateNow); //var newDate = (NSDate)date.Add(-diff); var newDate = (NSDate)date; return newDate; } public PickerTypes PickerType; public DateTime DateValue; public UIDatePicker datePicker; public CalendarMonthView calView; private UIBarButtonItem leftOld; private UIBarButtonItem rightOld; private UIBarButtonItem switchButton; private UIBarButtonItem doneButton; public bool DisableSwitching; public NSAction DoneEditing; public DateSelected OnDateSelected; public bool closeOnSelect; protected internal NSDateFormatter fmt = new NSDateFormatter () { DateStyle = NSDateFormatterStyle.Short }; public CalendarDateTimeElement (string caption, DateTime date) : base (caption) { PickerType = PickerTypes.Calendar; DateValue = date; Value = DateValue.ToShortDateString(); } public CalendarDateTimeElement (string caption, DateTime date, PickerTypes pickerType) : base (caption) { PickerType = pickerType; DateValue = date; Value = DateValue.ToShortDateString(); } public override UITableViewCell GetCell (UITableView tv) { if (DateValue.Year < 2000) Value = "No Due Date"; else Value = FormatDate(DateValue); var cell = base.GetCell (tv); return cell; } protected override void Dispose (bool disposing) { base.Dispose (disposing); if (disposing){ if (fmt != null){ fmt.Dispose (); fmt = null; } if (datePicker != null){ datePicker.Dispose (); datePicker = null; } } } public virtual string FormatDate (DateTime dt) { return fmt.ToString (dt) + " " + dt.ToLocalTime ().ToShortTimeString (); } public virtual UIDatePicker CreatePicker () { var picker = new UIDatePicker (RectangleF.Empty){ AutoresizingMask = UIViewAutoresizing.FlexibleWidth, Mode = UIDatePickerMode.Date, Date = DateValue }; return picker; } static RectangleF PickerFrameWithSize (SizeF size) { var screenRect = UIScreen.MainScreen.ApplicationFrame; float fY = 0, fX = 0; switch (UIApplication.SharedApplication.StatusBarOrientation){ case UIInterfaceOrientation.LandscapeLeft: case UIInterfaceOrientation.LandscapeRight: fX = (screenRect.Height - size.Width) /2; fY = (screenRect.Width - size.Height) / 2 -17; break; case UIInterfaceOrientation.Portrait: case UIInterfaceOrientation.PortraitUpsideDown: fX = (screenRect.Width - size.Width) / 2; fY = (screenRect.Height - size.Height) / 2 - 25; break; } return new RectangleF (fX, fY, size.Width, size.Height); } public override void Deselected (DialogViewController dvc, UITableView tableView, NSIndexPath path) { tableView.DeselectRow(path,true); if (datePicker != null) { this.DateValue = (DateTime)datePicker.Date; SlideDown(dvc,tableView,path); } if (calView != null) CloseCalendar(dvc,tableView,path); } public override void Selected (DialogViewController dvc, UITableView tableView, NSIndexPath path) { if (DisableSwitching) ShowDatePicker(dvc,tableView,path); else if (PickerType == PickerTypes.Calendar) ShowCalendar(dvc,tableView,path); else ShowDatePicker(dvc,tableView,path); } private void ShowCalendar(DialogViewController dvc, UITableView tableView, NSIndexPath path) { if (calView == null) { calView = new CalendarMonthView(DateValue,true){ AutoresizingMask = UIViewAutoresizing.FlexibleWidth }; //calView.ToolbarColor = dvc.SearchBarTintColor; calView.SizeChanged += delegate { RectangleF screenRect = tableView.Window.Frame; SizeF pickerSize = calView.Size; // compute the end frame RectangleF pickerRect = new RectangleF(0.0f, screenRect.Y + screenRect.Size.Height - pickerSize.Height, pickerSize.Width, pickerSize.Height); // start the slide up animation UIView.BeginAnimations(null); UIView.SetAnimationDuration(0.3); // we need to perform some post operations after the animation is complete UIView.SetAnimationDelegate(dvc); calView.Frame = pickerRect; UIView.CommitAnimations(); }; } if (calView.Superview == null) { if (DateValue.Year < 2010) DateValue = DateTime.Today; calView.SizeThatFits(SizeF.Empty); calView.OnDateSelected += (date) => { DateValue = date; if (OnDateSelected != null) OnDateSelected(date); //Console.WriteLine(String.Format("Selected {0}", date.ToShortDateString())); if(closeOnSelect) CloseCalendar(dvc,tableView,path); }; tableView.Window.AddSubview(calView); //dvc.View.Window.AddSubview(datePicker); // // size up the picker view to our screen and compute the start/end frame origin for our slide up animation // // compute the start frame RectangleF screenRect = tableView.Window.Frame; SizeF pickerSize = calView.Size; RectangleF startRect = new RectangleF(0.0f, screenRect.Y + screenRect.Size.Height, pickerSize.Width, pickerSize.Height); calView.Frame = startRect; // compute the end frame RectangleF pickerRect = new RectangleF(0.0f, screenRect.Y + screenRect.Size.Height - pickerSize.Height, pickerSize.Width, pickerSize.Height); // start the slide up animation UIView.BeginAnimations(null); UIView.SetAnimationDuration(0.3); // we need to perform some post operations after the animation is complete UIView.SetAnimationDelegate(dvc); calView.Frame = pickerRect; // shrink the table vertical size to make room for the date picker RectangleF newFrame = new RectangleF(tableView.Frame.X, tableView.Frame.Y, tableView.Frame.Size.Width, tableView.Frame.Size.Height + 55 - calView.Frame.Height) ; // newFrame.Size.Height -= datePicker.Frame.Height; //tableView.Frame = newFrame; UIView.CommitAnimations(); rightOld = dvc.NavigationItem.RightBarButtonItem; //Multi Buttons // create a toolbar to have two buttons in the right UIToolbar tools = new UIToolbar(new RectangleF(0, 0, 133, 44.01f)); tools.TintColor = dvc.NavigationController.NavigationBar.TintColor; // create the array to hold the buttons, which then gets added to the toolbar List<UIBarButtonItem> buttons = new List<UIBarButtonItem>(3); // create switch button switchButton = new UIBarButtonItem("Switch",UIBarButtonItemStyle.Bordered,delegate{ CloseCalendar(dvc,tableView,path); ShowDatePicker(dvc,tableView,path); }); buttons.Add(switchButton); // create a spacer UIBarButtonItem spacer = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace,null,null); buttons.Add(spacer); //create done button doneButton = new UIBarButtonItem("Done",UIBarButtonItemStyle.Done, delegate{ //DateValue = calView.CurrentDate; CloseCalendar(dvc,tableView,path); }); buttons.Add(doneButton); tools.SetItems(buttons.ToArray(),false); // dvc.NavigationItem.RightBarButtonItem = new UIBarButtonItem(tools); leftOld = dvc.NavigationItem.LeftBarButtonItem; dvc.NavigationItem.LeftBarButtonItem = new UIBarButtonItem("None",UIBarButtonItemStyle.Bordered, delegate{ DateValue = DateTime.MinValue; if (OnDateSelected != null) OnDateSelected(CalendarDateTimeElement.DateTimeMin); CloseCalendar(dvc,tableView,path); }); // add the "Done" button to the nav bar //dvc.NavigationItem.SetRightBarButtonItem(doneButton,true); // } } private void CloseCalendar(DialogViewController dvc, UITableView tableView, NSIndexPath path) { tableView.ReloadRows(new NSIndexPath[]{path},UITableViewRowAnimation.None); RectangleF screenRect = dvc.View.Window.Frame; RectangleF endFrame = new RectangleF( calView.Frame.X,calView.Frame.Y + screenRect.Size.Height, calView.Frame.Size.Width,calView.Frame.Size.Height); //endFrame.origin.y = screenRect.Y + screenRect.Size.Height; // start the slide down animation UIView.BeginAnimations(null); UIView.SetAnimationDuration(0.3); // we need to perform some post operations after the animation is complete UIView.SetAnimationDelegate(dvc); //UIView.SetAnimationDidStopSelector(slideDownDidStop()); calView.Frame = endFrame; UIView.CommitAnimations(); // remove the "Done" button in the nav bar dvc.NavigationItem.RightBarButtonItem = rightOld; dvc.NavigationItem.LeftBarButtonItem = leftOld; // deselect the current table row tableView.DeselectRow(path,true); calView.RemoveFromSuperview(); calView = null; if (DoneEditing != null) DoneEditing(); } private void ShowDatePicker(DialogViewController dvc, UITableView tableView, NSIndexPath path) { if (datePicker == null) datePicker = CreatePicker(); if (datePicker.Superview == null) { if (DateValue.Year < 2010) datePicker.Date = DateTime.Today; else datePicker.Date = DateValue ; datePicker.MinimumDate = new DateTime(2010,1,1); tableView.Window.AddSubview(datePicker); //dvc.View.Window.AddSubview(datePicker); // // size up the picker view to our screen and compute the start/end frame origin for our slide up animation // // compute the start frame RectangleF screenRect = tableView.Window.Frame; SizeF pickerSize = datePicker.Frame.Size; RectangleF startRect = new RectangleF(0.0f, screenRect.Y + screenRect.Size.Height, pickerSize.Width, pickerSize.Height); datePicker.Frame = startRect; // compute the end frame RectangleF pickerRect = new RectangleF(0.0f, screenRect.Y + screenRect.Size.Height - pickerSize.Height, pickerSize.Width, pickerSize.Height); // start the slide up animation UIView.BeginAnimations(null); UIView.SetAnimationDuration(0.3); // we need to perform some post operations after the animation is complete UIView.SetAnimationDelegate(dvc); datePicker.Frame = pickerRect; UIView.CommitAnimations(); rightOld = dvc.NavigationItem.RightBarButtonItem; //create done button doneButton = new UIBarButtonItem("Done",UIBarButtonItemStyle.Done, delegate{ SlideDown(dvc,tableView,path); }); // doneButton.TintColor = dvc.NavigationController.NavigationBar.TintColor; // create a toolbar to have two buttons in the right if(DisableSwitching) dvc.NavigationItem.RightBarButtonItem = doneButton; else { UIToolbar tools = new UIToolbar(new RectangleF(0, 0, 133, 44.01f)); // tools.TintColor = dvc.NavigationController.NavigationBar.TintColor; // create the array to hold the buttons, which then gets added to the toolbar List<UIBarButtonItem> buttons = new List<UIBarButtonItem>(3); // create switch button switchButton = new UIBarButtonItem("Switch",UIBarButtonItemStyle.Bordered,delegate{ SlideDown(dvc,tableView,path); ShowCalendar(dvc,tableView,path); }); // switchButton.TintColor = dvc.NavigationController.NavigationBar.TintColor; buttons.Add(switchButton); // create a spacer UIBarButtonItem spacer = new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace,null,null); buttons.Add(spacer); buttons.Add(doneButton); tools.SetItems(buttons.ToArray(),false); // dvc.NavigationItem.RightBarButtonItem = new UIBarButtonItem(tools); } leftOld = dvc.NavigationItem.LeftBarButtonItem; dvc.NavigationItem.LeftBarButtonItem = new UIBarButtonItem("None",UIBarButtonItemStyle.Bordered, delegate{ datePicker.Date = DateTime.MinValue; SlideDown(dvc,tableView,path); if (OnDateSelected != null) OnDateSelected(CalendarDateTimeElement.DateTimeMin); }); // add the "Done" button to the nav bar //dvc.NavigationItem.SetRightBarButtonItem(doneButton,true); // } } private void SlideDown(DialogViewController dvc, UITableView tableView, NSIndexPath path) { this.DateValue = datePicker.Date; tableView.ReloadRows(new NSIndexPath[]{path},UITableViewRowAnimation.None); RectangleF screenRect = dvc.View.Window.Frame; RectangleF endFrame = new RectangleF( datePicker.Frame.X,datePicker.Frame.Y + screenRect.Size.Height, datePicker.Frame.Size.Width,datePicker.Frame.Size.Height); //endFrame.origin.y = screenRect.Y + screenRect.Size.Height; // start the slide down animation UIView.BeginAnimations(null); UIView.SetAnimationDuration(0.3); // we need to perform some post operations after the animation is complete UIView.SetAnimationDelegate(dvc); //UIView.SetAnimationDidStopSelector(slideDownDidStop()); datePicker.Frame = endFrame; UIView.CommitAnimations(); // remove the "Done" button in the nav bar dvc.NavigationItem.RightBarButtonItem = rightOld; dvc.NavigationItem.LeftBarButtonItem = leftOld; // deselect the current table row tableView.DeselectRow(path,true); datePicker.RemoveFromSuperview(); datePicker = null; if (DoneEditing != null) DoneEditing(); } } public class CalendarElement : CalendarDateTimeElement { public CalendarElement (string caption, DateTime date) : base (caption, date) { fmt.DateStyle = NSDateFormatterStyle.Medium; } public override string FormatDate (DateTime dt) { return fmt.ToString (dt); } public override UIDatePicker CreatePicker () { var picker = base.CreatePicker (); picker.Mode = UIDatePickerMode.Date; return picker; } } public class CalendarTimeElement : CalendarDateTimeElement { public CalendarTimeElement (string caption, DateTime date) : base (caption,date) { } public override string FormatDate (DateTime dt) { return dt.ToLocalTime().ToShortTimeString (); } public override UIDatePicker CreatePicker () { var picker = base.CreatePicker (); picker.Mode = UIDatePickerMode.Time; return picker; } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Diagnostics; using Org.BouncyCastle.Math.Raw; namespace Org.BouncyCastle.Math.EC.Custom.Djb { internal class Curve25519Field { // 2^255 - 2^4 - 2^1 - 1 internal static readonly uint[] P = new uint[]{ 0xFFFFFFED, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x7FFFFFFF }; private const uint P7 = 0x7FFFFFFF; private static readonly uint[] PExt = new uint[]{ 0x00000169, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xFFFFFFED, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x3FFFFFFF }; private const uint PInv = 0x13; public static void Add(uint[] x, uint[] y, uint[] z) { Nat256.Add(x, y, z); if (Nat256.Gte(z, P)) { SubPFrom(z); } } public static void AddExt(uint[] xx, uint[] yy, uint[] zz) { Nat.Add(16, xx, yy, zz); if (Nat.Gte(16, zz, PExt)) { SubPExtFrom(zz); } } public static void AddOne(uint[] x, uint[] z) { Nat.Inc(8, x, z); if (Nat256.Gte(z, P)) { SubPFrom(z); } } public static uint[] FromBigInteger(BigInteger x) { uint[] z = Nat256.FromBigInteger(x); while (Nat256.Gte(z, P)) { Nat256.SubFrom(P, z); } return z; } public static void Half(uint[] x, uint[] z) { if ((x[0] & 1) == 0) { Nat.ShiftDownBit(8, x, 0, z); } else { Nat256.Add(x, P, z); Nat.ShiftDownBit(8, z, 0); } } public static void Multiply(uint[] x, uint[] y, uint[] z) { uint[] tt = Nat256.CreateExt(); Nat256.Mul(x, y, tt); Reduce(tt, z); } public static void MultiplyAddToExt(uint[] x, uint[] y, uint[] zz) { Nat256.MulAddTo(x, y, zz); if (Nat.Gte(16, zz, PExt)) { SubPExtFrom(zz); } } public static void Negate(uint[] x, uint[] z) { if (Nat256.IsZero(x)) { Nat256.Zero(z); } else { Nat256.Sub(P, x, z); } } public static void Reduce(uint[] xx, uint[] z) { Debug.Assert(xx[15] >> 30 == 0); uint xx07 = xx[7]; Nat.ShiftUpBit(8, xx, 8, xx07, z, 0); uint c = Nat256.MulByWordAddTo(PInv, xx, z) << 1; uint z7 = z[7]; c += (z7 >> 31) - (xx07 >> 31); z7 &= P7; z7 += Nat.AddWordTo(7, c * PInv, z); z[7] = z7; if (z7 >= P7 && Nat256.Gte(z, P)) { SubPFrom(z); } } public static void Reduce27(uint x, uint[] z) { Debug.Assert(x >> 26 == 0); uint z7 = z[7]; uint c = (x << 1 | z7 >> 31); z7 &= P7; z7 += Nat.AddWordTo(7, c * PInv, z); z[7] = z7; if (z7 >= P7 && Nat256.Gte(z, P)) { SubPFrom(z); } } public static void Square(uint[] x, uint[] z) { uint[] tt = Nat256.CreateExt(); Nat256.Square(x, tt); Reduce(tt, z); } public static void SquareN(uint[] x, int n, uint[] z) { Debug.Assert(n > 0); uint[] tt = Nat256.CreateExt(); Nat256.Square(x, tt); Reduce(tt, z); while (--n > 0) { Nat256.Square(z, tt); Reduce(tt, z); } } public static void Subtract(uint[] x, uint[] y, uint[] z) { int c = Nat256.Sub(x, y, z); if (c != 0) { AddPTo(z); } } public static void SubtractExt(uint[] xx, uint[] yy, uint[] zz) { int c = Nat.Sub(16, xx, yy, zz); if (c != 0) { AddPExtTo(zz); } } public static void Twice(uint[] x, uint[] z) { Nat.ShiftUpBit(8, x, 0, z); if (Nat256.Gte(z, P)) { SubPFrom(z); } } private static uint AddPTo(uint[] z) { long c = (long)z[0] - PInv; z[0] = (uint)c; c >>= 32; if (c != 0) { c = Nat.DecAt(7, z, 1); } c += (long)z[7] + (P7 + 1); z[7] = (uint)c; c >>= 32; return (uint)c; } private static uint AddPExtTo(uint[] zz) { long c = (long)zz[0] + PExt[0]; zz[0] = (uint)c; c >>= 32; if (c != 0) { c = Nat.IncAt(8, zz, 1); } c += (long)zz[8] - PInv; zz[8] = (uint)c; c >>= 32; if (c != 0) { c = Nat.DecAt(15, zz, 9); } c += (long)zz[15] + (PExt[15] + 1); zz[15] = (uint)c; c >>= 32; return (uint)c; } private static int SubPFrom(uint[] z) { long c = (long)z[0] + PInv; z[0] = (uint)c; c >>= 32; if (c != 0) { c = Nat.IncAt(7, z, 1); } c += (long)z[7] - (P7 + 1); z[7] = (uint)c; c >>= 32; return (int)c; } private static int SubPExtFrom(uint[] zz) { long c = (long)zz[0] - PExt[0]; zz[0] = (uint)c; c >>= 32; if (c != 0) { c = Nat.DecAt(8, zz, 1); } c += (long)zz[8] + PInv; zz[8] = (uint)c; c >>= 32; if (c != 0) { c = Nat.IncAt(15, zz, 9); } c += (long)zz[15] - (PExt[15] + 1); zz[15] = (uint)c; c >>= 32; return (int)c; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Threading; using Windows.Foundation; using Windows.Storage.Streams; namespace System.IO { /// <summary>Depending on the concrete type of the stream managed by a <c>NetFxToWinRtStreamAdapter</c>, /// we want the <c>ReadAsync</c> / <c>WriteAsync</c> / <c>FlushAsync</c> / etc. operation to be implemented /// differently. This is for best performance as we can take advantage of the specifics of particular stream /// types. For instance, <c>ReadAsync</c> currently has a special implementation for memory streams. /// Moreover, knowledge about the actual runtime type of the <c>IBuffer</c> can also help chosing the optimal /// implementation. This type provides static methods that encapsulate the performance logic and can be used /// by <c>NetFxToWinRtStreamAdapter</c>.</summary> internal static class StreamOperationsImplementation { #region ReadAsync implementations internal static IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync_MemoryStream(Stream stream, IBuffer buffer, UInt32 count) { Debug.Assert(stream != null); Debug.Assert(stream is MemoryStream); Debug.Assert(stream.CanRead); Debug.Assert(stream.CanSeek); Debug.Assert(buffer != null); Debug.Assert(buffer is IBufferByteAccess); Debug.Assert(0 <= count); Debug.Assert(count <= Int32.MaxValue); Debug.Assert(count <= buffer.Capacity); Contract.EndContractBlock(); // We will return a different buffer to the user backed directly by the memory stream (avoids memory copy). // This is permitted by the WinRT stream contract. // The user specified buffer will not have any data put into it: buffer.Length = 0; MemoryStream memStream = stream as MemoryStream; Debug.Assert(memStream != null); try { IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((Int32)memStream.Position, (Int32)count); if (dataBuffer.Length > 0) memStream.Seek(dataBuffer.Length, SeekOrigin.Current); return AsyncInfo.CreateCompletedOperation<IBuffer, UInt32>(dataBuffer); } catch (Exception ex) { return AsyncInfo.CreateFaultedOperation<IBuffer, UInt32>(ex); } } // ReadAsync_MemoryStream internal static IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync_AbstractStream(Stream stream, IBuffer buffer, UInt32 count, InputStreamOptions options) { Debug.Assert(stream != null); Debug.Assert(stream.CanRead); Debug.Assert(buffer != null); Debug.Assert(buffer is IBufferByteAccess); Debug.Assert(0 <= count); Debug.Assert(count <= Int32.MaxValue); Debug.Assert(count <= buffer.Capacity); Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead); Contract.EndContractBlock(); Int32 bytesRequested = (Int32)count; // Check if the buffer is our implementation. // IF YES: In that case, we can read directly into its data array. // IF NO: The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only // read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read. // The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own // buffer instance, read data *directly* into the array backing it and then return it to the user. // Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we we would need to create // an array to read into either way. IBuffer dataBuffer = buffer as WindowsRuntimeBuffer; if (dataBuffer == null) dataBuffer = WindowsRuntimeBuffer.Create((Int32)Math.Min((UInt32)Int32.MaxValue, buffer.Capacity)); // This operation delegate will we run inside of the returned IAsyncOperationWithProgress: Func<CancellationToken, IProgress<UInt32>, Task<IBuffer>> readOperation = async (cancelToken, progressListener) => { // No bytes read yet: dataBuffer.Length = 0; // Get the buffer backing array: Byte[] data; Int32 offset; bool managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset); Debug.Assert(managedBufferAssert); // Init tracking values: bool done = cancelToken.IsCancellationRequested; Int32 bytesCompleted = 0; // Loop until EOS, cancelled or read enough data according to options: while (!done) { Int32 bytesRead = 0; try { // Read asynchronously: bytesRead = await stream.ReadAsync(data, offset + bytesCompleted, bytesRequested - bytesCompleted, cancelToken) .ConfigureAwait(continueOnCapturedContext: false); // We will continue here on a different thread when read async completed: bytesCompleted += bytesRead; // We will handle a cancelation exception and re-throw all others: } catch (OperationCanceledException) { // We assume that cancelToken.IsCancellationRequested is has been set and simply proceed. // (we check cancelToken.IsCancellationRequested later) Debug.Assert(cancelToken.IsCancellationRequested); // This is because if the cancellation came after we read some bytes we want to return the results we got instead // of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation: if (bytesCompleted == 0 && bytesRead == 0) throw; } // Update target buffer: dataBuffer.Length = (UInt32)bytesCompleted; Debug.Assert(bytesCompleted <= bytesRequested); // Check if we are done: done = options == InputStreamOptions.Partial // If no complete read was requested, any amount of data is OK || bytesRead == 0 // this implies EndOfStream || bytesCompleted == bytesRequested // read all requested bytes || cancelToken.IsCancellationRequested; // operation was cancelled // Call user Progress handler: if (progressListener != null) progressListener.Report(dataBuffer.Length); } // while (!done) // If we got here, then no error was detected. Return the results buffer: return dataBuffer; }; // readOperation return AsyncInfo.Run<IBuffer, UInt32>(readOperation); } // ReadAsync_AbstractStream #endregion ReadAsync implementations #region WriteAsync implementations internal static IAsyncOperationWithProgress<UInt32, UInt32> WriteAsync_AbstractStream(Stream stream, IBuffer buffer) { Debug.Assert(stream != null); Debug.Assert(stream.CanWrite); Debug.Assert(buffer != null); Contract.EndContractBlock(); // Choose the optimal writing strategy for the kind of buffer supplied: Func<CancellationToken, IProgress<UInt32>, Task<UInt32>> writeOperation; Byte[] data; Int32 offset; // If buffer is backed by a managed array: if (buffer.TryGetUnderlyingData(out data, out offset)) { writeOperation = async (cancelToken, progressListener) => { if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable return 0; Debug.Assert(buffer.Length <= Int32.MaxValue); Int32 bytesToWrite = (Int32)buffer.Length; await stream.WriteAsync(data, offset, bytesToWrite, cancelToken).ConfigureAwait(continueOnCapturedContext: false); if (progressListener != null) progressListener.Report((UInt32)bytesToWrite); return (UInt32)bytesToWrite; }; // Otherwise buffer is of an unknown implementation: } else { writeOperation = async (cancelToken, progressListener) => { if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable return 0; UInt32 bytesToWrite = buffer.Length; Stream dataStream = buffer.AsStream(); Int32 buffSize = 0x4000; if (bytesToWrite < buffSize) buffSize = (Int32)bytesToWrite; await dataStream.CopyToAsync(stream, buffSize, cancelToken).ConfigureAwait(continueOnCapturedContext: false); if (progressListener != null) progressListener.Report((UInt32)bytesToWrite); return (UInt32)bytesToWrite; }; } // if-else // Construct and run the async operation: return AsyncInfo.Run<UInt32, UInt32>(writeOperation); } // WriteAsync_AbstractStream #endregion WriteAsync implementations #region FlushAsync implementations internal static IAsyncOperation<Boolean> FlushAsync_AbstractStream(Stream stream) { Debug.Assert(stream != null); Debug.Assert(stream.CanWrite); Contract.EndContractBlock(); Func<CancellationToken, Task<Boolean>> flushOperation = async (cancelToken) => { if (cancelToken.IsCancellationRequested) // CancellationToken is non-nullable return false; await stream.FlushAsync(cancelToken).ConfigureAwait(continueOnCapturedContext: false); return true; }; // Construct and run the async operation: return AsyncInfo.Run<Boolean>(flushOperation); } #endregion FlushAsync implementations } // class StreamOperationsImplementation } // namespace
// Copyright (c) 2010-2013 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.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using CommonDX; using SharpDX; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX.DXGI; using SharpDX.IO; using Windows.ApplicationModel; using Windows.ApplicationModel.Core; using Windows.Graphics.Display; using Windows.Storage; using Windows.Storage.Pickers; using Windows.Storage.Streams; using Windows.System.Threading; using Windows.UI.Core; using Windows.UI.Xaml; namespace MiniCubeTexture { /// <summary> /// SharpDX port of SharpDX-MiniCube Direct3D 11 Sample /// </summary> internal static class App { class SharpDXMiniCubeViewProvider : Component, IFrameworkView { DeviceManager deviceManager; CoreWindowTarget target; CubeTextureRenderer cubeRenderer; CoreWindow window; private bool IsInitialized = false; public SharpDXMiniCubeViewProvider() { } /// <inheritdoc/> public void Initialize(CoreApplicationView applicationView) { } /// <inheritdoc/> public void SetWindow(CoreWindow window) { this.window = window; // Safely dispose any previous instance RemoveAndDispose(ref deviceManager); RemoveAndDispose(ref target); RemoveAndDispose(ref cubeRenderer); // Creates a new DeviceManager (Direct3D, Direct2D, DirectWrite, WIC) deviceManager = ToDispose(new DeviceManager()); // Use CoreWindowTarget as the rendering target (Initialize SwapChain, RenderTargetView, DepthStencilView, BitmapTarget) target = ToDispose(new CoreWindowTarget(window)); // New CubeRenderer cubeRenderer = ToDispose(new CubeTextureRenderer()); } /// <inheritdoc/> public void Load(string entryPoint) { } private async void RunAsync() { var fileOpenPicker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.VideosLibrary, ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail }; fileOpenPicker.CommitButtonText = "Open the Selected Video"; fileOpenPicker.FileTypeFilter.Clear(); fileOpenPicker.FileTypeFilter.Add(".mp4"); fileOpenPicker.FileTypeFilter.Add(".m4v"); fileOpenPicker.FileTypeFilter.Add(".mts"); fileOpenPicker.FileTypeFilter.Add(".mov"); fileOpenPicker.FileTypeFilter.Add(".wmv"); fileOpenPicker.FileTypeFilter.Add(".avi"); fileOpenPicker.FileTypeFilter.Add(".asf"); var file = await fileOpenPicker.PickSingleFileAsync(); cubeRenderer.VideoStream = await file.OpenAsync(FileAccessMode.Read); // Add Initializer to device manager deviceManager.OnInitialize += target.Initialize; deviceManager.OnInitialize += cubeRenderer.Initialize; // Render the cube within the CoreWindow target.OnRender += cubeRenderer.Render; // Initialize the device manager and all registered deviceManager.OnInitialize deviceManager.Initialize(DisplayProperties.LogicalDpi); // Notifies the main loop that initialization is done lock (this) { IsInitialized = true; } } /// <inheritdoc/> public void Run() { DisplayProperties.LogicalDpiChanged += DisplayProperties_LogicalDpiChanged; // Specify the cursor type as the standard arrow cursor. window.PointerCursor = new CoreCursor(CoreCursorType.Arrow, 0); // Activate the application window, making it visible and enabling it to receive events. window.Activate(); // Run this method async // But because It was not possible to use correctly async here // we have to use a lock approach, which is far from ideal, but it is at least working. // The problem is described here: http://social.msdn.microsoft.com/Forums/mr-IN/winappswithcsharp/thread/d09dd944-f92b-484d-b2ef-d1850c4a587f RunAsync(); // Enter the render loop. Note that Metro style apps should never exit. while (true) { // Process events incoming to the window. window.Dispatcher.ProcessEvents(CoreProcessEventsOption.ProcessAllIfPresent); if (window.GetAsyncKeyState(Windows.System.VirtualKey.Escape) == CoreVirtualKeyStates.Down) break; bool isInitOk = false; // Check if initialization is done lock (this) { isInitOk = IsInitialized; } // If done, perform rendering if (isInitOk) { // Render the cube target.RenderAll(); // Present the cube target.Present(); } } } void DisplayProperties_LogicalDpiChanged(object sender) { deviceManager.Dpi = DisplayProperties.LogicalDpi; } public void Uninitialize() { } } class SharpDXMiniCubeViewProviderFactory : IFrameworkViewSource { public IFrameworkView CreateView() { return new SharpDXMiniCubeViewProvider(); } } [MTAThread] private static void Main() { var viewFactory = new SharpDXMiniCubeViewProviderFactory(); Windows.ApplicationModel.Core.CoreApplication.Run(viewFactory); } } }
//11JUN2008 RunUO SVN fix //11JUN2008 Client 6.0.5 Encryption fix //05MAR2009 Smjert's fix for double log in. using System; using System.Net; using System.Net.Sockets; using System.Collections; using Server.Accounting; using Server; using Server.Network; using Server.Misc; namespace Server.Engines.Encryption { // This class handles OSI client encryption for clients newer than 2.0.3. (not including 2.0.3) public class Encryption : IPacketEncoder { // Encryption state information private uint m_Seed; private bool m_Seeded; private ByteQueue m_Buffer; private IClientEncryption m_Encryption; private bool m_AlreadyRelayed; public Encryption() { m_AlreadyRelayed = false; m_Encryption = null; m_Buffer = new ByteQueue(); m_Seeded = false; m_Seed = 0; } static public void Initialize() { // Only initialize our subsystem if we're enabled if (Configuration.Enabled) { // Initialize static members and connect to the creation callback of a NetState. NetState.CreatedCallback = new NetStateCreatedCallback(NetStateCreated); // Overwrite the packet handler for the relay packet since we need to change the // encryption mode then. PacketHandlers.Register(0xA0, 3, false, new OnPacketReceive(HookedPlayServer)); } } public static void NetStateCreated(NetState state) { state.PacketEncoder = new Encryption(); } public static void HookedPlayServer(NetState state, PacketReader pvSrc) { // Call the original handler PacketHandlers.PlayServer(state, pvSrc); // Now indicate, that the state has been relayed already. If it's used again, // it means we're entering a special encryption state Encryption context = (Encryption)(state.PacketEncoder); context.m_AlreadyRelayed = true; } // Try to encrypt outgoing data. public void EncodeOutgoingPacket(NetState to, ref byte[] buffer, ref int length) { if (m_Encryption != null) { m_Encryption.serverEncrypt(ref buffer, length); return; } } public void RejectNoEncryption(NetState ns) { // Log it on the console Console.WriteLine("Client: {0}: Unencrypted client detected, disconnected", ns); // Send the client the typical "Bad communication" packet and also a sysmessage stating the error ns.Send(new AsciiMessage(Server.Serial.MinusOne, -1, MessageType.Label, 0x35, 3, "System", "Unencrypted connections are not allowed on this server.")); ns.Send(new AccountLoginRej(ALRReason.BadComm)); // Disconnect the client ns.Dispose(true); } // Try to decrypt incoming data. public void DecodeIncomingPacket(NetState from, ref byte[] buffer, ref int length) { #region m_Encryption != null if (m_Encryption != null) { /* // If we're decrypting using LoginCrypt and we've already been relayed, // only decrypt a single packet using logincrypt and then disable it if (m_AlreadyRelayed && m_Encryption is LoginEncryption) { uint newSeed = ((((LoginEncryption)(m_Encryption)).Key1 + 1) ^ ((LoginEncryption)(m_Encryption)).Key2); // Swap the seed newSeed = ((newSeed >> 24) & 0xFF) | ((newSeed >> 8) & 0xFF00) | ((newSeed << 8) & 0xFF0000) | ((newSeed << 24) & 0xFF000000); // XOR it with the old seed newSeed ^= m_Seed; IClientEncryption newEncryption = new GameEncryption(newSeed); // Game Encryption comes first newEncryption.clientDecrypt(ref buffer, length); // The login encryption is still used for this one packet m_Encryption.clientDecrypt(ref buffer, length); // Swap the encryption schemes m_Encryption = newEncryption; m_Seed = newSeed; return; }*/ m_Encryption.clientDecrypt(ref buffer, length); return; } #endregion #region Port Scan //11JUN2008 RunUO SVN fix ** START *** // If the client did not connect on the game server port, // it's not our business to handle encryption for it //if (((IPEndPoint)from.Socket.LocalEndPoint).Port != Listener.Port) //{ // m_Encryption = new NoEncryption(); // return; //} bool handle = false; for (int i = 0; i < Listener.EndPoints.Length; i++) { IPEndPoint ipep = (IPEndPoint)Listener.EndPoints[i]; if (((IPEndPoint)from.Socket.LocalEndPoint).Port == ipep.Port) handle = true; } if (!handle) { m_Encryption = new NoEncryption(); return; } //11JUN2008 RunUO SVN fix ** END *** #endregion #region !m_Seeded // For simplicities sake, enqueue what we just received as long as we're not initialized m_Buffer.Enqueue(buffer, 0, length); // Clear the array length = 0; // If we didn't receive the seed yet, queue data until we can read the seed //if (!m_Seeded) //{ // // Now check if we have at least 4 bytes to get the seed // if (m_Buffer.Length >= 4) // { // byte[] m_Peek = new byte[m_Buffer.Length]; // m_Buffer.Dequeue( m_Peek, 0, m_Buffer.Length ); // Dequeue everything // m_Seed = (uint)((m_Peek[0] << 24) | (m_Peek[1] << 16) | (m_Peek[2] << 8) | m_Peek[3]); // m_Seeded = true; // Buffer.BlockCopy(m_Peek, 0, buffer, 0, 4); // length = 4; // } // else // { // return; // } //} //http://uodev.de/viewtopic.php?t=5097&postdays=0&postorder=asc&start=15&sid=dfb8e6c73b9e3eb95c1634ca3586e8a7 //if (!m_Seeded) //{ // int seed_length = m_Buffer.GetSeedLength(); // if (m_Buffer.Length >= seed_length) // { // byte[] m_Peek = new byte[m_Buffer.Length]; // m_Buffer.Dequeue(m_Peek, 0, seed_length); // if (seed_length == 4) // m_Seed = (uint)((m_Peek[0] << 24) | (m_Peek[1] << 16) | (m_Peek[2] << 8) | m_Peek[3]); // else if (seed_length == 21) // m_Seed = (uint)((m_Peek[1] << 24) | (m_Peek[2] << 16) | (m_Peek[3] << 8) | m_Peek[4]); // m_Seeded = true; // Buffer.BlockCopy(m_Peek, 0, buffer, 0, seed_length); // length = seed_length; // } // else // { // return; // } //} //11JUN2008 My Version if (!m_Seeded) { if (m_Buffer.Length <= 3) //Short Length, try again. { Console.WriteLine("Encryption: Failed - Short Lenght"); return; } //else if ((m_Buffer.Length == 83) && (m_Buffer.GetPacketID() == 239)) //New Client //{ // byte[] m_Peek = new byte[21]; // m_Buffer.Dequeue(m_Peek, 0, 21); // m_Seed = (uint)((m_Peek[1] << 24) | (m_Peek[2] << 16) | (m_Peek[3] << 8) | m_Peek[4]); // m_Seeded = true; // Buffer.BlockCopy(m_Peek, 0, buffer, 0, 21); // length = 21; // Console.WriteLine("Encryption: Passed - New Client"); //} //05MAR2009 Smjert's fix for double log in. *** START *** else if ((m_Buffer.Length == 83 || m_Buffer.Length == 21) && (m_Buffer.GetPacketID() == 239)) //New Client { length = m_Buffer.Length; byte[] m_Peek = new byte[21]; m_Buffer.Dequeue(m_Peek, 0, 21); m_Seed = (uint)((m_Peek[1] << 24) | (m_Peek[2] << 16) | (m_Peek[3] << 8) | m_Peek[4]); m_Seeded = true; Buffer.BlockCopy(m_Peek, 0, buffer, 0, 21); Console.WriteLine("Encryption: Passed - New Client"); // We need to wait the next packet if (length == 21) return; length = 21; } else if (m_Buffer.Length >= 4) //Old Client //05MAR2009 Smjert's fix for double log in. *** END *** { byte[] m_Peek = new byte[4]; m_Buffer.Dequeue(m_Peek, 0, 4); m_Seed = (uint)((m_Peek[0] << 24) | (m_Peek[1] << 16) | (m_Peek[2] << 8) | m_Peek[3]); m_Seeded = true; Buffer.BlockCopy(m_Peek, 0, buffer, 0, 4); length = 4; Console.WriteLine("Encryption: Passed - Old Client"); } else //It should never reach here. { Console.WriteLine("Encryption: Failed - It should never reach here"); return; } } #endregion // If the context isn't initialized yet, that means we haven't decided on an encryption method yet #region m_Encryption == null if (m_Encryption == null) { int packetLength = m_Buffer.Length; int packetOffset = length; m_Buffer.Dequeue(buffer, length, packetLength); // Dequeue everything length += packetLength; // This is special handling for the "special" UOG packet if (packetLength >= 3) { if (buffer[packetOffset] == 0xf1 && buffer[packetOffset + 1] == ((packetLength >> 8) & 0xFF) && buffer[packetOffset + 2] == (packetLength & 0xFF)) { m_Encryption = new NoEncryption(); return; } } // Check if the current buffer contains a valid login packet (62 byte + 4 byte header) // Please note that the client sends these in two chunks. One 4 byte and one 62 byte. if (packetLength == 62) { Console.WriteLine("Checking packetLength 62 == " + packetLength); // Check certain indices in the array to see if the given data is unencrypted if (buffer[packetOffset] == 0x80 && buffer[packetOffset + 30] == 0x00 && buffer[packetOffset + 60] == 0x00) { if (Configuration.AllowUnencryptedClients) { m_Encryption = new NoEncryption(); } else { RejectNoEncryption(from); from.Dispose(); return; } } else { LoginEncryption encryption = new LoginEncryption(); if (encryption.init(m_Seed, buffer, packetOffset, packetLength)) { Console.WriteLine("Client: {0}: Encrypted client detected, using keys of client {1}", from, encryption.Name); m_Encryption = encryption; Console.WriteLine("Encryption: Check 1"); byte[] packet = new byte[packetLength]; Console.WriteLine("Encryption: Check 2"); Buffer.BlockCopy(buffer, packetOffset, packet, 0, packetLength); Console.WriteLine("Encryption: Check 3"); encryption.clientDecrypt(ref packet, packet.Length); Console.WriteLine("Encryption: Check 4"); Buffer.BlockCopy(packet, 0, buffer, packetOffset, packetLength); Console.WriteLine("Encryption: Check 5"); //return; //Just throwing this in. } else { Console.WriteLine("Detected an unknown client."); } } } else if (packetLength == 65) { Console.WriteLine("Checking packetLength 65 == " + packetLength); // If its unencrypted, use the NoEncryption class if (buffer[packetOffset] == '\x91' && buffer[packetOffset + 1] == ((m_Seed >> 24) & 0xFF) && buffer[packetOffset + 2] == ((m_Seed >> 16) & 0xFF) && buffer[packetOffset + 3] == ((m_Seed >> 8) & 0xFF) && buffer[packetOffset + 4] == (m_Seed & 0xFF)) { if (Configuration.AllowUnencryptedClients) { m_Encryption = new NoEncryption(); } else { RejectNoEncryption(from); from.Dispose(); } } else { // If it's not an unencrypted packet, simply assume it's encrypted with the seed m_Encryption = new GameEncryption(m_Seed); byte[] packet = new byte[packetLength]; Buffer.BlockCopy(buffer, packetOffset, packet, 0, packetLength); m_Encryption.clientDecrypt(ref packet, packet.Length); Buffer.BlockCopy(packet, 0, buffer, packetOffset, packetLength); } } // If it's still not initialized, copy the data back to the queue and wait for more if (m_Encryption == null) { Console.WriteLine("Encryption: Check - Waiting"); m_Buffer.Enqueue(buffer, packetOffset, packetLength); length -= packetLength; return; } } #endregion } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Xml.Linq; using Microsoft.Internal.Web.Utils; using NuGet.Resources; namespace NuGet { public class ProjectManager : IProjectManager { private event EventHandler<PackageOperationEventArgs> _packageReferenceAdding; private event EventHandler<PackageOperationEventArgs> _packageReferenceAdded; private event EventHandler<PackageOperationEventArgs> _packageReferenceRemoving; private event EventHandler<PackageOperationEventArgs> _packageReferenceRemoved; private ILogger _logger; private IPackageConstraintProvider _constraintProvider; // REVIEW: These should be externally pluggable private static readonly IDictionary<string, IPackageFileTransformer> _fileTransformers = new Dictionary<string, IPackageFileTransformer>(StringComparer.OrdinalIgnoreCase) { { ".transform", new XmlTransfomer(GetConfigMappings()) }, { ".pp", new Preprocessor() } }; public ProjectManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IProjectSystem project, IPackageRepository localRepository) { if (sourceRepository == null) { throw new ArgumentNullException("sourceRepository"); } if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (project == null) { throw new ArgumentNullException("project"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } SourceRepository = sourceRepository; Project = project; PathResolver = pathResolver; LocalRepository = localRepository; } public IPackagePathResolver PathResolver { get; private set; } public IPackageRepository LocalRepository { get; private set; } public IPackageRepository SourceRepository { get; private set; } public IPackageConstraintProvider ConstraintProvider { get { return _constraintProvider ?? NullConstraintProvider.Instance; } set { _constraintProvider = value; } } public IProjectSystem Project { get; private set; } public ILogger Logger { get { return _logger ?? NullLogger.Instance; } set { _logger = value; } } public event EventHandler<PackageOperationEventArgs> PackageReferenceAdding { add { _packageReferenceAdding += value; } remove { _packageReferenceAdding -= value; } } public event EventHandler<PackageOperationEventArgs> PackageReferenceAdded { add { _packageReferenceAdded += value; } remove { _packageReferenceAdded -= value; } } public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoving { add { _packageReferenceRemoving += value; } remove { _packageReferenceRemoving -= value; } } public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoved { add { _packageReferenceRemoved += value; } remove { _packageReferenceRemoved -= value; } } public virtual void AddPackageReference(string packageId) { AddPackageReference(packageId, version: null, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version) { AddPackageReference(packageId, version: version, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions) { IPackage package = PackageHelper.ResolvePackage(SourceRepository, LocalRepository, NullConstraintProvider.Instance, packageId, version, allowPrereleaseVersions); AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions); } public virtual void AddPackageReference(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions) { Execute(package, new UpdateWalker(LocalRepository, SourceRepository, new DependentsWalker(LocalRepository), ConstraintProvider, NullLogger.Instance, !ignoreDependencies, allowPrereleaseVersions) { AcceptedTargets = PackageTargets.Project }); } private void Execute(IPackage package, IPackageOperationResolver resolver) { IEnumerable<PackageOperation> operations = resolver.ResolveOperations(package); if (operations.Any()) { foreach (PackageOperation operation in operations) { Execute(operation); } } else if (LocalRepository.Exists(package)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, package.GetFullName()); } } protected void Execute(PackageOperation operation) { bool packageExists = LocalRepository.Exists(operation.Package); if (operation.Action == PackageAction.Install) { // If the package is already installed, then skip it if (packageExists) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, operation.Package.GetFullName()); } else { AddPackageReferenceToProject(operation.Package); } } else { if (packageExists) { RemovePackageReferenceFromProject(operation.Package); } } } protected void AddPackageReferenceToProject(IPackage package) { PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceAdding(args); if (args.Cancel) { return; } ExtractPackageFilesToProject(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyAddedPackageReference, package.GetFullName(), Project.ProjectName); OnPackageReferenceAdded(args); } protected virtual void ExtractPackageFilesToProject(IPackage package) { // BUG 491: Installing a package with incompatible binaries still does a partial install. // Resolve assembly references first so that if this fails we never do anything to the project IEnumerable<IPackageAssemblyReference> assemblyReferences = GetCompatibleItems(Project, package.AssemblyReferences, package.GetFullName()); IEnumerable<FrameworkAssemblyReference> frameworkReferences = Project.GetCompatibleItemsCore(package.FrameworkAssemblies); try { // Add content files Project.AddFiles(package.GetContentFiles(), _fileTransformers); // Add the references to the reference path foreach (IPackageAssemblyReference assemblyReference in assemblyReferences) { // Get the physical path of the assembly reference string referencePath = Path.Combine(PathResolver.GetInstallPath(package), assemblyReference.Path); string relativeReferencePath = PathUtility.GetRelativePath(Project.Root, referencePath); if (Project.ReferenceExists(assemblyReference.Name)) { Project.RemoveReference(assemblyReference.Name); } using (Stream stream = assemblyReference.GetStream()) { Project.AddReference(relativeReferencePath, stream); } } // Add GAC/Framework references foreach (FrameworkAssemblyReference frameworkReference in frameworkReferences) { if (!Project.ReferenceExists(frameworkReference.AssemblyName)) { Project.AddFrameworkReference(frameworkReference.AssemblyName); } } } finally { // Add package to local repository in the finally so that the user can uninstall it // if any exception occurs. This is easier than rolling back since the user can just // manually uninstall things that may have failed. // If this fails then the user is out of luck. LocalRepository.AddPackage(package); } } public bool IsInstalled(IPackage package) { return LocalRepository.Exists(package); } public void RemovePackageReference(string packageId) { RemovePackageReference(packageId, forceRemove: false, removeDependencies: false); } public void RemovePackageReference(string packageId, bool forceRemove) { RemovePackageReference(packageId, forceRemove: forceRemove, removeDependencies: false); } public virtual void RemovePackageReference(string packageId, bool forceRemove, bool removeDependencies) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage package = LocalRepository.FindPackage(packageId); if (package == null) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, NuGetResources.UnknownPackage, packageId)); } RemovePackageReference(package, forceRemove, removeDependencies); } public virtual void RemovePackageReference(IPackage package, bool forceRemove, bool removeDependencies) { Execute(package, new UninstallWalker(LocalRepository, new DependentsWalker(LocalRepository), NullLogger.Instance, removeDependencies, forceRemove)); } [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] private void RemovePackageReferenceFromProject(IPackage package) { PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceRemoving(args); if (args.Cancel) { return; } // Get other packages IEnumerable<IPackage> otherPackages = from p in LocalRepository.GetPackages() where p.Id != package.Id select p; // Get other references var otherAssemblyReferences = from p in otherPackages let assemblyReferences = Project.GetCompatibleItemsCore(p.AssemblyReferences) from assemblyReference in assemblyReferences ?? Enumerable.Empty<IPackageAssemblyReference>() // This can happen if package installed left the project in a bad state select assemblyReference; // Get content files from other packages // Exclude transform files since they are treated specially var otherContentFiles = from p in otherPackages from file in p.GetContentFiles() where !_fileTransformers.ContainsKey(Path.GetExtension(file.Path)) select file; // Get the files and references for this package, that aren't in use by any other packages so we don't have to do reference counting var assemblyReferencesToDelete = Project.GetCompatibleItemsCore(package.AssemblyReferences).Except(otherAssemblyReferences, PackageFileComparer.Default); var contentFilesToDelete = package.GetContentFiles() .Except(otherContentFiles, PackageFileComparer.Default); // Delete the content files Project.DeleteFiles(contentFilesToDelete, otherPackages, _fileTransformers); // Remove references foreach (IPackageAssemblyReference assemblyReference in assemblyReferencesToDelete) { Project.RemoveReference(assemblyReference.Name); } // Remove package to the repository LocalRepository.RemovePackage(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyRemovedPackageReference, package.GetFullName(), Project.ProjectName); OnPackageReferenceRemoved(args); } public void UpdatePackageReference(string packageId) { UpdatePackageReference(packageId, version: null, updateDependencies: true, allowPrereleaseVersions: false); } public void UpdatePackageReference(string packageId, SemanticVersion version) { UpdatePackageReference(packageId, version: version, updateDependencies: true, allowPrereleaseVersions: false); } public void UpdatePackageReference(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference( packageId, () => SourceRepository.FindPackage(packageId, versionSpec, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: versionSpec != null); } public virtual void UpdatePackageReference(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference(packageId, () => SourceRepository.FindPackage(packageId, version, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: version != null); } private void UpdatePackageReference(string packageId, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, bool targetVersionSetExplicitly) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage oldPackage = LocalRepository.FindPackage(packageId); // Check to see if this package is installed if (oldPackage == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.ProjectDoesNotHaveReference, Project.ProjectName, packageId)); } Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId); IPackage package = resolvePackage(); // the condition (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version) // is to fix bug 1574. We want to do nothing if, let's say, you have package 2.0alpha installed, and you do: // update-package // without specifying a version explicitly, and the feed only has version 1.0 as the latest stable version. if (package != null && oldPackage.Version != package.Version && (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_UpdatingPackages, package.Id, oldPackage.Version, package.Version, Project.ProjectName); UpdatePackageReference(package, updateDependencies, allowPrereleaseVersions); } else { IVersionSpec constraint = ConstraintProvider.GetConstraint(packageId); if (constraint != null) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ApplyingConstraints, packageId, VersionUtility.PrettyPrint(constraint), ConstraintProvider.Source); } Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailableForProject, packageId, Project.ProjectName); } } protected void UpdatePackageReference(IPackage package) { UpdatePackageReference(package, updateDependencies: true, allowPrereleaseVersions: false); } protected void UpdatePackageReference(IPackage package, bool updateDependencies, bool allowPrereleaseVersions) { AddPackageReference(package, !updateDependencies, allowPrereleaseVersions); } private void OnPackageReferenceAdding(PackageOperationEventArgs e) { if (_packageReferenceAdding != null) { _packageReferenceAdding(this, e); } } private void OnPackageReferenceAdded(PackageOperationEventArgs e) { if (_packageReferenceAdded != null) { _packageReferenceAdded(this, e); } } private void OnPackageReferenceRemoved(PackageOperationEventArgs e) { if (_packageReferenceRemoved != null) { _packageReferenceRemoved(this, e); } } private void OnPackageReferenceRemoving(PackageOperationEventArgs e) { if (_packageReferenceRemoving != null) { _packageReferenceRemoving(this, e); } } private PackageOperationEventArgs CreateOperation(IPackage package) { return new PackageOperationEventArgs(package, Project, PathResolver.GetInstallPath(package)); } private static IDictionary<XName, Action<XElement, XElement>> GetConfigMappings() { // REVIEW: This might be an edge case, but we're setting this rule for all xml files. // If someone happens to do a transform where the xml file has a configSections node // we will add it first. This is probably fine, but this is a config specific scenario return new Dictionary<XName, Action<XElement, XElement>>() { { "configSections" , (parent, element) => parent.AddFirst(element) } }; } private static IEnumerable<T> GetCompatibleItems<T>(IProjectSystem project, IEnumerable<T> items, string package) where T : IFrameworkTargetable { // A package might have references that target a specific version of the framework (.net/silverlight etc) // so we try to get the highest version that satisfies the target framework i.e. // if a package has 1.0, 2.0, 4.0 and the target framework is 3.5 we'd pick the 2.0 references. IEnumerable<T> compatibleItems; if (!project.TryGetCompatibleItems(items, out compatibleItems)) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToFindCompatibleItems, package, project.TargetFramework, NuGetResources.AssemblyReferences)); } return compatibleItems; } private class PackageFileComparer : IEqualityComparer<IPackageFile> { internal readonly static PackageFileComparer Default = new PackageFileComparer(); private PackageFileComparer() { } public bool Equals(IPackageFile x, IPackageFile y) { return x.Path.Equals(y.Path, StringComparison.OrdinalIgnoreCase); } public int GetHashCode(IPackageFile obj) { return obj.Path.GetHashCode(); } } // HACK: We need this to avoid a partial trust issue. We need to be able to evaluate closures // within this class. The attributes are necessary to prevent this method from being inlined into ClosureEvaluator [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] internal static object Eval(FieldInfo fieldInfo, object obj) { return fieldInfo.GetValue(obj); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using RefactoringEssentials; using RefactoringEssentials.Util; using System; using System.Collections.Generic; using System.Collections.Immutable; namespace RefactoringEssentials.CSharp.Diagnostics { /// <summary> /// Checks for str == null &amp;&amp; str == " " /// Converts to: string.IsNullOrEmpty (str) /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] public class ReplaceWithStringIsNullOrEmptyAnalyzer : DiagnosticAnalyzer { /// <summary> /// The name of the property referred to by the <see cref="Diagnostic"/> for the replacement code. /// </summary> public static readonly string ReplacementPropertyName = "Replacement"; static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( CSharpDiagnosticIDs.ReplaceWithStringIsNullOrEmptyAnalyzerID, GettextCatalog.GetString("Uses shorter string.IsNullOrEmpty call instead of a longer condition"), GettextCatalog.GetString("Expression can be replaced with '{0}'"), DiagnosticAnalyzerCategories.PracticesAndImprovements, DiagnosticSeverity.Info, isEnabledByDefault: true, helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.ReplaceWithStringIsNullOrEmptyAnalyzerID) ); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(descriptor); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterSyntaxNodeAction( (nodeContext) => { Diagnostic diagnostic; if (TryGetDiagnostic(nodeContext, out diagnostic)) { nodeContext.ReportDiagnostic(diagnostic); } }, SyntaxKind.LogicalAndExpression, SyntaxKind.LogicalOrExpression ); } static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic) { diagnostic = default(Diagnostic); var node = nodeContext.Node as BinaryExpressionSyntax; // Must be of binary expression of 2 binary expressions. if (!node.IsKind(SyntaxKind.LogicalAndExpression, SyntaxKind.LogicalOrExpression)) return false; // Verify left is a binary expression. var left = SimplifySyntax(node.Left) as BinaryExpressionSyntax; if (left == null) return false; // Verify right is a binary expression. var right = SimplifySyntax(node.Right) as BinaryExpressionSyntax; if (right == null) return false; // Ensure left and right are binary and not assignment. if (!SyntaxFacts.IsBinaryExpression(left.OperatorToken.Kind()) || !SyntaxFacts.IsBinaryExpression(right.OperatorToken.Kind())) return false; // Test if left and right are suitable for replacement. var leftReplace = ShouldReplace(nodeContext, left); var rightReplace = ShouldReplace(nodeContext, right); // Test both are suitable for replacement. if (!leftReplace.ShouldReplace || !rightReplace.ShouldReplace) return false; // Test that both are either positive or negative tests. if (!(leftReplace.IsNegative == rightReplace.IsNegative)) return false; // Ensure that one tests for null and the other tests for empty. var isNullOrEmptyTest = (leftReplace.IsNullTest && rightReplace.IsEmptyTest) || (leftReplace.IsEmptyTest && rightReplace.IsNullTest); if (!isNullOrEmptyTest) return false; // Ensure that both refer to the same identifier. // Good: foo != null && foo != "" // Bad: foo != null && bar != "" if (!string.Equals(leftReplace.IdentifierNode.ToString(), rightReplace.IdentifierNode.ToString(), StringComparison.OrdinalIgnoreCase)) return false; // Generate replacement string and negate if necessary. // Used within diagnostic message and also passed down for replacement. var replacementString = string.Format("string.IsNullOrEmpty({0})", leftReplace.IdentifierNode); if (leftReplace.IsNegative) replacementString = "!" + replacementString; // We already did the work now pass it down to the code fix provider via a property. var props = new Dictionary<string, string> { { ReplacementPropertyName, replacementString } }; diagnostic = Diagnostic.Create( descriptor, node.GetLocation(), ImmutableDictionary.CreateRange(props), replacementString); return true; } /// <summary> /// Indicates whether a binary expression is suitable for replacement and info about it. /// </summary> class ShouldReplaceResult { /// <summary> /// Is the expression suitable for replacement. /// </summary> public bool ShouldReplace { get; set; } = false; /// <summary> /// Is the expression a test for null? /// </summary> public bool IsNullTest { get; set; } = false; /// <summary> /// Is the expression a test for empty? /// </summary> public bool IsEmptyTest { get; set; } = false; /// <summary> /// Is the expression negated? /// </summary> public bool IsNegative { get; set; } = false; /// <summary> /// What string symbol is being tested for null or empty? /// </summary> public ExpressionSyntax IdentifierNode { get; set; } = null; } /// <summary> /// Test whether a binary expression is suitable for replacement. /// </summary> /// <returns> /// A <see cref="ShouldReplaceResult"/> indicating whether the node is suitable for replacement. /// </returns> static ShouldReplaceResult ShouldReplace(SyntaxNodeAnalysisContext nodeContext, BinaryExpressionSyntax node) { // input (left, right, operator) output Result var left = SimplifySyntax(node.Left); var right = SimplifySyntax(node.Right); // str == if (IsStringSyntax(nodeContext, left)) { return ShouldReplaceString(nodeContext, left, right, node.OperatorToken); } // == str if (IsStringSyntax(nodeContext, right)) { return ShouldReplaceString(nodeContext, right, left, node.OperatorToken); } // str.Length == if (IsStringLengthSyntax(nodeContext, left)) { return ShouldReplaceStringLength(left as MemberAccessExpressionSyntax, right, node.OperatorToken); } // == str.Length if (IsStringLengthSyntax(nodeContext, right)) { return ShouldReplaceStringLength(right as MemberAccessExpressionSyntax, left, node.OperatorToken); } // We did not find a suitable replacement. return new ShouldReplaceResult { ShouldReplace = false }; } /// <summary> /// Determine whether a binary expression with a string expression is suitable for replacement. /// </summary> /// <param name="left">A node representing a string expression.</param> /// <param name="right">A node to be tested.</param> /// <param name="operatorToken">The operator separating the nodes.</param> /// <returns></returns> static ShouldReplaceResult ShouldReplaceString(SyntaxNodeAnalysisContext nodeContext, ExpressionSyntax left, ExpressionSyntax right, SyntaxToken operatorToken) { var result = new ShouldReplaceResult(); result.ShouldReplace = false; // str == null or str != null if (IsNullSyntax(nodeContext, right)) { result.IsNullTest = true; result.ShouldReplace = true; } // str == "" or str != "" // str == string.Empty or str != string.Empty else if (IsEmptySyntax(nodeContext, right)) { result.IsEmptyTest = true; result.ShouldReplace = true; } if (result.ShouldReplace) { result.IdentifierNode = left; if (operatorToken.IsKind(SyntaxKind.ExclamationEqualsToken)) { result.IsNegative = true; } } return result; } /// <summary> /// Determines whether a binary expression with a string length expression is suitable for replacement. /// </summary> /// <param name="left">A node representing a string length expression.</param> /// <param name="right">A node to be tested.</param> /// <param name="operatorToken">The operator separating the nodes.</param> /// <returns></returns> static ShouldReplaceResult ShouldReplaceStringLength(MemberAccessExpressionSyntax left, ExpressionSyntax right, SyntaxToken operatorToken) { const string zeroLiteral = "0"; const string oneLiteral = "1"; var result = new ShouldReplaceResult(); result.ShouldReplace = false; // str.Length == 0 or str.Length <= 0 if (operatorToken.IsKind(SyntaxKind.EqualsEqualsToken, SyntaxKind.LessThanEqualsToken) && string.Equals(zeroLiteral, right.ToString())) { result.IsEmptyTest = true; result.ShouldReplace = true; } // str.Length < 1 else if (operatorToken.IsKind(SyntaxKind.LessThanToken) && string.Equals(oneLiteral, right.ToString())) { result.IsEmptyTest = true; result.ShouldReplace = true; } // str.Length != 0 or str.Length > 0 else if (operatorToken.IsKind(SyntaxKind.ExclamationEqualsToken, SyntaxKind.GreaterThanToken) && string.Equals(zeroLiteral, right.ToString())) { result.IsEmptyTest = true; result.IsNegative = true; result.ShouldReplace = true; } // str.Length >= 1 else if (operatorToken.IsKind(SyntaxKind.GreaterThanEqualsToken) && string.Equals(oneLiteral, right.ToString())) { result.IsEmptyTest = true; result.IsNegative = true; result.ShouldReplace = true; } if (result.ShouldReplace) { result.IdentifierNode = left.Expression; } return result; } /// <summary> /// Does the expression look like a string type? /// </summary> static bool IsStringSyntax(SyntaxNodeAnalysisContext nodeContext, ExpressionSyntax node) { if (!IsStringType(nodeContext, node)) return false; return node.IsKind(SyntaxKind.IdentifierName, SyntaxKind.InvocationExpression, SyntaxKind.SimpleMemberAccessExpression); } /// <summary> /// Does the expression look like a string length call? /// </summary> static bool IsStringLengthSyntax(SyntaxNodeAnalysisContext nodeContext, ExpressionSyntax node) { if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var smaNode = node as MemberAccessExpressionSyntax; if (smaNode.Name.Identifier.Text == "Length") { if (!IsStringType(nodeContext, smaNode.Expression)) return false; return true; } } return false; } /// <summary> /// Does the expression look like a null? /// </summary> static bool IsNullSyntax(SyntaxNodeAnalysisContext nodeContext, ExpressionSyntax node) { if (!IsStringType(nodeContext, node)) return false; return node.IsKind(SyntaxKind.NullLiteralExpression); } /// <summary> /// Does the expression look like a test for empty string ("" or string.Empty)? /// </summary> /// <param name="node"></param> /// <returns></returns> static bool IsEmptySyntax(SyntaxNodeAnalysisContext nodeContext, ExpressionSyntax node) { if (!IsStringType(nodeContext, node)) return false; if (node.IsKind(SyntaxKind.StringLiteralExpression)) { if (string.Equals("\"\"", node.ToString())) return true; } else if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var sma = node as MemberAccessExpressionSyntax; if (!string.Equals("string", sma.Expression.ToString(), StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals("Empty", sma.Name.ToString(), StringComparison.OrdinalIgnoreCase)) return false; return true; } return false; } /// <summary> /// Test if expression is a string type. /// </summary> static bool IsStringType(SyntaxNodeAnalysisContext nodeContext, ExpressionSyntax node) { var typeInfo = nodeContext.SemanticModel.GetTypeInfo(node); if (typeInfo.ConvertedType == null) return false; if (!string.Equals("String", typeInfo.ConvertedType.Name, StringComparison.OrdinalIgnoreCase)) return false; return true; } /// <summary> /// Simplify an <see cref="ExpressionSyntax"/> by removing unecessary parenthesis. /// </summary> /// <returns> /// A simplified <see cref="ExpressionSyntax"/>. /// </returns> static ExpressionSyntax SimplifySyntax(ExpressionSyntax syntax) { if (syntax.IsKind(SyntaxKind.ParenthesizedExpression)) { syntax = (syntax as ParenthesizedExpressionSyntax).Expression; syntax = SimplifySyntax(syntax); } return syntax; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Test.Common; using System.Threading; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class AcceptAsync { private readonly ITestOutputHelper _log; public AcceptAsync(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } public void OnAcceptCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnAcceptCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } public void OnConnectCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnConnectCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv4", "true")] public void AcceptAsync_IpV4_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv4 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv4 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [Trait("IPv6", "true")] public void AcceptAsync_IPv6_Success() { Assert.True(Capability.IPv6Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv6 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv6 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(PlatformID.Windows)] public void AcceptAsync_WithReceiveBuffer_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent accepted = new AutoResetEvent(false); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); const int acceptBufferOverheadSize = 288; // see https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync(v=vs.110).aspx const int acceptBufferDataSize = 256; const int acceptBufferSize = acceptBufferOverheadSize + acceptBufferDataSize; byte[] sendBuffer = new byte[acceptBufferDataSize]; new Random().NextBytes(sendBuffer); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = accepted; acceptArgs.SetBuffer(new byte[acceptBufferSize], 0, acceptBufferSize); Assert.True(server.AcceptAsync(acceptArgs)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { client.Connect(IPAddress.Loopback, port); client.Send(sendBuffer); client.Shutdown(SocketShutdown.Both); } Assert.True( accepted.WaitOne(TestSettings.PassingTestTimeout), "Test completed in alotted time"); Assert.Equal( SocketError.Success, acceptArgs.SocketError); Assert.Equal( acceptBufferDataSize, acceptArgs.BytesTransferred); Assert.Equal( new ArraySegment<byte>(sendBuffer), new ArraySegment<byte>(acceptArgs.Buffer, 0, acceptArgs.BytesTransferred)); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void AcceptAsync_WithReceiveBuffer_Failure() { // // Unix platforms don't yet support receiving data with AcceptAsync. // Assert.True(Capability.IPv4Support()); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = new ManualResetEvent(false); byte[] buffer = new byte[1024]; acceptArgs.SetBuffer(buffer, 0, buffer.Length); Assert.Throws<PlatformNotSupportedException>(() => server.AcceptAsync(acceptArgs)); } } #region GC Finalizer test // This test assumes sequential execution of tests and that it is going to be executed after other tests // that used Sockets. [OuterLoop] // TODO: Issue #11345 [Fact] public void TestFinalizers() { // Making several passes through the FReachable list. for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } #endregion } }
// 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 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// DataLakeStoreAccountsOperations operations. /// </summary> internal partial class DataLakeStoreAccountsOperations : IServiceOperations<DataLakeAnalyticsAccountManagementClient>, IDataLakeStoreAccountsOperations { /// <summary> /// Initializes a new instance of the DataLakeStoreAccountsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DataLakeStoreAccountsOperations(DataLakeAnalyticsAccountManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the DataLakeAnalyticsAccountManagementClient /// </summary> public DataLakeAnalyticsAccountManagementClient Client { get; private set; } /// <summary> /// Gets the specified Data Lake Store account details in the specified Data /// Lake Analytics account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to retrieve the /// Data Lake Store account details. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to retrieve /// </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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataLakeStoreAccountInfo>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string dataLakeStoreAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (dataLakeStoreAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataLakeStoreAccountName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("accountName", accountName); tracingParameters.Add("dataLakeStoreAccountName", dataLakeStoreAccountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/{dataLakeStoreAccountName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{dataLakeStoreAccountName}", Uri.EscapeDataString(dataLakeStoreAccountName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<DataLakeStoreAccountInfo>(); _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 = SafeJsonConvert.DeserializeObject<DataLakeStoreAccountInfo>(_responseContent, this.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> /// Updates the Data Lake Analytics account specified to remove the specified /// Data Lake Store account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to remove the Data /// Lake Store account. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to remove /// </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="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string dataLakeStoreAccountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (dataLakeStoreAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataLakeStoreAccountName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("accountName", accountName); tracingParameters.Add("dataLakeStoreAccountName", dataLakeStoreAccountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/{dataLakeStoreAccountName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{dataLakeStoreAccountName}", Uri.EscapeDataString(dataLakeStoreAccountName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } 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(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates the specified Data Lake Analytics account to include the /// additional Data Lake Store account. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to which to add the Data Lake /// Store account. /// </param> /// <param name='dataLakeStoreAccountName'> /// The name of the Data Lake Store account to add. /// </param> /// <param name='parameters'> /// The details of the Data Lake Store account. /// </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="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> AddWithHttpMessagesAsync(string resourceGroupName, string accountName, string dataLakeStoreAccountName, AddDataLakeStoreParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (dataLakeStoreAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataLakeStoreAccountName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("accountName", accountName); tracingParameters.Add("dataLakeStoreAccountName", dataLakeStoreAccountName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Add", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/{dataLakeStoreAccountName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{dataLakeStoreAccountName}", Uri.EscapeDataString(dataLakeStoreAccountName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } 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(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the first page of Data Lake Store accounts linked to the specified /// Data Lake Analytics account. The response includes a link to the next /// page, if any. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account for which to list Data Lake /// Store accounts. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just those /// requested, e.g. Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the matching /// resources included with the resources in the response, e.g. /// Categories?$count=true. Optional. /// </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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<DataLakeStoreAccountInfo>>> ListByAccountWithHttpMessagesAsync(string resourceGroupName, string accountName, ODataQuery<DataLakeStoreAccountInfo> odataQuery = default(ODataQuery<DataLakeStoreAccountInfo>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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("accountName", accountName); tracingParameters.Add("select", select); tracingParameters.Add("count", count); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccount", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/DataLakeStoreAccounts/").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (select != null) { _queryParameters.Add(string.Format("$select={0}", Uri.EscapeDataString(select))); } if (count != null) { _queryParameters.Add(string.Format("$count={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(count, this.Client.SerializationSettings).Trim('"')))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<DataLakeStoreAccountInfo>>(); _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 = SafeJsonConvert.DeserializeObject<Page<DataLakeStoreAccountInfo>>(_responseContent, this.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 the first page of Data Lake Store accounts linked to the specified /// Data Lake Analytics account. The response includes a link to the next /// page, if any. /// </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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<DataLakeStoreAccountInfo>>> ListByAccountNextWithHttpMessagesAsync(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, "ListByAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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<DataLakeStoreAccountInfo>>(); _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 = SafeJsonConvert.DeserializeObject<Page<DataLakeStoreAccountInfo>>(_responseContent, this.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; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The original content was ported from the C language from the 4.6 version of Proj4 libraries. // Frank Warmerdam has released the full content of that version under the MIT license which is // recognized as being approximately equivalent to public domain. The original work was done // mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here: // http://trac.osgeo.org/proj/ // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/10/2009 4:24:11 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** using System; namespace DotSpatial.Projections.Transforms { /// <summary> /// Orthographic /// </summary> public class Orthographic : Transform { #region Private Variables private double _cosph0; private Modes _mode; private double _sinph0; #endregion #region Constructors /// <summary> /// Creates a new instance of Orthographic /// </summary> public Orthographic() { Name = "Orthographic"; Proj4Name = "ortho"; } #endregion #region Methods /// <inheritdoc /> protected override void OnForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double cosphi = Math.Cos(lp[phi]); double coslam = Math.Cos(lp[lam]); switch (_mode) { case Modes.Equitorial: if (cosphi * coslam < -EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //ProjectionException(20); } xy[y] = Math.Sin(lp[phi]); break; case Modes.Oblique: double sinphi; if (_sinph0 * (sinphi = Math.Sin(lp[phi])) + _cosph0 * cosphi * coslam < -EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //ProjectionException(20); } xy[y] = _cosph0 * sinphi - _sinph0 * cosphi * coslam; break; default: if (_mode == Modes.NorthPole) coslam = -coslam; if (Math.Abs(lp[phi] - Phi0) - EPS10 > HALF_PI) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //ProjectionException(20); } xy[y] = cosphi * coslam; break; } xy[x] = cosphi * Math.Sin(lp[lam]); } } /// <inheritdoc /> protected override void OnInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double rh, sinc; double cx = xy[x]; double cy = xy[y]; if ((sinc = (rh = Proj.Hypot(cx, cy))) > 1) { if ((sinc - 1) > EPS10) { lp[lam] = double.NaN; lp[phi] = double.NaN; continue; //ProjectionException(20); } sinc = 1; } double cosc = Math.Sqrt(1 - sinc * sinc); if (Math.Abs(rh) <= EPS10) { lp[phi] = Phi0; lp[lam] = 0; } else { switch (_mode) { case Modes.NorthPole: cy = -cy; lp[phi] = Math.Acos(sinc); break; case Modes.SouthPole: lp[phi] = -Math.Acos(sinc); break; case Modes.Equitorial: lp[phi] = cy * sinc / rh; cx *= sinc; cy = cosc * rh; if (Math.Abs(lp[phi]) >= 1) { lp[phi] = lp[phi] < 0 ? -HALF_PI : HALF_PI; } else { lp[phi] = Math.Asin(lp[phi]); } break; case Modes.Oblique: lp[phi] = cosc * _sinph0 + cy * sinc * _cosph0 / rh; cy = (cosc - _sinph0 * lp[phi]) * rh; cx *= sinc * _cosph0; if (Math.Abs(lp[phi]) >= 1) { lp[phi] = lp[phi] < 0 ? -HALF_PI : HALF_PI; } else { lp[phi] = Math.Asin(lp[phi]); } break; } lp[lam] = (cy == 0 && (_mode == Modes.Oblique || _mode == Modes.Equitorial)) ? (cx == 0 ? 0 : cx < 0 ? -HALF_PI : HALF_PI) : Math.Atan2(cx, cy); } } } /// <summary> /// Initializes the transform using the parameters from the specified coordinate system information /// </summary> /// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param> protected override void OnInit(ProjectionInfo projInfo) { if (Math.Abs(Math.Abs(Phi0) - HALF_PI) <= EPS10) { _mode = Phi0 < 0 ? Modes.SouthPole : Modes.NorthPole; } else if (Math.Abs(Phi0) > EPS10) { _mode = Modes.Oblique; _sinph0 = Math.Sin(Phi0); _cosph0 = Math.Cos(Phi0); } else { _mode = Modes.Equitorial; } } #endregion #region Properties #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 Polacca.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; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using NuGet.Resources; namespace NuGet { public class LocalPackageRepository : PackageRepositoryBase, IPackageLookup { private readonly ConcurrentDictionary<string, PackageCacheEntry> _packageCache = new ConcurrentDictionary<string, PackageCacheEntry>(StringComparer.OrdinalIgnoreCase); private readonly ConcurrentDictionary<PackageName, string> _packagePathLookup = new ConcurrentDictionary<PackageName, string>(); private readonly bool _enableCaching; public LocalPackageRepository(string physicalPath) : this(physicalPath, enableCaching: true) { } public LocalPackageRepository(string physicalPath, bool enableCaching) : this(new DefaultPackagePathResolver(physicalPath), new PhysicalFileSystem(physicalPath), enableCaching) { } public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem) : this(pathResolver, fileSystem, enableCaching: true) { } public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem, bool enableCaching) { if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } FileSystem = fileSystem; PathResolver = pathResolver; _enableCaching = enableCaching; } public override string Source { get { return FileSystem.Root; } } public IPackagePathResolver PathResolver { get; set; } public override bool SupportsPrereleasePackages { get { return true; } } protected IFileSystem FileSystem { get; private set; } public override IQueryable<IPackage> GetPackages() { return GetPackages(OpenPackage).AsQueryable(); } public override void AddPackage(IPackage package) { if (PackageSaveMode.HasFlag(PackageSaveModes.Nuspec)) { // Starting from 2.1, we save the nuspec file into the subdirectory with the name as <packageId>.<version> // for example, for jQuery version 1.0, it will be "jQuery.1.0\\jQuery.1.0.nuspec" string packageFilePath = GetManifestFilePath(package.Id, package.Version); Manifest manifest = Manifest.Create(package); // The IPackage object doesn't carry the References information. // Thus we set the References for the manifest to the set of all valid assembly references manifest.Metadata.ReferenceSets = package.AssemblyReferences .GroupBy(f => f.TargetFramework) .Select( g => new ManifestReferenceSet { TargetFramework = g.Key == null ? null : VersionUtility.GetFrameworkString(g.Key), References = g.Select(p => new ManifestReference { File = p.Name }).ToList() }) .ToList(); FileSystem.AddFileWithCheck(packageFilePath, manifest.Save); } if (PackageSaveMode.HasFlag(PackageSaveModes.Nupkg)) { string packageFilePath = GetPackageFilePath(package); FileSystem.AddFileWithCheck(packageFilePath, package.GetStream); } } public override void RemovePackage(IPackage package) { string manifestFilePath = GetManifestFilePath(package.Id, package.Version); if (FileSystem.FileExists(manifestFilePath)) { // delete .nuspec file FileSystem.DeleteFileSafe(manifestFilePath); } // Delete the package file string packageFilePath = GetPackageFilePath(package); FileSystem.DeleteFileSafe(packageFilePath); // Delete the package directory if any FileSystem.DeleteDirectorySafe(PathResolver.GetPackageDirectory(package), recursive: false); // If this is the last package delete the package directory if (!FileSystem.GetFilesSafe(String.Empty).Any() && !FileSystem.GetDirectoriesSafe(String.Empty).Any()) { FileSystem.DeleteDirectorySafe(String.Empty, recursive: false); } } public virtual IPackage FindPackage(string packageId, SemanticVersion version) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } if (version == null) { throw new ArgumentNullException("version"); } return FindPackage(OpenPackage, packageId, version); } public virtual IEnumerable<IPackage> FindPackagesById(string packageId) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } return FindPackagesById(OpenPackage, packageId); } public virtual bool Exists(string packageId, SemanticVersion version) { return FindPackage(packageId, version) != null; } public virtual IEnumerable<string> GetPackageLookupPaths(string packageId, SemanticVersion version) { // Files created by the path resolver. This would take into account the non-side-by-side scenario // and we do not need to match this for id and version. var packageFileName = PathResolver.GetPackageFileName(packageId, version); var manifestFileName = Path.ChangeExtension(packageFileName, Constants.ManifestExtension); var filesMatchingFullName = Enumerable.Concat( GetPackageFiles(packageFileName), GetPackageFiles(manifestFileName)); if (version != null && version.Version.Revision < 1) { // If the build or revision number is not set, we need to look for combinations of the format // * Foo.1.2.nupkg // * Foo.1.2.3.nupkg // * Foo.1.2.0.nupkg // * Foo.1.2.0.0.nupkg // To achieve this, we would look for files named 1.2*.nupkg if both build and revision are 0 and // 1.2.3*.nupkg if only the revision is set to 0. string partialName = version.Version.Build < 1 ? String.Join(".", packageId, version.Version.Major, version.Version.Minor) : String.Join(".", packageId, version.Version.Major, version.Version.Minor, version.Version.Build); string partialManifestName = partialName + "*" + Constants.ManifestExtension; partialName += "*" + Constants.PackageExtension; // Partial names would result is gathering package with matching major and minor but different build and revision. // Attempt to match the version in the path to the version we're interested in. var partialNameMatches = GetPackageFiles(partialName).Where(path => FileNameMatchesPattern(packageId, version, path)); var partialManifestNameMatches = GetPackageFiles(partialManifestName).Where( path => FileNameMatchesPattern(packageId, version, path)); return Enumerable.Concat(filesMatchingFullName, partialNameMatches).Concat(partialManifestNameMatches); } return filesMatchingFullName; } internal IPackage FindPackage(Func<string, IPackage> openPackage, string packageId, SemanticVersion version) { var lookupPackageName = new PackageName(packageId, version); string packagePath; // If caching is enabled, check if we have a cached path. Additionally, verify that the file actually exists on disk since it might have moved. if (_enableCaching && _packagePathLookup.TryGetValue(lookupPackageName, out packagePath) && FileSystem.FileExists(packagePath)) { // When depending on the cached path, verify the file exists on disk. return GetPackage(openPackage, packagePath); } // Lookup files which start with the name "<Id>." and attempt to match it with all possible version string combinations (e.g. 1.2.0, 1.2.0.0) // before opening the package. To avoid creating file name strings, we attempt to specifically match everything after the last path separator // which would be the file name and extension. return (from path in GetPackageLookupPaths(packageId, version) let package = GetPackage(openPackage, path) where lookupPackageName.Equals(new PackageName(package.Id, package.Version)) select package).FirstOrDefault(); } internal IEnumerable<IPackage> FindPackagesById(Func<string, IPackage> openPackage, string packageId) { Debug.Assert(!String.IsNullOrEmpty(packageId), "The caller has to ensure packageId is never null."); var packagePaths = GetPackageFiles(packageId + "*" + Constants.PackageExtension); return from path in packagePaths let package = GetPackage(openPackage, path) where package.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase) select package; } internal IEnumerable<IPackage> GetPackages(Func<string, IPackage> openPackage) { return from path in GetPackageFiles() select GetPackage(openPackage, path); } private IPackage GetPackage(Func<string, IPackage> openPackage, string path) { PackageCacheEntry cacheEntry; DateTimeOffset lastModified = FileSystem.GetLastModified(path); // If we never cached this file or we did and it's current last modified time is newer // create a new entry if (!_packageCache.TryGetValue(path, out cacheEntry) || (cacheEntry != null && lastModified > cacheEntry.LastModifiedTime)) { // We need to do this so we capture the correct loop variable string packagePath = path; // Create the package IPackage package = openPackage(packagePath); // create a cache entry with the last modified time cacheEntry = new PackageCacheEntry(package, lastModified); if (_enableCaching) { // Store the entry _packageCache[packagePath] = cacheEntry; _packagePathLookup[new PackageName(package.Id, package.Version)] = path; } } return cacheEntry.Package; } internal IEnumerable<string> GetPackageFiles(string filter = null) { filter = filter ?? "*" + Constants.PackageExtension; Debug.Assert( filter.EndsWith(Constants.PackageExtension, StringComparison.OrdinalIgnoreCase) || filter.EndsWith(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase)); // Check for package files one level deep. We use this at package install time // to determine the set of installed packages. Installed packages are copied to // {id}.{version}\{packagefile}.{extension}. foreach (var dir in FileSystem.GetDirectories(String.Empty)) { foreach (var path in FileSystem.GetFiles(dir, filter)) { yield return path; } } // Check top level directory foreach (var path in FileSystem.GetFiles(String.Empty, filter)) { yield return path; } } protected virtual IPackage OpenPackage(string path) { if (!FileSystem.FileExists(path)) { return null; } if (Path.GetExtension(path) == Constants.PackageExtension) { OptimizedZipPackage package; try { package = new OptimizedZipPackage(FileSystem, path); } catch (FileFormatException ex) { throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ErrorReadingPackage, path), ex); } // Set the last modified date on the package package.Published = FileSystem.GetLastModified(path); return package; } else if (Path.GetExtension(path) == Constants.ManifestExtension) { if (FileSystem.FileExists(path)) { return new UnzippedPackage(FileSystem, Path.GetFileNameWithoutExtension(path)); } } return null; } protected virtual string GetPackageFilePath(IPackage package) { return Path.Combine(PathResolver.GetPackageDirectory(package), PathResolver.GetPackageFileName(package)); } protected virtual string GetPackageFilePath(string id, SemanticVersion version) { return Path.Combine(PathResolver.GetPackageDirectory(id, version), PathResolver.GetPackageFileName(id, version)); } private static bool FileNameMatchesPattern(string packageId, SemanticVersion version, string path) { var name = Path.GetFileNameWithoutExtension(path); SemanticVersion parsedVersion; // When matching by pattern, we will always have a version token. Packages without versions would be matched early on by the version-less path resolver // when doing an exact match. return name.Length > packageId.Length && SemanticVersion.TryParse(name.Substring(packageId.Length + 1), out parsedVersion) && parsedVersion == version; } private string GetManifestFilePath(string packageId, SemanticVersion version) { string packageDirectory = PathResolver.GetPackageDirectory(packageId, version); string manifestFileName = packageDirectory + Constants.ManifestExtension; return Path.Combine(packageDirectory, manifestFileName); } private class PackageCacheEntry { public PackageCacheEntry(IPackage package, DateTimeOffset lastModifiedTime) { Package = package; LastModifiedTime = lastModifiedTime; } public IPackage Package { get; private set; } public DateTimeOffset LastModifiedTime { get; private set; } } } }
// *********************************************************************** // Copyright (c) 2009-2014 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Security; using System.Web.UI; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnit.Framework.Api { /// <summary> /// FrameworkController provides a facade for use in loading, browsing /// and running tests without requiring a reference to the NUnit /// framework. All calls are encapsulated in constructors for /// this class and its nested classes, which only require the /// types of the Common Type System as arguments. /// /// The controller supports four actions: Load, Explore, Count and Run. /// They are intended to be called by a driver, which should allow for /// proper sequencing of calls. Load must be called before any of the /// other actions. The driver may support other actions, such as /// reload on run, by combining these calls. /// </summary> public class FrameworkController : LongLivedMarshalByRefObject { private const string LOG_FILE_FORMAT = "InternalTrace.{0}.{1}.log"; // Preloaded test assembly, if passed in constructor private readonly Assembly _testAssembly; #region Constructors /// <summary> /// Construct a FrameworkController using the default builder and runner. /// </summary> /// <param name="assemblyNameOrPath">The AssemblyName or path to the test assembly</param> /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param> /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param> public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings) { Initialize(assemblyNameOrPath, settings); this.Builder = new DefaultTestAssemblyBuilder(); this.Runner = new NUnitTestAssemblyRunner(this.Builder); Test.IdPrefix = idPrefix; } /// <summary> /// Construct a FrameworkController using the default builder and runner. /// </summary> /// <param name="assembly">The test assembly</param> /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param> /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param> public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings) : this(assembly.FullName, idPrefix, settings) { _testAssembly = assembly; } /// <summary> /// Construct a FrameworkController, specifying the types to be used /// for the runner and builder. This constructor is provided for /// purposes of development. /// </summary> /// <param name="assemblyNameOrPath">The full AssemblyName or the path to the test assembly</param> /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param> /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param> /// <param name="runnerType">The Type of the test runner</param> /// <param name="builderType">The Type of the test builder</param> public FrameworkController(string assemblyNameOrPath, string idPrefix, IDictionary settings, string runnerType, string builderType) { Initialize(assemblyNameOrPath, settings); Builder = (ITestAssemblyBuilder)Reflect.Construct(Type.GetType(builderType)); Runner = (ITestAssemblyRunner)Reflect.Construct(Type.GetType(runnerType), new object[] { Builder }); Test.IdPrefix = idPrefix ?? ""; } /// <summary> /// Construct a FrameworkController, specifying the types to be used /// for the runner and builder. This constructor is provided for /// purposes of development. /// </summary> /// <param name="assembly">The test assembly</param> /// <param name="idPrefix">A prefix used for all test ids created under this controller.</param> /// <param name="settings">A Dictionary of settings to use in loading and running the tests</param> /// <param name="runnerType">The Type of the test runner</param> /// <param name="builderType">The Type of the test builder</param> public FrameworkController(Assembly assembly, string idPrefix, IDictionary settings, string runnerType, string builderType) : this(assembly.FullName, idPrefix, settings, runnerType, builderType) { _testAssembly = assembly; } // This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of // the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the // Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather // than a 'SecurityCriticalAttribute' and allow use by security transparent callers. [SecuritySafeCritical] private void Initialize(string assemblyNameOrPath, IDictionary settings) { AssemblyNameOrPath = assemblyNameOrPath; var newSettings = settings as IDictionary<string, object>; Settings = newSettings ?? settings.Cast<DictionaryEntry>().ToDictionary(de => (string)de.Key, de => de.Value); if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceLevel)) { var traceLevel = (InternalTraceLevel)Enum.Parse(typeof(InternalTraceLevel), (string)Settings[FrameworkPackageSettings.InternalTraceLevel], true); if (Settings.ContainsKey(FrameworkPackageSettings.InternalTraceWriter)) InternalTrace.Initialize((TextWriter)Settings[FrameworkPackageSettings.InternalTraceWriter], traceLevel); else { var workDirectory = Settings.ContainsKey(FrameworkPackageSettings.WorkDirectory) ? (string)Settings[FrameworkPackageSettings.WorkDirectory] : Directory.GetCurrentDirectory(); #if NETSTANDARD1_4 var id = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"); #else var id = Process.GetCurrentProcess().Id; #endif var logName = string.Format(LOG_FILE_FORMAT, id, Path.GetFileName(assemblyNameOrPath)); InternalTrace.Initialize(Path.Combine(workDirectory, logName), traceLevel); } } } #endregion #region Properties /// <summary> /// Gets the ITestAssemblyBuilder used by this controller instance. /// </summary> /// <value>The builder.</value> public ITestAssemblyBuilder Builder { get; } /// <summary> /// Gets the ITestAssemblyRunner used by this controller instance. /// </summary> /// <value>The runner.</value> public ITestAssemblyRunner Runner { get; } /// <summary> /// Gets the AssemblyName or the path for which this FrameworkController was created /// </summary> public string AssemblyNameOrPath { get; private set; } /// <summary> /// Gets the Assembly for which this /// </summary> public Assembly Assembly { get; private set; } /// <summary> /// Gets a dictionary of settings for the FrameworkController /// </summary> internal IDictionary<string, object> Settings { get; private set; } #endregion #region Public Action methods Used by nunit.driver for running tests /// <summary> /// Loads the tests in the assembly /// </summary> /// <returns></returns> public string LoadTests() { if (_testAssembly != null) Runner.Load(_testAssembly, Settings); else Runner.Load(AssemblyNameOrPath, Settings); return Runner.LoadedTest.ToXml(false).OuterXml; } /// <summary> /// Returns info about the tests in an assembly /// </summary> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <returns>The XML result of exploring the tests</returns> public string ExploreTests(string filter) { if (Runner.LoadedTest == null) throw new InvalidOperationException("The Explore method was called but no test has been loaded"); return Runner.ExploreTests(TestFilter.FromXml(filter)).ToXml(true).OuterXml; } /// <summary> /// Runs the tests in an assembly /// </summary> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <returns>The XML result of the test run</returns> public string RunTests(string filter) { TNode result = Runner.Run(new TestProgressReporter(null), TestFilter.FromXml(filter)).ToXml(true); // Insert elements as first child in reverse order if (Settings != null) // Some platforms don't have settings InsertSettingsElement(result, Settings); InsertEnvironmentElement(result); return result.OuterXml; } #if !NET20 class ActionCallback : ICallbackEventHandler { Action<string> _callback; public ActionCallback(Action<string> callback) { _callback = callback; } public string GetCallbackResult() { throw new NotImplementedException(); } public void RaiseCallbackEvent(string report) { if (_callback != null) _callback.Invoke(report); } } /// <summary> /// Runs the tests in an assembly synchronously reporting back the test results through the callback /// or through the return value /// </summary> /// <param name="callback">The callback that receives the test results</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <returns>The XML result of the test run</returns> public string RunTests(Action<string> callback, string filter) { var handler = new ActionCallback(callback); TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true); // Insert elements as first child in reverse order if (Settings != null) // Some platforms don't have settings InsertSettingsElement(result, Settings); InsertEnvironmentElement(result); return result.OuterXml; } /// <summary> /// Runs the tests in an assembly asynchronously reporting back the test results through the callback /// </summary> /// <param name="callback">The callback that receives the test results</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> private void RunAsync(Action<string> callback, string filter) { var handler = new ActionCallback(callback); Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter)); } #endif /// <summary> /// Stops the test run /// </summary> /// <param name="force">True to force the stop, false for a cooperative stop</param> public void StopRun(bool force) { Runner.StopRun(force); } /// <summary> /// Counts the number of test cases in the loaded TestSuite /// </summary> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <returns>The number of tests</returns> public int CountTests(string filter) { return Runner.CountTestCases(TestFilter.FromXml(filter)); } #endregion #region Private Action Methods Used by Nested Classes private void LoadTests(ICallbackEventHandler handler) { handler.RaiseCallbackEvent(LoadTests()); } private void ExploreTests(ICallbackEventHandler handler, string filter) { if (Runner.LoadedTest == null) throw new InvalidOperationException("The Explore method was called but no test has been loaded"); handler.RaiseCallbackEvent(Runner.ExploreTests(TestFilter.FromXml(filter)).ToXml(true).OuterXml); } private void RunTests(ICallbackEventHandler handler, string filter) { TNode result = Runner.Run(new TestProgressReporter(handler), TestFilter.FromXml(filter)).ToXml(true); // Insert elements as first child in reverse order if (Settings != null) // Some platforms don't have settings InsertSettingsElement(result, Settings); InsertEnvironmentElement(result); handler.RaiseCallbackEvent(result.OuterXml); } private void RunAsync(ICallbackEventHandler handler, string filter) { Runner.RunAsync(new TestProgressReporter(handler), TestFilter.FromXml(filter)); } private void StopRun(ICallbackEventHandler handler, bool force) { StopRun(force); } private void CountTests(ICallbackEventHandler handler, string filter) { handler.RaiseCallbackEvent(CountTests(filter).ToString()); } /// <summary> /// Inserts environment element /// </summary> /// <param name="targetNode">Target node</param> /// <returns>The new node</returns> public static TNode InsertEnvironmentElement(TNode targetNode) { TNode env = new TNode("environment"); targetNode.ChildNodes.Insert(0, env); env.AddAttribute("framework-version", typeof(FrameworkController).GetTypeInfo().Assembly.GetName().Version.ToString()); #if NETSTANDARD1_4 env.AddAttribute("clr-version", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription); #else env.AddAttribute("clr-version", Environment.Version.ToString()); #endif #if !PLATFORM_DETECTION env.AddAttribute("os-version", System.Runtime.InteropServices.RuntimeInformation.OSDescription); #else env.AddAttribute("os-version", OSPlatform.CurrentPlatform.ToString()); #endif #if !NETSTANDARD1_4 env.AddAttribute("platform", Environment.OSVersion.Platform.ToString()); #endif env.AddAttribute("cwd", Directory.GetCurrentDirectory()); #if !NETSTANDARD1_4 env.AddAttribute("machine-name", Environment.MachineName); #endif #if !NETSTANDARD1_4 env.AddAttribute("user", Environment.UserName); env.AddAttribute("user-domain", Environment.UserDomainName); #endif env.AddAttribute("culture", CultureInfo.CurrentCulture.ToString()); env.AddAttribute("uiculture", CultureInfo.CurrentUICulture.ToString()); env.AddAttribute("os-architecture", GetProcessorArchitecture()); return env; } private static string GetProcessorArchitecture() { return IntPtr.Size == 8 ? "x64" : "x86"; } /// <summary> /// Inserts settings element /// </summary> /// <param name="targetNode">Target node</param> /// <param name="settings">Settings dictionary</param> /// <returns>The new node</returns> public static TNode InsertSettingsElement(TNode targetNode, IDictionary<string, object> settings) { TNode settingsNode = new TNode("settings"); targetNode.ChildNodes.Insert(0, settingsNode); foreach (string key in settings.Keys) AddSetting(settingsNode, key, settings[key]); #if PARALLEL // Add default values for display if (!settings.ContainsKey(FrameworkPackageSettings.NumberOfTestWorkers)) AddSetting(settingsNode, FrameworkPackageSettings.NumberOfTestWorkers, NUnitTestAssemblyRunner.DefaultLevelOfParallelism); #endif return settingsNode; } private static void AddSetting(TNode settingsNode, string name, object value) { TNode setting = new TNode("setting"); setting.AddAttribute("name", name); if (value != null) { var dict = value as IDictionary; if (dict != null) { AddDictionaryEntries(setting, dict); AddBackwardsCompatibleDictionaryEntries(setting, dict); } else { setting.AddAttribute("value", value.ToString()); } } else { setting.AddAttribute("value", null); } settingsNode.ChildNodes.Add(setting); } private static void AddBackwardsCompatibleDictionaryEntries(TNode settingsNode, IDictionary entries) { var pairs = new List<string>(entries.Count); foreach (var key in entries.Keys) { pairs.Add($"[{key}, {entries[key]}]"); } settingsNode.AddAttribute("value", string.Join(", ", pairs.ToArray())); } private static void AddDictionaryEntries(TNode settingNode, IDictionary entries) { foreach(var key in entries.Keys) { var value = entries[key]; var entryNode = new TNode("item"); entryNode.AddAttribute("key", key.ToString()); entryNode.AddAttribute("value", value?.ToString() ?? ""); settingNode.ChildNodes.Add(entryNode); } } #endregion #region Nested Action Classes #region TestContollerAction /// <summary> /// FrameworkControllerAction is the base class for all actions /// performed against a FrameworkController. /// </summary> public abstract class FrameworkControllerAction : LongLivedMarshalByRefObject { } #endregion #region LoadTestsAction /// <summary> /// LoadTestsAction loads a test into the FrameworkController /// </summary> public class LoadTestsAction : FrameworkControllerAction { /// <summary> /// LoadTestsAction loads the tests in an assembly. /// </summary> /// <param name="controller">The controller.</param> /// <param name="handler">The callback handler.</param> public LoadTestsAction(FrameworkController controller, object handler) { controller.LoadTests((ICallbackEventHandler)handler); } } #endregion #region ExploreTestsAction /// <summary> /// ExploreTestsAction returns info about the tests in an assembly /// </summary> public class ExploreTestsAction : FrameworkControllerAction { /// <summary> /// Initializes a new instance of the <see cref="ExploreTestsAction"/> class. /// </summary> /// <param name="controller">The controller for which this action is being performed.</param> /// <param name="filter">Filter used to control which tests are included (NYI)</param> /// <param name="handler">The callback handler.</param> public ExploreTestsAction(FrameworkController controller, string filter, object handler) { controller.ExploreTests((ICallbackEventHandler)handler, filter); } } #endregion #region CountTestsAction /// <summary> /// CountTestsAction counts the number of test cases in the loaded TestSuite /// held by the FrameworkController. /// </summary> public class CountTestsAction : FrameworkControllerAction { /// <summary> /// Construct a CountsTestAction and perform the count of test cases. /// </summary> /// <param name="controller">A FrameworkController holding the TestSuite whose cases are to be counted</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <param name="handler">A callback handler used to report results</param> public CountTestsAction(FrameworkController controller, string filter, object handler) { controller.CountTests((ICallbackEventHandler)handler, filter); } } #endregion #region RunTestsAction /// <summary> /// RunTestsAction runs the loaded TestSuite held by the FrameworkController. /// </summary> public class RunTestsAction : FrameworkControllerAction { /// <summary> /// Construct a RunTestsAction and run all tests in the loaded TestSuite. /// </summary> /// <param name="controller">A FrameworkController holding the TestSuite to run</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <param name="handler">A callback handler used to report results</param> public RunTestsAction(FrameworkController controller, string filter, object handler) { controller.RunTests((ICallbackEventHandler)handler, filter); } } #endregion #region RunAsyncAction /// <summary> /// RunAsyncAction initiates an asynchronous test run, returning immediately /// </summary> public class RunAsyncAction : FrameworkControllerAction { /// <summary> /// Construct a RunAsyncAction and run all tests in the loaded TestSuite. /// </summary> /// <param name="controller">A FrameworkController holding the TestSuite to run</param> /// <param name="filter">A string containing the XML representation of the filter to use</param> /// <param name="handler">A callback handler used to report results</param> public RunAsyncAction(FrameworkController controller, string filter, object handler) { controller.RunAsync((ICallbackEventHandler)handler, filter); } } #endregion #region StopRunAction /// <summary> /// StopRunAction stops an ongoing run. /// </summary> public class StopRunAction : FrameworkControllerAction { /// <summary> /// Construct a StopRunAction and stop any ongoing run. If no /// run is in process, no error is raised. /// </summary> /// <param name="controller">The FrameworkController for which a run is to be stopped.</param> /// <param name="force">True the stop should be forced, false for a cooperative stop.</param> /// <param name="handler">>A callback handler used to report results</param> /// <remarks>A forced stop will cause threads and processes to be killed as needed.</remarks> public StopRunAction(FrameworkController controller, bool force, object handler) { controller.StopRun((ICallbackEventHandler)handler, force); } } #endregion #endregion } }
// // ChangePhotoPathController.cs // // Author: // Stephane Delcroix <[email protected]> // // Copyright (C) 2008-2009 Novell, Inc. // Copyright (C) 2008-2009 Stephane Delcroix // // 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. // // // ChangePhotoPath.IChangePhotoPathController.cs: The logic to change the photo path in photos.db // // Author: // Bengt Thuree ([email protected]) // // Copyright (C) 2007 // using System; using System.IO; using System.Collections.Generic; using System.Collections.Specialized; using FSpot; using FSpot.Core; using FSpot.Utils; using Hyena; /* Need to 1) Find old base path, assuming starting /YYYY/MM/DD so look for /YY (/19 or /20) 2) Confirm old base path and display new base path 3) For each Photo, check each version, and change every instance of old base path to new path Consider!!! photo_store.Commit(photo) is using db.ExecuteNonQuery, which is not waiting for the command to finish. On my test set of 20.000 photos, it took SQLite another 1 hour or so to commit all rows after this extension had finished its execution. Consider 2!!! A bit of mixture between URI and path. Old and New base path are in String path. Rest in URI. */ namespace FSpot.Tools.ChangePhotoPath { public enum ProcessResult { Ok, Cancelled, Error, SamePath, NoPhotosFound, Processing } public class ChangePathController { PhotoStore photo_store = FSpot.App.Instance.Database.Photos; List<uint> photo_id_array; List<uint> version_id_array; StringCollection old_path_array, new_path_array; int total_photos; string orig_base_path; private const string BASE2000 = "/20"; private const string BASE1900 = "/19"; private const string BASE1800 = "/18"; private IChangePhotoPathGui gui_controller; private bool user_cancelled; public bool UserCancelled { get {return user_cancelled;} set {user_cancelled = value;} } public ChangePathController (IChangePhotoPathGui gui) { gui_controller = gui; total_photos = photo_store.TotalPhotos; orig_base_path = EnsureEndsWithOneDirectorySeparator (FindOrigBasePath()); // NOT URI string new_base_path = EnsureEndsWithOneDirectorySeparator (FSpot.Core.Global.PhotoUri.LocalPath); // NOT URI gui_controller.DisplayDefaultPaths (orig_base_path, new_base_path); user_cancelled = false; } private string EnsureEndsWithOneDirectorySeparator (string tmp_str) { if ( (tmp_str == null) || (tmp_str.Length == 0) ) return String.Format ("{0}", Path.DirectorySeparatorChar); while (tmp_str.EndsWith(String.Format ("{0}", Path.DirectorySeparatorChar))) tmp_str = tmp_str.Remove (tmp_str.Length-1, 1); return String.Format ("{0}{1}", tmp_str, Path.DirectorySeparatorChar); } // Should always return TRUE, since path always ends with "/" public bool CanWeRun () { return (orig_base_path != null); } private string IsThisPhotoOnOrigBasePath (string check_this_path) { int i; i = check_this_path.IndexOf(BASE2000); if (i > 0) return (check_this_path.Substring(0, i)); i = check_this_path.IndexOf(BASE1900); if (i > 0) return (check_this_path.Substring(0, i)); i = check_this_path.IndexOf(BASE1800); if (i > 0) return (check_this_path.Substring(0, i)); return null; } private string FindOrigBasePath() { string res_path = null; foreach ( IPhoto photo in photo_store.Query ( "SELECT * FROM photos " ) ) { string tmp_path = (photo as Photo).DefaultVersion.Uri.AbsolutePath; res_path = IsThisPhotoOnOrigBasePath (tmp_path); if (res_path != null) break; } return res_path; } private void InitializeArrays() { photo_id_array = new List<uint> (); version_id_array = new List<uint> (); old_path_array = new StringCollection(); new_path_array = new StringCollection(); } private void AddVersionToArrays ( uint photo_id, uint version_id, string old_path, string new_path) { photo_id_array.Add (photo_id); version_id_array.Add (version_id); old_path_array.Add (old_path); new_path_array.Add (new_path); } private string CreateNewPath (string old_base, string new_base, PhotoVersion version) { return string.Format ("{0}{1}", new_base, version.Uri.AbsolutePath.Substring(old_base.Length)); } private bool ChangeThisVersionUri (PhotoVersion version, string old_base, string new_base) { // Change to path from URI, since easier to compare with old_base which is not in URI format. string tmp_path = System.IO.Path.GetDirectoryName (version.Uri.AbsolutePath); return ( tmp_path.StartsWith (old_base) ); } private void SearchVersionUriToChange (Photo photo, string old_base, string new_base) { foreach (uint version_id in photo.VersionIds) { PhotoVersion version = photo.GetVersion (version_id) as PhotoVersion; if ( ChangeThisVersionUri (version, old_base, new_base) ) AddVersionToArrays ( photo.Id, version_id, version.Uri.AbsolutePath, CreateNewPath (old_base, new_base, version)); // else // System.Console.WriteLine ("L : {0}", version.Uri.AbsolutePath); } } public bool SearchUrisToChange (string old_base, string new_base) { int count = 0; foreach ( IPhoto ibrows in photo_store.Query ( "SELECT * FROM photos " ) ) { count++; if (gui_controller.UpdateProgressBar ("Scanning through database", "Checking photo", total_photos)) return false; SearchVersionUriToChange ((ibrows as Photo), old_base, new_base); } return true; } public bool StillOnSamePhotoId (int old_index, int current_index, List<uint> array) { try { return (array[old_index] == array[current_index]); } catch { return true; // return true if out of index. } } public void UpdateThisUri (int index, string path, ref Photo photo) { if (photo == null) photo = photo_store.Get (photo_id_array[index]); PhotoVersion version = photo.GetVersion ( (uint) version_id_array[index]) as PhotoVersion; version.BaseUri = new SafeUri ( path ).GetBaseUri (); version.Filename = new SafeUri ( path ).GetFilename (); photo.Changes.UriChanged = true; photo.Changes.ChangeVersion ( (uint) version_id_array[index] ); } // FIXME: Refactor, try to use one common method.... public void RevertAllUris (int last_index) { gui_controller.remove_progress_dialog(); Photo photo = null; for (int k = last_index; k >= 0; k--) { if (gui_controller.UpdateProgressBar ("Reverting changes to database", "Reverting photo", last_index)) {} // do nothing, ignore trying to abort the revert... if ( (photo != null) && !StillOnSamePhotoId (k+1, k, photo_id_array) ) { photo_store.Commit (photo); photo = null; } UpdateThisUri (k, old_path_array[k], ref photo); Log.DebugFormat ("R : {0} - {1}", k, old_path_array[k]); } if (photo != null) photo_store.Commit (photo); Log.Debug ("Changing path failed due to above error. Have reverted any modification that took place."); } public ProcessResult ChangeAllUris ( ref int last_index) { gui_controller.remove_progress_dialog(); Photo photo = null; last_index = 0; try { photo = null; for (last_index = 0; last_index < photo_id_array.Count; last_index++) { if (gui_controller.UpdateProgressBar ("Changing photos base path", "Changing photo", photo_id_array.Count)) { Log.Debug("User aborted the change of paths..."); return ProcessResult.Cancelled; } if ( (photo != null) && !StillOnSamePhotoId (last_index-1, last_index, photo_id_array) ) { photo_store.Commit (photo); photo = null; } UpdateThisUri (last_index, new_path_array[last_index], ref photo); Log.DebugFormat ("U : {0} - {1}", last_index, new_path_array[last_index]); // DEBUG ONLY // Cause an TEST exception on 6'th URI to be changed. // float apa = last_index / (last_index-6); } if (photo != null) photo_store.Commit (photo); } catch (Exception e) { Log.Exception(e); return ProcessResult.Error; } return ProcessResult.Ok; } public ProcessResult ProcessArrays() { int last_index = 0; ProcessResult tmp_res; tmp_res = ChangeAllUris(ref last_index); if (!(tmp_res == ProcessResult.Ok)) RevertAllUris(last_index); return tmp_res; } /* public void CheckIfUpdated (int test_index, StringCollection path_array) { Photo photo = photo_store.Get ( (uint) photo_id_array[test_index]) as Photo; PhotoVersion version = photo.GetVersion ( (uint) version_id_array[test_index]) as PhotoVersion; if (version.Uri.AbsolutePath.ToString() == path_array[ test_index ]) Log.DebugFormat ("Test URI ({0}) matches --- Should be finished", test_index); else Log.DebugFormat ("Test URI ({0}) DO NOT match --- Should NOT BE finished", test_index); } */ /* Check paths are different If (Scan all photos) // user might cancel If (Check there are photos on old path) ChangePathsOnPhotos */ public bool NewOldPathSame (ref string newpath, ref string oldpath) { string p1 = EnsureEndsWithOneDirectorySeparator(newpath); string p2 = EnsureEndsWithOneDirectorySeparator(oldpath); return (p1 == p2); } public ProcessResult ChangePathOnPhotos (string old_base, string new_base) { ProcessResult tmp_res = ProcessResult.Processing; InitializeArrays(); if (NewOldPathSame (ref new_base, ref old_base)) tmp_res = ProcessResult.SamePath; if ( (tmp_res == ProcessResult.Processing) && (!SearchUrisToChange (old_base, new_base)) ) tmp_res = ProcessResult.Cancelled; if ( (tmp_res == ProcessResult.Processing) && (photo_id_array.Count == 0) ) tmp_res = ProcessResult.NoPhotosFound; if (tmp_res == ProcessResult.Processing) tmp_res = ProcessArrays(); // if (res) // CheckIfUpdated (photo_id_array.Count-1, new_path_array); // else // CheckIfUpdated (0, old_path_array); return tmp_res; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Security; namespace System.IO.MemoryMappedFiles { public partial class MemoryMappedFile : IDisposable { private readonly SafeMemoryMappedFileHandle _handle; private readonly bool _leaveOpen; private readonly FileStream _fileStream; internal const int DefaultSize = 0; // Private constructors to be used by the factory methods. [SecurityCritical] private MemoryMappedFile(SafeMemoryMappedFileHandle handle) { Debug.Assert(handle != null); Debug.Assert(!handle.IsClosed); Debug.Assert(!handle.IsInvalid); _handle = handle; _leaveOpen = true; // No FileStream to dispose of in this case. } [SecurityCritical] private MemoryMappedFile(SafeMemoryMappedFileHandle handle, FileStream fileStream, bool leaveOpen) { Debug.Assert(handle != null); Debug.Assert(!handle.IsClosed); Debug.Assert(!handle.IsInvalid); Debug.Assert(fileStream != null); _handle = handle; _fileStream = fileStream; _leaveOpen = leaveOpen; } // Factory Method Group #1: Opens an existing named memory mapped file. The native OpenFileMapping call // will check the desiredAccessRights against the ACL on the memory mapped file. Note that a memory // mapped file created without an ACL will use a default ACL taken from the primary or impersonation token // of the creator. On my machine, I always get ReadWrite access to it so I never have to use anything but // the first override of this method. Note: having ReadWrite access to the object does not mean that we // have ReadWrite access to the pages mapping the file. The OS will check against the access on the pages // when a view is created. public static MemoryMappedFile OpenExisting(string mapName) { return OpenExisting(mapName, MemoryMappedFileRights.ReadWrite, HandleInheritability.None); } public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights) { return OpenExisting(mapName, desiredAccessRights, HandleInheritability.None); } [SecurityCritical] public static MemoryMappedFile OpenExisting(string mapName, MemoryMappedFileRights desiredAccessRights, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.ArgumentNull_MapName); } if (mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } if (((int)desiredAccessRights & ~((int)(MemoryMappedFileRights.FullControl | MemoryMappedFileRights.AccessSystemSecurity))) != 0) { throw new ArgumentOutOfRangeException("desiredAccessRights"); } SafeMemoryMappedFileHandle handle = OpenCore(mapName, inheritability, desiredAccessRights, false); return new MemoryMappedFile(handle); } // Factory Method Group #2: Creates a new memory mapped file where the content is taken from an existing // file on disk. This file must be opened by a FileStream before given to us. Specifying DefaultSize to // the capacity will make the capacity of the memory mapped file match the size of the file. Specifying // a value larger than the size of the file will enlarge the new file to this size. Note that in such a // case, the capacity (and there for the size of the file) will be rounded up to a multiple of the system // page size. One can use FileStream.SetLength to bring the length back to a desirable size. By default, // the MemoryMappedFile will close the FileStream object when it is disposed. This behavior can be // changed by the leaveOpen boolean argument. public static MemoryMappedFile CreateFromFile(string path) { return CreateFromFile(path, FileMode.Open, null, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(string path, FileMode mode) { return CreateFromFile(path, mode, null, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string mapName) { return CreateFromFile(path, mode, mapName, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string mapName, long capacity) { return CreateFromFile(path, mode, mapName, capacity, MemoryMappedFileAccess.ReadWrite); } [SecurityCritical] public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { if (path == null) { throw new ArgumentNullException("path"); } if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (mode == FileMode.Append) { throw new ArgumentException(SR.Argument_NewMMFAppendModeNotAllowed, "mode"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } bool existed = File.Exists(path); FileStream fileStream = new FileStream(path, mode, GetFileAccess(access), FileShare.None, 0x1000, FileOptions.None); if (capacity == 0 && fileStream.Length == 0) { CleanupFile(fileStream, existed, path); throw new ArgumentException(SR.Argument_EmptyFile); } if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) { CleanupFile(fileStream, existed, path); throw new ArgumentException(SR.Argument_ReadAccessWithLargeCapacity); } if (capacity == DefaultSize) { capacity = fileStream.Length; } // one can always create a small view if they do not want to map an entire file if (fileStream.Length > capacity) { CleanupFile(fileStream, existed, path); throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityGEFileSizeRequired); } SafeMemoryMappedFileHandle handle = null; try { handle = CreateCore(fileStream, mapName, HandleInheritability.None, access, MemoryMappedFileOptions.None, capacity); } catch { CleanupFile(fileStream, existed, path); throw; } Debug.Assert(handle != null); Debug.Assert(!handle.IsInvalid); return new MemoryMappedFile(handle, fileStream, false); } [SecurityCritical] public static MemoryMappedFile CreateFromFile(FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { if (fileStream == null) { throw new ArgumentNullException("fileStream", SR.ArgumentNull_FileStream); } if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired); } if (capacity == 0 && fileStream.Length == 0) { throw new ArgumentException(SR.Argument_EmptyFile); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) { throw new ArgumentException(SR.Argument_ReadAccessWithLargeCapacity); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } // flush any bytes written to the FileStream buffer so that we can see them in our MemoryMappedFile fileStream.Flush(); if (capacity == DefaultSize) { capacity = fileStream.Length; } // one can always create a small view if they do not want to map an entire file if (fileStream.Length > capacity) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityGEFileSizeRequired); } SafeMemoryMappedFileHandle handle = CreateCore(fileStream, mapName, inheritability, access, MemoryMappedFileOptions.None, capacity); return new MemoryMappedFile(handle, fileStream, leaveOpen); } // Factory Method Group #3: Creates a new empty memory mapped file. Such memory mapped files are ideal // for IPC, when mapName != null. public static MemoryMappedFile CreateNew(string mapName, long capacity) { return CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); } public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access) { return CreateNew(mapName, capacity, access, MemoryMappedFileOptions.None, HandleInheritability.None); } [SecurityCritical] public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName != null && mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > uint.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (access == MemoryMappedFileAccess.Write) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle = CreateCore(null, mapName, inheritability, access, options, capacity); return new MemoryMappedFile(handle); } // Factory Method Group #4: Creates a new empty memory mapped file or opens an existing // memory mapped file if one exists with the same name. The capacity, options, and // memoryMappedFileSecurity arguments will be ignored in the case of the later. // This is ideal for P2P style IPC. public static MemoryMappedFile CreateOrOpen(string mapName, long capacity) { return CreateOrOpen(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None); } public static MemoryMappedFile CreateOrOpen(string mapName, long capacity, MemoryMappedFileAccess access) { return CreateOrOpen(mapName, capacity, access, MemoryMappedFileOptions.None, HandleInheritability.None); } [SecurityCritical] public static MemoryMappedFile CreateOrOpen(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { if (mapName == null) { throw new ArgumentNullException("mapName", SR.ArgumentNull_MapName); } if (mapName.Length == 0) { throw new ArgumentException(SR.Argument_MapNameEmptyString); } if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedPositiveNumber); } if (IntPtr.Size == 4 && capacity > uint.MaxValue) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) { throw new ArgumentOutOfRangeException("options"); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { throw new ArgumentOutOfRangeException("inheritability"); } SafeMemoryMappedFileHandle handle; // special case for write access; create will never succeed if (access == MemoryMappedFileAccess.Write) { handle = OpenCore(mapName, inheritability, access, true); } else { handle = CreateOrOpenCore(mapName, inheritability, access, options, capacity); } return new MemoryMappedFile(handle); } // Creates a new view in the form of a stream. public MemoryMappedViewStream CreateViewStream() { return CreateViewStream(0, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public MemoryMappedViewStream CreateViewStream(long offset, long size) { return CreateViewStream(offset, size, MemoryMappedFileAccess.ReadWrite); } [SecurityCritical] public MemoryMappedViewStream CreateViewStream(long offset, long size, MemoryMappedFileAccess access) { if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (size < 0) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (IntPtr.Size == 4 && size > uint.MaxValue) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size); return new MemoryMappedViewStream(view); } // Creates a new view in the form of an accessor. Accessors are for random access. public MemoryMappedViewAccessor CreateViewAccessor() { return CreateViewAccessor(0, DefaultSize, MemoryMappedFileAccess.ReadWrite); } public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size) { return CreateViewAccessor(offset, size, MemoryMappedFileAccess.ReadWrite); } [SecurityCritical] public MemoryMappedViewAccessor CreateViewAccessor(long offset, long size, MemoryMappedFileAccess access) { if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (size < 0) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_PositiveOrDefaultSizeRequired); } if (access < MemoryMappedFileAccess.ReadWrite || access > MemoryMappedFileAccess.ReadWriteExecute) { throw new ArgumentOutOfRangeException("access"); } if (IntPtr.Size == 4 && size > uint.MaxValue) { throw new ArgumentOutOfRangeException("size", SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed); } MemoryMappedView view = MemoryMappedView.CreateView(_handle, access, offset, size); return new MemoryMappedViewAccessor(view); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [SecuritySafeCritical] protected virtual void Dispose(bool disposing) { try { if (!_handle.IsClosed) { _handle.Dispose(); } } finally { if (_fileStream != null && _leaveOpen == false) { _fileStream.Dispose(); } } } public SafeMemoryMappedFileHandle SafeMemoryMappedFileHandle { [SecurityCritical] get { return _handle; } } // This converts a MemoryMappedFileAccess to a FileAccess. MemoryMappedViewStream and // MemoryMappedViewAccessor subclass UnmanagedMemoryStream and UnmanagedMemoryAccessor, which both use // FileAccess to determine whether they are writable and/or readable. internal static FileAccess GetFileAccess(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: case MemoryMappedFileAccess.ReadExecute: return FileAccess.Read; case MemoryMappedFileAccess.ReadWrite: case MemoryMappedFileAccess.CopyOnWrite: case MemoryMappedFileAccess.ReadWriteExecute: return FileAccess.ReadWrite; default: Debug.Assert(access == MemoryMappedFileAccess.Write); return FileAccess.Write; } } // clean up: close file handle and delete files we created private static void CleanupFile(FileStream fileStream, bool existed, string path) { fileStream.Dispose(); if (!existed) { File.Delete(path); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MyApp.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The sample generation is done synchronously.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.ComponentModel; using System.Threading.Tasks; using Android.App; using Android.Support.V4.Widget; using Android.Views; using AView = Android.Views.View; using AColor = Android.Graphics.Drawables.ColorDrawable; namespace Xamarin.Forms.Platform.Android { public class MasterDetailRenderer : DrawerLayout, IVisualElementRenderer, DrawerLayout.IDrawerListener { //from Android source code const uint DefaultScrimColor = 0x99000000; int _currentLockMode = -1; MasterDetailContainer _detailLayout; bool _isPresentingFromCore; MasterDetailContainer _masterLayout; MasterDetailPage _page; bool _presented; public MasterDetailRenderer() : base(Forms.Context) { } IMasterDetailPageController MasterDetailPageController => _page as IMasterDetailPageController; public bool Presented { get { return _presented; } set { if (value == _presented) return; UpdateSplitViewLayout(); _presented = value; if (_page.MasterBehavior == MasterBehavior.Default && MasterDetailPageController.ShouldShowSplitMode) return; if (_presented) OpenDrawer(_masterLayout); else CloseDrawer(_masterLayout); } } IPageController MasterPageController => _page.Master as IPageController; IPageController DetailPageController => _page.Detail as IPageController; IPageController PageController => Element as IPageController; public void OnDrawerClosed(AView drawerView) { } public void OnDrawerOpened(AView drawerView) { } public void OnDrawerSlide(AView drawerView, float slideOffset) { } public void OnDrawerStateChanged(int newState) { _presented = IsDrawerVisible(_masterLayout); UpdateIsPresented(); } public VisualElement Element { get { return _page; } } public event EventHandler<VisualElementChangedEventArgs> ElementChanged; public SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint) { Measure(widthConstraint, heightConstraint); return new SizeRequest(new Size(MeasuredWidth, MeasuredHeight)); } public void SetElement(VisualElement element) { MasterDetailPage oldElement = _page; _page = element as MasterDetailPage; _detailLayout = new MasterDetailContainer(_page, false, Context) { LayoutParameters = new LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent) }; _masterLayout = new MasterDetailContainer(_page, true, Context) { LayoutParameters = new LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent) { Gravity = (int)GravityFlags.Start } }; AddView(_detailLayout); AddView(_masterLayout); var activity = Context as Activity; activity.ActionBar.SetDisplayShowHomeEnabled(true); activity.ActionBar.SetHomeButtonEnabled(true); UpdateBackgroundColor(_page); UpdateBackgroundImage(_page); OnElementChanged(oldElement, element); if (oldElement != null) ((IMasterDetailPageController)oldElement).BackButtonPressed -= OnBackButtonPressed; if (_page != null) MasterDetailPageController.BackButtonPressed += OnBackButtonPressed; if (Tracker == null) Tracker = new VisualElementTracker(this); _page.PropertyChanged += HandlePropertyChanged; _page.Appearing += MasterDetailPageAppearing; _page.Disappearing += MasterDetailPageDisappearing; UpdateMaster(); UpdateDetail(); Device.Info.PropertyChanged += DeviceInfoPropertyChanged; SetGestureState(); Presented = _page.IsPresented; AddDrawerListener(this); if (element != null) element.SendViewInitialized(this); if (element != null && !string.IsNullOrEmpty(element.AutomationId)) ContentDescription = element.AutomationId; } public VisualElementTracker Tracker { get; private set; } public void UpdateLayout() { if (Tracker != null) Tracker.UpdateLayout(); } public ViewGroup ViewGroup { get { return this; } } protected override void Dispose(bool disposing) { if (disposing) { if (Tracker != null) { Tracker.Dispose(); Tracker = null; } if (_detailLayout != null) { _detailLayout.Dispose(); _detailLayout = null; } if (_masterLayout != null) { _masterLayout.Dispose(); _masterLayout = null; } Device.Info.PropertyChanged -= DeviceInfoPropertyChanged; if (_page != null) { MasterDetailPageController.BackButtonPressed -= OnBackButtonPressed; _page.PropertyChanged -= HandlePropertyChanged; _page.Appearing -= MasterDetailPageAppearing; _page.Disappearing -= MasterDetailPageDisappearing; _page.ClearValue(Platform.RendererProperty); _page = null; } } base.Dispose(disposing); } protected override void OnAttachedToWindow() { base.OnAttachedToWindow(); PageController.SendAppearing(); } protected override void OnDetachedFromWindow() { base.OnDetachedFromWindow(); PageController.SendDisappearing(); } protected virtual void OnElementChanged(VisualElement oldElement, VisualElement newElement) { EventHandler<VisualElementChangedEventArgs> changed = ElementChanged; if (changed != null) changed(this, new VisualElementChangedEventArgs(oldElement, newElement)); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { base.OnLayout(changed, l, t, r, b); //hack to make the split layout handle touches the full width if (MasterDetailPageController.ShouldShowSplitMode && _masterLayout != null) _masterLayout.Right = r; } async void DeviceInfoPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "CurrentOrientation") { if (!MasterDetailPageController.ShouldShowSplitMode && Presented) { MasterDetailPageController.CanChangeIsPresented = true; //hack : when the orientation changes and we try to close the Master on Android //sometimes Android picks the width of the screen previous to the rotation //this leaves a little of the master visible, the hack is to delay for 50ms closing the drawer await Task.Delay(50); CloseDrawer(_masterLayout); } UpdateSplitViewLayout(); } } void HandleMasterPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == Page.TitleProperty.PropertyName || e.PropertyName == Page.IconProperty.PropertyName) ((Platform)_page.Platform).UpdateMasterDetailToggle(true); } void HandlePropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Master") UpdateMaster(); else if (e.PropertyName == "Detail") { UpdateDetail(); ((Platform)_page.Platform).UpdateActionBar(); } else if (e.PropertyName == MasterDetailPage.IsPresentedProperty.PropertyName) { _isPresentingFromCore = true; Presented = _page.IsPresented; _isPresentingFromCore = false; } else if (e.PropertyName == "IsGestureEnabled") SetGestureState(); else if (e.PropertyName == Page.BackgroundImageProperty.PropertyName) UpdateBackgroundImage(_page); if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName) UpdateBackgroundColor(_page); } void MasterDetailPageAppearing(object sender, EventArgs e) { MasterPageController?.SendAppearing(); DetailPageController?.SendAppearing(); } void MasterDetailPageDisappearing(object sender, EventArgs e) { MasterPageController?.SendDisappearing(); DetailPageController?.SendDisappearing(); } void OnBackButtonPressed(object sender, BackButtonPressedEventArgs backButtonPressedEventArgs) { if (IsDrawerOpen((int)GravityFlags.Start)) { if (_currentLockMode != LockModeLockedOpen) { CloseDrawer((int)GravityFlags.Start); backButtonPressedEventArgs.Handled = true; } } } void SetGestureState() { SetDrawerLockMode(_page.IsGestureEnabled ? LockModeUnlocked : LockModeLockedClosed); } void SetLockMode(int lockMode) { if (_currentLockMode != lockMode) { SetDrawerLockMode(lockMode); _currentLockMode = lockMode; } } void UpdateBackgroundColor(Page view) { if (view.BackgroundColor != Color.Default) SetBackgroundColor(view.BackgroundColor.ToAndroid()); } void UpdateBackgroundImage(Page view) { if (!string.IsNullOrEmpty(view.BackgroundImage)) this.SetBackground(Context.Resources.GetDrawable(view.BackgroundImage)); } void UpdateDetail() { Context.HideKeyboard(this); _detailLayout.ChildView = _page.Detail; } void UpdateIsPresented() { if (_isPresentingFromCore) return; if (Presented != _page.IsPresented) ((IElementController)_page).SetValueFromRenderer(MasterDetailPage.IsPresentedProperty, Presented); } void UpdateMaster() { if (_masterLayout != null && _masterLayout.ChildView != null) _masterLayout.ChildView.PropertyChanged -= HandleMasterPropertyChanged; _masterLayout.ChildView = _page.Master; if (_page.Master != null) _page.Master.PropertyChanged += HandleMasterPropertyChanged; } void UpdateSplitViewLayout() { if (Device.Idiom == TargetIdiom.Tablet) { bool isShowingSplit = MasterDetailPageController.ShouldShowSplitMode || (MasterDetailPageController.ShouldShowSplitMode && _page.MasterBehavior != MasterBehavior.Default && _page.IsPresented); SetLockMode(isShowingSplit ? LockModeLockedOpen : LockModeUnlocked); unchecked { SetScrimColor(isShowingSplit ? Color.Transparent.ToAndroid() : (int)DefaultScrimColor); } ((Platform)_page.Platform).UpdateMasterDetailToggle(); } } } }
/********************************************************************++ * Copyright (c) Microsoft Corporation. All rights reserved. * --********************************************************************/ using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation.Tracing; using System.Xml; using System.Text; using System.Management.Automation.Internal; using Dbg = System.Management.Automation.Diagnostics; using TypeTable = System.Management.Automation.Runspaces.TypeTable; namespace System.Management.Automation.Remoting { /// <summary> /// This class is used to hold a fragment of remoting PSObject for transporting to remote computer. /// /// A large remoting PSObject will be broken into fragments. Each fragment has a ObjectId and a FragmentId. /// The first fragment has a StartFragment marker. The last fragment also an EndFragment marker. /// These fragments can be reassembled on the receiving /// end by sequencing the fragment ids. /// /// Currently control objects (Control-C for stopping a pipeline execution) is not /// really fragmented. These objects are small. They are just wrapped into a single /// fragment. /// </summary> internal class FragmentedRemoteObject { private byte[] _blob; private int _blobLength; /// <summary> /// SFlag stands for the IsStartFragment. It is the bit value in the binary encoding. /// </summary> internal const byte SFlag = 0x1; /// <summary> /// EFlag stands for the IsEndFragment. It is the bit value in the binary encoding. /// </summary> internal const byte EFlag = 0x2; /// <summary> /// HeaderLength is the total number of bytes in the binary encoding header. /// </summary> internal const int HeaderLength = 8 + 8 + 1 + 4; /// <summary> /// _objectIdOffset is the offset of the ObjectId in the binary encoding. /// </summary> private const int _objectIdOffset = 0; /// <summary> /// _fragmentIdOffset is the offset of the FragmentId in the binary encoding. /// </summary> private const int _fragmentIdOffset = 8; /// <summary> /// _flagsOffset is the offset of the byte in the binary encoding that contains the SFlag, EFlag and CFlag. /// </summary> private const int _flagsOffset = 16; /// <summary> /// _blobLengthOffset is the offset of the BlobLength in the binary encoding. /// </summary> private const int _blobLengthOffset = 17; /// <summary> /// _blobOffset is the offset of the Blob in the binary encoding. /// </summary> private const int _blobOffset = 21; #region Constructors /// <summary> /// Default Constructor /// </summary> internal FragmentedRemoteObject() { } /// <summary> /// Used to construct a fragment of PSObject to be sent to remote computer. /// </summary> /// <param name="blob"></param> /// <param name="objectId"> /// ObjectId of the fragment. /// Caller should make sure this is not less than 0. /// </param> /// <param name="fragmentId"> /// FragmentId within the object. /// Caller should make sure this is not less than 0. /// </param> /// <param name="isEndFragment"> /// true if this is a EndFragment. /// </param> internal FragmentedRemoteObject(byte[] blob, long objectId, long fragmentId, bool isEndFragment) { Dbg.Assert((null != blob) || (blob.Length == 0), "Cannot create a fragment for null or empty data."); Dbg.Assert(objectId >= 0, "Object Id cannot be < 0"); Dbg.Assert(fragmentId >= 0, "Fragment Id cannot be < 0"); ObjectId = objectId; FragmentId = fragmentId; IsStartFragment = (fragmentId == 0) ? true : false; IsEndFragment = isEndFragment; _blob = blob; _blobLength = _blob.Length; } #endregion Constructors #region Data Fields being sent /// <summary> /// All fragments of the same PSObject have the same ObjectId /// </summary> internal long ObjectId { get; set; } /// <summary> /// FragmentId starts from 0. It increases sequentially by an increment of 1. /// </summary> internal long FragmentId { get; set; } /// <summary> /// The first fragment of a PSObject. /// </summary> internal bool IsStartFragment { get; set; } /// <summary> /// The last fragment of a PSObject. /// </summary> internal bool IsEndFragment { get; set; } /// <summary> /// Blob length. This enables scenarios where entire byte[] is /// not filled for the fragment. /// </summary> internal int BlobLength { get { return _blobLength; } set { Dbg.Assert(value >= 0, "BlobLength cannot be less than 0."); _blobLength = value; } } /// <summary> /// This is the actual data in bytes form. /// </summary> internal byte[] Blob { get { return _blob; } set { Dbg.Assert(null != value, "Blob cannot be null"); _blob = value; } } #endregion Data Fields being sent /// <summary> /// This method generate a binary encoding of the FragmentedRemoteObject as follows: /// ObjectId: 8 bytes as long, byte order is big-endian. this value can only be non-negative. /// FragmentId: 8 bytes as long, byte order is big-endian. this value can only be non-negative. /// FlagsByte: 1 byte: /// 0x1 if IsStartOfFragment is true: This is called S-flag. /// 0x2 if IsEndOfFragment is true: This is called the E-flag. /// 0x4 if IsControl is true: This is called the C-flag. /// /// The other bits are reserved for future use. /// Now they must be zero when sending, /// and they are ignored when receiving. /// BlobLength: 4 bytes as int, byte order is big-endian. this value can only be non-negative. /// Blob: BlobLength number of bytes. /// /// 0 1 2 3 /// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// | | /// +-+-+-+-+-+-+-+- ObjectId +-+-+-+-+-+-+-+-+ /// | | /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// | | /// +-+-+-+-+-+-+-+- FragmentId +-+-+-+-+-+-+-+-+ /// | | /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// |reserved |C|E|S| /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// | BlobLength | /// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ /// | Blob ... /// +-+-+-+-+-+-+-+- /// /// </summary> /// <returns> /// The binary encoded FragmentedRemoteObject to be ready to pass to WinRS Send API. /// </returns> internal byte[] GetBytes() { int objectIdSize = 8; // number of bytes of long int fragmentIdSize = 8; // number of bytes of long int flagsSize = 1; // 1 byte for IsEndOfFrag and IsControl int blobLengthSize = 4; // number of bytes of int int totalLength = objectIdSize + fragmentIdSize + flagsSize + blobLengthSize + BlobLength; byte[] result = new byte[totalLength]; int idx = 0; // release build will optimize the calculation of the constants // ObjectId idx = _objectIdOffset; result[idx++] = (byte)((ObjectId >> (7 * 8)) & 0x7F); // sign bit is 0 result[idx++] = (byte)((ObjectId >> (6 * 8)) & 0xFF); result[idx++] = (byte)((ObjectId >> (5 * 8)) & 0xFF); result[idx++] = (byte)((ObjectId >> (4 * 8)) & 0xFF); result[idx++] = (byte)((ObjectId >> (3 * 8)) & 0xFF); result[idx++] = (byte)((ObjectId >> (2 * 8)) & 0xFF); result[idx++] = (byte)((ObjectId >> 8) & 0xFF); result[idx++] = (byte)(ObjectId & 0xFF); // FragmentId idx = _fragmentIdOffset; result[idx++] = (byte)((FragmentId >> (7 * 8)) & 0x7F); // sign bit is 0 result[idx++] = (byte)((FragmentId >> (6 * 8)) & 0xFF); result[idx++] = (byte)((FragmentId >> (5 * 8)) & 0xFF); result[idx++] = (byte)((FragmentId >> (4 * 8)) & 0xFF); result[idx++] = (byte)((FragmentId >> (3 * 8)) & 0xFF); result[idx++] = (byte)((FragmentId >> (2 * 8)) & 0xFF); result[idx++] = (byte)((FragmentId >> 8) & 0xFF); result[idx++] = (byte)(FragmentId & 0xFF); // E-flag and S-Flag idx = _flagsOffset; byte s_flag = IsStartFragment ? SFlag : (byte)0; byte e_flag = IsEndFragment ? EFlag : (byte)0; result[idx++] = (byte)(s_flag | e_flag); // BlobLength idx = _blobLengthOffset; result[idx++] = (byte)((BlobLength >> (3 * 8)) & 0xFF); result[idx++] = (byte)((BlobLength >> (2 * 8)) & 0xFF); result[idx++] = (byte)((BlobLength >> 8) & 0xFF); result[idx++] = (byte)(BlobLength & 0xFF); Array.Copy(_blob, 0, result, _blobOffset, BlobLength); return result; } /// <summary> /// Extract the objectId from a byte array, starting at the index indicated by /// startIndex parameter. /// </summary> /// <param name="fragmentBytes"></param> /// <param name="startIndex"></param> /// <returns> /// The objectId. /// </returns> /// <exception cref="ArgumentNullException"> /// If fragmentBytes is null. /// </exception> /// <exception cref="ArgumentException"> /// If startIndex is negative or fragmentBytes is not large enough to hold the entire header of /// a binary encoded FragmentedRemoteObject. /// </exception> internal static long GetObjectId(byte[] fragmentBytes, int startIndex) { Dbg.Assert(null != fragmentBytes, "fragmentBytes cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode object id"); long objectId = 0; int idx = startIndex + _objectIdOffset; objectId = (((long)fragmentBytes[idx++]) << (7 * 8)) & 0x7F00000000000000; objectId += (((long)fragmentBytes[idx++]) << (6 * 8)) & 0xFF000000000000; objectId += (((long)fragmentBytes[idx++]) << (5 * 8)) & 0xFF0000000000; objectId += (((long)fragmentBytes[idx++]) << (4 * 8)) & 0xFF00000000; objectId += (((long)fragmentBytes[idx++]) << (3 * 8)) & 0xFF000000; objectId += (((long)fragmentBytes[idx++]) << (2 * 8)) & 0xFF0000; objectId += (((long)fragmentBytes[idx++]) << 8) & 0xFF00; objectId += ((long)fragmentBytes[idx++]) & 0xFF; return objectId; } /// <summary> /// Extract the FragmentId from the byte array, starting at the index indicated by /// startIndex parameter. /// </summary> /// <param name="fragmentBytes"></param> /// <param name="startIndex"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// If fragmentBytes is null. /// </exception> /// <exception cref="ArgumentException"> /// If startIndex is negative or fragmentBytes is not large enough to hold the entire header of /// a binary encoded FragmentedRemoteObject. /// </exception> internal static long GetFragmentId(byte[] fragmentBytes, int startIndex) { Dbg.Assert(null != fragmentBytes, "fragmentBytes cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode fragment id"); long fragmentId = 0; int idx = startIndex + _fragmentIdOffset; fragmentId = (((long)fragmentBytes[idx++]) << (7 * 8)) & 0x7F00000000000000; fragmentId += (((long)fragmentBytes[idx++]) << (6 * 8)) & 0xFF000000000000; fragmentId += (((long)fragmentBytes[idx++]) << (5 * 8)) & 0xFF0000000000; fragmentId += (((long)fragmentBytes[idx++]) << (4 * 8)) & 0xFF00000000; fragmentId += (((long)fragmentBytes[idx++]) << (3 * 8)) & 0xFF000000; fragmentId += (((long)fragmentBytes[idx++]) << (2 * 8)) & 0xFF0000; fragmentId += (((long)fragmentBytes[idx++]) << 8) & 0xFF00; fragmentId += ((long)fragmentBytes[idx++]) & 0xFF; return fragmentId; } /// <summary> /// Extract the IsStartFragment value from the byte array, starting at the index indicated by /// startIndex parameter. /// </summary> /// <param name="fragmentBytes"></param> /// <param name="startIndex"></param> /// <returns> /// True is the S-flag is set in the encoding. Otherwise false. /// </returns> /// <exception cref="ArgumentNullException"> /// If fragmentBytes is null. /// </exception> /// <exception cref="ArgumentException"> /// If startIndex is negative or fragmentBytes is not large enough to hold the entire header of /// a binary encoded FragmentedRemoteObject. /// </exception> internal static bool GetIsStartFragment(byte[] fragmentBytes, int startIndex) { Dbg.Assert(null != fragmentBytes, "fragment cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode if it is a start fragment."); if ((fragmentBytes[startIndex + _flagsOffset] & SFlag) != 0) { return true; } return false; } /// <summary> /// Extract the IsEndFragment value from the byte array, starting at the index indicated by /// startIndex parameter. /// </summary> /// <param name="fragmentBytes"></param> /// <param name="startIndex"></param> /// <returns> /// True if the the E-flag is set in the encoding. Otherwise false. /// </returns> /// <exception cref="ArgumentNullException"> /// If fragmentBytes is null. /// </exception> /// <exception cref="ArgumentException"> /// If startIndex is negative or fragmentBytes is not large enough to hold the entire header of /// a binary encoded FragmentedRemoteObject. /// </exception> internal static bool GetIsEndFragment(byte[] fragmentBytes, int startIndex) { Dbg.Assert(null != fragmentBytes, "fragment cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode if it is an end fragment."); if ((fragmentBytes[startIndex + _flagsOffset] & EFlag) != 0) { return true; } return false; } /// <summary> /// Extract the BlobLength value from the byte array, starting at the index indicated by /// startIndex parameter. /// </summary> /// <param name="fragmentBytes"></param> /// <param name="startIndex"></param> /// <returns> /// The BlobLength value. /// </returns> /// <exception cref="ArgumentNullException"> /// If fragmentBytes is null. /// </exception> /// <exception cref="ArgumentException"> /// If startIndex is negative or fragmentBytes is not large enough to hold the entire header of /// a binary encoded FragmentedRemoteObject. /// </exception> internal static int GetBlobLength(byte[] fragmentBytes, int startIndex) { Dbg.Assert(null != fragmentBytes, "fragment cannot be null"); Dbg.Assert(fragmentBytes.Length >= HeaderLength, "not enough data to decode blob length."); int blobLength = 0; int idx = startIndex + _blobLengthOffset; blobLength += (((int)fragmentBytes[idx++]) << (3 * 8)) & 0x7F000000; blobLength += (((int)fragmentBytes[idx++]) << (2 * 8)) & 0xFF0000; blobLength += (((int)fragmentBytes[idx++]) << 8) & 0xFF00; blobLength += ((int)fragmentBytes[idx++]) & 0xFF; return blobLength; } } /// <summary> /// A stream used to store serialized data. This stream holds serialized data in the /// form of fragments. Every "fragment size" data will hold a blob identifying the fragment. /// The blob has "ObjectId","FragmentId","Properties like Start,End","BlobLength" /// </summary> internal class SerializedDataStream : Stream, IDisposable { [TraceSourceAttribute("SerializedDataStream", "SerializedDataStream")] private static PSTraceSource s_trace = PSTraceSource.GetTracer("SerializedDataStream", "SerializedDataStream"); #region Global Constants private static long s_objectIdSequenceNumber = 0; #endregion #region Private Data private bool _isEntered; private FragmentedRemoteObject _currentFragment; private long _fragmentId; private int _fragmentSize; private object _syncObject; private bool _isDisposed; private bool _notifyOnWriteFragmentImmediately; // MemoryStream does not dynamically resize as data is read. This will waste // lot of memory as data sent on the network will still be there in memory. // To avoid this a queue of memory streams (each stream is of fragmentsize) // is created..so after data is sent the MemoryStream is disposed there by // clearing resources. private Queue<MemoryStream> _queuedStreams; private MemoryStream _writeStream; private MemoryStream _readStream; private int _writeOffset; private int _readOffSet; private long _length; /// <summary> /// Callback that is called once a fragmented data is available. /// </summary> /// <param name="data"> /// Data that resulted in this callback. /// </param> /// <param name="isEndFragment"> /// true if data represents EndFragment of an object. /// </param> internal delegate void OnDataAvailableCallback(byte[] data, bool isEndFragment); private OnDataAvailableCallback _onDataAvailableCallback; #endregion #region Constructor /// <summary> /// Creates a stream to hold serialized data. /// </summary> /// <param name="fragmentSize"> /// fragmentSize to be used while creating fragment boundaries. /// </param> internal SerializedDataStream(int fragmentSize) { s_trace.WriteLine("Creating SerializedDataStream with fragmentsize : {0}", fragmentSize); Dbg.Assert(fragmentSize > 0, "fragmentsize should be greater than 0."); _syncObject = new object(); _currentFragment = new FragmentedRemoteObject(); _queuedStreams = new Queue<MemoryStream>(); _fragmentSize = fragmentSize; } /// <summary> /// Use this constructor carefully. This will not write data into internal /// streams. Instead this will make the SerializedDataStream call the /// callback whenever a fragmented data is available. It is upto the caller /// to figure out what to do with the data. /// </summary> /// <param name="fragmentSize"> /// fragmentSize to be used while creating fragment boundaries. /// </param> /// <param name="callbackToNotify"> /// If this is not null, then callback will get notified whenever fragmented /// data is available. Read() will return null in this case always. /// </param> internal SerializedDataStream(int fragmentSize, OnDataAvailableCallback callbackToNotify) : this(fragmentSize) { if (null != callbackToNotify) { _notifyOnWriteFragmentImmediately = true; _onDataAvailableCallback = callbackToNotify; } } #endregion #region Internal methods / Protected overrides /// <summary> /// Start using the stream exclusively (to write data). The stream can be entered only once. /// If you want to Enter again, first Exit and then Enter. /// This method is not thread-safe. /// </summary> internal void Enter() { Dbg.Assert(!_isEntered, "Stream is already entered. You cannot enter into stream again."); _isEntered = true; _fragmentId = 0; // Initialize the current fragment _currentFragment.ObjectId = GetObjectId(); _currentFragment.FragmentId = _fragmentId; _currentFragment.IsStartFragment = true; _currentFragment.BlobLength = 0; _currentFragment.Blob = new byte[_fragmentSize]; } /// <summary> /// Notify that the stream is not used to write anymore. /// This method is not thread-safe. /// </summary> internal void Exit() { _isEntered = false; // write left over data if (_currentFragment.BlobLength > 0) { // this is endfragment...as we are in Exit _currentFragment.IsEndFragment = true; WriteCurrentFragmentAndReset(); } } /// <summary> /// Writes a block of bytes to the current stream using data read from buffer. /// The base MemoryStream is written to only if "FragmentSize" is reached. /// </summary> /// <param name="buffer"> /// The buffer to read data from. /// </param> /// <param name="offset"> /// The byte offset in buffer at which to begin writing from. /// </param> /// <param name="count"> /// The maximum number of bytes to write. /// </param> public override void Write(byte[] buffer, int offset, int count) { Dbg.Assert(_isEntered, "Stream should be Entered before writing into."); int offsetToReadFrom = offset; int amountLeft = count; while (amountLeft > 0) { int dataLeftInTheFragment = _fragmentSize - FragmentedRemoteObject.HeaderLength - _currentFragment.BlobLength; if (dataLeftInTheFragment > 0) { int amountToWriteIntoFragment = (amountLeft > dataLeftInTheFragment) ? dataLeftInTheFragment : amountLeft; amountLeft = amountLeft - amountToWriteIntoFragment; // Write data into fragment Array.Copy(buffer, offsetToReadFrom, _currentFragment.Blob, _currentFragment.BlobLength, amountToWriteIntoFragment); _currentFragment.BlobLength += amountToWriteIntoFragment; offsetToReadFrom += amountToWriteIntoFragment; // write only if amountLeft is more than 0. I dont write if amountLeft is 0 as we are not // sure if the fragment is EndFragment..we will know this only in Exit. if (amountLeft > 0) { WriteCurrentFragmentAndReset(); } } else { WriteCurrentFragmentAndReset(); } } } /// <summary> /// Writes a byte to the current stream. /// </summary> /// <param name="value"></param> public override void WriteByte(byte value) { Dbg.Assert(_isEntered, "Stream should be Entered before writing into."); byte[] buffer = new byte[1]; buffer[0] = value; Write(buffer, 0, 1); } /// <summary> /// Returns a byte[] which holds data of fragment size (or) serialized data of /// one object, which ever is greater. If data is not currently available, then /// the callback is registered and called whenever the data is available. /// </summary> /// <param name="callback"> /// callback to call once the data becomes available. /// </param> /// <returns> /// a byte[] holding data read from the stream /// </returns> internal byte[] ReadOrRegisterCallback(OnDataAvailableCallback callback) { lock (_syncObject) { if (_length <= 0) { _onDataAvailableCallback = callback; return null; } int bytesToRead = _length > _fragmentSize ? _fragmentSize : (int)_length; byte[] result = new byte[bytesToRead]; Read(result, 0, bytesToRead); return result; } } /// <summary> /// Read the currently accumulated data in queued memory streams /// </summary> /// <returns></returns> internal byte[] Read() { lock (_syncObject) { if (_isDisposed) { return null; } int bytesToRead = _length > _fragmentSize ? _fragmentSize : (int)_length; if (bytesToRead > 0) { byte[] result = new byte[bytesToRead]; Read(result, 0, bytesToRead); return result; } else { return null; } } } /// <summary> /// /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public override int Read(byte[] buffer, int offset, int count) { int offSetToWriteTo = offset; int dataWritten = 0; Collection<MemoryStream> memoryStreamsToDispose = new Collection<MemoryStream>(); MemoryStream prevReadStream = null; lock (_syncObject) { // technically this should throw an exception..but remoting callstack // is optimized ie., we are not locking in every layer (in powershell) // to save on performance..as a result there may be cases where // upper layer is trying to add stuff and stream is disposed while // adding stuff. if (_isDisposed) { return 0; } while (dataWritten < count) { if (null == _readStream) { if (_queuedStreams.Count > 0) { _readStream = _queuedStreams.Dequeue(); if ((!_readStream.CanRead) || (prevReadStream == _readStream)) { // if the stream is disposed CanRead returns false // this will happen if a Write enqueues the stream // and a Read reads the data without dequeuing _readStream = null; continue; } } else { _readStream = _writeStream; } Dbg.Assert(_readStream.Length > 0, "Not enough data to read."); _readOffSet = 0; } _readStream.Position = _readOffSet; int result = _readStream.Read(buffer, offSetToWriteTo, count - dataWritten); s_trace.WriteLine("Read {0} data from readstream: {1}", result, _readStream.GetHashCode()); dataWritten += result; offSetToWriteTo += result; _readOffSet += result; _length -= result; // dispose only if we dont read from the current write stream. if ((_readStream.Capacity == _readOffSet) && (_readStream != _writeStream)) { s_trace.WriteLine("Adding readstream {0} to dispose collection.", _readStream.GetHashCode()); memoryStreamsToDispose.Add(_readStream); prevReadStream = _readStream; _readStream = null; } } } // Dispose the memory streams outside of the lock foreach (MemoryStream streamToDispose in memoryStreamsToDispose) { s_trace.WriteLine("Disposing stream: {0}", streamToDispose.GetHashCode()); streamToDispose.Dispose(); } return dataWritten; } private void WriteCurrentFragmentAndReset() { // log trace of the fragment PSEtwLog.LogAnalyticVerbose( PSEventId.SentRemotingFragment, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, (Int64)(_currentFragment.ObjectId), (Int64)(_currentFragment.FragmentId), _currentFragment.IsStartFragment ? 1 : 0, _currentFragment.IsEndFragment ? 1 : 0, (UInt32)(_currentFragment.BlobLength), new PSETWBinaryBlob(_currentFragment.Blob, 0, _currentFragment.BlobLength)); // finally write into memory stream byte[] data = _currentFragment.GetBytes(); int amountLeft = data.Length; int offSetToReadFrom = 0; // user asked us to notify immediately..so no need // to write into memory stream..instead give the // data directly to user and let him figure out what to do. // This will save write + read + dispose!! if (!_notifyOnWriteFragmentImmediately) { lock (_syncObject) { // technically this should throw an exception..but remoting callstack // is optimized ie., we are not locking in every layer (in powershell) // to save on performance..as a result there may be cases where // upper layer is trying to add stuff and stream is disposed while // adding stuff. if (_isDisposed) { return; } if (null == _writeStream) { _writeStream = new MemoryStream(_fragmentSize); s_trace.WriteLine("Created write stream: {0}", _writeStream.GetHashCode()); _writeOffset = 0; } while (amountLeft > 0) { int dataLeftInWriteStream = _writeStream.Capacity - _writeOffset; if (dataLeftInWriteStream == 0) { // enqueue the current write stream and create a new one. EnqueueWriteStream(); dataLeftInWriteStream = _writeStream.Capacity - _writeOffset; } int amountToWriteIntoStream = (amountLeft > dataLeftInWriteStream) ? dataLeftInWriteStream : amountLeft; amountLeft = amountLeft - amountToWriteIntoStream; // write data _writeStream.Position = _writeOffset; _writeStream.Write(data, offSetToReadFrom, amountToWriteIntoStream); offSetToReadFrom += amountToWriteIntoStream; _writeOffset += amountToWriteIntoStream; _length += amountToWriteIntoStream; } } } // call the callback since we have data available if (null != _onDataAvailableCallback) { _onDataAvailableCallback(data, _currentFragment.IsEndFragment); } // prepare a new fragment _currentFragment.FragmentId = ++_fragmentId; _currentFragment.IsStartFragment = false; _currentFragment.IsEndFragment = false; _currentFragment.BlobLength = 0; _currentFragment.Blob = new byte[_fragmentSize]; } private void EnqueueWriteStream() { s_trace.WriteLine("Queuing write stream: {0} Length: {1} Capacity: {2}", _writeStream.GetHashCode(), _writeStream.Length, _writeStream.Capacity); _queuedStreams.Enqueue(_writeStream); _writeStream = new MemoryStream(_fragmentSize); _writeOffset = 0; s_trace.WriteLine("Created write stream: {0}", _writeStream.GetHashCode()); } /// <summary> /// This method provides a thread safe way to get an object id. /// </summary> /// <returns> /// An object Id in integer. /// </returns> private static long GetObjectId() { return System.Threading.Interlocked.Increment(ref s_objectIdSequenceNumber); } #endregion #region Disposable Overrides protected override void Dispose(bool disposing) { if (disposing) { lock (_syncObject) { foreach (MemoryStream streamToDispose in _queuedStreams) { // make sure we dispose only once. if (streamToDispose.CanRead) { streamToDispose.Dispose(); } } if ((null != _readStream) && (_readStream.CanRead)) { _readStream.Dispose(); } if ((null != _writeStream) && (_writeStream.CanRead)) { _writeStream.Dispose(); } _isDisposed = true; } } } #endregion #region Stream Overrides /// <summary> /// /// </summary> public override bool CanRead { get { return true; } } /// <summary> /// /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// /// </summary> public override bool CanWrite { get { return true; } } /// <summary> /// Gets the length of the stream in bytes. /// </summary> public override long Length { get { return _length; } } /// <summary> /// /// </summary> public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// <summary> /// This is a No-Op intentionally as there is nothing /// to flush. /// </summary> public override void Flush() { } /// <summary> /// /// </summary> /// <param name="offset"></param> /// <param name="origin"></param> /// <returns></returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// /// </summary> /// <param name="value"></param> public override void SetLength(long value) { throw new NotSupportedException(); } #endregion #region IDisposable Members private bool _disposed = false; public new void Dispose() { if (!_disposed) { GC.SuppressFinalize(this); _disposed = true; } base.Dispose(); } #endregion } /// <summary> /// This class performs the fragmentation as well as defragmentation operations of large objects to be sent /// to the other side. A large remoting PSObject will be broken into fragments. Each fragment has a ObjectId /// and a FragmentId. The last fragment also has an end of fragment marker. These fragments can be reassembled /// on the receiving end by sequencing the fragment ids. /// </summary> internal class Fragmentor { #region Global Constants private static UTF8Encoding s_utf8Encoding = new UTF8Encoding(); // This const defines the default depth to be used for serializing objects for remoting. private const int SerializationDepthForRemoting = 1; #endregion private int _fragmentSize; private SerializationContext _serializationContext; #region Constructor /// <summary> /// Constructor which initializes fragmentor with FragmentSize. /// </summary> /// <param name="fragmentSize"> /// size of each fragment /// </param> /// <param name="cryptoHelper"></param> internal Fragmentor(int fragmentSize, PSRemotingCryptoHelper cryptoHelper) { Dbg.Assert(fragmentSize > 0, "fragment size cannot be less than 0."); _fragmentSize = fragmentSize; _serializationContext = new SerializationContext( SerializationDepthForRemoting, SerializationOptions.RemotingOptions, cryptoHelper); DeserializationContext = new DeserializationContext( DeserializationOptions.RemotingOptions, cryptoHelper); } #endregion /// <summary> /// The method performs the fragmentation operation. /// All fragments of the same object have the same ObjectId. /// All fragments of the same object have the same ObjectId. /// Each fragment has its own Fragment Id. Fragment Id always starts from zero (0), /// and increments sequentially with an increment of 1. /// The last fragment is indicated by an End of Fragment marker. /// </summary> /// <param name="obj"> /// The object to be fragmented. Caller should make sure this is not null. /// </param> /// <param name="dataToBeSent"> /// Caller specified dataToStore to which the fragments are added /// one-by-one /// </param> internal void Fragment<T>(RemoteDataObject<T> obj, SerializedDataStream dataToBeSent) { Dbg.Assert(null != obj, "Cannot fragment a null object"); Dbg.Assert(null != dataToBeSent, "SendDataCollection cannot be null"); dataToBeSent.Enter(); try { obj.Serialize(dataToBeSent, this); } finally { dataToBeSent.Exit(); } } /// <summary> /// The deserialization context used by this fragmentor. DeserializationContext /// controls the amount of memory a deserializer can use and other things. /// </summary> internal DeserializationContext DeserializationContext { get; } /// <summary> /// The size limit of the fragmented object. /// </summary> internal int FragmentSize { get { return _fragmentSize; } set { Dbg.Assert(value > 0, "FragmentSize cannot be less than 0."); _fragmentSize = value; } } /// <summary> /// TypeTable used for Serialization/Deserialization. /// </summary> internal TypeTable TypeTable { get; set; } /// <summary> /// Serialize an PSObject into a byte array. /// </summary> internal void SerializeToBytes(object obj, Stream streamToWriteTo) { Dbg.Assert(null != obj, "Cannot serialize a null object"); Dbg.Assert(null != streamToWriteTo, "Stream to write to cannot be null"); XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.CheckCharacters = false; xmlSettings.Indent = false; // we dont want the underlying stream to be closed as we expect // the stream to be usable after this call. xmlSettings.CloseOutput = false; xmlSettings.Encoding = UTF8Encoding.UTF8; xmlSettings.NewLineHandling = NewLineHandling.None; xmlSettings.OmitXmlDeclaration = true; xmlSettings.ConformanceLevel = ConformanceLevel.Fragment; using (XmlWriter xmlWriter = XmlWriter.Create(streamToWriteTo, xmlSettings)) { Serializer serializer = new Serializer(xmlWriter, _serializationContext); serializer.TypeTable = TypeTable; serializer.Serialize(obj); serializer.Done(); xmlWriter.Flush(); } return; } /// <summary> /// Converts the bytes back to PSObject. /// </summary> /// <param name="serializedDataStream"> /// The bytes to be deserialized. /// </param> /// <returns> /// The deserialized object. /// </returns> /// <exception cref="PSRemotingDataStructureException"> /// If the deserialized object is null. /// </exception> internal PSObject DeserializeToPSObject(Stream serializedDataStream) { Dbg.Assert(null != serializedDataStream, "Cannot Deserialize null data"); Dbg.Assert(serializedDataStream.Length != 0, "Cannot Deserialize empty data"); object result = null; using (XmlReader xmlReader = XmlReader.Create(serializedDataStream, InternalDeserializer.XmlReaderSettingsForCliXml)) { Deserializer deserializer = new Deserializer(xmlReader, DeserializationContext); deserializer.TypeTable = TypeTable; result = deserializer.Deserialize(); deserializer.Done(); } if (result == null) { // cannot be null. throw new PSRemotingDataStructureException(RemotingErrorIdStrings.DeserializedObjectIsNull); } return PSObject.AsPSObject(result); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.DDF { using System; using System.Text; using System.Collections; using NPOI.Util; using System.Collections.Generic; /// <summary> /// This record is used whenever a escher record is encountered that /// we do not explicitly support. /// @author Glen Stampoultzis (glens at apache.org) /// </summary> public class UnknownEscherRecord : EscherRecord { private static byte[] NO_BYTES = new byte[0]; /** The data for this record not including the the 8 byte header */ private byte[] _thedata = NO_BYTES; private List<EscherRecord> _childRecords = new List<EscherRecord>(); public UnknownEscherRecord() { } /// <summary> /// This method deSerializes the record from a byte array. /// </summary> /// <param name="data"> The byte array containing the escher record information</param> /// <param name="offset">The starting offset into data </param> /// <param name="recordFactory">May be null since this is not a container record.</param> /// <returns>The number of bytes Read from the byte array.</returns> public override int FillFields(byte[] data, int offset, IEscherRecordFactory recordFactory) { int bytesRemaining = ReadHeader(data, offset); /* * Modified by Zhang Zhang * Have a check between avaliable bytes and bytesRemaining, * take the avaliable length if the bytesRemaining out of range. * July 09, 2010 */ int avaliable = data.Length - (offset + 8); if (bytesRemaining > avaliable) { bytesRemaining = avaliable; } if (IsContainerRecord) { int bytesWritten = 0; _thedata = new byte[0]; offset += 8; bytesWritten += 8; while (bytesRemaining > 0) { EscherRecord child = recordFactory.CreateRecord(data, offset); int childBytesWritten = child.FillFields(data, offset, recordFactory); bytesWritten += childBytesWritten; offset += childBytesWritten; bytesRemaining -= childBytesWritten; ChildRecords.Add(child); } return bytesWritten; } else { _thedata = new byte[bytesRemaining]; Array.Copy(data, offset + 8, _thedata, 0, bytesRemaining); return bytesRemaining + 8; } } /// <summary> /// Writes this record and any contained records to the supplied byte /// array. /// </summary> /// <param name="offset"></param> /// <param name="data"></param> /// <param name="listener">a listener for begin and end serialization events.</param> /// <returns>the number of bytes written.</returns> public override int Serialize(int offset, byte[] data, EscherSerializationListener listener) { listener.BeforeRecordSerialize(offset, RecordId, this); LittleEndian.PutShort(data, offset, Options); LittleEndian.PutShort(data, offset + 2, RecordId); int remainingBytes = _thedata.Length; for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; remainingBytes += r.RecordSize; } LittleEndian.PutInt(data, offset + 4, remainingBytes); Array.Copy(_thedata, 0, data, offset + 8, _thedata.Length); int pos = offset + 8 + _thedata.Length; for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; pos += r.Serialize(pos, data); } listener.AfterRecordSerialize(pos, RecordId, pos - offset, this); return pos - offset; } /// <summary> /// Gets the data. /// </summary> /// <value>The data.</value> public byte[] Data { get { return _thedata; } } /// <summary> /// Returns the number of bytes that are required to Serialize this record. /// </summary> /// <value>Number of bytes</value> public override int RecordSize { get { return 8 + _thedata.Length; } } /// <summary> /// Returns the children of this record. By default this will /// be an empty list. EscherCotainerRecord is the only record /// that may contain children. /// </summary> /// <value></value> public override List<EscherRecord> ChildRecords { get { return _childRecords; } set { this._childRecords = value; } } /// <summary> /// The short name for this record /// </summary> /// <value></value> public override String RecordName { get { return "Unknown 0x" + HexDump.ToHex(RecordId); } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { String nl = Environment.NewLine; StringBuilder children = new StringBuilder(); if (ChildRecords.Count > 0) { children.Append(" children: " + nl); for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord record = (EscherRecord)iterator.Current; children.Append(record.ToString()); children.Append(nl); } } String theDumpHex = ""; try { if (_thedata.Length != 0) { theDumpHex = " Extra Data(" + _thedata.Length + "):" + nl; theDumpHex += HexDump.Dump(_thedata, 0, 0); } } catch (Exception) { theDumpHex = "Error!!"; } return this.GetType().Name + ":" + nl + " isContainer: " + IsContainerRecord + nl + " version: 0x" + HexDump.ToHex(Version) + nl + " instance: 0x" + HexDump.ToHex(Instance) + nl + " recordId: 0x" + HexDump.ToHex(RecordId) + nl + " numchildren: " + ChildRecords.Count + nl + theDumpHex + children.ToString(); } public override String ToXml(String tab) { String theDumpHex = HexDump.ToHex(_thedata, 32); StringBuilder builder = new StringBuilder(); builder.Append(tab).Append(FormatXmlRecordHeader(GetType().Name, HexDump.ToHex(RecordId), HexDump.ToHex(Version), HexDump.ToHex(Instance))) .Append(tab).Append("\t").Append("<IsContainer>").Append(IsContainerRecord).Append("</IsContainer>\n") .Append(tab).Append("\t").Append("<Numchildren>").Append(HexDump.ToHex(_childRecords.Count)).Append("</Numchildren>\n"); for (IEnumerator<EscherRecord> iterator = _childRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord record = iterator.Current; builder.Append(record.ToXml(tab + "\t")); } builder.Append(theDumpHex).Append("\n"); builder.Append(tab).Append("</").Append(GetType().Name).Append(">\n"); return builder.ToString(); } /// <summary> /// Adds the child record. /// </summary> /// <param name="childRecord">The child record.</param> public void AddChildRecord(EscherRecord childRecord) { ChildRecords.Add(childRecord); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using BTDB.FieldHandler; using BTDB.IL; using BTDB.ODBLayer; using BTDB.StreamLayer; namespace BTDB.EventStoreLayer; class ListTypeDescriptor : ITypeDescriptor, IPersistTypeDescriptor { readonly ITypeDescriptorCallbacks _typeSerializers; Type? _type; Type? _itemType; ITypeDescriptor? _itemDescriptor; string? _name; readonly ITypeConvertorGenerator _convertGenerator; public ListTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, Type type) { _convertGenerator = typeSerializers.ConvertorGenerator; _typeSerializers = typeSerializers; _type = type; _itemType = GetItemType(type); } public ListTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ref SpanReader reader, DescriptorReader nestedDescriptorReader) : this(typeSerializers, nestedDescriptorReader(ref reader)) { } ListTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ITypeDescriptor itemDesc) { _convertGenerator = typeSerializers.ConvertorGenerator; _typeSerializers = typeSerializers; InitFromItemDescriptor(itemDesc); } void InitFromItemDescriptor(ITypeDescriptor descriptor) { if (descriptor == _itemDescriptor && _name != null) return; _itemDescriptor = descriptor; if ((descriptor.Name?.Length ?? 0) == 0) return; Sealed = _itemDescriptor.Sealed; Name = $"List<{_itemDescriptor.Name}>"; } public bool Equals(ITypeDescriptor other) { return Equals(other, new HashSet<ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance)); } public override int GetHashCode() { #pragma warning disable RECS0025 // Non-readonly field referenced in 'GetHashCode()' // ReSharper disable once NonReadonlyMemberInGetHashCode return 33 * _itemDescriptor!.GetHashCode(); #pragma warning restore RECS0025 // Non-readonly field referenced in 'GetHashCode()' } public string Name { get { if (_name == null) InitFromItemDescriptor(_itemDescriptor!); return _name!; } private set => _name = value; } public bool FinishBuildFromType(ITypeDescriptorFactory factory) { var descriptor = factory.Create(_itemType!); if (descriptor == null) return false; InitFromItemDescriptor(descriptor); return true; } public void BuildHumanReadableFullName(StringBuilder text, HashSet<ITypeDescriptor> stack, uint indent) { text.Append("List<"); _itemDescriptor!.BuildHumanReadableFullName(text, stack, indent); text.Append(">"); } public bool Equals(ITypeDescriptor other, HashSet<ITypeDescriptor> stack) { if (!(other is ListTypeDescriptor o)) return false; return _itemDescriptor!.Equals(o._itemDescriptor!, stack); } public Type GetPreferredType() { if (_type == null) { _itemType = _typeSerializers.LoadAsType(_itemDescriptor!); _type = typeof(ICollection<>).MakeGenericType(_itemType); } return _type; } public Type GetPreferredType(Type targetType) { if (_type == targetType) return _type; var targetICollection = targetType.GetInterface("ICollection`1") ?? targetType; var targetTypeArguments = targetICollection.GetGenericArguments(); var itemType = _typeSerializers.LoadAsType(_itemDescriptor!, targetTypeArguments[0]); return targetType.GetGenericTypeDefinition().MakeGenericType(itemType); } public bool AnyOpNeedsCtx() { return !_itemDescriptor!.StoredInline || _itemDescriptor.AnyOpNeedsCtx(); } static Type GetInterface(Type type) => type.GetInterface("ICollection`1") ?? type; public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx, Action<IILGen> pushDescriptor, Type targetType) { if (targetType == typeof(object)) targetType = GetPreferredType(); var localCount = ilGenerator.DeclareLocal(typeof(int)); var targetICollection = GetInterface(targetType); var targetTypeArguments = targetICollection.GetGenericArguments(); var itemType = _typeSerializers.LoadAsType(_itemDescriptor!, targetTypeArguments[0]); if (targetType.IsArray) { var localArray = ilGenerator.DeclareLocal(targetType); var loadFinished = ilGenerator.DefineLabel(); var localIndex = ilGenerator.DeclareLocal(typeof(int)); var next = ilGenerator.DefineLabel(); ilGenerator .Ldnull() .Stloc(localArray) .LdcI4(0) .Stloc(localIndex) .Do(pushReader) .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!) .ConvI4() .Dup() .Stloc(localCount) .Brfalse(loadFinished) .Ldloc(localCount) .LdcI4(1) .Sub() .Dup() .Stloc(localCount) .Newarr(itemType) .Stloc(localArray) .Mark(next) .Ldloc(localCount) .Ldloc(localIndex) .Sub() .Brfalse(loadFinished) .Ldloc(localArray) .Ldloc(localIndex); _itemDescriptor.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(0).Callvirt(() => default(ITypeDescriptor).NestedType(0)), itemType, _convertGenerator); ilGenerator .Stelem(itemType) .Ldloc(localIndex) .LdcI4(1) .Add() .Stloc(localIndex) .Br(next) .Mark(loadFinished) .Ldloc(localArray) .Castclass(targetType); } else { var isSet = targetType.InheritsOrImplements(typeof(ISet<>)); var listType = (isSet ? typeof(HashSetWithDescriptor<>) : typeof(ListWithDescriptor<>)).MakeGenericType(itemType); if (!targetType.IsAssignableFrom(listType)) throw new NotSupportedException($"List type {listType.ToSimpleName()} is not assignable to {targetType.ToSimpleName()}."); var localList = ilGenerator.DeclareLocal(listType); var loadFinished = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Ldnull() .Stloc(localList) .Do(pushReader) .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!) .ConvI4() .Dup() .Stloc(localCount) .Brfalse(loadFinished) .Ldloc(localCount) .LdcI4(1) .Sub() .Dup() .Stloc(localCount) .Do(pushDescriptor) .Newobj(listType.GetConstructor(new[] { typeof(int), typeof(ITypeDescriptor) })!) .Stloc(localList) .Mark(next) .Ldloc(localCount) .Brfalse(loadFinished) .Ldloc(localCount) .LdcI4(1) .Sub() .Stloc(localCount) .Ldloc(localList); _itemDescriptor.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(0).Callvirt(() => default(ITypeDescriptor).NestedType(0)), itemType, _convertGenerator); ilGenerator .Callvirt(listType.GetInterface("ICollection`1")!.GetMethod("Add")!) .Br(next) .Mark(loadFinished) .Ldloc(localList) .Castclass(targetType); } } public ITypeNewDescriptorGenerator? BuildNewDescriptorGenerator() { if (_itemDescriptor!.Sealed) return null; return new TypeNewDescriptorGenerator(this); } class TypeNewDescriptorGenerator : ITypeNewDescriptorGenerator { readonly ListTypeDescriptor _listTypeDescriptor; public TypeNewDescriptorGenerator(ListTypeDescriptor listTypeDescriptor) { _listTypeDescriptor = listTypeDescriptor; } public void GenerateTypeIterator(IILGen ilGenerator, Action<IILGen> pushObj, Action<IILGen> pushCtx, Type type) { var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); if (type == typeof(object)) type = _listTypeDescriptor.GetPreferredType(); var targetInterface = GetInterface(type); var targetTypeArguments = targetInterface.GetGenericArguments(); var itemType = _listTypeDescriptor._typeSerializers.LoadAsType(_listTypeDescriptor._itemDescriptor!, targetTypeArguments[0]); if (_listTypeDescriptor._type == null) _listTypeDescriptor._type = type; var isConcreteImplementation = type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || type.GetGenericTypeDefinition() == typeof(HashSet<>)); var typeAsICollection = isConcreteImplementation ? type : typeof(ICollection<>).MakeGenericType(itemType); var getEnumeratorMethod = isConcreteImplementation ? typeAsICollection.GetMethods() .Single( m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0) : typeAsICollection.GetInterface("IEnumerable`1")!.GetMethod(nameof(IEnumerable.GetEnumerator)); var typeAsIEnumerator = getEnumeratorMethod!.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); ilGenerator .Do(pushObj) .Castclass(typeAsICollection) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Do(il => { if (isConcreteImplementation) { il .Ldloca(localEnumerator) .Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!); } else { il .Ldloc(localEnumerator) .Callvirt(() => default(IEnumerator).MoveNext()); } }) .Brfalse(finish) .Do(pushCtx) .Do(il => { if (isConcreteImplementation) { il .Ldloca(localEnumerator) .Call(currentGetter!); } else { il .Ldloc(localEnumerator) .Callvirt(currentGetter!); } }) .Callvirt(typeof(IDescriptorSerializerLiteContext).GetMethod(nameof(IDescriptorSerializerLiteContext.StoreNewDescriptors))!) .Br(next) .Mark(finish) .Finally() .Do(il => { if (isConcreteImplementation) { il .Ldloca(localEnumerator) .Constrained(typeAsIEnumerator); } else { il.Ldloc(localEnumerator); } }) .Callvirt(() => default(IDisposable).Dispose()) .EndTry(); } } public ITypeDescriptor? NestedType(int index) { return index == 0 ? _itemDescriptor : null; } public void MapNestedTypes(Func<ITypeDescriptor, ITypeDescriptor> map) { InitFromItemDescriptor(map(_itemDescriptor)); } public bool Sealed { get; private set; } public bool StoredInline => true; public bool LoadNeedsHelpWithConversion => false; public void ClearMappingToType() { _type = null; _itemType = null; } public bool ContainsField(string name) { return false; } public IEnumerable<KeyValuePair<string, ITypeDescriptor>> Fields => Array.Empty<KeyValuePair<string, ITypeDescriptor>>(); public void Persist(ref SpanWriter writer, DescriptorWriter nestedDescriptorWriter) { nestedDescriptorWriter(ref writer, _itemDescriptor!); } public void GenerateSave(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue, Type valueType) { var notnull = ilGenerator.DefineLabel(); var completeFinish = ilGenerator.DefineLabel(); var notList = ilGenerator.DefineLabel(); var notHashSet = ilGenerator.DefineLabel(); var itemType = GetItemType(valueType); var typeAsICollection = typeof(ICollection<>).MakeGenericType(itemType); var localCollection = ilGenerator.DeclareLocal(typeAsICollection); ilGenerator .Do(pushValue) .Castclass(typeAsICollection) .Stloc(localCollection) .Ldloc(localCollection) .Brtrue(notnull) .Do(pushWriter) .Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteByteZero))!) .Br(completeFinish) .Mark(notnull) .Do(pushWriter) .Ldloc(localCollection) .Callvirt(typeAsICollection!.GetProperty(nameof(ICollection.Count))!.GetGetMethod()!) .LdcI4(1) .Add() .Call(typeof(SpanWriter).GetMethod(nameof(SpanWriter.WriteVUInt32))!); { var typeAsList = typeof(List<>).MakeGenericType(itemType); var getEnumeratorMethod = typeAsList.GetMethods() .Single(m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0); var typeAsIEnumerator = getEnumeratorMethod.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Ldloc(localCollection) .Isinst(typeAsList) .Brfalse(notList) .Ldloc(localCollection) .Castclass(typeAsList) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Ldloca(localEnumerator) .Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!) .Brfalse(finish); _itemDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localEnumerator).Callvirt(currentGetter!), itemType); ilGenerator .Br(next) .Mark(finish) .Finally() .Ldloca(localEnumerator) .Constrained(typeAsIEnumerator) .Callvirt(() => default(IDisposable).Dispose()) .EndTry() .Br(completeFinish); } { var typeAsHashSet = typeof(HashSet<>).MakeGenericType(itemType); var getEnumeratorMethod = typeAsHashSet.GetMethods() .Single(m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0); var typeAsIEnumerator = getEnumeratorMethod.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Mark(notList) .Ldloc(localCollection) .Isinst(typeAsHashSet) .Brfalse(notHashSet) .Ldloc(localCollection) .Castclass(typeAsHashSet) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Ldloca(localEnumerator) .Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!) .Brfalse(finish); _itemDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localEnumerator).Callvirt(currentGetter!), itemType); ilGenerator .Br(next) .Mark(finish) .Finally() .Ldloca(localEnumerator) .Constrained(typeAsIEnumerator) .Callvirt(() => default(IDisposable).Dispose()) .EndTry() .Br(completeFinish); } { var getEnumeratorMethod = typeAsICollection.GetInterface("IEnumerable`1")!.GetMethod(nameof(IEnumerable.GetEnumerator)); var typeAsIEnumerator = getEnumeratorMethod!.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Mark(notHashSet) .Ldloc(localCollection) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Ldloc(localEnumerator) .Callvirt(() => default(IEnumerator).MoveNext()) .Brfalse(finish); _itemDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloc(localEnumerator) .Callvirt(currentGetter!), itemType); ilGenerator .Br(next) .Mark(finish) .Finally() .Ldloc(localEnumerator) .Callvirt(() => default(IDisposable).Dispose()) .EndTry() .Mark(completeFinish); } } static Type GetItemType(Type valueType) { if (valueType.IsArray) { return valueType.GetElementType()!; } return valueType.GetGenericArguments()[0]; } public void GenerateSkip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx) { var localCount = ilGenerator.DeclareLocal(typeof(int)); var skipFinished = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Do(pushReader) .Call(typeof(SpanReader).GetMethod(nameof(SpanReader.ReadVUInt32))!) .ConvI4() .Dup() .Stloc(localCount) .Brfalse(skipFinished) .Ldloc(localCount) .LdcI4(1) .Sub() .Stloc(localCount) .Mark(next) .Ldloc(localCount) .Brfalse(skipFinished) .Ldloc(localCount) .LdcI4(1) .Sub() .Stloc(localCount); _itemDescriptor!.GenerateSkipEx(ilGenerator, pushReader, pushCtx); ilGenerator .Br(next) .Mark(skipFinished); } public ITypeDescriptor CloneAndMapNestedTypes(ITypeDescriptorCallbacks typeSerializers, Func<ITypeDescriptor, ITypeDescriptor> map) { var itemDesc = map(_itemDescriptor); if (_typeSerializers == typeSerializers && itemDesc == _itemDescriptor) return this; return new ListTypeDescriptor(typeSerializers, itemDesc); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Compute { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Resource; /// <summary> /// Compute task holder interface used to avoid generics. /// </summary> internal interface IComputeTaskHolder { /// <summary> /// Perform map step. /// </summary> /// <param name="inStream">Stream with IN data (topology info).</param> /// <param name="outStream">Stream for OUT data (map result).</param> /// <returns>Map with produced jobs.</returns> void Map(PlatformMemoryStream inStream, PlatformMemoryStream outStream); /// <summary> /// Process local job result. /// </summary> /// <param name="jobId">Job pointer.</param> /// <returns>Policy.</returns> int JobResultLocal(ComputeJobHolder jobId); /// <summary> /// Process remote job result. /// </summary> /// <param name="jobId">Job pointer.</param> /// <param name="stream">Stream.</param> /// <returns>Policy.</returns> int JobResultRemote(ComputeJobHolder jobId, PlatformMemoryStream stream); /// <summary> /// Perform task reduce. /// </summary> void Reduce(); /// <summary> /// Complete task. /// </summary> /// <param name="taskHandle">Task handle.</param> void Complete(long taskHandle); /// <summary> /// Complete task with error. /// </summary> /// <param name="taskHandle">Task handle.</param> /// <param name="stream">Stream with serialized exception.</param> void CompleteWithError(long taskHandle, PlatformMemoryStream stream); } /// <summary> /// Compute task holder. /// </summary> internal class ComputeTaskHolder<TA, T, TR> : IComputeTaskHolder { /** Empty results. */ private static readonly IList<IComputeJobResult<T>> EmptyRes = new ReadOnlyCollection<IComputeJobResult<T>>(new List<IComputeJobResult<T>>()); /** Compute instance. */ private readonly ComputeImpl _compute; /** Actual task. */ private readonly IComputeTask<TA, T, TR> _task; /** Task argument. */ private readonly TA _arg; /** Results cache flag. */ private readonly bool _resCache; /** Task future. */ private readonly Future<TR> _fut = new Future<TR>(); /** Jobs whose results are cached. */ private ISet<object> _resJobs; /** Cached results. */ private IList<IComputeJobResult<T>> _ress; /** Handles for jobs which are not serialized right away. */ private volatile List<long> _jobHandles; /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="compute">Compute.</param> /// <param name="task">Task.</param> /// <param name="arg">Argument.</param> public ComputeTaskHolder(Ignite grid, ComputeImpl compute, IComputeTask<TA, T, TR> task, TA arg) { _compute = compute; _arg = arg; _task = task; ResourceTypeDescriptor resDesc = ResourceProcessor.Descriptor(task.GetType()); IComputeResourceInjector injector = task as IComputeResourceInjector; if (injector != null) injector.Inject(grid); else resDesc.InjectIgnite(task, grid); _resCache = !resDesc.TaskNoResultCache; } /** <inheritDoc /> */ [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User code can throw any exception")] public void Map(PlatformMemoryStream inStream, PlatformMemoryStream outStream) { IList<IClusterNode> subgrid; ClusterGroupImpl prj = (ClusterGroupImpl)_compute.ClusterGroup; var ignite = (Ignite) prj.Ignite; // 1. Unmarshal topology info if topology changed. var reader = prj.Marshaller.StartUnmarshal(inStream); if (reader.ReadBoolean()) { long topVer = reader.ReadLong(); List<IClusterNode> nodes = new List<IClusterNode>(reader.ReadInt()); int nodesCnt = reader.ReadInt(); subgrid = new List<IClusterNode>(nodesCnt); for (int i = 0; i < nodesCnt; i++) { IClusterNode node = ignite.GetNode(reader.ReadGuid()); nodes.Add(node); if (reader.ReadBoolean()) subgrid.Add(node); } // Update parent projection to help other task callers avoid this overhead. // Note that there is a chance that topology changed even further and this update fails. // It means that some of subgrid nodes could have left the Grid. This is not critical // for us, because Java will handle it gracefully. prj.UpdateTopology(topVer, nodes); } else { IList<IClusterNode> nodes = prj.NodesNoRefresh(); Debug.Assert(nodes != null, "At least one topology update should have occurred."); subgrid = IgniteUtils.Shuffle(nodes); } // 2. Perform map. IDictionary<IComputeJob<T>, IClusterNode> map; Exception err; try { map = _task.Map(subgrid, _arg); err = null; } catch (Exception e) { map = null; err = e; // Java can receive another exception in case of marshalling failure but it is not important. Finish(default(TR), e); } // 3. Write map result to the output stream. BinaryWriter writer = prj.Marshaller.StartMarshal(outStream); try { if (err == null) { writer.WriteBoolean(true); // Success flag. if (map == null) writer.WriteBoolean(false); // Map produced no result. else { writer.WriteBoolean(true); // Map produced result. _jobHandles = WriteJobs(writer, map); } } else { writer.WriteBoolean(false); // Map failed. // Write error as string because it is not important for Java, we need only to print // a message in the log. writer.WriteString("Map step failed [errType=" + err.GetType().Name + ", errMsg=" + err.Message + ']'); } } catch (Exception e) { // Something went wrong during marshaling. Finish(default(TR), e); outStream.Reset(); writer.WriteBoolean(false); // Map failed. writer.WriteString(e.Message); // Write error message. } finally { prj.Marshaller.FinishMarshal(writer); } } /// <summary> /// Writes job map. /// </summary> /// <param name="writer">Writer.</param> /// <param name="map">Map</param> /// <returns>Job handle list.</returns> private static List<long> WriteJobs(BinaryWriter writer, IDictionary<IComputeJob<T>, IClusterNode> map) { Debug.Assert(writer != null && map != null); writer.WriteInt(map.Count); // Amount of mapped jobs. var jobHandles = new List<long>(map.Count); var ignite = writer.Marshaller.Ignite; try { foreach (KeyValuePair<IComputeJob<T>, IClusterNode> mapEntry in map) { var job = new ComputeJobHolder(ignite, mapEntry.Key.ToNonGeneric()); IClusterNode node = mapEntry.Value; var jobHandle = ignite.HandleRegistry.Allocate(job); jobHandles.Add(jobHandle); writer.WriteLong(jobHandle); if (node.IsLocal) writer.WriteBoolean(false); // Job is not serialized. else { writer.WriteBoolean(true); // Job is serialized. writer.WriteObject(job); } writer.WriteGuid(node.Id); } } catch (Exception) { foreach (var handle in jobHandles) ignite.HandleRegistry.Release(handle); throw; } return jobHandles; } /** <inheritDoc /> */ public int JobResultLocal(ComputeJobHolder job) { return (int)JobResult0(job.JobResult); } /** <inheritDoc /> */ [SuppressMessage("ReSharper", "PossibleInvalidOperationException")] public int JobResultRemote(ComputeJobHolder job, PlatformMemoryStream stream) { // 1. Unmarshal result. BinaryReader reader = _compute.Marshaller.StartUnmarshal(stream); var nodeId = reader.ReadGuid(); Debug.Assert(nodeId.HasValue); bool cancelled = reader.ReadBoolean(); try { object err; var data = BinaryUtils.ReadInvocationResult(reader, out err); // 2. Process the result. return (int) JobResult0(new ComputeJobResultImpl(data, (Exception) err, job.Job, nodeId.Value, cancelled)); } catch (Exception e) { Finish(default(TR), e); if (!(e is IgniteException)) throw new IgniteException("Failed to process job result: " + e.Message, e); throw; } } /** <inheritDoc /> */ public void Reduce() { try { TR taskRes = _task.Reduce(_resCache ? _ress : EmptyRes); Finish(taskRes, null); } catch (Exception e) { Finish(default(TR), e); if (!(e is IgniteException)) throw new IgniteException("Failed to reduce task: " + e.Message, e); throw; } } /** <inheritDoc /> */ public void Complete(long taskHandle) { Clean(taskHandle); } /// <summary> /// Complete task with error. /// </summary> /// <param name="taskHandle">Task handle.</param> /// <param name="e">Error.</param> public void CompleteWithError(long taskHandle, Exception e) { Finish(default(TR), e); Clean(taskHandle); } /** <inheritDoc /> */ [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User object deserialization can throw any exception")] public void CompleteWithError(long taskHandle, PlatformMemoryStream stream) { BinaryReader reader = _compute.Marshaller.StartUnmarshal(stream); Exception err; try { err = reader.ReadBoolean() ? reader.ReadObject<BinaryObject>().Deserialize<Exception>() : ExceptionUtils.GetException(_compute.Marshaller.Ignite, reader.ReadString(), reader.ReadString(), reader.ReadString()); } catch (Exception e) { err = new IgniteException("Task completed with error, but it cannot be unmarshalled: " + e.Message, e); } CompleteWithError(taskHandle, err); } /// <summary> /// Task completion future. /// </summary> internal Future<TR> Future { get { return _fut; } } /// <summary> /// Manually set job handles. Used by closures because they have separate flow for map step. /// </summary> /// <param name="jobHandles">Job handles.</param> internal void JobHandles(List<long> jobHandles) { _jobHandles = jobHandles; } /// <summary> /// Process job result. /// </summary> /// <param name="res">Result.</param> private ComputeJobResultPolicy JobResult0(IComputeJobResult<object> res) { try { IList<IComputeJobResult<T>> ress0; // 1. Prepare old results. if (_resCache) { if (_resJobs == null) { _resJobs = new HashSet<object>(); _ress = new List<IComputeJobResult<T>>(); } ress0 = _ress; } else ress0 = EmptyRes; // 2. Invoke user code. var policy = _task.OnResult(new ComputeJobResultGenericWrapper<T>(res), ress0); // 3. Add result to the list only in case of success. if (_resCache) { var job = res.Job.Unwrap(); if (!_resJobs.Add(job)) { // Duplicate result => find and replace it with the new one. var oldRes = _ress.Single(item => item.Job == job); _ress.Remove(oldRes); } _ress.Add(new ComputeJobResultGenericWrapper<T>(res)); } return policy; } catch (Exception e) { Finish(default(TR), e); if (!(e is IgniteException)) throw new IgniteException("Failed to process job result: " + e.Message, e); throw; } } /// <summary> /// Finish task. /// </summary> /// <param name="res">Result.</param> /// <param name="err">Error.</param> private void Finish(TR res, Exception err) { _fut.OnDone(res, err); } /// <summary> /// Clean-up task resources. /// </summary> /// <param name="taskHandle"></param> private void Clean(long taskHandle) { var handles = _jobHandles; var handleRegistry = _compute.Marshaller.Ignite.HandleRegistry; if (handles != null) foreach (var handle in handles) handleRegistry.Release(handle, true); handleRegistry.Release(taskHandle, true); } } }
using System; using System.Threading.Tasks; using Marqueone.TimeAndMaterials.Api.DataAccess; using Marqueone.TimeAndMaterials.Api.DataAccess.Services; using Marqueone.TimeAndMaterials.Api.Models.ViewModels; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace Marqueone.TimeAndMaterials.Api.Controllers { [Route("_api/[controller]")] [Produces("application/json")] public class AdminController : Controller { private TamContext _context { get; } private ILogger<AdminController> _logger; private ServicesService _servicesService { get; set; } private TradeService _tradeService { get; set; } private CompanyService _companyService { get; set; } public AdminController(ILogger<AdminController> logger, TamContext context, ServicesService servicesService, TradeService tradeService, CompanyService companyService) { _context = context; _logger = logger; _servicesService = servicesService; _tradeService = tradeService; _companyService = companyService; } #region trade management [HttpGet] [Route("trades")] public async Task<IActionResult> GetTrades() { try { return Ok(await _tradeService.GetTrades()); } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); return StatusCode(500); } } [HttpPost] [Route("trade/add")] public async Task<IActionResult> AddTrade([FromBody] NewTradeViewModel model) { try { if (!ModelState.IsValid) { return StatusCode(400, ModelState); } var result = await _tradeService.Add(model.Name, model.PayRate, model.IsActive); if (!result) { return StatusCode(400, new { Message = $"Unable to add new Trade: {model.Name}", Status = 400 }); } return Ok(); } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); return StatusCode(500); } } [HttpPost] [Route("trade/update")] public async Task<IActionResult> Update([FromBody] UpdateTradeViewModel model) { try { if (!ModelState.IsValid) { return StatusCode(400, ModelState); } var result = await _tradeService.Update(model.Id, model.Name, model.PayRate, model.IsActive); if (!result) { return StatusCode(400, new { Message = $"Unable to update Trade: {model.Name}", Status = 400 }); } return Ok(); } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); return StatusCode(500); } } [HttpPost] [Route("trade/delete/{id}")] public async Task<IActionResult> Delete(int id) { try { if (id == 0) { return StatusCode(400, new { Message = $"Invalid id provided", Status = 400 }); } var result = await _tradeService.Delete(id: id); if (!result) { return StatusCode(400, new { Message = $"Unable to delete Trade with id: {id}", Status = 400 }); } return Ok(id); } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); return StatusCode(500, new { Message = ex.Message, Status = 500 }); } } #endregion #region companies [HttpGet] [Route("companies")] public async Task<IActionResult> GetCompanies() { try { return Ok(await _companyService.GetCompanies()); } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); return StatusCode(500); } } [HttpPost] [Route("company/add")] public async Task<IActionResult> ADdCompany([FromBody] NewCompanyViewModel model) { try { if (!ModelState.IsValid) { return StatusCode(400, ModelState); } var result = await _companyService.Add(model.Name); if (!result) { return StatusCode(400, new { Message = $"Unable to add new Company: {model.Name}", Status = 400 }); } return Ok(); } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); return StatusCode(500); } } /*[HttpPost] [Route("trade/update")] public async Task<IActionResult> Update([FromBody] UpdateTradeViewModel model) { try { if (!ModelState.IsValid) { return StatusCode(400, ModelState); } var result = await _tradeService.Update(model.Id, model.Name, model.PayRate, model.IsActive); if (!result) { return StatusCode(400, new { Message = $"Unable to update Trade: {model.Name}", Status = 400 }); } return Ok(); } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); return StatusCode(500); } } [HttpPost] [Route("trade/delete/{id}")] public async Task<IActionResult> Delete(int id) { try { if (id == 0) { return StatusCode(400, new { Message = $"Invalid id provided", Status = 400 }); } var result = await _tradeService.Delete(id: id); if (!result) { return StatusCode(400, new { Message = $"Unable to delete Trade with id: {id}", Status = 400 }); } return Ok(id); } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); return StatusCode(500, new { Message = ex.Message, Status = 500 }); } }*/ #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace System.Net.WebSockets { public sealed partial class ClientWebSocket : WebSocket { private enum InternalState { Created = 0, Connecting = 1, Connected = 2, Disposed = 3 } private readonly ClientWebSocketOptions _options; private WebSocketHandle _innerWebSocket; // may be mutable struct; do not make readonly // NOTE: this is really an InternalState value, but Interlocked doesn't support // operations on values of enum types. private int _state; public ClientWebSocket() { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.WebSocket, this, ".ctor", null); } WebSocketHandle.CheckPlatformSupport(); _state = (int)InternalState.Created; _options = new ClientWebSocketOptions(); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.WebSocket, this, ".ctor", null); } } #region Properties public ClientWebSocketOptions Options { get { return _options; } } public override WebSocketCloseStatus? CloseStatus { get { if (WebSocketHandle.IsValid(_innerWebSocket)) { return _innerWebSocket.CloseStatus; } return null; } } public override string CloseStatusDescription { get { if (WebSocketHandle.IsValid(_innerWebSocket)) { return _innerWebSocket.CloseStatusDescription; } return null; } } public override string SubProtocol { get { if (WebSocketHandle.IsValid(_innerWebSocket)) { return _innerWebSocket.SubProtocol; } return null; } } public override WebSocketState State { get { // state == Connected or Disposed if (WebSocketHandle.IsValid(_innerWebSocket)) { return _innerWebSocket.State; } switch ((InternalState)_state) { case InternalState.Created: return WebSocketState.None; case InternalState.Connecting: return WebSocketState.Connecting; default: // We only get here if disposed before connecting Debug.Assert((InternalState)_state == InternalState.Disposed); return WebSocketState.Closed; } } } #endregion Properties public Task ConnectAsync(Uri uri, CancellationToken cancellationToken) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (!uri.IsAbsoluteUri) { throw new ArgumentException(SR.net_uri_NotAbsolute, nameof(uri)); } if (uri.Scheme != UriScheme.Ws && uri.Scheme != UriScheme.Wss) { throw new ArgumentException(SR.net_WebSockets_Scheme, nameof(uri)); } // Check that we have not started already var priorState = (InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connecting, (int)InternalState.Created); if (priorState == InternalState.Disposed) { throw new ObjectDisposedException(GetType().FullName); } else if (priorState != InternalState.Created) { throw new InvalidOperationException(SR.net_WebSockets_AlreadyStarted); } _options.SetToReadOnly(); return ConnectAsyncCore(uri, cancellationToken); } private async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken) { _innerWebSocket = WebSocketHandle.Create(); try { // Change internal state to 'connected' to enable the other methods if ((InternalState)Interlocked.CompareExchange(ref _state, (int)InternalState.Connected, (int)InternalState.Connecting) != InternalState.Connecting) { // Aborted/Disposed during connect. throw new ObjectDisposedException(GetType().FullName); } await _innerWebSocket.ConnectAsyncCore(uri, cancellationToken, _options).ConfigureAwait(false); } catch (Exception ex) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exception(NetEventSource.ComponentType.WebSocket, this, nameof(ConnectAsync), ex); } throw; } } public override Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) { ThrowIfNotConnected(); return _innerWebSocket.SendAsync(buffer, messageType, endOfMessage, cancellationToken); } public override Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) { ThrowIfNotConnected(); return _innerWebSocket.ReceiveAsync(buffer, cancellationToken); } public override Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { ThrowIfNotConnected(); return _innerWebSocket.CloseAsync(closeStatus, statusDescription, cancellationToken); } public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { ThrowIfNotConnected(); return _innerWebSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken); } public override void Abort() { if ((InternalState)_state == InternalState.Disposed) { return; } if (WebSocketHandle.IsValid(_innerWebSocket)) { _innerWebSocket.Abort(); } Dispose(); } public override void Dispose() { var priorState = (InternalState)Interlocked.Exchange(ref _state, (int)InternalState.Disposed); if (priorState == InternalState.Disposed) { // No cleanup required. return; } if (WebSocketHandle.IsValid(_innerWebSocket)) { _innerWebSocket.Dispose(); } } private void ThrowIfNotConnected() { if ((InternalState)_state == InternalState.Disposed) { throw new ObjectDisposedException(GetType().FullName); } else if ((InternalState)_state != InternalState.Connected) { throw new InvalidOperationException(SR.net_WebSockets_NotConnected); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class ReadTo : PortsTest { //The number of random bytes to receive for read method testing private const int DEFAULT_NUM_CHARS_TO_READ = 8; //The number of new lines to insert into the string not including the one at the end private const int DEFAULT_NUMBER_NEW_LINES = 2; //The number of random bytes to receive for large input buffer testing private const int LARGE_NUM_CHARS_TO_READ = 2048; private const int MIN_NUM_NEWLINE_CHARS = 1; private const int MAX_NUM_NEWLINE_CHARS = 5; private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; #region Test Cases [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void NewLine_Contains_nullChar() { VerifyRead(new ASCIIEncoding(), "\0"); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void NewLine_CR() { VerifyRead(new ASCIIEncoding(), "\r"); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void NewLine_LF() { VerifyRead(new ASCIIEncoding(), "\n"); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void NewLine_CRLF_RndStr() { VerifyRead(new ASCIIEncoding(), "\r\n"); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void NewLine_CRLF_CRStr() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\r"); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); VerifyReadTo(com1, com2, "TEST\r", "\r\n"); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void NewLine_CRLF_LFStr() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\n"); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); VerifyReadTo(com1, com2, "TEST\n", "\r\n"); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void NewLine_END() { VerifyRead(new ASCIIEncoding(), "END"); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ASCIIEncoding() { VerifyRead(new ASCIIEncoding(), GenRandomNewLine(true)); } /* public void UTF7Encoding() { VerifyRead(new System.Text.UTF7Encoding(), GenRandomNewLine(false)); } */ [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void UTF8Encoding() { VerifyRead(new UTF8Encoding(), GenRandomNewLine(false)); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void UTF32Encoding() { VerifyRead(new UTF32Encoding(), GenRandomNewLine(false)); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void UnicodeEncoding() { VerifyRead(new UnicodeEncoding(), GenRandomNewLine(false)); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void LargeInputBuffer() { VerifyRead(LARGE_NUM_CHARS_TO_READ); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadToWriteLine_ASCII() { VerifyReadToWithWriteLine(new ASCIIEncoding(), GenRandomNewLine(true)); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadToWriteLine_UTF8() { VerifyReadToWithWriteLine(new UTF8Encoding(), GenRandomNewLine(true)); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadToWriteLine_UTF32() { VerifyReadToWithWriteLine(new UTF32Encoding(), GenRandomNewLine(true)); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void ReadToWriteLine_Unicode() { VerifyReadToWithWriteLine(new UnicodeEncoding(), GenRandomNewLine(true)); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_ReadBufferedData() { int numBytesToRead = 32; using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(-55); StringBuilder strBldrToWrite = new StringBuilder(); //Genrate random characters for (int i = 0; i < numBytesToRead; i++) { strBldrToWrite.Append((char)rndGen.Next(40, 60)); } int newLineIndex; while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) { strBldrToWrite[newLineIndex] = (char)rndGen.Next(40, 60); } com1.ReadTimeout = 500; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); strBldrToWrite.Append(com1.NewLine); BufferData(com1, com2, strBldrToWrite.ToString()); PerformReadOnCom1FromCom2(com1, com2, strBldrToWrite.ToString(), com1.NewLine); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_IterativeReadBufferedData() { int numBytesToRead = 32; VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.Buffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_ReadBufferedAndNonBufferedData() { int numBytesToRead = 32; using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(-55); StringBuilder strBldrToWrite = new StringBuilder(); StringBuilder strBldrExpected = new StringBuilder(); //Genrate random characters for (int i = 0; i < numBytesToRead; i++) { strBldrToWrite.Append((char)rndGen.Next(0, 256)); } int newLineIndex; while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) { strBldrToWrite[newLineIndex] = (char)rndGen.Next(0, 256); } com1.ReadTimeout = 500; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); BufferData(com1, com2, strBldrToWrite.ToString()); strBldrExpected.Append(strBldrToWrite); strBldrToWrite.Append(com1.NewLine); strBldrExpected.Append(strBldrToWrite); VerifyReadTo(com1, com2, strBldrToWrite.ToString(), strBldrExpected.ToString(), com1.NewLine); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void SerialPort_IterativeReadBufferedAndNonBufferedData() { int numBytesToRead = 3; VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.BufferedAndNonBuffered); } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void GreedyRead() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(128, TCSupport.CharacterOptions.Surrogates); byte[] byteXmitBuffer = new byte[1024]; char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); int numBytes; Debug.WriteLine("Verifying that ReadTo() will read everything from internal buffer and drivers buffer"); //Put the first byte of the utf32 encoder char in the last byte of this buffer //when we read this later the buffer will have to be resized byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length); //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so //the other 3 bytes of the ut32 encoded char can be in the buffer com1.Read(new char[1023], 0, 1023); Assert.Equal(1, com1.BytesToRead); com1.Encoding = Encoding.UTF32; com2.Encoding = Encoding.UTF32; com2.Write(utf32CharBytes, 1, 3); com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); com2.WriteLine(string.Empty); numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer); byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer); char[] expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)]; expectedChars[0] = utf32Char; Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); TCSupport.WaitForReadBufferToLoad(com1, 4 + numBytes); string rcvString = com1.ReadTo(com2.NewLine); Assert.NotNull(rcvString); Assert.Equal(expectedChars, rcvString.ToCharArray()); Assert.Equal(0, com1.BytesToRead); } } [ConditionalFact(nameof(HasOneSerialPort))] public void NullNewLine() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method thows ArgumentExcpetion with a null NewLine string"); com.Open(); VerifyReadException(com, null, typeof(ArgumentNullException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void EmptyNewLine() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method thows ArgumentExcpetion with a empty NewLine string"); com.Open(); VerifyReadException(com, "", typeof(ArgumentException)); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void NewLineSubstring() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Debug.WriteLine("Verifying read method with sub strings of the new line appearing in the string being read"); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); string newLine = "asfg"; string newLineSubStrings = "a" + "as" + "asf" + "sfg" + "fg" + "g"; //All the substrings of newLine string testStr = newLineSubStrings + "asfg" + newLineSubStrings; VerifyReadTo(com1, com2, testStr, newLine); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Read_DataReceivedBeforeTimeout() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); string endString = "END"; ASyncRead asyncRead = new ASyncRead(com1, endString); var asyncReadTask = new Task(asyncRead.Read); char endChar = endString[0]; char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); Debug.WriteLine( "Verifying that ReadTo(string) will read characters that have been received after the call to Read was made"); //Ensure the new line is not in charXmitBuffer for (int i = 0; i < charXmitBuffer.Length; ++i) { //Se any appearances of a character in the new line string to some other char if (endChar == charXmitBuffer[i]) { charXmitBuffer[i] = notEndChar; } } com1.Encoding = Encoding.UTF8; com2.Encoding = Encoding.UTF8; com1.ReadTimeout = 20000; // 20 seconds com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); asyncReadTask.Start(); asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); com2.Write(endString); asyncRead.ReadCompletedEvent.WaitOne(); if (null != asyncRead.Exception) { Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); } else if (null == asyncRead.Result || 0 == asyncRead.Result.Length) { Fail("Err_0158ahei Expected Read to read at least one character"); } else { char[] charRcvBuffer = asyncRead.Result.ToCharArray(); if (charRcvBuffer.Length != charXmitBuffer.Length) { Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length, charRcvBuffer.Length); } else { for (int i = 0; i < charXmitBuffer.Length; ++i) { if (charRcvBuffer[i] != charXmitBuffer[i]) { Fail( "Err_0518895akiezp Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", i, charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); } } } } VerifyReadTo(com1, com2, new string(charXmitBuffer), endString); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Read_Timeout() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); string endString = "END"; char endChar = endString[0]; char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); Debug.WriteLine("Verifying that ReadTo(string) works appropriately after TimeoutException has been thrown"); // Ensure the new line is not in charXmitBuffer for (int i = 0; i < charXmitBuffer.Length; ++i) { // Set any appearances of a character in the new line string to some other char if (endChar == charXmitBuffer[i]) { charXmitBuffer[i] = notEndChar; } } com1.Encoding = Encoding.Unicode; com2.Encoding = Encoding.Unicode; com1.ReadTimeout = 2000; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); Assert.Throws<TimeoutException>(() => com1.ReadTo(endString)); Assert.Equal(2 * charXmitBuffer.Length, com1.BytesToRead); com2.Write(endString); string result = com1.ReadTo(endString); char[] charRcvBuffer = result.ToCharArray(); Assert.Equal(charRcvBuffer, charXmitBuffer); VerifyReadTo(com1, com2, new string(charXmitBuffer), endString); } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Read_LargeBuffer() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); bool continueRunning = true; int numberOfIterations = 0; var writeToCom2Task = new Task(delegate () { while (continueRunning) { com1.Write(charXmitBuffer, 0, charXmitBuffer.Length); ++numberOfIterations; } }); char endChar = TCSupport.GenerateRandomCharNonSurrogate(); char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); //Ensure the new line is not in charXmitBuffer for (int i = 0; i < charXmitBuffer.Length; ++i) { //Se any appearances of a character in the new line string to some other char if (endChar == charXmitBuffer[i]) { charXmitBuffer[i] = notEndChar; } } com1.BaudRate = 115200; com2.BaudRate = 115200; com1.Encoding = Encoding.Unicode; com2.Encoding = Encoding.Unicode; com2.ReadTimeout = 10000; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); writeToCom2Task.Start(); Assert.Throws<TimeoutException>(() => com2.ReadTo(new string(endChar, 1))); continueRunning = false; writeToCom2Task.Wait(); com1.Write(new string(endChar, 1)); string stringRcvBuffer = com2.ReadTo(new string(endChar, 1)); if (charXmitBuffer.Length * numberOfIterations == stringRcvBuffer.Length) { for (int i = 0; i < charXmitBuffer.Length * numberOfIterations; ++i) { if (stringRcvBuffer[i] != charXmitBuffer[i % charXmitBuffer.Length]) { Fail("Err_292aneid Expected to read {0} actually read {1}", charXmitBuffer[i % charXmitBuffer.Length], stringRcvBuffer[i]); break; } } } else { Fail("Err_292haie Expected to read {0} characters actually read {1}", charXmitBuffer.Length * numberOfIterations, stringRcvBuffer.Length); } } } [ConditionalFact(nameof(HasLoopbackOrNullModem))] public void Read_SurrogateCharacter() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Debug.WriteLine( "Verifying read method with surrogate pair in the input and a surrogate pair for the newline"); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); string surrogatePair = "\uD800\uDC00"; string newLine = "\uD801\uDC01"; string input = TCSupport.GetRandomString(256, TCSupport.CharacterOptions.None) + surrogatePair + newLine; com1.NewLine = newLine; VerifyReadTo(com1, com2, input, newLine); } } #endregion #region Verification for Test Cases private void VerifyReadException(SerialPort com, string newLine, Type expectedException) { Assert.Throws(expectedException, () => com.ReadTo(newLine)); } private void VerifyRead(int numberOfBytesToRead) { VerifyRead(new ASCIIEncoding(), "\n", numberOfBytesToRead, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); } private void VerifyRead(Encoding encoding) { VerifyRead(encoding, "\n", DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); } private void VerifyRead(Encoding encoding, string newLine) { VerifyRead(encoding, newLine, DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); } private void VerifyRead(Encoding encoding, string newLine, int numBytesRead, int numNewLines, ReadDataFromEnum readDataFrom) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(-55); StringBuilder strBldrToWrite; int numNewLineChars = newLine.ToCharArray().Length; int minLength = (1 + numNewLineChars) * numNewLines; if (minLength < numBytesRead) strBldrToWrite = TCSupport.GetRandomStringBuilder(numBytesRead, TCSupport.CharacterOptions.None); else strBldrToWrite = TCSupport.GetRandomStringBuilder(rndGen.Next(minLength, minLength * 2), TCSupport.CharacterOptions.None); //We need place the newLine so that they do not write over eachother int divisionLength = strBldrToWrite.Length / numNewLines; int range = divisionLength - numNewLineChars; for (int i = 0; i < numNewLines; i++) { int newLineIndex = rndGen.Next(0, range + 1); strBldrToWrite.Insert(newLineIndex + (i * divisionLength) + (i * numNewLineChars), newLine); } Debug.WriteLine("Verifying ReadTo encoding={0}, newLine={1}, numBytesRead={2}, numNewLines={3}", encoding, newLine, numBytesRead, numNewLines); com1.ReadTimeout = 500; com1.Encoding = encoding; TCSupport.SetHighSpeed(com1, com2); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); switch (readDataFrom) { case ReadDataFromEnum.NonBuffered: VerifyReadNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); break; case ReadDataFromEnum.Buffered: VerifyReadBuffered(com1, com2, strBldrToWrite.ToString(), newLine); break; case ReadDataFromEnum.BufferedAndNonBuffered: VerifyReadBufferedAndNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); break; default: throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); } } } private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { VerifyReadTo(com1, com2, strToWrite, newLine); } private void VerifyReadBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { BufferData(com1, com2, strToWrite); PerformReadOnCom1FromCom2(com1, com2, strToWrite, newLine); } private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { BufferData(com1, com2, strToWrite); VerifyReadTo(com1, com2, strToWrite, strToWrite + strToWrite, newLine); } private void BufferData(SerialPort com1, SerialPort com2, string strToWrite) { char[] charsToWrite = strToWrite.ToCharArray(); byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite); com2.Write(bytesToWrite, 0, 1); // Write one byte at the beginning because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); while (com1.BytesToRead < bytesToWrite.Length + 1) { Thread.Sleep(50); } com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPort's own internal buffer Assert.Equal(bytesToWrite.Length, com1.BytesToRead); } private void VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { VerifyReadTo(com1, com2, strToWrite, strToWrite, newLine); } private void VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string expectedString, string newLine) { char[] charsToWrite = strToWrite.ToCharArray(); byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite); com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; Thread.Sleep((int)((((bytesToWrite.Length + 1) * 10.0) / com1.BaudRate) * 1000) + 250); PerformReadOnCom1FromCom2(com1, com2, expectedString, newLine); } private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { StringBuilder strBldrRead = new StringBuilder(); int newLineStringLength = newLine.Length; int numNewLineChars = newLine.ToCharArray().Length; int numNewLineBytes = com1.Encoding.GetByteCount(newLine.ToCharArray()); int totalBytesRead; int totalCharsRead; int lastIndexOfNewLine = -newLineStringLength; string expectedString; bool isUTF7Encoding = com1.Encoding.EncodingName == Encoding.UTF7.EncodingName; char[] charsToWrite = strToWrite.ToCharArray(); byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite); expectedString = new string(com1.Encoding.GetChars(bytesToWrite)); totalBytesRead = 0; totalCharsRead = 0; while (true) { string rcvString; try { rcvString = com1.ReadTo(newLine); } catch (TimeoutException) { break; } //While their are more characters to be read char[] rcvCharBuffer = rcvString.ToCharArray(); int charsRead = rcvCharBuffer.Length; if (isUTF7Encoding) { totalBytesRead = GetUTF7EncodingBytes(charsToWrite, 0, totalCharsRead + charsRead + numNewLineChars); } else { int bytesRead = com1.Encoding.GetByteCount(rcvCharBuffer, 0, charsRead); totalBytesRead += bytesRead + numNewLineBytes; } // indexOfNewLine = strToWrite.IndexOf(newLine, lastIndexOfNewLine + newLineStringLength); int indexOfNewLine = TCSupport.OrdinalIndexOf(expectedString, lastIndexOfNewLine + newLineStringLength, newLine); if ((indexOfNewLine - (lastIndexOfNewLine + newLineStringLength)) != charsRead) { //If we have not read all of the characters that we should have Debug.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2} numNewLineChars={3} newLineStringLength={4} strToWrite.Length={5}", indexOfNewLine, lastIndexOfNewLine, charsRead, numNewLineChars, newLineStringLength, strToWrite.Length); Debug.WriteLine(strToWrite); Fail("Err_1707ahsp!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (charsToWrite.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect Fail("Err_21707adad!!!: We have received more characters then were sent"); } strBldrRead.Append(rcvString); strBldrRead.Append(newLine); totalCharsRead += charsRead + numNewLineChars; lastIndexOfNewLine = indexOfNewLine; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("Err_99087ahpbx!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } }//End while there are more characters to read if (0 != com1.BytesToRead) { //If there are more bytes to read but there must not be a new line char at the end int charRead; while (true) { try { charRead = com1.ReadChar(); strBldrRead.Append((char)charRead); } catch (TimeoutException) { break; } } } if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead)) { Fail("Err_558596ahbpa!!!: BytesToRead is not zero"); } if (0 != expectedString.CompareTo(strBldrRead.ToString())) { Fail("Err_7797ajpba!!!: Expected to read \"{0}\" actual read \"{1}\"", expectedString, strBldrRead.ToString()); } /* if (!retValue) { Debug.WriteLine("\nstrToWrite = "); TCSupport.PrintChars(strToWrite.ToCharArray()); Debug.WriteLine("\nnewLine = "); TCSupport.PrintChars(newLine.ToCharArray()); } */ } private void VerifyReadToWithWriteLine(Encoding encoding, string newLine) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(-55); StringBuilder strBldrToWrite; string strExpected; bool isUTF7Encoding = encoding.EncodingName == Encoding.UTF7.EncodingName; Debug.WriteLine("Verifying ReadTo with WriteLine encoding={0}, newLine={1}", encoding, newLine); com1.ReadTimeout = 500; com2.NewLine = newLine; com1.Encoding = encoding; com2.Encoding = encoding; //Generate random characters do { strBldrToWrite = new StringBuilder(); for (int i = 0; i < DEFAULT_NUM_CHARS_TO_READ; i++) { strBldrToWrite.Append((char)rndGen.Next(0, 128)); } } while (-1 != TCSupport.OrdinalIndexOf(strBldrToWrite.ToString(), newLine)); //SerialPort does a Ordinal comparison string strWrite = strBldrToWrite.ToString(); strExpected = new string(com1.Encoding.GetChars(com1.Encoding.GetBytes(strWrite.ToCharArray()))); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback com2.Open(); com2.WriteLine(strBldrToWrite.ToString()); string strRead = com1.ReadTo(newLine); if (0 != strBldrToWrite.ToString().CompareTo(strRead)) { Fail("ERROR!!! The string written: \"{0}\" and the string read \"{1}\" differ", strBldrToWrite, strRead); } if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead)) { Fail("ERROR!!! BytesToRead={0} expected 0", com1.BytesToRead); } } } private string GenRandomNewLine(bool validAscii) { Random rndGen = new Random(-55); int newLineLength = rndGen.Next(MIN_NUM_NEWLINE_CHARS, MAX_NUM_NEWLINE_CHARS); if (validAscii) return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.ASCII)); else return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.Surrogates)); } private int GetUTF7EncodingBytes(char[] chars, int index, int count) { byte[] bytes = Encoding.UTF7.GetBytes(chars, index, count); int byteCount = bytes.Length; while (Encoding.UTF7.GetCharCount(bytes, 0, byteCount) == count) { --byteCount; } return byteCount + 1; } private class ASyncRead { private readonly SerialPort _com; private readonly string _value; private string _result; private readonly AutoResetEvent _readCompletedEvent; private readonly AutoResetEvent _readStartedEvent; private Exception _exception; public ASyncRead(SerialPort com, string value) { _com = com; _value = value; _result = null; _readCompletedEvent = new AutoResetEvent(false); _readStartedEvent = new AutoResetEvent(false); _exception = null; } public void Read() { try { _readStartedEvent.Set(); _result = _com.ReadTo(_value); } catch (Exception e) { _exception = e; } finally { _readCompletedEvent.Set(); } } public AutoResetEvent ReadStartedEvent => _readStartedEvent; public AutoResetEvent ReadCompletedEvent => _readCompletedEvent; public string Result => _result; public Exception Exception => _exception; } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Threading; namespace Eto { /// <summary> /// Arguments for when a widget is created /// </summary> /// <copyright>(c) 2012-2015 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class WidgetCreatedEventArgs : EventArgs { /// <summary> /// Gets the instance of the widget that was created /// </summary> public Widget Instance { get; private set; } /// <summary> /// Initializes a new instance of the WidgetCreatedArgs class /// </summary> /// <param name="instance">Instance of the widget that was created</param> public WidgetCreatedEventArgs(Widget instance) { this.Instance = instance; } } /// <summary> /// Arguments for when a widget is created /// </summary> /// <copyright>(c) 2012-2015 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class HandlerCreatedEventArgs : EventArgs { /// <summary> /// Gets the instance of the widget that was created /// </summary> public object Instance { get; private set; } /// <summary> /// Initializes a new instance of the WidgetCreatedArgs class /// </summary> /// <param name="instance">Instance of the widget that was created</param> public HandlerCreatedEventArgs(object instance) { this.Instance = instance; } } class HandlerInfo { public bool Initialize { get; private set; } public Func<object> Instantiator { get; private set; } public HandlerInfo(bool initialize, Func<object> instantiator) { Initialize = initialize; Instantiator = instantiator; } } /// <summary> /// Base platform class /// </summary> /// <remarks> /// This class takes care of creating the platform-specific implementations of each control. /// All controls the platform can handle should be added using <see cref="Platform.Add{T}"/>. /// </remarks> /// <copyright>(c) 2012-2015 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public abstract class Platform { readonly Dictionary<Type, Func<object>> instantiatorMap = new Dictionary<Type, Func<object>>(); readonly Dictionary<Type, HandlerInfo> handlerMap = new Dictionary<Type, HandlerInfo>(); readonly Dictionary<Type, object> sharedInstances = new Dictionary<Type, object>(); readonly Dictionary<object, object> properties = new Dictionary<object, object>(); static Platform globalInstance; static readonly ThreadLocal<Platform> instance = new ThreadLocal<Platform>(() => globalInstance); internal T GetSharedProperty<T>(object key, Func<T> instantiator) { object value; lock (properties) { if (!properties.TryGetValue(key, out value)) { value = instantiator(); properties[key] = value; } } return (T)value; } internal void SetSharedProperty(object key, object value) { lock (properties) { properties[key] = value; } } #region Events /// <summary> /// Event to handle when widgets are created by this platform /// </summary> public event EventHandler<HandlerCreatedEventArgs> HandlerCreated; /// <summary> /// Handles the <see cref="WidgetCreated"/> event /// </summary> /// <param name="e">Arguments for the event</param> protected virtual void OnHandlerCreated(HandlerCreatedEventArgs e) { if (HandlerCreated != null) HandlerCreated(this, e); } /// <summary> /// Event to handle when widgets are created by this platform /// </summary> public event EventHandler<WidgetCreatedEventArgs> WidgetCreated; /// <summary> /// Handles the <see cref="WidgetCreated"/> event /// </summary> /// <param name="e">Arguments for the event</param> protected virtual void OnWidgetCreated(WidgetCreatedEventArgs e) { Eto.Style.OnStyleWidgetDefaults(e.Instance); if (WidgetCreated != null) WidgetCreated(this, e); } internal void TriggerWidgetCreated(WidgetCreatedEventArgs args) { OnWidgetCreated(args); } #endregion /// <summary> /// Gets the ID of this platform /// </summary> /// <remarks> /// The platform ID can be used to determine which platform is currently in use. The platform /// does not necessarily correspond to the OS that it is running on, as for example the GTK platform /// can run on OS X and Windows. /// </remarks> public abstract string ID { get; } /// <summary> /// Gets a value indicating whether this platform is a mac based platform (MonoMac/XamMac) /// </summary> /// <value><c>true</c> if this platform is mac; otherwise, <c>false</c>.</value> public virtual bool IsMac { get { return false; } } /// <summary> /// Gets a value indicating whether this platform is based on Windows Forms /// </summary> /// <value><c>true</c> if this platform is window forms; otherwise, <c>false</c>.</value> public virtual bool IsWinForms { get { return false; } } /// <summary> /// Gets a value indicating whether this platform is based on WPF /// </summary> /// <value><c>true</c> if this platform is wpf; otherwise, <c>false</c>.</value> public virtual bool IsWpf { get { return false; } } /// <summary> /// Gets a value indicating whether this platform is based on GTK# (2 or 3) /// </summary> /// <value><c>true</c> if this platform is gtk; otherwise, <c>false</c>.</value> public virtual bool IsGtk { get { return false; } } /// <summary> /// Gets a value indicating whether this platform is based on Xamarin.iOS /// </summary> /// <value><c>true</c> if this platform is ios; otherwise, <c>false</c>.</value> public virtual bool IsIos { get { return false; } } /// <summary> /// Gets a value indicating whether this platform is based on Xamarin.Android. /// </summary> /// <value><c>true</c> if this platform is android; otherwise, <c>false</c>.</value> public virtual bool IsAndroid { get { return false; } } /// <summary> /// Gets a value indicating whether this is a desktop platform. This includes Mac, Gtk, WinForms, Wpf, Direct2D. /// </summary> /// <remarks> /// A desktop platform is usually used via mouse &amp; keyboard, and can have complex user interface elements. /// </remarks> /// <value><c>true</c> if this is a desktop platform; otherwise, <c>false</c>.</value> public virtual bool IsDesktop { get { return false; } } /// <summary> /// Gets a value indicating whether this is a mobile platform. This includes iOS, Android, and WinRT. /// </summary> /// <remarks> /// A mobile platform is usually touch friendly, and have a simpler interface. /// </remarks> /// <value><c>true</c> if this instance is mobile; otherwise, <c>false</c>.</value> public virtual bool IsMobile { get { return false; } } /// <summary> /// Gets a value indicating that this platform is valid on the running device /// </summary> /// <remarks> /// This is used in platform detection to ensure that the correct platform is loaded. /// For example, the Mac platforms are only valid when run in an .app bundle. /// </remarks> /// <value><c>true</c> if this platform is valid and can be run; otherwise, <c>false</c>.</value> public virtual bool IsValid { get { return true; } } /// <summary> /// Initializes a new instance of the Platform class /// </summary> protected Platform() { } /// <summary> /// Gets a value indicating that the specified type is supported by this platform /// </summary> /// <typeparam name="T">Type of the handler or class with HandlerAttribute to test for.</typeparam> /// <returns>true if the specified type is supported, false otherwise</returns> public bool Supports<T>() where T: class { return Supports(typeof(T)); } /// <summary> /// Gets a value indicating that the specified <paramref name="type"/> is supported by this platform /// </summary> /// <param name="type">Type of the handler or class with HandlerAttribute to test for.</param> /// <returns>true if the specified type is supported, false otherwise</returns> public virtual bool Supports(Type type) { return Find(type) != null; } /// <summary> /// Gets the platform for the current thread /// </summary> /// <remarks> /// Typically you'd have only one platform active at a time, and this holds an instance to that value. /// The current platform is set automatically by the <see cref="Forms.Application"/> class /// when it is initially created. /// /// This will return a different value for each thread, so if you have multiple platforms running /// (e.g. GTK + Mac for OS X), then this will allow for that. /// /// This will be used when creating controls. To create controls on a different platform outside of its own thread, /// use the <see cref="Context"/> property. /// </remarks> public static Platform Instance { get { return instance.Value; } } /// <summary> /// Returns the current generator, or detects the generator to use if no current generator is set. /// </summary> /// <remarks> /// This detects the platform to use based on the generator assemblies available and the current OS. /// /// For windows, it will prefer WPF to Windows Forms. /// Mac OS X will prefer the Mac platform. /// Other unix-based platforms will prefer GTK. /// </remarks> public static Platform Detect { get { if (globalInstance != null) return globalInstance; Platform detected = null; if (EtoEnvironment.Platform.IsMac) { if (EtoEnvironment.Is64BitProcess) detected = Platform.Get(Platforms.Mac64, true); if (detected == null) detected = Platform.Get(Platforms.XamMac, true); if (detected == null) detected = Platform.Get(Platforms.Mac, true); } else if (EtoEnvironment.Platform.IsWindows) { detected = Platform.Get(Platforms.Wpf, true); if (detected == null) detected = Platform.Get(Platforms.WinForms, true); } if (detected == null && EtoEnvironment.Platform.IsUnix) { detected = Platform.Get(Platforms.Gtk3, true); if (detected == null) detected = Platform.Get(Platforms.Gtk2, true); } if (detected == null) throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Could not detect platform. Are you missing a platform assembly?")); Initialize(detected); return globalInstance; } } /// <summary> /// Initializes the specified <paramref name="platform"/> as the current generator, for the current thread /// </summary> /// <remarks> /// This is called automatically by the <see cref="Forms.Application"/> when it is constructed /// </remarks> /// <param name="platform">Generator to set as the current generator</param> public static void Initialize(Platform platform) { if (globalInstance == null) globalInstance = platform; instance.Value = platform; } /// <summary> /// Initialize the generator with the specified <paramref name="platformType"/> as the current generator /// </summary> /// <param name="platformType">Type of the generator to set as the current generator</param> public static void Initialize(string platformType) { Initialize(Get(platformType)); } /// <summary> /// Gets the generator of the specified type /// </summary> /// <param name="generatorType">Type of the generator to get</param> /// <returns>An instance of a Generator of the specified type, or null if it cannot be loaded</returns> public static Platform Get(string generatorType) { return Get(generatorType, true); } internal static Platform Get(string platformType, bool allowNull) { Type type = Type.GetType(platformType); if (type == null) { if (allowNull) return null; throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Platform not found. Are you missing the platform assembly?")); } try { var platform = (Platform)Activator.CreateInstance(type); if (!platform.IsValid) { var message = string.Format("Platform type {0} was loaded but is not valid in the current context. E.g. Mac platforms require to be in an .app bundle to run", platformType); if (allowNull) Debug.WriteLine(message); else throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, message)); return null; } return platform; } catch (Exception ex) { Debug.WriteLine(string.Format("Error creating instance of platform type '{0}'\n{1}", platformType, ex)); if (allowNull) return null; throw; } } /// <summary> /// Add the <paramref name="instantiator"/> for the specified handler type of <typeparamref name="T"/> /// </summary> /// <param name="instantiator">Instantiator to create an instance of the handler</param> /// <typeparam name="T">The handler type to add the instantiator for (usually an interface derived from <see cref="Widget.IHandler"/>)</typeparam> public void Add<T>(Func<T> instantiator) where T: class { Add(typeof(T), instantiator); } /// <summary> /// Add the specified type and instantiator. /// </summary> /// <param name="type">Type of the handler (usually an interface derived from <see cref="Widget.IHandler"/>)</param> /// <param name="instantiator">Instantiator to create an instance of the handler</param> public void Add(Type type, Func<object> instantiator) { var handler = type.GetCustomAttribute<HandlerAttribute>(true); if (handler != null) instantiatorMap[handler.Type] = instantiator; // for backward compatibility, for now instantiatorMap[type] = instantiator; } /// <summary> /// Find the delegate to create instances of the specified <paramref name="type"/> /// </summary> /// <param name="type">Type of the handler interface to get the instantiator for (usually derived from <see cref="Widget.IHandler"/> or another type)</param> public Func<object> Find(Type type) { Func<object> activator; if (instantiatorMap.TryGetValue(type, out activator)) return activator; var handler = type.GetCustomAttribute<HandlerAttribute>(true); if (handler != null && instantiatorMap.TryGetValue(handler.Type, out activator)) { instantiatorMap.Add(type, activator); return activator; } return null; } /// <summary> /// Finds the delegate to create instances of the specified type /// </summary> /// <typeparam name="T">Type of the handler interface (usually derived from <see cref="Widget.IHandler"/> or another type)</typeparam> /// <returns>The delegate to use to create instances of the specified type</returns> public Func<T> Find<T>() where T: class { return (Func<T>)Find(typeof(T)); } internal HandlerInfo FindHandler(Type type) { HandlerInfo info; if (handlerMap.TryGetValue(type, out info)) return info; var handler = type.GetCustomAttribute<HandlerAttribute>(true); Func<object> activator; if (handler != null && instantiatorMap.TryGetValue(handler.Type, out activator)) { var autoInit = handler.Type.GetCustomAttribute<AutoInitializeAttribute>(true); info = new HandlerInfo(autoInit == null || autoInit.Initialize, activator); handlerMap.Add(type, info); return info; } return null; } /// <summary> /// Creates a new instance of the handler of the specified type of <typeparamref name="T"/> /// </summary> /// <remarks> /// This extension should be used when creating instances of a fixed type. /// </remarks> /// <typeparam name="T">Type of handler to create</typeparam> /// <returns>A new instance of a handler</returns> public T Create<T>() { return (T)Create(typeof(T)); } /// <summary> /// Creates a new instance of the handler of the specified type /// </summary> /// <param name="type">Type of handler to create</param> /// <returns>A new instance of a handler</returns> public object Create(Type type) { try { var instantiator = Find(type); if (instantiator == null) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Type {0} could not be found in this generator", type.FullName)); var handler = instantiator(); OnHandlerCreated(new HandlerCreatedEventArgs(handler)); return handler; } catch (Exception e) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Could not create instance of type {0}", type), e); } } /// <summary> /// Creates a shared singleton instance of the specified type of <paramref name="type"/> /// </summary> /// <param name="type">The type of handler to get a shared instance for</param> /// <returns>The shared instance of a handler of the given type, or a new instance if not already created</returns> public object CreateShared(Type type) { object instance; lock (sharedInstances) { if (!sharedInstances.TryGetValue(type, out instance)) { instance = Create(type); sharedInstances[type] = instance; } } return instance; } /// <summary> /// Creates a shared singleton instance of the specified type of <typeparamref name="T"/> /// </summary> /// <remarks> /// This extension should be used when creating shared instances of a fixed type. /// </remarks> /// <typeparam name="T">The type of handler to get a shared instance for</typeparam> /// <returns>The shared instance of a handler of the given type, or a new instance if not already created</returns> public T CreateShared<T>() { return (T)CreateShared(typeof(T)); } /// <summary> /// Gets a shared cache dictionary /// </summary> /// <remarks> /// This is used to cache things like brushes and pens, but can also be used to cache other things for your /// application's use. /// </remarks> /// <param name="cacheKey">Unique cache key to load the cache instance</param> /// <typeparam name="TKey">The type of the lookup key</typeparam> /// <typeparam name="TValue">The type of the lookup value</typeparam> public Dictionary<TKey, TValue> Cache<TKey, TValue>(object cacheKey) { return GetSharedProperty<Dictionary<TKey, TValue>>(cacheKey, () => new Dictionary<TKey, TValue>()); } /// <summary> /// Used at the start of your custom threads /// </summary> /// <returns></returns> public virtual IDisposable ThreadStart() { return null; } /// <summary> /// Gets an object to wrap in the platform's context, when using multiple platforms. /// </summary> /// <remarks> /// This sets this platform as current, and reverts back to the previous platform when disposed. /// /// This value may be null. /// </remarks> /// <example> /// <code> /// using (platform.Context) /// { /// // do some stuff with the specified platform /// } /// </code> /// </example> public IDisposable Context { get { return instance.Value != this ? new PlatformContext(this) : null; } } /// <summary> /// Invoke the specified action within the context of this platform /// </summary> /// <remarks> /// This is useful when you are using multiple platforms at the same time, and gives you an easy /// way to execute code within the context of this platform. /// </remarks> /// <param name="action">Action to execute.</param> public void Invoke(Action action) { using (Context) { action(); } } /// <summary> /// Invoke the specified function within the context of this platform, returning its value. /// </summary> /// <remarks> /// This is useful when you are using multiple platforms at the same time, and gives you an easy /// way to execute code within the context of this platform, and return its value. /// </remarks> /// <example> /// <code> /// var mycontrol = MyPlatform.Invoke(() => new MyControl()); /// </code> /// </example> /// <param name="action">Action to execute.</param> /// <typeparam name="T">The type of value to return.</typeparam> public T Invoke<T>(Func<T> action) { using (Context) { return action(); } } } }
using NetDimension.NanUI.JavaScript; using NetDimension.NanUI.JavaScript.WindowBinding; using System.Net.NetworkInformation; using Xilium.CefGlue; namespace NetDimension.NanUI.Browser.WindowBinding; class FormiumObjectWindowBinding : JavaScriptWindowBindingObject { public override string Name { get; } = "WinFormiumWindowBindingObject"; public override string JavaScriptCode { get; } = Properties.Resources.FormiumWindowBinding; public FormiumObjectWindowBinding() { // WinFormium Object functions RegisterHandler(GetCurrentCulture); // Network Object functions RegisterHandler(GetNetworkAvailableStatus); // Version Object functions RegisterHandler(GetWinFormiumVersion); RegisterHandler(GetChromiumVersion); // HostWindow Object functions // - methods RegisterHandler(Minimize); RegisterHandler(Maximize); RegisterHandler(Restore); RegisterHandler(Close); RegisterHandler(FullScreen); RegisterHandler(MoveTo); RegisterHandler(MoveBy); RegisterHandler(SizeTo); RegisterHandler(SizeBy); RegisterHandler(Active); RegisterHandler(Center); // - properties RegisterHandler(GetWindowState); RegisterHandler(GetWindowLocation); RegisterHandler(GetWindowSize); RegisterHandler(GetWindowRectangle); // SplashScreen Object functions RegisterHandler(ShowSplashScreen); RegisterHandler(HideSplashScreen); // Borderless Window settings RegisterHandler(GetCornerStyle); RegisterHandler(SetCornerStyle); RegisterHandler(GetShadowEffect); RegisterHandler(SetShadowEffect); RegisterHandler(GetShadowColor); RegisterHandler(SetShadowColor); RegisterHandler(GetInactiveShadowColor); RegisterHandler(SetInactiveShadowColor); RegisterHandler(SendDataMessage); } #region WinFormium private JavaScriptValue GetCurrentCulture(JavaScriptArray _) { var retval = new JavaScriptObject(); retval.Add("name", $"{Thread.CurrentThread.CurrentCulture.Name}"); var array = new JavaScriptArray() { $"{Thread.CurrentThread.CurrentCulture.DisplayName}", $"{Thread.CurrentThread.CurrentCulture.EnglishName}", }; retval.Add("cultureName", array); retval.Add("lcid", Thread.CurrentThread.CurrentCulture.LCID); return retval; } #endregion #region Network private JavaScriptValue GetNetworkAvailableStatus(JavaScriptArray _) { return new JavaScriptValue(NetworkInterface.GetIsNetworkAvailable()); } #endregion #region Version private JavaScriptValue GetWinFormiumVersion(JavaScriptArray _) { return new JavaScriptValue($"{Assembly.GetExecutingAssembly().GetName().Version}"); } private JavaScriptValue GetChromiumVersion(JavaScriptArray _) { return new JavaScriptValue($"{CefRuntime.ChromeVersion}"); } #endregion #region HostWindow private JavaScriptValue Minimize(Formium owner, JavaScriptArray _) { if (owner.WindowType == HostWindow.HostWindowType.Kiosk || !owner.Minimizable) return null; owner.InvokeIfRequired(() => owner.WindowState = FormWindowState.Minimized); return null; } private JavaScriptValue Maximize(Formium owner, JavaScriptArray _) { if (owner.WindowType == HostWindow.HostWindowType.Kiosk || !owner.Maximizable) return null; if (owner.WindowState != FormWindowState.Maximized) { owner.InvokeIfRequired(() => owner.WindowState = FormWindowState.Maximized); } else if (owner.WindowState == FormWindowState.Maximized) { if (owner.FullScreen) { owner.InvokeIfRequired(() => owner.FullScreen = !owner.FullScreen); } else { owner.InvokeIfRequired(() => owner.WindowState = FormWindowState.Normal); } } return null; } private JavaScriptValue Restore(Formium owner, JavaScriptArray _) { if (owner.WindowType == HostWindow.HostWindowType.Kiosk) return null; if (owner.WindowState != FormWindowState.Normal) { if (owner.FullScreen) { owner.InvokeIfRequired(() => owner.FullScreen = false); } owner.InvokeIfRequired(() => owner.WindowState = FormWindowState.Normal); } return null; } private JavaScriptValue Close(Formium owner, JavaScriptArray _) { if (owner.WindowType == HostWindow.HostWindowType.Kiosk) { return null; } owner.InvokeIfRequired(() => { owner.Close(); }); return null; } private JavaScriptValue FullScreen(Formium owner, JavaScriptArray _) { if (owner.WindowType == HostWindow.HostWindowType.Kiosk) return null; if (owner.AllowFullScreen) { owner.InvokeIfRequired(() => owner.FullScreen = !owner.FullScreen); } return null; } private JavaScriptValue MoveTo(Formium owner, JavaScriptArray arguments) { if (owner.WindowType == HostWindow.HostWindowType.Kiosk || owner.WindowState != System.Windows.Forms.FormWindowState.Normal) return null; var x = arguments.Count == 2 ? arguments[0].GetInt() : 0; var y = arguments.Count == 2 ? arguments[1].GetInt() : 0; owner.InvokeIfRequired(() => { owner.Left = x; owner.Top = y; }); return null; } private JavaScriptValue MoveBy(Formium owner, JavaScriptArray arguments) { if (owner.WindowType == HostWindow.HostWindowType.Kiosk || owner.WindowState != System.Windows.Forms.FormWindowState.Normal) return null; var x = arguments.Count == 2 ? arguments[0].GetInt() : 0; var y = arguments.Count == 2 ? arguments[1].GetInt() : 0; owner.InvokeIfRequired(() => { owner.Left += x; owner.Top += y; }); return null; } private JavaScriptValue SizeTo(Formium owner, JavaScriptArray arguments) { if (!owner.Sizable || owner.WindowState != System.Windows.Forms.FormWindowState.Normal) return null; var width = arguments.Count == 2 ? arguments[0].GetInt() : 0; var height = arguments.Count == 2 ? arguments[1].GetInt() : 0; owner.InvokeIfRequired(() => { if (width > 0 && height > 0) { owner.Size = new Size(width, height); } else if (width <= 0) { owner.Size = new Size(owner.Width, height); } else if (height <= 0) { owner.Size = new Size(width, owner.Height); } }); return null; } private JavaScriptValue SizeBy(Formium owner, JavaScriptArray arguments) { if (!owner.Sizable || owner.WindowState != System.Windows.Forms.FormWindowState.Normal) return null; var width = arguments.Count == 2 ? arguments[0].GetInt() : 0; var height = arguments.Count == 2 ? arguments[1].GetInt() : 0; owner.InvokeIfRequired(() => { width = owner.Width + width; height = owner.Height + height; if (width > 0 && height > 0) { owner.Size = new Size(width, height); } else if (width <= 0) { owner.Size = new Size(owner.Width, height); } else if (height <= 0) { owner.Size = new Size(width, owner.Height); } }); return null; } private JavaScriptValue Active(Formium owner, JavaScriptArray _) { owner.InvokeIfRequired(() => { owner.Active(); }); return null; } private JavaScriptValue Center(Formium owner, JavaScriptArray _) { if (owner.WindowType == HostWindow.HostWindowType.Kiosk || owner.WindowState != FormWindowState.Normal) return null; owner.InvokeIfRequired(() => { var scr = Screen.FromHandle(owner.HostWindowHandle); if (scr != null) { owner.Location = new Point(scr.WorkingArea.Left + (scr.WorkingArea.Width - owner.Width) / 2, scr.WorkingArea.Top + (scr.WorkingArea.Height - owner.Height) / 2); } }); return null; } private JavaScriptValue GetWindowState(Formium owner, JavaScriptArray _) { return new JavaScriptValue($"{owner?.WindowState.ToString().ToLower() ?? "normal"}"); } private JavaScriptValue GetWindowLocation(Formium owner, JavaScriptArray _) { var obj = new JavaScriptObject(); obj.Add("x", owner?.Location.X ?? 0); obj.Add("y", owner?.Location.Y ?? 0); return obj; } private JavaScriptValue GetWindowSize(Formium owner, JavaScriptArray _) { var obj = new JavaScriptObject(); obj.Add("width", owner?.Size.Width ?? 0); obj.Add("height", owner?.Size.Height ?? 0); return obj; } private JavaScriptValue GetWindowRectangle(Formium owner, JavaScriptArray _) { var obj = new JavaScriptObject(); obj.Add("left", owner?.Location.X ?? 0); obj.Add("top", owner?.Location.Y ?? 0); obj.Add("right", (owner?.Location.X ?? 0) + (owner?.Size.Width ?? 0)); obj.Add("bottom", (owner?.Location.Y ?? 0) + (owner?.Size.Height ?? 0)); obj.Add("width", owner?.Size.Width ?? 0); obj.Add("height", owner?.Size.Height ?? 0); return obj; } #endregion #region SplashScreen private JavaScriptValue ShowSplashScreen(Formium owner, JavaScriptArray _) { owner.InvokeIfRequired(() => { owner.SplashScreen.ShowPanel(); }); return null; } private JavaScriptValue HideSplashScreen(Formium owner, JavaScriptArray _) { owner.InvokeIfRequired(() => { owner.SplashScreen.HidePanel(); }); return null; } #endregion #region BorderlessWindow private JavaScriptValue GetCornerStyle(Formium owner, JavaScriptArray _) { if(owner.FormHostWindow is HostWindow.BorderlessWindow) { var target = (HostWindow.BorderlessWindow)owner.FormHostWindow; return new JavaScriptValue($"{target.CornerStyle}"); } return null; } private JavaScriptValue SetCornerStyle(Formium owner, JavaScriptArray args) { if (owner.FormHostWindow is HostWindow.BorderlessWindow) { var target = (HostWindow.BorderlessWindow)owner.FormHostWindow; var isStringParam = args.FirstOrDefault()?.IsString ?? false; if (isStringParam) { string param = args.First(); target.InvokeIfRequired(() => { if(Enum.TryParse<HostWindow.CornerStyle>(param, true, out var result)) { target.CornerStyle = result; } }); } } return null; } private JavaScriptValue GetShadowEffect(Formium owner, JavaScriptArray _) { if (owner.FormHostWindow is HostWindow.BorderlessWindow) { var target = (HostWindow.BorderlessWindow)owner.FormHostWindow; return new JavaScriptValue($"{target.ShadowEffect}"); } return null; } private JavaScriptValue SetShadowEffect(Formium owner, JavaScriptArray args) { if (owner.FormHostWindow is HostWindow.BorderlessWindow) { var target = (HostWindow.BorderlessWindow)owner.FormHostWindow; var isStringParam = args.FirstOrDefault()?.IsString ?? false; if (isStringParam) { string param = args.First(); target.InvokeIfRequired(() => { if (Enum.TryParse<HostWindow.ShadowEffect>(param, true, out var result)) { target.ShadowEffect = result; } }); } } return null; } private JavaScriptValue GetShadowColor(Formium owner, JavaScriptArray _) { if (owner.FormHostWindow is HostWindow.BorderlessWindow) { var target = (HostWindow.BorderlessWindow)owner.FormHostWindow; return new JavaScriptValue(ColorTranslator.ToHtml(target.ShadowColor)); } return null; } private JavaScriptValue SetShadowColor(Formium owner, JavaScriptArray args) { if (owner.FormHostWindow is HostWindow.BorderlessWindow) { var target = (HostWindow.BorderlessWindow)owner.FormHostWindow; var isStringParam = args.FirstOrDefault()?.IsString ?? false; if (isStringParam) { string param = args.First(); target.InvokeIfRequired(() => { try { var color = ColorTranslator.FromHtml(param); target.ShadowColor = color; } catch { } }); } } return null; } private JavaScriptValue GetInactiveShadowColor(Formium owner, JavaScriptArray _) { if (owner.FormHostWindow is HostWindow.BorderlessWindow) { var target = (HostWindow.BorderlessWindow)owner.FormHostWindow; if (target.InactiveShadowColor.HasValue) { return new JavaScriptValue(ColorTranslator.ToHtml(target.InactiveShadowColor.Value)); } else { return new JavaScriptValue(); } } return null; } private JavaScriptValue SetInactiveShadowColor(Formium owner, JavaScriptArray args) { if (owner.FormHostWindow is HostWindow.BorderlessWindow) { var target = (HostWindow.BorderlessWindow)owner.FormHostWindow; var isStringParam = args.FirstOrDefault()?.IsString ?? false; var isNullParam = args.FirstOrDefault()?.IsNull ?? false; if (isStringParam) { string param = args.First(); target.InvokeIfRequired(() => { try { var color = ColorTranslator.FromHtml(param); target.InactiveShadowColor = color; } catch { } }); } else if (isNullParam) { target.InvokeIfRequired(() => { target.InactiveShadowColor = null; }); } } return null; } #endregion #region DataMessage private JavaScriptValue SendDataMessage(Formium owner, JavaScriptArray args) { if (args.Count < 1 || !args[0].IsString) { return null; } string messageName = args[0]; string json = null; if (args.Count >= 2 && args[1].IsString) { json = args[1]; } owner.InvokeIfRequired(() => { owner.OnDataMessageReceived(messageName, json); }); return null; } #endregion }
using System; using System.Collections; using System.Threading; using System.Timers; using System.Runtime.InteropServices; using AW_API_NET; using AWIComponentLib.Communication; using AWIComponentLib.Utility; using System.Windows.Forms; namespace AWIComponentLib.Tag { #region delegates public delegate void SearchTagEvent(ushort rdr, ushort host, ushort fgen, uint tag); #endregion #region TagSrchStruct [StructLayout(LayoutKind.Sequential)] public struct tagSrchStruct { public ushort reader; public ushort host; public ushort fGen; public short rssi; tagSrchStruct(int a) { reader = 0; host = 0; fGen = 0; rssi = 0; } } #endregion public class TagSearchClass { #region events public static SearchTagEvent SearchTagEventHandler; #endregion #region vars private ArrayList rdrStatusList = new ArrayList(); private UtilityClass utility = new UtilityClass(); private ArrayList tagSrchList = new ArrayList(); private Object myLock = new Object(); private System.Timers.Timer searchReaderTimer; private CommunicationClass communication; private int srchIndex; private bool startSearch; private uint srchTagID; private string srchTagType; private ushort counter; private static ushort MAX_TRY = 3; #endregion #region Constructor public TagSearchClass(CommunicationClass comm) { #region events communication = comm; CommunicationClass.PowerupEventHandler += new PowerupEvent(this.PowerupReaderEventNotifty); CommunicationClass.QueryTagEventHandler += new QueryTagAckEvent(this.QueryTagEventNotifty); srchIndex = -1; startSearch = false; srchTagID = 0; counter = 0; searchReaderTimer = new System.Timers.Timer(); searchReaderTimer.Interval = 3000; searchReaderTimer.AutoReset = true; searchReaderTimer.Enabled = true; searchReaderTimer.Elapsed += new ElapsedEventHandler(OnSearchReaderTimer); #endregion } #endregion #region SearchTag(uint tagID, string type) public void SearchTag(uint tagID, string type) { counter = 0; srchIndex = 0; srchTagID = tagID; srchTagType = type; startSearch = true; } #endregion #region ProcessSrchList private void ProcessSrchList() { ushort rdr = 0; ushort host = 0; ushort fgen = 0; short rssi = 0; foreach (tagSrchStruct tagListObj in tagSrchList) { if (tagListObj.rssi >= rssi) { rdr = tagListObj.reader; host = tagListObj.host; fgen = tagListObj.fGen; } } if (SearchTagEventHandler != null) SearchTagEventHandler(rdr, host, fgen, srchTagID); } #endregion #region OnSearchReaderTimer private void OnSearchReaderTimer(object source, ElapsedEventArgs e) { lock(myLock) { if (startSearch) { if (srchIndex >= rdrStatusList.Count) { if (counter >= MAX_TRY) { startSearch = false; srchIndex = 0; ProcessSrchList(); return; } srchIndex = 0; counter += 1; } readerStatStruct rdrStat = new readerStatStruct(0); //create an readerStatStruct object with temp rdr id for (int n=srchIndex; n<rdrStatusList.Count; n++) { rdrStat = (readerStatStruct)rdrStatusList[n]; if (rdrStat.GetSearchReader()) { if (rdrStat.GetCounter() < MAX_TRY) { if (!rdrStat.GetSrchStatus()) //tagFound { Console.WriteLine ("OnSearchTimer(TagSearchClass) send Query Cmd time:" + DateTime.Now.ToString()); int ret = communication.QueryTag(rdrStat.rdrID, srchTagID, "AST"); return; } } } srchIndex += 1; } }//if (startSearch) }//lock } #endregion #region QueryTagEventNotifty void QueryTagEventNotifty(AW_API_NET.rfTagEvent_t tagEvent) { lock(myLock) { if (tagEvent.tag.id == srchTagID) { tagSrchStruct tagSrchObj = new tagSrchStruct(); tagSrchObj.host = tagEvent.host; tagSrchObj.reader = tagEvent.reader; tagSrchObj.fGen = tagEvent.fGenerator; tagSrchObj.rssi = tagEvent.RSSI; tagSrchList.Add(tagSrchObj); //if rdr exits in the rdrStatusList remove it and replace it otherwise add it. readerStatStruct readerObj = new readerStatStruct(tagEvent.reader); if (utility.GetRdrFromList (tagEvent.reader, ref readerObj, rdrStatusList)) { //make the timer to start processing startSearch = false; srchIndex = 0; counter = 0; readerStatStruct rdrStat = new readerStatStruct(tagEvent.reader); readerObj.Copy(ref rdrStat); rdrStatusList.Remove(readerObj); rdrStat.SetSrchStatus(true); rdrStatusList.Add(rdrStat); Console.WriteLine ("QueryTagNotify(TagSearchClass) ProcessSrchList time:" + DateTime.Now.ToString()); ProcessSrchList(); } }//if (tagEvent.tag.id == srchTagID) }//lock } #endregion #region PowerupReaderEventNotifty void PowerupReaderEventNotifty(AW_API_NET.rfReaderEvent_t readerEvent) { //populating rdrStat for polling rdr module //check if reader is on network lock(myLock) { string ip; if ((ip=utility.GetStringIP(readerEvent.ip)) != "") { //if ip exits in the rdrStatusList remove it and replace it otherwise add it. readerStatStruct readerObj = new readerStatStruct(readerEvent.reader); if (utility.GetRdrFromList (ip, ref readerObj, rdrStatusList)) rdrStatusList.Remove(readerObj); readerStatStruct rdrStat = new readerStatStruct(readerEvent.reader); rdrStat.hostID = readerEvent.host; rdrStat.SetIP(utility.GetStringIP(readerEvent.ip)); rdrStat.SetStatus(1); //online rdrStat.SetProcessing(false); rdrStatusList.Add(rdrStat); } } } #endregion #region SetSearchReader(ushort rdr) //application will set the reader to be a search rdr by looking at zone table, rdr type public void SetSearchReader(ushort rdr) { readerStatStruct readerObj = new readerStatStruct(rdr); if (utility.GetRdrFromList (rdr, ref readerObj, rdrStatusList)) { readerStatStruct readerObj2 = new readerStatStruct(rdr); readerObj.Copy(ref readerObj); rdrStatusList.Remove(readerObj); readerObj2.SetSearchReader(true); rdrStatusList.Add(readerObj2); } } #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. ==================================================================== */ namespace TestCases.SS.Formula.Functions { using NPOI.HSSF; using NPOI.SS.Formula.Eval; using NPOI.HSSF.UserModel; using NPOI.HSSF.Util; using NPOI.SS.UserModel; using System; using NUnit.Framework; using System.Text; using NPOI.SS.Util; using TestCases.Exceptions; using System.IO; using TestCases.HSSF; using NPOI.Util; /** * Tests lookup functions (VLOOKUP, HLOOKUP, LOOKUP, MATCH) as loaded from a Test data spreadsheet.<p/> * These Tests have been Separated from the common function and operator Tests because the lookup * functions have more complex Test cases and Test data Setup. * * Tests for bug fixes and specific/tricky behaviour can be found in the corresponding Test class * (<c>TestXxxx</c>) of the target (<c>Xxxx</c>) implementor, where execution can be observed * more easily. * * @author Josh Micich */ [TestFixture] public class TestLookupFunctionsFromSpreadsheet { private static class Result { public const int SOME_EVALUATIONS_FAILED = -1; public const int ALL_EVALUATIONS_SUCCEEDED = +1; public const int NO_EVALUATIONS_FOUND = 0; } /** * This class defines constants for navigating around the Test data spreadsheet used for these Tests. */ private static class SS { /** Name of the Test spreadsheet (found in the standard Test data folder) */ public static String FILENAME = "LookupFunctionsTestCaseData.xls"; /** Name of the first sheet in the spreadsheet (Contains comments) */ public static String README_SHEET_NAME = "Read Me"; /** Row (zero-based) in each sheet where the Evaluation cases start. */ public static int START_TEST_CASES_ROW_INDEX = 4; // Row '5' /** Index of the column that Contains the function names */ public static int COLUMN_INDEX_MARKER = 0; // Column 'A' public static int COLUMN_INDEX_EVALUATION = 1; // Column 'B' public static int COLUMN_INDEX_EXPECTED_RESULT = 2; // Column 'C' public static int COLUMN_ROW_COMMENT = 3; // Column 'D' /** Used to indicate when there are no more Test cases on the current sheet */ public static String TEST_CASES_END_MARKER = "<end>"; /** Used to indicate that the Test on the current row should be ignored */ public static String SKIP_CURRENT_TEST_CASE_MARKER = "<skip>"; } // Note - multiple failures are aggregated before ending. // If one or more functions fail, a single AssertionFailedError is thrown at the end private int _sheetFailureCount; private int _sheetSuccessCount; private int _EvaluationFailureCount; private int _EvaluationSuccessCount; private static void ConfirmExpectedResult(String msg, ICell expected, CellValue actual) { if (expected == null) { throw new AssertionException(msg + " - Bad Setup data expected value is null"); } if (actual == null) { throw new AssertionException(msg + " - actual value was null"); } if (expected.CellType == CellType.Error) { ConfirmErrorResult(msg, expected.ErrorCellValue, actual); return; } if (actual.CellType == CellType.Error) { throw unexpectedError(msg, expected, actual.ErrorValue); } if (actual.CellType != expected.CellType) { throw wrongTypeError(msg, expected, actual); } switch (expected.CellType) { case CellType.Boolean: Assert.AreEqual(expected.BooleanCellValue, actual.BooleanValue, msg); break; case CellType.Formula: // will never be used, since we will call method After formula Evaluation throw new InvalidOperationException("Cannot expect formula as result of formula Evaluation: " + msg); case CellType.Numeric: Assert.AreEqual(expected.NumericCellValue, actual.NumberValue, 0.0); break; case CellType.String: Assert.AreEqual(expected.RichStringCellValue.String, actual.StringValue, msg); break; } } private static AssertionException wrongTypeError(String msgPrefix, ICell expectedCell, CellValue actualValue) { return new AssertionException(msgPrefix + " Result type mismatch. Evaluated result was " + actualValue.FormatAsString() + " but the expected result was " + formatValue(expectedCell) ); } private static AssertionException unexpectedError(String msgPrefix, ICell expected, int actualErrorCode) { return new AssertionException(msgPrefix + " Error code (" + ErrorEval.GetText(actualErrorCode) + ") was Evaluated, but the expected result was " + formatValue(expected) ); } private static void ConfirmErrorResult(String msgPrefix, int expectedErrorCode, CellValue actual) { if (actual.CellType != CellType.Error) { throw new AssertionException(msgPrefix + " Expected cell error (" + ErrorEval.GetText(expectedErrorCode) + ") but actual value was " + actual.FormatAsString()); } if (expectedErrorCode != actual.ErrorValue) { throw new AssertionException(msgPrefix + " Expected cell error code (" + ErrorEval.GetText(expectedErrorCode) + ") but actual error code was (" + ErrorEval.GetText(actual.ErrorValue) + ")"); } } private static String formatValue(ICell expecedCell) { switch (expecedCell.CellType) { case CellType.Blank: return "<blank>"; case CellType.Boolean: return expecedCell.BooleanCellValue.ToString(); case CellType.Numeric: return expecedCell.NumericCellValue.ToString(); case CellType.String: return expecedCell.RichStringCellValue.String; } throw new RuntimeException("Unexpected cell type of expected value (" + expecedCell.CellType + ")"); } [SetUp] public void SetUp() { _sheetFailureCount = 0; _sheetSuccessCount = 0; _EvaluationFailureCount = 0; _EvaluationSuccessCount = 0; } [Test] public void TestFunctionsFromTestSpreadsheet() { HSSFWorkbook workbook = HSSFTestDataSamples.OpenSampleWorkbook(SS.FILENAME); ConfirmReadMeSheet(workbook); int nSheets = workbook.NumberOfSheets; for (int i = 1; i < nSheets; i++) { int sheetResult = ProcessTestSheet(workbook, i, workbook.GetSheetName(i)); switch (sheetResult) { case Result.ALL_EVALUATIONS_SUCCEEDED: _sheetSuccessCount++; break; case Result.SOME_EVALUATIONS_FAILED: _sheetFailureCount++; break; } } // confirm results String successMsg = "There were " + _sheetSuccessCount + " successful sheets(s) and " + _EvaluationSuccessCount + " function(s) without error"; if (_sheetFailureCount > 0) { String msg = _sheetFailureCount + " sheets(s) failed with " + _EvaluationFailureCount + " Evaluation(s). " + successMsg; throw new AssertionException(msg); } //if (false) //{ // normally no output for successful Tests // Console.WriteLine(this.GetType().Name + ": " + successMsg); //} } private int ProcessTestSheet(HSSFWorkbook workbook, int sheetIndex, String sheetName) { ISheet sheet = workbook.GetSheetAt(sheetIndex); HSSFFormulaEvaluator Evaluator = new HSSFFormulaEvaluator(workbook); int maxRows = sheet.LastRowNum + 1; int result = Result.NO_EVALUATIONS_FOUND; // so far String currentGroupComment = null; for (int rowIndex = SS.START_TEST_CASES_ROW_INDEX; rowIndex < maxRows; rowIndex++) { IRow r = sheet.GetRow(rowIndex); String newMarkerValue = GetMarkerColumnValue(r); if (r == null) { continue; } if (SS.TEST_CASES_END_MARKER.Equals(newMarkerValue, StringComparison.OrdinalIgnoreCase)) { // normal exit point return result; } if (SS.SKIP_CURRENT_TEST_CASE_MARKER.Equals(newMarkerValue, StringComparison.OrdinalIgnoreCase)) { // currently disabled Test case row continue; } if (newMarkerValue != null) { currentGroupComment = newMarkerValue; } ICell c = r.GetCell(SS.COLUMN_INDEX_EVALUATION); if (c == null || c.CellType != CellType.Formula) { continue; } CellValue actualValue = Evaluator.Evaluate(c); ICell expectedValueCell = r.GetCell(SS.COLUMN_INDEX_EXPECTED_RESULT); String rowComment = GetRowCommentColumnValue(r); String msgPrefix = FormatTestCaseDetails(sheetName, r.RowNum, c, currentGroupComment, rowComment); try { ConfirmExpectedResult(msgPrefix, expectedValueCell, actualValue); _EvaluationSuccessCount++; if (result != Result.SOME_EVALUATIONS_FAILED) { result = Result.ALL_EVALUATIONS_SUCCEEDED; } } catch (RuntimeException e) { _EvaluationFailureCount++; printshortStackTrace(System.Console.Error, e); result = Result.SOME_EVALUATIONS_FAILED; } catch (AssertionException e) { _EvaluationFailureCount++; printshortStackTrace(System.Console.Error, e); result = Result.SOME_EVALUATIONS_FAILED; } } throw new Exception("Missing end marker '" + SS.TEST_CASES_END_MARKER + "' on sheet '" + sheetName + "'"); } private static String FormatTestCaseDetails(String sheetName, int rowIndex, ICell c, String currentGroupComment, String rowComment) { StringBuilder sb = new StringBuilder(); CellReference cr = new CellReference(sheetName, rowIndex, c.ColumnIndex, false, false); sb.Append(cr.FormatAsString()); sb.Append(" {=").Append(c.CellFormula).Append("}"); if (currentGroupComment != null) { sb.Append(" '"); sb.Append(currentGroupComment); if (rowComment != null) { sb.Append(" - "); sb.Append(rowComment); } sb.Append("' "); } else { if (rowComment != null) { sb.Append(" '"); sb.Append(rowComment); sb.Append("' "); } } return sb.ToString(); } /** * Asserts that the 'read me' comment page exists, and has this class' name in one of the * cells. This back-link is to make it easy to find this class if a Reader encounters the * spreadsheet first. */ private void ConfirmReadMeSheet(HSSFWorkbook workbook) { String firstSheetName = workbook.GetSheetName(0); if (!firstSheetName.Equals(SS.README_SHEET_NAME, StringComparison.OrdinalIgnoreCase)) { throw new RuntimeException("First sheet's name was '" + firstSheetName + "' but expected '" + SS.README_SHEET_NAME + "'"); } ISheet sheet = workbook.GetSheetAt(0); String specifiedClassName = sheet.GetRow(2).GetCell(0).RichStringCellValue.String; Assert.AreEqual("org.apache.poi.ss.formula.functions.TestLookupFunctionsFromSpreadsheet", specifiedClassName, "Test class name in spreadsheet comment"); } /** * Useful to keep output concise when expecting many failures to be reported by this Test case */ private static void printshortStackTrace(TextWriter ps, Exception e) { ps.WriteLine(e.Message); ps.WriteLine(e.StackTrace); //StackTraceElement[] stes = e.GetStackTrace(); //int startIx = 0; //// skip any top frames inside junit.framework.Assert //while(startIx<stes.Length) { // if(!stes[startIx].GetClassName().Equals(Assert.class.GetName())) { // break; // } // startIx++; //} //// skip bottom frames (part of junit framework) //int endIx = startIx+1; //while(endIx < stes.Length) { // if(stes[endIx].GetClassName().Equals(TestCase.class.GetName())) { // break; // } // endIx++; //} //if(startIx >= endIx) { // // something went wrong. just print the whole stack trace // e.printStackTrace(ps); //} //endIx -= 4; // skip 4 frames of reflection invocation //ps.println(e.ToString()); //for(int i=startIx; i<endIx; i++) { // ps.println("\tat " + stes[i].ToString()); //} } private static String GetRowCommentColumnValue(IRow r) { return GetCellTextValue(r, SS.COLUMN_ROW_COMMENT, "row comment"); } private static String GetMarkerColumnValue(IRow r) { return GetCellTextValue(r, SS.COLUMN_INDEX_MARKER, "marker"); } /** * @return <code>null</code> if cell is missing, empty or blank */ private static String GetCellTextValue(IRow r, int colIndex, String columnName) { if (r == null) { return null; } ICell cell = r.GetCell(colIndex); if (cell == null) { return null; } if (cell.CellType == CellType.Blank) { return null; } if (cell.CellType == CellType.String) { return cell.RichStringCellValue.String; } throw new RuntimeException("Bad cell type for '" + columnName + "' column: (" + cell.CellType + ") row (" + (r.RowNum + 1) + ")"); } } }
// 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. #if CONTRACTS_EXPERIMENTAL using System; using System.Text; using System.Collections.Generic; using Microsoft.Research.AbstractDomains; using Microsoft.Research.AbstractDomains.Numerical; using Microsoft.Research.AbstractDomains.Expressions; using Microsoft.Research.DataStructures; using Microsoft.Research.CodeAnalysis; namespace Microsoft.Research.AbstractDomains { public interface IArrayAbstraction<Variable, Expression> : IAbstractDomain, IAssignInParallel<Variable, Expression> { IArrayAbstraction<Variable, Expression> ArrayUnknown(Set<int> dimensions, ExpressionType type); IArrayAbstraction<Variable, Expression> TestTrue(int dimension, Expression constraint); IArrayAbstraction<Variable, Expression> Transform(Dictionary<int, Set<int>> transformationMap); IArrayAbstraction<Variable, Expression> Assign(int dimension, TouchKind kind, Variable dest, Variable value); //IArrayAbstraction<Variable, Expression> Simplify(Expression exp); } public class FakeAbstractDomain<Variable, Expression> : FlatAbstractDomain<Expression>, IAbstractDomainForEnvironments<Variable, Expression> { private IExpressionDecoder<Variable, Expression> decoder; public FakeAbstractDomain(IExpressionDecoder<Variable, Expression> decoder) : base (State.Top) { this.decoder = decoder; } public FakeAbstractDomain(FakeAbstractDomain<Variable, Expression> source) { this.decoder = source.decoder; this.state = source.state; } public override object Clone() { return new FakeAbstractDomain<Variable, Expression>(this); } #region IAbstractDomainForEnvironments<Variable, Expression> Members public string ToString(Expression exp) { return "FAKE"; } #endregion #region IPureExpressionAssignments<Expression> Members public Set<Variable> Variables { get { return new Set<Variable>(); } } public void AddVariable(Variable var) { return; } public void Assign(Expression x, Expression exp) { return; } public void ProjectVariable(Variable var) { return; } public void RemoveVariable(Variable var) { return; } public void RenameVariable(Variable OldName, Variable NewName) { return; } #endregion #region IPureExpressionTest<Expression> Members public IAbstractDomainForEnvironments<Variable, Expression> TestTrue(Expression guard) { // TODO: if guard is unsat if(this.decoder.IsConstant(guard) && (this.decoder.TypeOf(guard) == ExpressionType.Bool)) { var b = (Boolean)this.decoder.Constant(guard); if (!b) { this.state = State.Bottom; } } return this; } public IAbstractDomainForEnvironments<Variable, Expression> TestFalse(Expression guard) { return this; } public FlatAbstractDomain<bool> CheckIfHolds(Expression exp) { return new FlatAbstractDomain<bool>(true).Top; } #endregion #region IAssignInParallel<Expression> Members public void AssignInParallel(Dictionary<Variable, FList<Variable>> sourcesToTargets, Converter<Variable, Expression> converter) { return; } #endregion } public class SimpleArrayPropertiesAbstractDomain<Variable, Expression> : FunctionalAbstractDomain<SimpleArrayPropertiesAbstractDomain<Variable, Expression>, Variable, IArrayAbstraction<Variable, Expression>>, IAbstractDomainForEnvironments<Variable, Expression> { #region Private State IArrayAbstraction<Variable, Expression> arrayAbstractor; IExpressionDecoder<Variable, Expression> decoder; IExpressionEncoder<Variable, Expression> encoder; #endregion #region Constructors public SimpleArrayPropertiesAbstractDomain(IExpressionEncoder<Variable, Expression> encoder, IExpressionDecoder<Variable, Expression> decoder) : base() { this.arrayAbstractor = new SimpleArrayAbstraction<Variable, Expression>(encoder, decoder); this.encoder = encoder; this.decoder = decoder; } public SimpleArrayPropertiesAbstractDomain(SimpleArrayPropertiesAbstractDomain<Variable, Expression> source) : base(source) { this.arrayAbstractor = source.arrayAbstractor; this.encoder = source.encoder; this.decoder = source.decoder; } #endregion #region From FunctionalAbstractDomain public override object Clone() { return new SimpleArrayPropertiesAbstractDomain<Variable, Expression>(this); } protected override SimpleArrayPropertiesAbstractDomain<Variable, Expression> Factory() { return new SimpleArrayPropertiesAbstractDomain<Variable, Expression>(this.encoder, this.decoder); } protected override string ToLogicalFormula(Variable d, IArrayAbstraction<Variable, Expression> c) { // TODO return null; } protected override T To<T>(Variable d, IArrayAbstraction<Variable, Expression> c, IFactory<T> factory) { // TODO return factory.Constant(true); } public override SimpleArrayPropertiesAbstractDomain<Variable, Expression> Join(SimpleArrayPropertiesAbstractDomain<Variable, Expression> right) { //// Here we do not have trivial joins as we want to join maps of different cardinality //if (this.IsBottom) // return right; //if (right.IsBottom) // return (SimpleArrayPropertiesAbstractDomain<Variable, Expression>)this; //SimpleArrayPropertiesAbstractDomain<Variable, Expression> result = this.Factory(); //foreach (var x in this.Keys) // For all the elements in the intersection do the point-wise join //{ // IArrayAbstraction<Variable, Expression> right_x; // if (right.TryGetValue(x, out right_x)) // { // var join = this[x].Join(right_x); // //if (!join.IsTop) // { // We keep in the map only the elements that are != top // //result[x] = (Codomain)join; // result.AddElement(x, (IArrayAbstraction<Variable, Expression>)join); // } // } //} //return result; return this.Join(right, new Set<Variable>()); } public SimpleArrayPropertiesAbstractDomain<Variable, Expression> Join(SimpleArrayPropertiesAbstractDomain<Variable, Expression> right, Set<Variable> keep) { // Here we do not have trivial joins as we want to join maps of different cardinality if (this.IsBottom) return right; if (right.IsBottom) return this; var result = this.Factory(); foreach (var x in this.Keys) // For all the elements in the intersection do the point-wise join { IArrayAbstraction<Variable, Expression> right_x; if (right.TryGetValue(x, out right_x)) { var join = this[x].Join(right_x); //if (!join.IsTop) { // We keep in the map only the elements that are != top //result[x] = (Codomain)join; result.AddElement(x, (IArrayAbstraction<Variable, Expression>)join); } } else { if (keep.Contains(x)) { result.AddElement(x, this[x]); } keep.Remove(x); } } foreach (var x in keep) { if (!result.ContainsKey(x)) { result.AddElement(x, right[x]); } } return result; } #endregion #region IPureExpressionAssignmentsWithForward<Expression> Members public void Assign(Expression x, Expression exp) { throw new NotImplementedException(); } #endregion #region IPureExpressionAssignments<Expression> Members public Set<Variable> Variables { get { return new Set<Variable>(this.Keys); } } public void AddVariable(Variable var) { // do nothing // TODO } public void ProjectVariable(Variable var) { // TODO: project also in other arrays the corresponding slice variables this.RemoveVariable(var); } public void RemoveVariable(Variable var) { // TODO: see above this.RemoveElement(var); } public void RenameVariable(Variable OldName, Variable NewName) { // TODO: see above this[NewName] = this[OldName]; this.RemoveVariable(OldName); } #endregion #region IPureExpressionTest<Expression> Members public IAbstractDomainForEnvironments<Variable, Expression>/*!*/ TestTrue(Expression/*!*/ guard) { return this; //TODO!! } public IAbstractDomainForEnvironments<Variable, Expression>/*!*/ TestFalse(Expression/*!*/ guard) { return this; //TODO!! } public FlatAbstractDomain<bool> CheckIfHolds(Expression/*!*/ exp) { return new FlatAbstractDomain<bool>(true).Top; //TODO!! } #endregion #region IAssignInParallel<Expression> Members public void AssignInParallel(Dictionary<Variable, FList<Variable>> sourcesToTargets, Converter<Variable, Expression> converter) { // TODO : this code can be factored with the one in SimplePartitionAbstractDomain.AssignInParallel if (this.IsBottom) { return; } //make easier the in-place computation var result = new Dictionary<Variable, IArrayAbstraction<Variable, Expression>>(); var multipleAssignedVariables = new Dictionary<Variable, FList<Variable>>(); // consider the functional mapping renamings foreach (var source in this.Variables) { if (!sourcesToTargets.ContainsKey(source)) { continue; } var targetsList = sourcesToTargets[source]; if (targetsList.Length() > 1) { multipleAssignedVariables.Add(targetsList.Head, targetsList.Tail); } IArrayAbstraction<Variable, Expression> value; if (this.TryGetValue(source, out value)) { var target = targetsList.Head; if (result.ContainsKey(target)) { throw new AbstractInterpretationException("Assign in parallel not consistent"); } result[target] = (IArrayAbstraction<Variable, Expression>)value.Clone(); } else { throw new AbstractInterpretationException("elements changed during foreach"); } } // consider the inside array properties renaming foreach (var p in result) { (p.Value).AssignInParallel(sourcesToTargets, converter); } // handling the multiple assignements: copy foreach (var e in multipleAssignedVariables) { foreach (var target in e.Value.GetEnumerable()) { result[target] = (IArrayAbstraction<Variable, Expression>)result[e.Key].Clone(); } } this.SetElements(result); return; } #endregion #region IAbstractDomainForEnvironments public string ToString(Expression exp) { //if (this.decoder != null) //{ // return ExpressionPrinter.ToString(exp, this.decoder); //} //else //{ // return "< missing expression decoder >"; //} throw new NotImplementedException(); } #endregion public void TransformArray(Variable array, Dictionary<int, Set<int>> transformationMap) { if (!ContainsKey(array)) { throw new AbstractInterpretationException(); } var arrayAbstraction = this[array]; arrayAbstraction = arrayAbstraction.Transform(transformationMap); this[array] = arrayAbstraction; return; } public void SimplifyArray(Variable array, Set<int> emptyDimensions) { if (!ContainsKey(array)) { throw new AbstractInterpretationException(); } var arrayAbstraction = this[array]; var falseConstraint = this.encoder.ConstantFor(false); //var falseConstraint = this.encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Equal, this.encoder.ConstantFor(0), this.encoder.ConstantFor(1)); foreach (var dimension in emptyDimensions) { arrayAbstraction = arrayAbstraction.TestTrue(dimension, falseConstraint); } this[array] = arrayAbstraction; return; } public void CreateArray(Variable array, Set<int> dimensions, int bodyDimension, Expression defaultValue) { if (ContainsKey(array)) { throw new AbstractInterpretationException(); } IArrayAbstraction<Variable, Expression> arrayAbstraction; if (defaultValue != null) { arrayAbstraction = this.arrayAbstractor.ArrayUnknown(dimensions, this.decoder.TypeOf(defaultValue)); var bodyConstraint = this.encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Equal, this.encoder.VariableFor(array), defaultValue); arrayAbstraction = arrayAbstraction.TestTrue(bodyDimension, bodyConstraint); } else { arrayAbstraction = this.arrayAbstractor.ArrayUnknown(dimensions, ExpressionType.Unknown); } var falseConstraint = this.encoder.ConstantFor(false); //var falseConstraint = this.encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Equal, this.encoder.ConstantFor(0), this.encoder.ConstantFor(1)); var b = dimensions.Remove(bodyDimension); foreach (var dim in dimensions) { arrayAbstraction = arrayAbstraction.TestTrue(dim, falseConstraint); //var WORKAROUNDTOMAKEEMPTYOCTAGONSBOTTOMOCTAGONS = arrayAbstraction.ToString(); } this.AddElement(array, arrayAbstraction); return; } public void HandleArrayAssignment(Variable array, Set<Pair<int,TouchKind>> touchedDimensions, Variable value) { if (!ContainsKey(array)) { throw new AbstractInterpretationException(); } foreach (var e in touchedDimensions) { this[array].Assign(e.One, e.Two, array, value); } return; } } //public class SimpleArrayAbstractDomain<Variable, Expression> : //t-maper@56: ,AbstractPartitionDomain<Expression> //ReducedCartesianAbstractDomain<INumericalAbstractDomain<Variable, Expression>, AbstractPartitionDomain>, //ReducedCartesianAbstractDomain<INumericalAbstractDomain<Variable, Expression>, FunctionalAbstractDomain<,Expression,<FunctionalAbstractDomain<AbstractPartitionDomain, IAbstractDomain>>>, //IAbstractDomain //t-maper@54: Do I need to introduce a particular type of abstract domain?IArrayAbstraction<IPartitionAbstractDomain, Expression> public class SimpleArrayAbstractDomain<Variable, Expression> : ReducedCartesianAbstractDomain<INumericalAbstractDomain<Variable, Expression>, SimpleArrayPropertiesAbstractDomain<Variable, Expression>>, IAbstractDomainForEnvironments<Variable, Expression> { #region Private State IExpressionDecoder<Variable, Expression>/*!*/ decoder; IExpressionEncoder<Variable, Expression>/*!*/ encoder; #endregion #region Constructors public SimpleArrayAbstractDomain(INumericalAbstractDomain<Variable, Expression> indexes, SimpleArrayPropertiesAbstractDomain<Variable, Expression> contents) : base(indexes, contents) { } public SimpleArrayAbstractDomain(INumericalAbstractDomain<Variable, Expression> indexes, SimpleArrayPropertiesAbstractDomain<Variable, Expression> contents, IExpressionDecoder<Variable, Expression> decoder, IExpressionEncoder<Variable, Expression> encoder) : base(indexes, contents) { this.encoder = encoder; this.decoder = decoder; } #endregion #region ReducedCartesianAbstractDomain protected override ReducedCartesianAbstractDomain<INumericalAbstractDomain<Variable, Expression>, SimpleArrayPropertiesAbstractDomain<Variable, Expression>> Factory(INumericalAbstractDomain<Variable, Expression> left, SimpleArrayPropertiesAbstractDomain<Variable, Expression> right) { // TODO return new SimpleArrayAbstractDomain<Variable, Expression>(left, right, this.decoder, this.encoder); } public override ReducedCartesianAbstractDomain<INumericalAbstractDomain<Variable, Expression>, SimpleArrayPropertiesAbstractDomain<Variable, Expression>> Reduce(INumericalAbstractDomain<Variable, Expression> left, SimpleArrayPropertiesAbstractDomain<Variable, Expression> right) { if (left.IsBottom) { return (SimpleArrayAbstractDomain<Variable, Expression>)this.Bottom; } return new SimpleArrayAbstractDomain<Variable, Expression>(left, right, this.decoder, this.encoder); } public override IAbstractDomain Widening(IAbstractDomain prev) { var previous = (SimpleArrayAbstractDomain<Variable, Expression>)prev; var leftWidened = (INumericalAbstractDomain<Variable, Expression>)this.Left.Widening(previous.Left); var rightWidened = (SimpleArrayPropertiesAbstractDomain<Variable, Expression>)this.Right.Widening(previous.Right); var widened = new SimpleArrayAbstractDomain<Variable, Expression>(leftWidened, rightWidened); return (IAbstractDomain)widened; } #endregion #region IPureExpressionAssignmentsWithForward public void Assign(Expression x, Expression exp) { throw new NotImplementedException(); } #endregion #region IPureExpressionAssignments public Set<Variable> Variables { get { var leftVariables = new Set<Variable>(this.Left.Variables); return leftVariables.Union(this.Right.Variables); } } public void AddVariable(Variable var) { } public void ProjectVariable(Variable var) { } public void RemoveVariable(Variable var) { } public void RenameVariable(Variable OldName, Variable NewName) { // F: Why it is a nop???? } #endregion #region IPureExpressionTest public IAbstractDomainForEnvironments<Variable, Expression> TestTrue(Expression guard) { var leftTested = (INumericalAbstractDomain<Variable, Expression>)this.Left.TestTrue(guard); var rightTested = (SimpleArrayPropertiesAbstractDomain<Variable, Expression>)this.Right.TestTrue(guard); return (IAbstractDomainForEnvironments<Variable, Expression>)this.Reduce(leftTested, rightTested); } public IAbstractDomainForEnvironments<Variable, Expression> TestFalse(Expression guard) { var leftTested = (INumericalAbstractDomain<Variable, Expression>)this.Left.TestFalse(guard); var rightTested = (SimpleArrayPropertiesAbstractDomain<Variable, Expression>)this.Right.TestFalse(guard); return (IAbstractDomainForEnvironments<Variable, Expression>)this.Reduce(leftTested, rightTested); } public FlatAbstractDomain<bool> CheckIfHolds(Expression exp) { return new FlatAbstractDomain<bool>(true).Top; //throw new NotImplementedException(); } #endregion public SimpleArrayAbstractDomain<Variable, Expression> Join(SimpleArrayAbstractDomain<Variable, Expression> a, Set<Variable> keep) { SimpleArrayAbstractDomain<Variable, Expression> result; if (AbstractDomainsHelper.TryTrivialJoin(this, a, out result)) { return result; } var joinLeftPart = (INumericalAbstractDomain<Variable, Expression>)this.Left.Join(a.Left); var joinRightPart = this.Right.Join(a.Right, keep); return (SimpleArrayAbstractDomain<Variable, Expression>)this.Reduce(joinLeftPart, joinRightPart); } #region IAssignInParallel public void AssignInParallel(Dictionary<Variable, FList<Variable>> sourcesToTargets, Converter<Variable, Expression> convert) { // NOTE : not called if (this.IsBottom) return; this.Left.AssignInParallel(sourcesToTargets, convert); this.Right.AssignInParallel(sourcesToTargets, convert); return; } #endregion #region ToString public string ToString(Expression exp) { if (this.decoder != null) { return ExpressionPrinter.ToString(exp, this.decoder); } else { return "< missing expression decoder >"; } } #endregion } public class SimpleArrayAbstraction<Variable, Expression> : IArrayAbstraction<Variable, Expression> { #region Private Variables protected Dictionary<int, IAbstractDomainForEnvironments<Variable, Expression>> content; protected IExpressionEncoder<Variable, Expression> encoder; protected IExpressionDecoder<Variable, Expression> decoder; #endregion #region Constructors public SimpleArrayAbstraction(IExpressionEncoder<Variable, Expression> encoder, IExpressionDecoder<Variable, Expression> decoder) { this.encoder = encoder; this.decoder = decoder; this.content = new Dictionary<int, IAbstractDomainForEnvironments<Variable, Expression>>(); } public SimpleArrayAbstraction(SimpleArrayAbstraction<Variable, Expression> source) { this.encoder = source.encoder; this.decoder = source.decoder; this.content = new Dictionary<int, IAbstractDomainForEnvironments<Variable, Expression>>(source.content); } #endregion public IArrayAbstraction<Variable, Expression> ArrayUnknown(Set<int> dimensions, ExpressionType type) { var result = new SimpleArrayAbstraction<Variable, Expression>(this.encoder,this.decoder); IAbstractDomainForEnvironments<Variable, Expression> topProperty; switch (type) { case ExpressionType.Int8: case ExpressionType.Int16: case ExpressionType.Int32: case ExpressionType.Int64: case ExpressionType.UInt8: case ExpressionType.UInt16: case ExpressionType.UInt32: topProperty = new OctagonEnvironment<Variable, Expression>(this.decoder, this.encoder, OctagonEnvironment<Variable, Expression>.OctagonPrecision.FullPrecision); break; default: topProperty = new FakeAbstractDomain<Variable, Expression>(this.decoder); break; } foreach (var dim in dimensions) { result.content.Add(dim, (IAbstractDomainForEnvironments<Variable, Expression>)topProperty.Clone()); } return (IArrayAbstraction<Variable, Expression>)result; } public IArrayAbstraction<Variable, Expression> TestTrue(int dimension, Expression constraint) { //var result = new SimpleArrayAbstraction<Variable, Expression>(this); this.content[dimension] = this.content[dimension].TestTrue(constraint); return this; } public IArrayAbstraction<Variable, Expression> Transform(Dictionary<int, Set<int>> transformationMap) { var result = new SimpleArrayAbstraction<Variable, Expression>(this.encoder, this.decoder); foreach (var e in transformationMap) { var dimensionsEnumerator = e.Value.GetEnumerator(); if (dimensionsEnumerator.MoveNext()) { IAbstractDomainForEnvironments<Variable, Expression> aProperty; if (this.content.TryGetValue(dimensionsEnumerator.Current, out aProperty)) { var property = (IAbstractDomainForEnvironments<Variable, Expression>)aProperty.Clone(); while (dimensionsEnumerator.MoveNext()) { if (this.content.TryGetValue(dimensionsEnumerator.Current, out aProperty)) { property = (IAbstractDomainForEnvironments<Variable, Expression>)property.Join(aProperty); } else { throw new AbstractInterpretationException("incorrect transformation map"); } } result.content.Add(e.Key, property); } else { throw new AbstractInterpretationException("incorrect transformation map"); } } else { throw new AbstractInterpretationException("incorrect transformation map"); } } return result; } #region Lattice elements and operators public SimpleArrayAbstraction<Variable, Expression> Bottom { get { //This bottom = this.Factory(); //var topSlice = this.oneSlice.Top; //bottom.content.Add((SliceAbstractDomain)topSlice.Clone()); //return bottom; throw new NotImplementedException(); } } public SimpleArrayAbstraction<Variable, Expression> Top { get { return new SimpleArrayAbstraction<Variable, Expression>(this.encoder, this.decoder); } } /// <summary> /// Order ... /// </summary> /// public bool LessEqual(SimpleArrayAbstraction<Variable, Expression> right) { bool result; if (AbstractDomainsHelper.TryTrivialLessEqual(this, right, out result)) { return result; } foreach (var e in this.content) { IAbstractDomainForEnvironments<Variable, Expression> rightProperty; var leftProperty = e.Value; if (right.content.TryGetValue(e.Key, out rightProperty)) { if (!leftProperty.LessEqual(rightProperty)) { return false; } } else { throw new AbstractInterpretationException(); } } return true; } public SimpleArrayAbstraction<Variable, Expression> Join(SimpleArrayAbstraction<Variable, Expression> right) { SimpleArrayAbstraction<Variable, Expression> trivialResult; if (AbstractDomainsHelper.TryTrivialJoin(this, right, out trivialResult)) { return trivialResult; } SimpleArrayAbstraction<Variable, Expression> result = new SimpleArrayAbstraction<Variable, Expression>(this.encoder, this.decoder); foreach (var e in this.content) { IAbstractDomainForEnvironments<Variable, Expression> rightProperty; var leftProperty = e.Value; if (right.content.TryGetValue(e.Key, out rightProperty)) { result.content.Add(e.Key, (IAbstractDomainForEnvironments<Variable, Expression>)leftProperty.Join(rightProperty)); } else { throw new AbstractInterpretationException(); } } return result; } public SimpleArrayAbstraction<Variable, Expression> Meet(SimpleArrayAbstraction<Variable, Expression> right) { SimpleArrayAbstraction<Variable, Expression> trivialResult; if (AbstractDomainsHelper.TryTrivialMeet(this, right, out trivialResult)) { return trivialResult; } var result = new SimpleArrayAbstraction<Variable, Expression>(this.encoder, this.decoder); foreach (var e in this.content) { IAbstractDomainForEnvironments<Variable, Expression> rightProperty; var leftProperty = e.Value; if (right.content.TryGetValue(e.Key, out rightProperty)) { result.content.Add(e.Key, (IAbstractDomainForEnvironments<Variable, Expression>)leftProperty.Meet(rightProperty)); } else { throw new AbstractInterpretationException(); } } return result; } #endregion #region IAbstractDomain Members /// <summary> /// TODO /// </summary> public bool IsBottom { get { // TODO return false; } } /// <summary> /// TODO /// </summary> public bool IsTop { get { foreach (var property in this.content.Values) { if (!property.IsTop) { return false; } } return true; } } public bool LessEqual(IAbstractDomain a) { return this.LessEqual((SimpleArrayAbstraction<Variable, Expression>)a); } IAbstractDomain IAbstractDomain.Bottom { get { return this.Bottom; } } IAbstractDomain IAbstractDomain.Top { get { return this.Top; } } IAbstractDomain/*!*/ IAbstractDomain.Join(IAbstractDomain/*!*/ a) { return this.Join((SimpleArrayAbstraction<Variable, Expression>)a); } IAbstractDomain/*!*/ IAbstractDomain.Meet(IAbstractDomain/*!*/ a) { return this.Meet((SimpleArrayAbstraction<Variable, Expression>)a); } IAbstractDomain/*!*/ IAbstractDomain.Widening(IAbstractDomain/*!*/ prev) { return this.Join((SimpleArrayAbstraction<Variable, Expression>)prev); } public string ToRewritingRule() { return null; } public T To<T>(IFactory<T> factory) { return factory.Constant(true); } #endregion #region ICloneable Members public object Clone() { return new SimpleArrayAbstraction<Variable, Expression>(this); } #endregion #region IAssignInParallel<Expression> Members public void AssignInParallel(Dictionary<Variable, FList<Variable>> sourcesToTargets, Converter<Variable, Expression> convert) { // TODO: this code can be factored with SimplePartitionAbstractionFactory.PartialAssignInParallel(...) var multipleAssignedVariables = new Dictionary<Variable, FList<Variable>>(); foreach (var e in sourcesToTargets) { if (e.Value.Length() > 1) { multipleAssignedVariables.Add(e.Key, e.Value); } } foreach (var arrayProperty in this.content.Values) { if (!arrayProperty.IsBottom) { var originalVariables = arrayProperty.Variables; arrayProperty.AssignInParallel(sourcesToTargets, convert); // removing variables introduced by the treatment of assignment to multiple variables foreach (var e in multipleAssignedVariables) { if (!originalVariables.Contains(e.Key)) { foreach (var v in e.Value.GetEnumerable()) { arrayProperty.RemoveVariable(v); } } else { // TODO? } } } } return; } #endregion public IArrayAbstraction<Variable, Expression> Assign(int dimension, TouchKind kind, Variable dest, Variable value) { if (this.content.ContainsKey(dimension)) { Expression destExp, valueExp; switch (kind) { case TouchKind.Strong: destExp = this.encoder.VariableFor(dest); valueExp = this.encoder.VariableFor(value); this.content[dimension].Assign(destExp, valueExp); break; case TouchKind.Weak: var result = (IAbstractDomainForEnvironments<Variable, Expression>)this.content[dimension].Top.Clone(); destExp = this.encoder.VariableFor(dest); valueExp = this.encoder.VariableFor(value); result.Assign(destExp, valueExp); this.content[dimension] = (IAbstractDomainForEnvironments<Variable, Expression>)this.content[dimension].Join(result); break; } } else { throw new AbstractInterpretationException(); } return (IArrayAbstraction<Variable, Expression>)this; } #region ToString public override string ToString() { string result; if (this.IsBottom) { result = "_|_"; } else if (this.IsTop) { result = "Top"; } else { StringBuilder tempStr = new StringBuilder(); foreach (var e in this.content) { //string xAsString = this.decoder != null ? this.decoder.NameOf(x) : x.ToString(); tempStr.Append(e.Key + ":" + e.Value + ";"); } result = tempStr.ToString(); int indexOfLastComma = result.LastIndexOf(";"); if (indexOfLastComma > 0) { result = result.Remove(indexOfLastComma); } } return result; } #endregion } } #endif
// // CryptoConfigTest.cs - NUnit Test Cases for CryptoConfig // // Author: // Sebastien Pouliot <[email protected]> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Security.Cryptography; namespace MonoTests.System.Security.Cryptography { [TestFixture] public class CryptoConfigTest { void CreateFromName (string name, string objectname) { object o = CryptoConfig.CreateFromName (name); if (objectname == null) Assert.IsNull (o, name); else Assert.AreEqual (objectname, o.ToString (), name); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void CreateFromNameNull () { object o = CryptoConfig.CreateFromName (null); } // validate that CryptoConfig create the exact same implementation between mono and MS [Test] public void CreateFromName () { CreateFromName ("SHA", "System.Security.Cryptography.SHA1CryptoServiceProvider"); // FIXME: We need to support the machine.config file to get exact same results // with the MS .NET Framework CreateFromName ("SHA1", "System.Security.Cryptography.SHA1CryptoServiceProvider"); CreateFromName( "System.Security.Cryptography.SHA1", "System.Security.Cryptography.SHA1CryptoServiceProvider"); // after installing the WSDK - changes to the machine.config file (not documented) // CreateFromName ("SHA1", "System.Security.Cryptography.SHA1Managed"); // CreateFromName ("System.Security.Cryptography.SHA1", "System.Security.Cryptography.SHA1Managed"); CreateFromName ("System.Security.Cryptography.HashAlgorithm", "System.Security.Cryptography.SHA1CryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.SHA1CryptoServiceProvider", "System.Security.Cryptography.SHA1CryptoServiceProvider"); CreateFromName ("MD5", "System.Security.Cryptography.MD5CryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.MD5", "System.Security.Cryptography.MD5CryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.MD5CryptoServiceProvider", "System.Security.Cryptography.MD5CryptoServiceProvider"); CreateFromName ("SHA256", "System.Security.Cryptography.SHA256Managed"); CreateFromName ("SHA-256", "System.Security.Cryptography.SHA256Managed"); CreateFromName ("System.Security.Cryptography.SHA256", "System.Security.Cryptography.SHA256Managed"); CreateFromName ("SHA384", "System.Security.Cryptography.SHA384Managed"); CreateFromName ("SHA-384", "System.Security.Cryptography.SHA384Managed"); CreateFromName ("System.Security.Cryptography.SHA384", "System.Security.Cryptography.SHA384Managed"); CreateFromName ("SHA512", "System.Security.Cryptography.SHA512Managed"); CreateFromName ("SHA-512", "System.Security.Cryptography.SHA512Managed"); CreateFromName ("System.Security.Cryptography.SHA512", "System.Security.Cryptography.SHA512Managed"); CreateFromName ("RSA", "System.Security.Cryptography.RSACryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.RSA", "System.Security.Cryptography.RSACryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.AsymmetricAlgorithm", "System.Security.Cryptography.RSACryptoServiceProvider"); CreateFromName ("DSA", "System.Security.Cryptography.DSACryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.DSA", "System.Security.Cryptography.DSACryptoServiceProvider"); CreateFromName ("DES", "System.Security.Cryptography.DESCryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.DES", "System.Security.Cryptography.DESCryptoServiceProvider"); CreateFromName ("3DES", "System.Security.Cryptography.TripleDESCryptoServiceProvider"); CreateFromName ("TripleDES", "System.Security.Cryptography.TripleDESCryptoServiceProvider"); CreateFromName ("Triple DES", "System.Security.Cryptography.TripleDESCryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.TripleDES", "System.Security.Cryptography.TripleDESCryptoServiceProvider"); // LAMESPEC SymmetricAlgorithm documented as TripleDESCryptoServiceProvider CreateFromName ("System.Security.Cryptography.SymmetricAlgorithm", "System.Security.Cryptography.RijndaelManaged"); CreateFromName ("RC2", "System.Security.Cryptography.RC2CryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.RC2", "System.Security.Cryptography.RC2CryptoServiceProvider"); CreateFromName ("Rijndael", "System.Security.Cryptography.RijndaelManaged"); CreateFromName ("System.Security.Cryptography.Rijndael", "System.Security.Cryptography.RijndaelManaged"); // LAMESPEC Undocumented Names in CryptoConfig CreateFromName ("RandomNumberGenerator", "System.Security.Cryptography.RNGCryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.RandomNumberGenerator", "System.Security.Cryptography.RNGCryptoServiceProvider"); CreateFromName ("System.Security.Cryptography.KeyedHashAlgorithm", "System.Security.Cryptography.HMACSHA1"); CreateFromName ("HMACSHA1", "System.Security.Cryptography.HMACSHA1"); CreateFromName ("System.Security.Cryptography.HMACSHA1", "System.Security.Cryptography.HMACSHA1"); CreateFromName ("MACTripleDES", "System.Security.Cryptography.MACTripleDES"); CreateFromName ("System.Security.Cryptography.MACTripleDES", "System.Security.Cryptography.MACTripleDES"); #if NET_2_0 // new HMAC - new base class doesn't return anything with it's short name Assert.IsNull (CryptoConfig.CreateFromName ("HMAC"), "HMAC"); CreateFromName ("System.Security.Cryptography.HMAC", "System.Security.Cryptography.HMACSHA1"); CreateFromName ("HMACMD5", "System.Security.Cryptography.HMACMD5"); CreateFromName ("System.Security.Cryptography.HMACMD5", "System.Security.Cryptography.HMACMD5"); CreateFromName ("HMACRIPEMD160", "System.Security.Cryptography.HMACRIPEMD160"); CreateFromName ("System.Security.Cryptography.HMACRIPEMD160", "System.Security.Cryptography.HMACRIPEMD160"); CreateFromName ("HMACSHA256", "System.Security.Cryptography.HMACSHA256"); CreateFromName ("System.Security.Cryptography.HMACSHA256", "System.Security.Cryptography.HMACSHA256"); CreateFromName ("HMACSHA384", "System.Security.Cryptography.HMACSHA384"); CreateFromName ("System.Security.Cryptography.HMACSHA384", "System.Security.Cryptography.HMACSHA384"); CreateFromName ("HMACSHA512", "System.Security.Cryptography.HMACSHA512"); CreateFromName ("System.Security.Cryptography.HMACSHA512", "System.Security.Cryptography.HMACSHA512"); // new hash algorithm CreateFromName ("RIPEMD160", "System.Security.Cryptography.RIPEMD160Managed"); CreateFromName ("RIPEMD-160", "System.Security.Cryptography.RIPEMD160Managed"); CreateFromName ("System.Security.Cryptography.RIPEMD160", "System.Security.Cryptography.RIPEMD160Managed"); #endif // note: CryptoConfig can create any object ! CreateFromName ("System.Security.Cryptography.CryptoConfig", "System.Security.Cryptography.CryptoConfig"); CreateFromName ("System.IO.MemoryStream", "System.IO.MemoryStream"); // non existing algo should return null (without exception) Assert.IsNull (CryptoConfig.CreateFromName ("NonExistingAlgorithm"), "NonExistingAlgorithm"); } // additional names (URL) used for XMLDSIG (System.Security.Cryptography.Xml) // URL taken from http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/ [Test] public void CreateFromURL () { // URL used in SignatureMethod element CreateFromName ("http://www.w3.org/2000/09/xmldsig#dsa-sha1", "System.Security.Cryptography.DSASignatureDescription"); CreateFromName ("http://www.w3.org/2000/09/xmldsig#rsa-sha1", "System.Security.Cryptography.RSAPKCS1SHA1SignatureDescription"); CreateFromName ("http://www.w3.org/2000/09/xmldsig#hmac-sha1", null); // URL used in DigestMethod element CreateFromName ("http://www.w3.org/2000/09/xmldsig#sha1", "System.Security.Cryptography.SHA1CryptoServiceProvider"); // URL used in Canonicalization or Transform elements CreateFromName ("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", "System.Security.Cryptography.Xml.XmlDsigC14NTransform"); CreateFromName ("http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments", "System.Security.Cryptography.Xml.XmlDsigC14NWithCommentsTransform"); // URL used in Transform element CreateFromName ("http://www.w3.org/2000/09/xmldsig#base64", "System.Security.Cryptography.Xml.XmlDsigBase64Transform"); // after installing the WSDK - changes to the machine.config file (not documented) // CreateFromName ("http://www.w3.org/TR/1999/REC-xpath-19991116", "Microsoft.WSDK.Security.XmlDsigXPathTransform"); CreateFromName ("http://www.w3.org/TR/1999/REC-xpath-19991116", "System.Security.Cryptography.Xml.XmlDsigXPathTransform"); CreateFromName ("http://www.w3.org/TR/1999/REC-xslt-19991116", "System.Security.Cryptography.Xml.XmlDsigXsltTransform"); CreateFromName ("http://www.w3.org/2000/09/xmldsig#enveloped-signature", "System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform"); // URL used in Reference element CreateFromName ("http://www.w3.org/2000/09/xmldsig#Object", null); CreateFromName ("http://www.w3.org/2000/09/xmldsig#Manifest", null); CreateFromName ("http://www.w3.org/2000/09/xmldsig#SignatureProperties", null); // LAMESPEC: only documentated in ".NET Framework Security" book CreateFromName ("http://www.w3.org/2000/09/xmldsig# X509Data", "System.Security.Cryptography.Xml.KeyInfoX509Data"); CreateFromName ("http://www.w3.org/2000/09/xmldsig# KeyName", "System.Security.Cryptography.Xml.KeyInfoName"); CreateFromName ("http://www.w3.org/2000/09/xmldsig# KeyValue/DSAKeyValue", "System.Security.Cryptography.Xml.DSAKeyValue"); CreateFromName ("http://www.w3.org/2000/09/xmldsig# KeyValue/RSAKeyValue", "System.Security.Cryptography.Xml.RSAKeyValue"); CreateFromName ("http://www.w3.org/2000/09/xmldsig# RetrievalMethod", "System.Security.Cryptography.Xml.KeyInfoRetrievalMethod"); } // Tests created using "A Layer Man Guide to ASN.1" from RSA, page 19-20 // Need to find an OID ? goto http://www.alvestrand.no/~hta/objectid/top.html static byte[] oidETSI = { 0x06, 0x03, 0x04, 0x00, 0x00 }; static byte[] oidSHA1 = { 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A }; static byte[] oidASN1CharacterModule = { 0x06, 0x04, 0x51, 0x00, 0x00, 0x00 }; static byte[] oidmd5withRSAEncryption = { 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04 }; [Test] #if NET_2_0 [ExpectedException (typeof (ArgumentNullException))] #else [ExpectedException (typeof (NullReferenceException))] #endif public void EncodeOIDNull () { byte[] o = CryptoConfig.EncodeOID (null); } [Test] public void EncodeOID () { // OID starts with 0, 1 or 2 Assert.AreEqual (oidETSI, CryptoConfig.EncodeOID ("0.4.0.0"), "OID starting with 0."); Assert.AreEqual (oidSHA1, CryptoConfig.EncodeOID ("1.3.14.3.2.26"), "OID starting with 1."); Assert.AreEqual (oidASN1CharacterModule, CryptoConfig.EncodeOID ("2.1.0.0.0"), "OID starting with 2."); // OID numbers can span multiple bytes Assert.AreEqual (oidmd5withRSAEncryption, CryptoConfig.EncodeOID ("1.2.840.113549.1.1.4"), "OID with numbers spanning multiple bytes"); } [Test] [ExpectedException (typeof (CryptographicUnexpectedOperationException))] // LAMESPEC: OID greater that 0x7F (127) bytes aren't supported by the MS Framework public void EncodeOID_BiggerThan127bytes () { // "ms"-invalid OID - greater than 127 bytes (length encoding) // OID longer than 127 bytes (so length must be encoded on multiple bytes) string baseOID = "1.3.6.1.4.1.11071.0."; string lastPart = "1111111111"; // must fit in int32 for (int i = 1; i < 30; i++) { baseOID += lastPart + "."; } baseOID += "0"; byte[] tooLongOID = CryptoConfig.EncodeOID (baseOID); } [Test] [ExpectedException (typeof (OverflowException))] // LAMESPEC: OID with numbers > Int32 aren't supported by the MS BCL public void EncodeOID_BiggerThanInt32 () { // "ms"-invalid OID - where a number of the OID > Int32 byte[] tooLongOID = CryptoConfig.EncodeOID ("1.1.4294967295"); } [Test] public void EncodeOID_InvalidStart () { // invalid OID - must start with 0, 1 or 2 // however it works with MS BCL byte[] oid3 = CryptoConfig.EncodeOID ("3.0"); byte[] res3 = { 0x06, 0x01, 0x78 }; Assert.AreEqual (res3, oid3, "OID: 3.0"); } [Test] [ExpectedException (typeof (CryptographicUnexpectedOperationException))] public void EncodeOID_TooShort () { // invalid OID - must have at least 2 parts (according to X.208) byte[] tooShortOID = CryptoConfig.EncodeOID ("0"); } [Test] public void EncodeOID_InvalidSecondPart () { // invalid OID - second value < 40 for 0. and 1. (modulo 40) // however it works with MS BCL byte[] tooBigSecondPartOID = CryptoConfig.EncodeOID ("0.40"); byte[] tooBigSecondPartRes = { 0x06, 0x01, 0x28 }; Assert.AreEqual (tooBigSecondPartRes, tooBigSecondPartOID, "OID: 0.40"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void MapNameToOIDNull () { CryptoConfig.MapNameToOID (null); } private void MapNameToOID (string name, string oid) { Assert.AreEqual (oid, CryptoConfig.MapNameToOID (name), "oid(" + name + ")"); } // LAMESPEC: doesn't support all names defined in CryptoConfig // non supported names (in MSFW) are commented or null-ed // LAMESPEC: undocumented but full class name is supported [Test] public void MapNameToOID() { // MapNameToOID ("SHA", "1.3.14.3.2.26"); MapNameToOID ("SHA1", "1.3.14.3.2.26"); MapNameToOID ("System.Security.Cryptography.SHA1", "1.3.14.3.2.26"); // MapNameToOID ("System.Security.Cryptography.HashAlgorithm", "1.3.14.3.2.26"); MapNameToOID ("System.Security.Cryptography.SHA1CryptoServiceProvider", "1.3.14.3.2.26"); MapNameToOID ("System.Security.Cryptography.SHA1Managed", "1.3.14.3.2.26"); MapNameToOID ("MD5", "1.2.840.113549.2.5"); MapNameToOID ("System.Security.Cryptography.MD5", "1.2.840.113549.2.5"); MapNameToOID ("System.Security.Cryptography.MD5CryptoServiceProvider", "1.2.840.113549.2.5"); #if NET_2_0 MapNameToOID ("SHA256", "2.16.840.1.101.3.4.2.1"); MapNameToOID ("System.Security.Cryptography.SHA256", "2.16.840.1.101.3.4.2.1"); MapNameToOID ("System.Security.Cryptography.SHA256Managed", "2.16.840.1.101.3.4.2.1"); MapNameToOID ("SHA384", "2.16.840.1.101.3.4.2.2"); MapNameToOID ("System.Security.Cryptography.SHA384", "2.16.840.1.101.3.4.2.2"); MapNameToOID ("System.Security.Cryptography.SHA384Managed", "2.16.840.1.101.3.4.2.2"); MapNameToOID ("SHA512", "2.16.840.1.101.3.4.2.3"); MapNameToOID ("System.Security.Cryptography.SHA512", "2.16.840.1.101.3.4.2.3"); MapNameToOID ("System.Security.Cryptography.SHA512Managed", "2.16.840.1.101.3.4.2.3"); #else MapNameToOID ("SHA256", "2.16.840.1.101.3.4.1"); // MapNameToOID ("SHA-256", "2.16.840.1.101.3.4.1"); MapNameToOID ("System.Security.Cryptography.SHA256", "2.16.840.1.101.3.4.1"); MapNameToOID ("System.Security.Cryptography.SHA256Managed", "2.16.840.1.101.3.4.1"); MapNameToOID ("SHA384", "2.16.840.1.101.3.4.2"); // MapNameToOID ("SHA-384", "2.16.840.1.101.3.4.2"); MapNameToOID ("System.Security.Cryptography.SHA384", "2.16.840.1.101.3.4.2"); MapNameToOID ("System.Security.Cryptography.SHA384Managed", "2.16.840.1.101.3.4.2"); MapNameToOID ("SHA512", "2.16.840.1.101.3.4.3"); // MapNameToOID ("SHA-512", "2.16.840.1.101.3.4.3"); MapNameToOID ("System.Security.Cryptography.SHA512", "2.16.840.1.101.3.4.3"); MapNameToOID ("System.Security.Cryptography.SHA512Managed", "2.16.840.1.101.3.4.3"); #endif // LAMESPEC: only documentated in ".NET Framework Security" book MapNameToOID ("TripleDESKeyWrap", "1.2.840.113549.1.9.16.3.6"); #if NET_2_0 // new OID defined in Fx 2.0 // MapNameToOID ("RSA", "1.2.840.113549.1.1.1"); MapNameToOID ("DSA", "1.2.840.10040.4.1"); MapNameToOID ("DES", "1.3.14.3.2.7"); MapNameToOID ("3DES", "1.2.840.113549.3.7"); MapNameToOID ("TripleDES", "1.2.840.113549.3.7"); MapNameToOID ("RC2", "1.2.840.113549.3.2"); #else // no OID defined before Fx 2.0 MapNameToOID ("RSA", null); MapNameToOID ("DSA", null); MapNameToOID ("DES", null); MapNameToOID ("3DES", null); MapNameToOID ("TripleDES", null); MapNameToOID ("RC2", null); #endif // no OID defined ? MapNameToOID ("System.Security.Cryptography.RSA", null); MapNameToOID ("System.Security.Cryptography.AsymmetricAlgorithm", null); MapNameToOID ("System.Security.Cryptography.DSA", null); MapNameToOID ("System.Security.Cryptography.DES", null); MapNameToOID ("Triple DES", null); MapNameToOID ("System.Security.Cryptography.TripleDES", null); MapNameToOID ("System.Security.Cryptography.RC2", null); MapNameToOID ("Rijndael", null); MapNameToOID ("System.Security.Cryptography.Rijndael", null); MapNameToOID ("System.Security.Cryptography.SymmetricAlgorithm", null); // LAMESPEC Undocumented Names in CryptoConfig MapNameToOID ("RandomNumberGenerator", null); MapNameToOID ("System.Security.Cryptography.RandomNumberGenerator", null); MapNameToOID ("System.Security.Cryptography.KeyedHashAlgorithm", null); #if NET_2_0 MapNameToOID ("HMAC", null); MapNameToOID ("System.Security.Cryptography.HMAC", null); MapNameToOID ("HMACMD5", null); MapNameToOID ("System.Security.Cryptography.HMACMD5", null); MapNameToOID ("HMACRIPEMD160", null); MapNameToOID ("System.Security.Cryptography.HMACRIPEMD160", null); MapNameToOID ("HMACSHA256", null); MapNameToOID ("System.Security.Cryptography.HMACSHA256", null); MapNameToOID ("HMACSHA384", null); MapNameToOID ("System.Security.Cryptography.HMACSHA384", null); MapNameToOID ("HMACSHA512", null); MapNameToOID ("System.Security.Cryptography.HMACSHA512", null); #endif MapNameToOID ("HMACSHA1", null); MapNameToOID ("System.Security.Cryptography.HMACSHA1", null); MapNameToOID ("MACTripleDES", null); MapNameToOID ("System.Security.Cryptography.MACTripleDES", null); // non existing algo should return null (without exception) MapNameToOID ("NonExistingAlgorithm", null); } [Test] public void CCToString () { // under normal circumstance there are no need to create a CryptoConfig object // because all interesting stuff are in static methods CryptoConfig cc = new CryptoConfig (); Assert.AreEqual ("System.Security.Cryptography.CryptoConfig", cc.ToString ()); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleHistoryTestingParallel.SampleHistoryTestingParallelPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleHistoryTestingParallel { using System; using System.IO; using System.Linq; using System.Windows; using System.Windows.Media; using Ecng.Xaml; using Ecng.Common; using StockSharp.Algo; using StockSharp.Algo.Candles; using StockSharp.Algo.Storages; using StockSharp.Algo.Strategies; using StockSharp.Algo.Strategies.Testing; using StockSharp.Algo.Testing; using StockSharp.Algo.Indicators; using StockSharp.BusinessEntities; using StockSharp.Logging; using StockSharp.Messages; using StockSharp.Xaml.Charting; using StockSharp.Localization; public partial class MainWindow { private DateTime _startEmulationTime; public MainWindow() { InitializeComponent(); HistoryPath.Folder = @"..\..\..\HistoryData\".ToFullPath(); } private void StartBtnClick(object sender, RoutedEventArgs e) { if (HistoryPath.Folder.IsEmpty() || !Directory.Exists(HistoryPath.Folder)) { MessageBox.Show(this, LocalizedStrings.Str3014); return; } if (Math.Abs(TestingProcess.Value - 0) > double.Epsilon) { MessageBox.Show(this, LocalizedStrings.Str3015); return; } var logManager = new LogManager(); var fileLogListener = new FileLogListener("sample.log"); logManager.Listeners.Add(fileLogListener); // SMA periods var periods = new[] { new Tuple<int, int, Color>(80, 10, Colors.DarkGreen), new Tuple<int, int, Color>(70, 8, Colors.Red), new Tuple<int, int, Color>(60, 6, Colors.DarkBlue) }; // storage to historical data var storageRegistry = new StorageRegistry { // set historical path DefaultDrive = new LocalMarketDataDrive(HistoryPath.Folder) }; var timeFrame = TimeSpan.FromMinutes(5); // create test security var security = new Security { Id = "RIZ2@FORTS", // sec id has the same name as folder with historical data Code = "RIZ2", Name = "RTS-12.12", Board = ExchangeBoard.Forts, }; var startTime = new DateTime(2012, 10, 1); var stopTime = new DateTime(2012, 10, 31); var level1Info = new Level1ChangeMessage { SecurityId = security.ToSecurityId(), ServerTime = startTime, } .TryAdd(Level1Fields.PriceStep, 10m) .TryAdd(Level1Fields.StepPrice, 6m) .TryAdd(Level1Fields.MinPrice, 10m) .TryAdd(Level1Fields.MaxPrice, 1000000m) .TryAdd(Level1Fields.MarginBuy, 10000m) .TryAdd(Level1Fields.MarginSell, 10000m); // test portfolio var portfolio = new Portfolio { Name = "test account", BeginValue = 1000000, }; // create backtesting connector var batchEmulation = new BatchEmulation(new[] { security }, new[] { portfolio }, storageRegistry) { EmulationSettings = { MarketTimeChangedInterval = timeFrame, StartTime = startTime, StopTime = stopTime, // count of parallel testing strategies BatchSize = periods.Length, } }; // handle historical time for update ProgressBar batchEmulation.ProgressChanged += (curr, total) => this.GuiAsync(() => TestingProcess.Value = total); batchEmulation.StateChanged += (oldState, newState) => { if (batchEmulation.State != EmulationStates.Stopped) return; this.GuiAsync(() => { if (batchEmulation.IsFinished) { TestingProcess.Value = TestingProcess.Maximum; MessageBox.Show(this, LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime)); } else MessageBox.Show(this, LocalizedStrings.cancelled); }); }; // get emulation connector var connector = batchEmulation.EmulationConnector; logManager.Sources.Add(connector); connector.NewSecurity += s => { if (s != security) return; // fill level1 values connector.SendInMessage(level1Info); connector.RegisterMarketDepth(new TrendMarketDepthGenerator(connector.GetSecurityId(security)) { // order book freq refresh is 1 sec Interval = TimeSpan.FromSeconds(1), }); }; TestingProcess.Maximum = 100; TestingProcess.Value = 0; _startEmulationTime = DateTime.Now; var strategies = periods .Select(period => { var candleManager = new CandleManager(connector); var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame); // create strategy based SMA var strategy = new SmaStrategy(candleManager, series, new SimpleMovingAverage { Length = period.Item1 }, new SimpleMovingAverage { Length = period.Item2 }) { Volume = 1, Security = security, Portfolio = portfolio, Connector = connector, // by default interval is 1 min, // it is excessively for time range with several months UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>() }; strategy.SetCandleManager(candleManager); var curveItems = Curve.CreateCurve(LocalizedStrings.Str3026Params.Put(period.Item1, period.Item2), period.Item3); strategy.PnLChanged += () => { var data = new EquityData { Time = strategy.CurrentTime, Value = strategy.PnL, }; this.GuiAsync(() => curveItems.Add(data)); }; Stat.AddStrategies(new[] { strategy }); return strategy; }); // start emulation batchEmulation.Start(strategies, periods.Length); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { /// <devdoc> /// <para> /// Provides access to local and remote /// processes. Enables you to start and stop system processes. /// </para> /// </devdoc> public partial class Process : Component { private bool _haveProcessId; private int _processId; private bool _haveProcessHandle; private SafeProcessHandle _processHandle; private bool _isRemoteMachine; private string _machineName; private ProcessInfo _processInfo; private ProcessThreadCollection _threads; private ProcessModuleCollection _modules; private bool _haveWorkingSetLimits; private IntPtr _minWorkingSet; private IntPtr _maxWorkingSet; private bool _haveProcessorAffinity; private IntPtr _processorAffinity; private bool _havePriorityClass; private ProcessPriorityClass _priorityClass; private ProcessStartInfo _startInfo; private bool _watchForExit; private bool _watchingForExit; private EventHandler _onExited; private bool _exited; private int _exitCode; private DateTime? _startTime; private DateTime _exitTime; private bool _haveExitTime; private bool _priorityBoostEnabled; private bool _havePriorityBoostEnabled; private bool _raisedOnExited; private RegisteredWaitHandle _registeredWaitHandle; private WaitHandle _waitHandle; private StreamReader _standardOutput; private StreamWriter _standardInput; private StreamReader _standardError; private bool _disposed; private static object s_createProcessLock = new object(); private StreamReadMode _outputStreamReadMode; private StreamReadMode _errorStreamReadMode; // Support for asynchronously reading streams public event DataReceivedEventHandler OutputDataReceived; public event DataReceivedEventHandler ErrorDataReceived; // Abstract the stream details internal AsyncStreamReader _output; internal AsyncStreamReader _error; internal bool _pendingOutputRead; internal bool _pendingErrorRead; #if FEATURE_TRACESWITCH internal static TraceSwitch _processTracing = #if DEBUG new TraceSwitch("processTracing", "Controls debug output from Process component"); #else null; #endif #endif /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class. /// </para> /// </devdoc> public Process() { // This class once inherited a finalizer. For backward compatibility it has one so that // any derived class that depends on it will see the behaviour expected. Since it is // not used by this class itself, suppress it immediately if this is not an instance // of a derived class it doesn't suffer the GC burden of finalization. if (GetType() == typeof(Process)) { GC.SuppressFinalize(this); } _machineName = "."; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo) { GC.SuppressFinalize(this); _processInfo = processInfo; _machineName = machineName; _isRemoteMachine = isRemoteMachine; _processId = processId; _haveProcessId = true; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } public SafeProcessHandle SafeHandle { get { EnsureState(State.Associated); return OpenProcessHandle(); } } public IntPtr Handle => SafeHandle.DangerousGetHandle(); /// <devdoc> /// Returns whether this process component is associated with a real process. /// </devdoc> /// <internalonly/> bool Associated { get { return _haveProcessId || _haveProcessHandle; } } /// <devdoc> /// <para> /// Gets the base priority of /// the associated process. /// </para> /// </devdoc> public int BasePriority { get { EnsureState(State.HaveProcessInfo); return _processInfo.BasePriority; } } /// <devdoc> /// <para> /// Gets /// the /// value that was specified by the associated process when it was terminated. /// </para> /// </devdoc> public int ExitCode { get { EnsureState(State.Exited); return _exitCode; } } /// <devdoc> /// <para> /// Gets a /// value indicating whether the associated process has been terminated. /// </para> /// </devdoc> public bool HasExited { get { if (!_exited) { EnsureState(State.Associated); UpdateHasExited(); if (_exited) { RaiseOnExited(); } } return _exited; } } /// <summary>Gets the time the associated process was started.</summary> public DateTime StartTime { get { if (!_startTime.HasValue) { _startTime = StartTimeCore; } return _startTime.Value; } } /// <devdoc> /// <para> /// Gets the time that the associated process exited. /// </para> /// </devdoc> public DateTime ExitTime { get { if (!_haveExitTime) { EnsureState(State.Exited); _exitTime = ExitTimeCore; _haveExitTime = true; } return _exitTime; } } /// <devdoc> /// <para> /// Gets /// the unique identifier for the associated process. /// </para> /// </devdoc> public int Id { get { EnsureState(State.HaveId); return _processId; } } /// <devdoc> /// <para> /// Gets /// the name of the computer on which the associated process is running. /// </para> /// </devdoc> public string MachineName { get { EnsureState(State.Associated); return _machineName; } } /// <devdoc> /// <para> /// Gets or sets the maximum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MaxWorkingSet { get { EnsureWorkingSetLimits(); return _maxWorkingSet; } set { SetWorkingSetLimits(null, value); } } /// <devdoc> /// <para> /// Gets or sets the minimum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MinWorkingSet { get { EnsureWorkingSetLimits(); return _minWorkingSet; } set { SetWorkingSetLimits(value, null); } } public ProcessModuleCollection Modules { get { if (_modules == null) { EnsureState(State.HaveId | State.IsLocal); _modules = ProcessManager.GetModules(_processId); } return _modules; } } public long NonpagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolNonPagedBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int NonpagedSystemMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PoolNonPagedBytes); } } public long PagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PagedMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PageFileBytes); } } public long PagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolPagedBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PagedSystemMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PoolPagedBytes); } } public long PeakPagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytesPeak; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakPagedMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PageFileBytesPeak); } } public long PeakWorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSetPeak; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakWorkingSet { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.WorkingSetPeak); } } public long PeakVirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytesPeak; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakVirtualMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.VirtualBytesPeak); } } /// <devdoc> /// <para> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </para> /// </devdoc> public bool PriorityBoostEnabled { get { if (!_havePriorityBoostEnabled) { _priorityBoostEnabled = PriorityBoostEnabledCore; _havePriorityBoostEnabled = true; } return _priorityBoostEnabled; } set { PriorityBoostEnabledCore = value; _priorityBoostEnabled = value; _havePriorityBoostEnabled = true; } } /// <devdoc> /// <para> /// Gets or sets the overall priority category for the /// associated process. /// </para> /// </devdoc> public ProcessPriorityClass PriorityClass { get { if (!_havePriorityClass) { _priorityClass = PriorityClassCore; _havePriorityClass = true; } return _priorityClass; } set { if (!Enum.IsDefined(typeof(ProcessPriorityClass), value)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessPriorityClass)); } PriorityClassCore = value; _priorityClass = value; _havePriorityClass = true; } } public long PrivateMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PrivateBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PrivateMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PrivateBytes); } } /// <devdoc> /// <para> /// Gets /// the friendly name of the process. /// </para> /// </devdoc> public string ProcessName { get { EnsureState(State.HaveProcessInfo); return _processInfo.ProcessName; } } /// <devdoc> /// <para> /// Gets /// or sets which processors the threads in this process can be scheduled to run on. /// </para> /// </devdoc> public IntPtr ProcessorAffinity { get { if (!_haveProcessorAffinity) { _processorAffinity = ProcessorAffinityCore; _haveProcessorAffinity = true; } return _processorAffinity; } set { ProcessorAffinityCore = value; _processorAffinity = value; _haveProcessorAffinity = true; } } public int SessionId { get { EnsureState(State.HaveProcessInfo); return _processInfo.SessionId; } } /// <devdoc> /// <para> /// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/> /// . /// </para> /// </devdoc> public ProcessStartInfo StartInfo { get { if (_startInfo == null) { if (Associated) { throw new InvalidOperationException(SR.CantGetProcessStartInfo); } _startInfo = new ProcessStartInfo(); } return _startInfo; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (Associated) { throw new InvalidOperationException(SR.CantSetProcessStartInfo); } _startInfo = value; } } /// <devdoc> /// <para> /// Gets the set of threads that are running in the associated /// process. /// </para> /// </devdoc> public ProcessThreadCollection Threads { get { if (_threads == null) { EnsureState(State.HaveProcessInfo); int count = _processInfo._threadInfoList.Count; ProcessThread[] newThreadsArray = new ProcessThread[count]; for (int i = 0; i < count; i++) { newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]); } ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray); _threads = newThreads; } return _threads; } } public int HandleCount { get { EnsureState(State.HaveProcessInfo); EnsureHandleCountPopulated(); return _processInfo.HandleCount; } } partial void EnsureHandleCountPopulated(); [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public long VirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytes; } } public int VirtualMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.VirtualBytes); } } /// <devdoc> /// <para> /// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/> /// event is fired /// when the process terminates. /// </para> /// </devdoc> public bool EnableRaisingEvents { get { return _watchForExit; } set { if (value != _watchForExit) { if (Associated) { if (value) { OpenProcessHandle(); EnsureWatchingForExit(); } else { StopWatchingForExit(); } } _watchForExit = value; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamWriter StandardInput { get { if (_standardInput == null) { throw new InvalidOperationException(SR.CantGetStandardIn); } return _standardInput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardOutput { get { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.SyncMode; } else if (_outputStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardOutput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardError { get { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.SyncMode; } else if (_errorStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardError; } } public long WorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSet; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int WorkingSet { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.WorkingSet); } } public event EventHandler Exited { add { _onExited += value; } remove { _onExited -= value; } } /// <devdoc> /// This is called from the threadpool when a process exits. /// </devdoc> /// <internalonly/> private void CompletionCallback(object context, bool wasSignaled) { StopWatchingForExit(); RaiseOnExited(); } /// <internalonly/> /// <devdoc> /// <para> /// Free any resources associated with this component. /// </para> /// </devdoc> protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { //Dispose managed and unmanaged resources Close(); } _disposed = true; } } public bool CloseMainWindow() { return CloseMainWindowCore(); } public bool WaitForInputIdle() { return WaitForInputIdle(int.MaxValue); } public bool WaitForInputIdle(int milliseconds) { return WaitForInputIdleCore(milliseconds); } public ISynchronizeInvoke SynchronizingObject { get; set; } /// <devdoc> /// <para> /// Frees any resources associated with this component. /// </para> /// </devdoc> public void Close() { if (Associated) { if (_haveProcessHandle) { StopWatchingForExit(); #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()"); #endif _processHandle.Dispose(); _processHandle = null; _haveProcessHandle = false; } _haveProcessId = false; _isRemoteMachine = false; _machineName = "."; _raisedOnExited = false; //Don't call close on the Readers and writers //since they might be referenced by somebody else while the //process is still alive but this method called. _standardOutput = null; _standardInput = null; _standardError = null; _output = null; _error = null; CloseCore(); Refresh(); } } /// <devdoc> /// Helper method for checking preconditions when accessing properties. /// </devdoc> /// <internalonly/> private void EnsureState(State state) { if ((state & State.Associated) != (State)0) if (!Associated) throw new InvalidOperationException(SR.NoAssociatedProcess); if ((state & State.HaveId) != (State)0) { if (!_haveProcessId) { if (_haveProcessHandle) { SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle)); } else { EnsureState(State.Associated); throw new InvalidOperationException(SR.ProcessIdRequired); } } } if ((state & State.IsLocal) != (State)0 && _isRemoteMachine) { throw new NotSupportedException(SR.NotSupportedRemote); } if ((state & State.HaveProcessInfo) != (State)0) { if (_processInfo == null) { if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId); _processInfo = ProcessManager.GetProcessInfo(_processId, _machineName); if (_processInfo == null) { throw new InvalidOperationException(SR.NoProcessInfo); } } } if ((state & State.Exited) != (State)0) { if (!HasExited) { throw new InvalidOperationException(SR.WaitTillExit); } if (!_haveProcessHandle) { throw new InvalidOperationException(SR.NoProcessHandle); } } } /// <devdoc> /// Make sure we are watching for a process exit. /// </devdoc> /// <internalonly/> private void EnsureWatchingForExit() { if (!_watchingForExit) { lock (this) { if (!_watchingForExit) { Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle"); Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process"); _watchingForExit = true; try { _waitHandle = new ProcessWaitHandle(_processHandle); _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(CompletionCallback), null, -1, true); } catch { _watchingForExit = false; throw; } } } } } /// <devdoc> /// Make sure we have obtained the min and max working set limits. /// </devdoc> /// <internalonly/> private void EnsureWorkingSetLimits() { if (!_haveWorkingSetLimits) { GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } } /// <devdoc> /// Helper to set minimum or maximum working set limits. /// </devdoc> /// <internalonly/> private void SetWorkingSetLimits(IntPtr? min, IntPtr? max) { SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and /// the name of a computer in the network. /// </para> /// </devdoc> public static Process GetProcessById(int processId, string machineName) { if (!ProcessManager.IsProcessRunning(processId, machineName)) { throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture))); } return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null); } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given the /// identifier of a process on the local computer. /// </para> /// </devdoc> public static Process GetProcessById(int processId) { return GetProcessById(processId, "."); } /// <devdoc> /// <para> /// Creates an array of <see cref='System.Diagnostics.Process'/> components that are /// associated /// with process resources on the /// local computer. These process resources share the specified process name. /// </para> /// </devdoc> public static Process[] GetProcessesByName(string processName) { return GetProcessesByName(processName, "."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each process resource on the local computer. /// </para> /// </devdoc> public static Process[] GetProcesses() { return GetProcesses("."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each /// process resource on the specified computer. /// </para> /// </devdoc> public static Process[] GetProcesses(string machineName) { bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName); ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); Process[] processes = new Process[processInfos.Length]; for (int i = 0; i < processInfos.Length; i++) { ProcessInfo processInfo = processInfos[i]; processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo); } #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")"); #if DEBUG if (_processTracing.TraceVerbose) { Debug.Indent(); for (int i = 0; i < processInfos.Length; i++) { Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName); } Debug.Unindent(); } #endif #endif return processes; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> /// component and associates it with the current active process. /// </para> /// </devdoc> public static Process GetCurrentProcess() { return new Process(".", false, GetCurrentProcessId(), null); } /// <devdoc> /// <para> /// Raises the <see cref='System.Diagnostics.Process.Exited'/> event. /// </para> /// </devdoc> protected void OnExited() { EventHandler exited = _onExited; if (exited != null) { exited(this, EventArgs.Empty); } } /// <devdoc> /// Raise the Exited event, but make sure we don't do it more than once. /// </devdoc> /// <internalonly/> private void RaiseOnExited() { if (!_raisedOnExited) { lock (this) { if (!_raisedOnExited) { _raisedOnExited = true; OnExited(); } } } } /// <devdoc> /// <para> /// Discards any information about the associated process /// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the /// first request for information for each property causes the process component /// to obtain a new value from the associated process. /// </para> /// </devdoc> public void Refresh() { _processInfo = null; _threads = null; _modules = null; _exited = false; _haveWorkingSetLimits = false; _haveProcessorAffinity = false; _havePriorityClass = false; _haveExitTime = false; _havePriorityBoostEnabled = false; RefreshCore(); } /// <summary> /// Opens a long-term handle to the process, with all access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle OpenProcessHandle() { if (!_haveProcessHandle) { //Cannot open a new process handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } SetProcessHandle(GetProcessHandle()); } return _processHandle; } /// <devdoc> /// Helper to associate a process handle with this component. /// </devdoc> /// <internalonly/> private void SetProcessHandle(SafeProcessHandle processHandle) { _processHandle = processHandle; _haveProcessHandle = true; if (_watchForExit) { EnsureWatchingForExit(); } } /// <devdoc> /// Helper to associate a process id with this component. /// </devdoc> /// <internalonly/> private void SetProcessId(int processId) { _processId = processId; _haveProcessId = true; ConfigureAfterProcessIdSet(); } /// <summary>Additional optional configuration hook after a process ID is set.</summary> partial void ConfigureAfterProcessIdSet(); /// <devdoc> /// <para> /// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/> /// component and associates it with the /// <see cref='System.Diagnostics.Process'/> . If a process resource is reused /// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public bool Start() { Close(); ProcessStartInfo startInfo = StartInfo; if (startInfo.FileName.Length == 0) { throw new InvalidOperationException(SR.FileNameMissing); } if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput) { throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); } if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); } //Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } return StartCore(startInfo); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of a /// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName) { return Start(new ProcessStartInfo(fileName)); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of an /// application and a set of command line arguments. Associates the process resource /// with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName, string arguments) { return Start(new ProcessStartInfo(fileName, arguments)); } /// <devdoc> /// <para> /// Starts a process resource specified by the process start /// information passed in, for example the file name of the process to start. /// Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(ProcessStartInfo startInfo) { Process process = new Process(); if (startInfo == null) throw new ArgumentNullException(nameof(startInfo)); process.StartInfo = startInfo; return process.Start() ? process : null; } /// <devdoc> /// Make sure we are not watching for process exit. /// </devdoc> /// <internalonly/> private void StopWatchingForExit() { if (_watchingForExit) { RegisteredWaitHandle rwh = null; WaitHandle wh = null; lock (this) { if (_watchingForExit) { _watchingForExit = false; wh = _waitHandle; _waitHandle = null; rwh = _registeredWaitHandle; _registeredWaitHandle = null; } } if (rwh != null) { rwh.Unregister(null); } if (wh != null) { wh.Dispose(); } } } public override string ToString() { if (Associated) { string processName = ProcessName; if (processName.Length != 0) { return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName); } } return base.ToString(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to wait /// indefinitely for the associated process to exit. /// </para> /// </devdoc> public void WaitForExit() { WaitForExit(Timeout.Infinite); } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for /// the associated process to exit. /// </summary> public bool WaitForExit(int milliseconds) { bool exited = WaitForExitCore(milliseconds); if (exited && _watchForExit) { RaiseOnExited(); } return exited; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardOutput stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to OutputDataReceived. /// </para> /// </devdoc> public void BeginOutputReadLine() { if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.AsyncMode; } else if (_outputStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingOutputRead) throw new InvalidOperationException(SR.PendingAsyncOperation); _pendingOutputRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_output == null) { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } Stream s = _standardOutput.BaseStream; _output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding); } _output.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardError stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to ErrorDataReceived. /// </para> /// </devdoc> public void BeginErrorReadLine() { if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.AsyncMode; } else if (_errorStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingErrorRead) { throw new InvalidOperationException(SR.PendingAsyncOperation); } _pendingErrorRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_error == null) { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } Stream s = _standardError.BaseStream; _error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding); } _error.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginOutputReadLine(). /// </para> /// </devdoc> public void CancelOutputRead() { if (_output != null) { _output.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingOutputRead = false; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginErrorReadLine(). /// </para> /// </devdoc> public void CancelErrorRead() { if (_error != null) { _error.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingErrorRead = false; } internal void OutputReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler outputDataReceived = OutputDataReceived; if (outputDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); outputDataReceived(this, e); // Call back to user informing data is available } } internal void ErrorReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler errorDataReceived = ErrorDataReceived; if (errorDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); errorDataReceived(this, e); // Call back to user informing data is available. } } /// <summary> /// This enum defines the operation mode for redirected process stream. /// We don't support switching between synchronous mode and asynchronous mode. /// </summary> private enum StreamReadMode { Undefined, SyncMode, AsyncMode } /// <summary>A desired internal state.</summary> private enum State { HaveId = 0x1, IsLocal = 0x2, HaveProcessInfo = 0x8, Exited = 0x10, Associated = 0x20, } } }
//--------------------------------------------------------------------------- // // <copyright file="PathStreamGeometryContext.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This class is used by the StreamGeometry class to generate an inlined, // flattened geometry stream. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows.Threading; using System.Windows; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Diagnostics; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Security; using System.Security.Permissions; namespace System.Windows.Media { /// <summary> /// PathStreamGeometryContext /// </summary> internal class PathStreamGeometryContext : CapacityStreamGeometryContext { #region Public Methods static PathStreamGeometryContext() { // We grab the default values for these properties so that we can avoid setting // properties to their default values (as this will require that we reserve // storage for these values). s_defaultFillRule = (FillRule)PathGeometry.FillRuleProperty.GetDefaultValue(typeof(PathGeometry)); s_defaultValueForPathFigureIsClosed = (bool)PathFigure.IsClosedProperty.GetDefaultValue(typeof(PathFigure)); s_defaultValueForPathFigureIsFilled = (bool)PathFigure.IsFilledProperty.GetDefaultValue(typeof(PathFigure)); s_defaultValueForPathFigureStartPoint = (Point)PathFigure.StartPointProperty.GetDefaultValue(typeof(PathFigure)); // This code assumes that sub-classes of PathSegment don't override the default value for these properties s_defaultValueForPathSegmentIsStroked = (bool)PathSegment.IsStrokedProperty.GetDefaultValue(typeof(PathSegment)); s_defaultValueForPathSegmentIsSmoothJoin = (bool)PathSegment.IsSmoothJoinProperty.GetDefaultValue(typeof(PathSegment)); s_defaultValueForArcSegmentIsLargeArc = (bool)ArcSegment.IsLargeArcProperty.GetDefaultValue(typeof(ArcSegment)); s_defaultValueForArcSegmentSweepDirection = (SweepDirection)ArcSegment.SweepDirectionProperty.GetDefaultValue(typeof(ArcSegment)); s_defaultValueForArcSegmentRotationAngle = (double)ArcSegment.RotationAngleProperty.GetDefaultValue(typeof(ArcSegment)); } internal PathStreamGeometryContext() { _pathGeometry = new PathGeometry(); } internal PathStreamGeometryContext(FillRule fillRule, Transform transform) { _pathGeometry = new PathGeometry(); if (fillRule != s_defaultFillRule) { _pathGeometry.FillRule = fillRule; } if ((transform != null) && !transform.IsIdentity) { _pathGeometry.Transform = transform.Clone(); } } internal override void SetFigureCount(int figureCount) { Debug.Assert(_figures == null, "It is illegal to call SetFigureCount multiple times or after BeginFigure."); Debug.Assert(figureCount > 0); _figures = new PathFigureCollection(figureCount); _pathGeometry.Figures = _figures; } internal override void SetSegmentCount(int segmentCount) { Debug.Assert(_figures != null, "It is illegal to call SetSegmentCount before BeginFigure."); Debug.Assert(_currentFigure != null, "It is illegal to call SetSegmentCount before BeginFigure."); Debug.Assert(_segments == null, "It is illegal to call SetSegmentCount multiple times per BeginFigure or after a *To method."); Debug.Assert(segmentCount > 0); _segments = new PathSegmentCollection(segmentCount); _currentFigure.Segments = _segments; } /// <summary> /// SetClosed - Sets the current closed state of the figure. /// </summary> override internal void SetClosedState(bool isClosed) { Debug.Assert(_currentFigure != null); if (isClosed != _currentIsClosed) { _currentFigure.IsClosed = isClosed; _currentIsClosed = isClosed; } } /// <summary> /// BeginFigure - Start a new figure. /// </summary> public override void BeginFigure(Point startPoint, bool isFilled, bool isClosed) { // _currentFigure != null -> _figures != null Debug.Assert(_currentFigure == null || _figures != null); // Is this the first figure? if (_currentFigure == null) { // If so, have we not yet allocated the collection? if (_figures == null) { // While we could always just retrieve _pathGeometry.Figures (which would auto-promote) // it's more efficient to create the collection ourselves and set it explicitly. _figures = new PathFigureCollection(); _pathGeometry.Figures = _figures; } } FinishSegment(); // Clear the old reference to the segment collection _segments = null; _currentFigure = new PathFigure(); _currentIsClosed = isClosed; if (startPoint != s_defaultValueForPathFigureStartPoint) { _currentFigure.StartPoint = startPoint; } if (isClosed != s_defaultValueForPathFigureIsClosed) { _currentFigure.IsClosed = isClosed; } if (isFilled != s_defaultValueForPathFigureIsFilled) { _currentFigure.IsFilled = isFilled; } _figures.Add(_currentFigure); _currentSegmentType = MIL_SEGMENT_TYPE.MilSegmentNone; } /// <summary> /// LineTo - append a LineTo to the current figure. /// </summary> public override void LineTo(Point point, bool isStroked, bool isSmoothJoin) { PrepareToAddPoints( 1 /*count*/, isStroked, isSmoothJoin, MIL_SEGMENT_TYPE.MilSegmentPolyLine); _currentSegmentPoints.Add(point); } /// <summary> /// QuadraticBezierTo - append a QuadraticBezierTo to the current figure. /// </summary> public override void QuadraticBezierTo(Point point1, Point point2, bool isStroked, bool isSmoothJoin) { PrepareToAddPoints( 2 /*count*/, isStroked, isSmoothJoin, MIL_SEGMENT_TYPE.MilSegmentPolyQuadraticBezier); _currentSegmentPoints.Add(point1); _currentSegmentPoints.Add(point2); } /// <summary> /// BezierTo - apply a BezierTo to the current figure. /// </summary> public override void BezierTo(Point point1, Point point2, Point point3, bool isStroked, bool isSmoothJoin) { PrepareToAddPoints( 3 /*count*/, isStroked, isSmoothJoin, MIL_SEGMENT_TYPE.MilSegmentPolyBezier); _currentSegmentPoints.Add(point1); _currentSegmentPoints.Add(point2); _currentSegmentPoints.Add(point3); } /// <summary> /// PolyLineTo - append a PolyLineTo to the current figure. /// </summary> public override void PolyLineTo(IList<Point> points, bool isStroked, bool isSmoothJoin) { GenericPolyTo(points, isStroked, isSmoothJoin, MIL_SEGMENT_TYPE.MilSegmentPolyLine); } /// <summary> /// PolyQuadraticBezierTo - append a PolyQuadraticBezierTo to the current figure. /// </summary> public override void PolyQuadraticBezierTo(IList<Point> points, bool isStroked, bool isSmoothJoin) { GenericPolyTo(points, isStroked, isSmoothJoin, MIL_SEGMENT_TYPE.MilSegmentPolyQuadraticBezier); } /// <summary> /// PolyBezierTo - append a PolyBezierTo to the current figure. /// </summary> public override void PolyBezierTo(IList<Point> points, bool isStroked, bool isSmoothJoin) { GenericPolyTo(points, isStroked, isSmoothJoin, MIL_SEGMENT_TYPE.MilSegmentPolyBezier); } /// <summary> /// ArcTo - append an ArcTo to the current figure. /// </summary> public override void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection, bool isStroked, bool isSmoothJoin) { Debug.Assert(_figures != null); Debug.Assert(_currentFigure != null); FinishSegment(); // Is this the first segment? if (_segments == null) { // While we could always just retrieve _currentFigure.Segments (which would auto-promote) // it's more efficient to create the collection ourselves and set it explicitly. _segments = new PathSegmentCollection(); _currentFigure.Segments = _segments; } ArcSegment segment = new ArcSegment(); segment.Point = point; segment.Size = size; if (isLargeArc != s_defaultValueForArcSegmentIsLargeArc) { segment.IsLargeArc = isLargeArc; } if (sweepDirection != s_defaultValueForArcSegmentSweepDirection) { segment.SweepDirection = sweepDirection; } if (rotationAngle != s_defaultValueForArcSegmentRotationAngle) { segment.RotationAngle = rotationAngle; } // Handle common PathSegment properties. if (isStroked != s_defaultValueForPathSegmentIsStroked) { segment.IsStroked = isStroked; } if (isSmoothJoin != s_defaultValueForPathSegmentIsSmoothJoin) { segment.IsSmoothJoin = isSmoothJoin; } _segments.Add(segment); _currentSegmentType = MIL_SEGMENT_TYPE.MilSegmentArc; } /// <summary> /// PathStreamGeometryContext is never opened, so it shouldn't be closed. /// </summary> public override void Close() { Debug.Assert(false); } #endregion Public Methods /// <summary> /// GetPathGeometry - Retrieves the PathGeometry built by this Context. /// </summary> internal PathGeometry GetPathGeometry() { FinishSegment(); Debug.Assert(_currentSegmentPoints == null); return _pathGeometry; } private void GenericPolyTo(IList<Point> points, bool isStroked, bool isSmoothJoin, MIL_SEGMENT_TYPE segmentType) { Debug.Assert(points != null); int count = points.Count; PrepareToAddPoints(count, isStroked, isSmoothJoin, segmentType); for (int i = 0; i < count; ++i) { _currentSegmentPoints.Add(points[i]); } } private void PrepareToAddPoints( int count, bool isStroked, bool isSmoothJoin, MIL_SEGMENT_TYPE segmentType) { Debug.Assert(_figures != null); Debug.Assert(_currentFigure != null); Debug.Assert(count != 0); if (_currentSegmentType != segmentType || _currentSegmentIsStroked != isStroked || _currentSegmentIsSmoothJoin != isSmoothJoin) { FinishSegment(); _currentSegmentType = segmentType; _currentSegmentIsStroked = isStroked; _currentSegmentIsSmoothJoin = isSmoothJoin; } if (_currentSegmentPoints == null) { _currentSegmentPoints = new PointCollection(); } } /// <summary> /// FinishSegment - called to completed any outstanding Segment which may be present. /// </summary> private void FinishSegment() { if (_currentSegmentPoints != null) { Debug.Assert(_currentFigure != null); int count = _currentSegmentPoints.Count; Debug.Assert(count > 0); // Is this the first segment? if (_segments == null) { // While we could always just retrieve _currentFigure.Segments (which would auto-promote) // it's more efficient to create the collection ourselves and set it explicitly. _segments = new PathSegmentCollection(); _currentFigure.Segments = _segments; } PathSegment segment; switch (_currentSegmentType) { case MIL_SEGMENT_TYPE.MilSegmentPolyLine: if (count == 1) { LineSegment lSegment = new LineSegment(); lSegment.Point = _currentSegmentPoints[0]; segment = lSegment; } else { PolyLineSegment pSegment = new PolyLineSegment(); pSegment.Points = _currentSegmentPoints; segment = pSegment; } break; case MIL_SEGMENT_TYPE.MilSegmentPolyBezier: if (count == 3) { BezierSegment bSegment = new BezierSegment(); bSegment.Point1 = _currentSegmentPoints[0]; bSegment.Point2 = _currentSegmentPoints[1]; bSegment.Point3 = _currentSegmentPoints[2]; segment = bSegment; } else { Debug.Assert(count % 3 == 0); PolyBezierSegment pSegment = new PolyBezierSegment(); pSegment.Points = _currentSegmentPoints; segment = pSegment; } break; case MIL_SEGMENT_TYPE.MilSegmentPolyQuadraticBezier: if (count == 2) { QuadraticBezierSegment qSegment = new QuadraticBezierSegment(); qSegment.Point1 = _currentSegmentPoints[0]; qSegment.Point2 = _currentSegmentPoints[1]; segment = qSegment; } else { Debug.Assert(count % 2 == 0); PolyQuadraticBezierSegment pSegment = new PolyQuadraticBezierSegment(); pSegment.Points = _currentSegmentPoints; segment = pSegment; } break; default: segment = null; Debug.Assert(false); break; } // Handle common PathSegment properties. if (_currentSegmentIsStroked != s_defaultValueForPathSegmentIsStroked) { segment.IsStroked = _currentSegmentIsStroked; } if (_currentSegmentIsSmoothJoin != s_defaultValueForPathSegmentIsSmoothJoin) { segment.IsSmoothJoin = _currentSegmentIsSmoothJoin; } _segments.Add(segment); _currentSegmentPoints = null; _currentSegmentType = MIL_SEGMENT_TYPE.MilSegmentNone; } } #region Private Fields private PathGeometry _pathGeometry; private PathFigureCollection _figures; private PathFigure _currentFigure; private PathSegmentCollection _segments; private bool _currentIsClosed; private MIL_SEGMENT_TYPE _currentSegmentType; private PointCollection _currentSegmentPoints; private bool _currentSegmentIsStroked; private bool _currentSegmentIsSmoothJoin; private static FillRule s_defaultFillRule; private static bool s_defaultValueForPathFigureIsClosed; private static bool s_defaultValueForPathFigureIsFilled; private static Point s_defaultValueForPathFigureStartPoint; // This code assumes that sub-classes of PathSegment don't override the default value for these properties private static bool s_defaultValueForPathSegmentIsStroked; private static bool s_defaultValueForPathSegmentIsSmoothJoin; private static bool s_defaultValueForArcSegmentIsLargeArc; private static SweepDirection s_defaultValueForArcSegmentSweepDirection; private static double s_defaultValueForArcSegmentRotationAngle; #endregion Private Fields } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Debugging; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CompilationContext { private static readonly SymbolDisplayFormat s_fullNameFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); internal readonly CSharpCompilation Compilation; internal readonly Binder NamespaceBinder; // Internal for test purposes. private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; private readonly ImmutableHashSet<string> _hoistedParameterNames; private readonly ImmutableArray<LocalSymbol> _localsForBinding; private readonly CSharpSyntaxNode _syntax; private readonly bool _methodNotType; /// <summary> /// Create a context to compile expressions within a method scope. /// </summary> internal CompilationContext( CSharpCompilation compilation, MethodSymbol currentFrame, ImmutableArray<LocalSymbol> locals, InScopeHoistedLocals inScopeHoistedLocals, MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo, CSharpSyntaxNode syntax) { Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax)); // TODO: syntax.SyntaxTree should probably be added to the compilation, // but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet). _currentFrame = currentFrame; _syntax = syntax; _methodNotType = !locals.IsDefault; // NOTE: Since this is done within CompilationContext, it will not be cached. // CONSIDER: The values should be the same everywhere in the module, so they // could be cached. // (Catch: what happens in a type context without a method def?) this.Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords); // Each expression compile should use a unique compilation // to ensure expression-specific synthesized members can be // added (anonymous types, for instance). Debug.Assert(this.Compilation != compilation); this.NamespaceBinder = CreateBinderChain( this.Compilation, (PEModuleSymbol)currentFrame.ContainingModule, currentFrame.ContainingNamespace, methodDebugInfo.ImportRecordGroups); if (_methodNotType) { _locals = locals; ImmutableArray<string> displayClassVariableNamesInOrder; GetDisplayClassVariables( currentFrame, _locals, inScopeHoistedLocals, out displayClassVariableNamesInOrder, out _displayClassVariables, out _hoistedParameterNames); Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count); _localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables); } else { _locals = ImmutableArray<LocalSymbol>.Empty; _displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; _localsForBinding = ImmutableArray<LocalSymbol>.Empty; } // Assert that the cheap check for "this" is equivalent to the expensive check for "this". Debug.Assert( _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) == _displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This)); } internal CommonPEModuleBuilder CompileExpression( string typeName, string methodName, ImmutableArray<Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var properties = default(ResultProperties); var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( this.Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, methodName, this, (method, diags) => { var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()); var binder = ExtendBinderChain( _syntax, aliases, method, this.NamespaceBinder, hasDisplayClassThis, _methodNotType); var statementSyntax = _syntax as StatementSyntax; return (statementSyntax == null) ? BindExpression(binder, (ExpressionSyntax)_syntax, diags, out properties) : BindStatement(binder, statementSyntax, diags, out properties); }); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), synthesizedType: synthesizedType, testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } // Should be no name mangling since the caller provided explicit names. Debug.Assert(synthesizedType.MetadataName == typeName); Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName); resultProperties = properties; return module; } internal CommonPEModuleBuilder CompileAssignment( string typeName, string methodName, ImmutableArray<Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, methodName, this, (method, diags) => { var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()); var binder = ExtendBinderChain( _syntax, aliases, method, this.NamespaceBinder, hasDisplayClassThis, methodNotType: true); return BindAssignment(binder, (ExpressionSyntax)_syntax, diags); }); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType), synthesizedType: synthesizedType, testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } // Should be no name mangling since the caller provided explicit names. Debug.Assert(synthesizedType.MetadataName == typeName); Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName); resultProperties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect); return module; } private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder) { return string.Format("<>m{0}", builder.Count); } /// <summary> /// Generate a class containing methods that represent /// the set of arguments and locals at the current scope. /// </summary> internal CommonPEModuleBuilder CompileGetLocals( string typeName, ArrayBuilder<LocalAndMethod> localBuilder, bool argumentsOnly, ImmutableArray<Alias> aliases, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics) { var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object); var allTypeParameters = _currentFrame.GetAllTypeParameters(); var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance(); EENamedTypeSymbol typeVariablesType = null; if (!argumentsOnly && (allTypeParameters.Length > 0)) { // Generate a generic type with matching type parameters. // A null instance of the type will be used to represent the // "Type variables" local. typeVariablesType = new EENamedTypeSymbol( this.Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, ExpressionCompilerConstants.TypeVariablesClassName, (m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)), allTypeParameters, (t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2)); additionalTypes.Add(typeVariablesType); } var synthesizedType = new EENamedTypeSymbol( Compilation.SourceModule.GlobalNamespace, objectType, _syntax, _currentFrame, typeName, (m, container) => { var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance(); if (!argumentsOnly) { // Pseudo-variables: $exception, $ReturnValue, etc. if (aliases.Length > 0) { var sourceAssembly = Compilation.SourceAssembly; var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule); foreach (var alias in aliases) { if (alias.IsReturnValueWithoutIndex()) { Debug.Assert(aliases.Count(a => a.Kind == DkmClrAliasKind.ReturnValue) > 1); continue; } var local = PlaceholderLocalSymbol.Create( typeNameDecoder, _currentFrame, sourceAssembly, alias); var methodName = GetNextMethodName(methodBuilder); var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); var aliasMethod = this.CreateMethod(container, methodName, syntax, (method, diags) => { var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type); return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); var flags = local.IsWritable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult; localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags)); methodBuilder.Add(aliasMethod); } } // "this" for non-static methods that are not display class methods or // display class methods where the display class contains "<>4__this". if (!m.IsStatic && (!IsDisplayClassType(m.ContainingType) || _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()))) { var methodName = GetNextMethodName(methodBuilder); var method = this.GetThisMethod(container, methodName); localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11. methodBuilder.Add(method); } } // Hoisted method parameters (represented as locals in the EE). if (!_hoistedParameterNames.IsEmpty) { int localIndex = 0; foreach (var local in _localsForBinding) { // Since we are showing hoisted method parameters first, the parameters may appear out of order // in the Locals window if only some of the parameters are hoisted. This is consistent with the // behavior of the old EE. if (_hoistedParameterNames.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } } // Method parameters (except those that have been hoisted). int parameterIndex = m.IsStatic ? 0 : 1; foreach (var parameter in m.Parameters) { var parameterName = parameter.Name; if (!_hoistedParameterNames.Contains(parameterName) && GeneratedNames.GetKind(parameterName) == GeneratedNameKind.None) { AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex); } parameterIndex++; } if (!argumentsOnly) { // Locals. int localIndex = 0; foreach (var local in _localsForBinding) { if (!_hoistedParameterNames.Contains(local.Name)) { AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local)); } localIndex++; } // "Type variables". if ((object)typeVariablesType != null) { var methodName = GetNextMethodName(methodBuilder); var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); var method = this.GetTypeVariablesMethod(container, methodName, returnType); localBuilder.Add(new CSharpLocalAndMethod( ExpressionCompilerConstants.TypeVariablesLocalName, ExpressionCompilerConstants.TypeVariablesLocalName, method, DkmClrCompilationResultFlags.ReadOnlyResult)); methodBuilder.Add(method); } } return methodBuilder.ToImmutableAndFree(); }); additionalTypes.Add(synthesizedType); var module = CreateModuleBuilder( this.Compilation, synthesizedType.Methods, additionalTypes: additionalTypes.ToImmutableAndFree(), synthesizedType: synthesizedType, testData: testData, diagnostics: diagnostics); Debug.Assert(module != null); this.Compilation.Compile( module, emittingPdb: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: CancellationToken.None); return diagnostics.HasAnyErrors() ? null : module; } private void AppendLocalAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, LocalSymbol local, EENamedTypeSymbol container, int localIndex, DkmClrCompilationResultFlags resultFlags) { var methodName = GetNextMethodName(methodBuilder); var method = this.GetLocalMethod(container, methodName, local.Name, localIndex); localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags)); methodBuilder.Add(method); } private void AppendParameterAndMethod( ArrayBuilder<LocalAndMethod> localBuilder, ArrayBuilder<MethodSymbol> methodBuilder, ParameterSymbol parameter, EENamedTypeSymbol container, int parameterIndex) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name); var methodName = GetNextMethodName(methodBuilder); var method = this.GetParameterMethod(container, methodName, name, parameterIndex); localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None)); methodBuilder.Add(method); } private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags) { // Note: The native EE doesn't do this, but if we don't escape keyword identifiers, // the ResultProvider needs to be able to disambiguate cases like "this" and "@this", // which it can't do correctly without semantic information. var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name); var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName; return new CSharpLocalAndMethod(escapedName, displayName, method, flags); } private static EEAssemblyBuilder CreateModuleBuilder( CSharpCompilation compilation, ImmutableArray<MethodSymbol> methods, ImmutableArray<NamedTypeSymbol> additionalTypes, EENamedTypeSymbol synthesizedType, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData, DiagnosticBag diagnostics) { // Each assembly must have a unique name. var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName()); var dynamicOperationContextType = GetNonDisplayClassContainer(synthesizedType.SubstitutedSourceType); string runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics); var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion); return new EEAssemblyBuilder(compilation.SourceAssembly, emitOptions, methods, serializationProperties, additionalTypes, dynamicOperationContextType, testData); } internal EEMethodSymbol CreateMethod( EENamedTypeSymbol container, string methodName, CSharpSyntaxNode syntax, GenerateMethodBody generateMethodBody) { return new EEMethodSymbol( container, methodName, syntax.Location, _currentFrame, _locals, _localsForBinding, _displayClassVariables, generateMethodBody); } private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex) { var syntax = SyntaxFactory.IdentifierName(localName); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var local = method.LocalsForBinding[localIndex]; var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, diagnostics), type: local.Type); return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex) { var syntax = SyntaxFactory.IdentifierName(parameterName); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var parameter = method.Parameters[parameterIndex]; var expression = new BoundParameter(syntax, parameter); return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName) { var syntax = SyntaxFactory.ThisExpression(); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType)); return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; }); } private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType) { var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); return this.CreateMethod(container, methodName, syntax, (method, diagnostics) => { var type = method.TypeMap.SubstituteNamedType(typeVariablesType); var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]); var statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; return statement; }); } private static BoundStatement BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties) { var flags = DkmClrCompilationResultFlags.None; binder = binder.GetBinder(syntax); Debug.Assert(binder != null); // In addition to C# expressions, the native EE also supports // type names which are bound to a representation of the type // (but not System.Type) that the user can expand to see the // base type. Instead, we only allow valid C# expressions. var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } try { if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression)) { flags |= DkmClrCompilationResultFlags.PotentialSideEffect; } } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); resultProperties = default(ResultProperties); return null; } var expressionType = expression.Type; if ((object)expressionType == null) { expression = binder.CreateReturnConversion( syntax, diagnostics, expression, RefKind.None, binder.Compilation.GetSpecialType(SpecialType.System_Object)); if (diagnostics.HasAnyErrors()) { resultProperties = default(ResultProperties); return null; } } else if (expressionType.SpecialType == SpecialType.System_Void) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; Debug.Assert(expression.ConstantValue == null); resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false); return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else if (expressionType.SpecialType == SpecialType.System_Boolean) { flags |= DkmClrCompilationResultFlags.BoolResult; } if (!IsAssignableExpression(binder, expression)) { flags |= DkmClrCompilationResultFlags.ReadOnlyResult; } resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null); return binder.WrapWithVariablesIfAny(syntax, new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }); } private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties) { properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); return binder.BindStatement(syntax, diagnostics); } private static bool IsAssignableExpression(Binder binder, BoundExpression expression) { // NOTE: Surprisingly, binder.CheckValueKind will return true (!) for readonly fields // in contexts where they cannot be assigned - it simply reports a diagnostic. // Presumably, this is done to avoid producing a confusing error message about the // field not being an lvalue. var diagnostics = DiagnosticBag.GetInstance(); var result = binder.CheckValueKind(expression, Binder.BindValueKind.Assignment, diagnostics) && !diagnostics.HasAnyErrors(); diagnostics.Free(); return result; } private static BoundStatement BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics) { binder = binder.GetBinder(syntax); Debug.Assert(binder != null); var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue); if (diagnostics.HasAnyErrors()) { return null; } return binder.WrapWithVariablesIfAny(syntax, new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true }); } private static Binder CreateBinderChain( CSharpCompilation compilation, PEModuleSymbol module, NamespaceSymbol @namespace, ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups) { var stack = ArrayBuilder<string>.GetInstance(); while ((object)@namespace != null) { stack.Push(@namespace.Name); @namespace = @namespace.ContainingNamespace; } Binder binder = new BuckStopsHereBinder(compilation); var hasImports = !importRecordGroups.IsDefaultOrEmpty; var numImportStringGroups = hasImports ? importRecordGroups.Length : 0; var currentStringGroup = numImportStringGroups - 1; // PERF: We used to call compilation.GetCompilationNamespace on every iteration, // but that involved walking up to the global namespace, which we have to do // anyway. Instead, we'll inline the functionality into our own walk of the // namespace chain. @namespace = compilation.GlobalNamespace; while (stack.Count > 0) { var namespaceName = stack.Pop(); if (namespaceName.Length > 0) { // We're re-getting the namespace, rather than using the one containing // the current frame method, because we want the merged namespace. @namespace = @namespace.GetNestedNamespace(namespaceName); Debug.Assert((object)@namespace != null, $"We worked backwards from symbols to names, but no symbol exists for name '{namespaceName}'"); } else { Debug.Assert((object)@namespace == (object)compilation.GlobalNamespace); } Imports imports = null; if (hasImports) { if (currentStringGroup < 0) { Debug.WriteLine($"No import string group for namespace '{@namespace}'"); break; } var importsBinder = new InContainerBinder(@namespace, binder); imports = BuildImports(compilation, module, importRecordGroups[currentStringGroup], importsBinder); currentStringGroup--; } binder = new InContainerBinder(@namespace, binder, imports); } stack.Free(); if (currentStringGroup >= 0) { // CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since // the usings are already for the wrong method. Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces"); } return binder; } private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords) { if (externAliasRecords.IsDefaultOrEmpty) { return compilation.Clone(); } var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance(); var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance(); foreach (var reference in compilation.References) { updatedReferences.Add(reference); assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference)); } Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count); var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree(); foreach (var externAliasRecord in externAliasRecords) { var targetAssembly = externAliasRecord.TargetAssembly as AssemblySymbol; int index; if (targetAssembly != null) { index = assembliesAndModules.IndexOf(targetAssembly); } else { index = IndexOfMatchingAssembly((AssemblyIdentity)externAliasRecord.TargetAssembly, assembliesAndModules, compilation.Options.AssemblyIdentityComparer); } if (index < 0) { Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'"); continue; } var externAlias = externAliasRecord.Alias; var assemblyReference = updatedReferences[index]; var oldAliases = assemblyReference.Properties.Aliases; var newAliases = oldAliases.IsEmpty ? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias) : oldAliases.Concat(ImmutableArray.Create(externAlias)); // NOTE: Dev12 didn't emit custom debug info about "global", so we don't have // a good way to distinguish between a module aliased with both (e.g.) "X" and // "global" and a module aliased with only "X". As in Dev12, we assume that // "global" is a valid alias to remain at least as permissive as source. // NOTE: In the event that this introduces ambiguities between two assemblies // (e.g. because one was "global" in source and the other was "X"), it should be // possible to disambiguate as long as each assembly has a distinct extern alias, // not necessarily used in source. Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias)); // Replace the value in the map with the updated reference. updatedReferences[index] = assemblyReference.WithAliases(newAliases); } compilation = compilation.WithReferences(updatedReferences); updatedReferences.Free(); return compilation; } private static int IndexOfMatchingAssembly(AssemblyIdentity referenceIdentity, ImmutableArray<Symbol> assembliesAndModules, AssemblyIdentityComparer assemblyIdentityComparer) { for (int i = 0; i < assembliesAndModules.Length; i++) { var assembly = assembliesAndModules[i] as AssemblySymbol; if (assembly != null && assemblyIdentityComparer.ReferenceMatchesDefinition(referenceIdentity, assembly.Identity)) { return i; } } return -1; } private static Binder ExtendBinderChain( CSharpSyntaxNode syntax, ImmutableArray<Alias> aliases, EEMethodSymbol method, Binder binder, bool hasDisplayClassThis, bool methodNotType) { var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis); var substitutedSourceType = substitutedSourceMethod.ContainingType; var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance(); for (var type = substitutedSourceType; (object)type != null; type = type.ContainingType) { stack.Add(type); } while (stack.Count > 0) { substitutedSourceType = stack.Pop(); binder = new InContainerBinder(substitutedSourceType, binder); if (substitutedSourceType.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArguments, binder); } } stack.Free(); if (substitutedSourceMethod.Arity > 0) { binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArguments, binder); } if (methodNotType) { // Method locals and parameters shadow pseudo-variables. var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule); binder = new PlaceholderLocalBinder( syntax, aliases, method, typeNameDecoder, binder); } binder = new EEMethodBinder(method, substitutedSourceMethod, binder); if (methodNotType) { binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder); } binder = new ExecutableCodeBinder(syntax, binder.ContainingMemberOrLambda, binder); return binder; } private static Imports BuildImports(CSharpCompilation compilation, PEModuleSymbol module, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder) { // We make a first pass to extract all of the extern aliases because other imports may depend on them. var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance(); foreach (var importRecord in importRecords) { if (importRecord.TargetKind != ImportTargetKind.Assembly) { continue; } var alias = importRecord.Alias; IdentifierNameSyntax aliasNameSyntax; if (!TryParseIdentifierNameSyntax(alias, out aliasNameSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'"); continue; } var externAliasSyntax = SyntaxFactory.ExternAliasDirective(aliasNameSyntax.Identifier); var aliasSymbol = new AliasSymbol(binder, externAliasSyntax); // Binder is only used to access compilation. externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null)); // We have one, but we pass null for consistency. } var externs = externsBuilder.ToImmutableAndFree(); if (externs.Any()) { // NB: This binder (and corresponding Imports) is only used to bind the other imports. // We'll merge the externs into a final Imports object and return that to be used in // the actual binder chain. binder = new InContainerBinder( binder.Container, binder, Imports.FromCustomDebugInfo(binder.Compilation, ImmutableDictionary<string, AliasAndUsingDirective>.Empty, ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty, externs)); } var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>(); var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); foreach (var importRecord in importRecords) { switch (importRecord.TargetKind) { case ImportTargetKind.Type: { TypeSymbol typeSymbol = (TypeSymbol)importRecord.TargetType; Debug.Assert((object)typeSymbol != null); if (typeSymbol.IsErrorType()) { // Type is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } else if (importRecord.Alias == null && !typeSymbol.IsStatic) { // Only static types can be directly imported. continue; } if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Namespace: { var namespaceName = importRecord.TargetString; NameSyntax targetSyntax; if (!SyntaxHelpers.TryParseDottedName(namespaceName, out targetSyntax)) { // DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}". // Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}" // (which will rarely work and never be correct). Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'"); continue; } NamespaceSymbol globalNamespace; AssemblySymbol targetAssembly = (AssemblySymbol)importRecord.TargetAssembly; if (targetAssembly != null) { if (targetAssembly.IsMissing) { Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'"); continue; } globalNamespace = targetAssembly.GlobalNamespace; } else if (importRecord.TargetAssemblyAlias != null) { IdentifierNameSyntax externAliasSyntax = null; if (!TryParseIdentifierNameSyntax(importRecord.TargetAssemblyAlias, out externAliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } var unusedDiagnostics = DiagnosticBag.GetInstance(); var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, unusedDiagnostics); unusedDiagnostics.Free(); if ((object)aliasSymbol == null) { Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{importRecord.TargetAssemblyAlias}'"); continue; } globalNamespace = (NamespaceSymbol)aliasSymbol.Target; } else { globalNamespace = compilation.GlobalNamespace; } var namespaceSymbol = BindNamespace(namespaceName, globalNamespace); if ((object)namespaceSymbol == null) { // Namespace is unrecognized. The import may have been // valid in the original source but unnecessary. continue; // Don't add anything for this import. } if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord)) { continue; } break; } case ImportTargetKind.Assembly: { // Handled in first pass (above). break; } default: { throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind); } } } return Imports.FromCustomDebugInfo(binder.Compilation, usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs); } private static NamespaceSymbol BindNamespace(string namespaceName, NamespaceSymbol globalNamespace) { var namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = members.Length == 1 ? members[0] as NamespaceSymbol : null; if ((object)namespaceSymbol == null) { break; } } return namespaceSymbol; } private static bool TryAddImport( string alias, NamespaceOrTypeSymbol targetSymbol, ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder, ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases, InContainerBinder binder, ImportRecord importRecord) { if (alias == null) { usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null)); } else { IdentifierNameSyntax aliasSyntax; if (!TryParseIdentifierNameSyntax(alias, out aliasSyntax)) { Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'"); return false; } var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder); usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null)); } return true; } private static bool TryParseIdentifierNameSyntax(string name, out IdentifierNameSyntax syntax) { Debug.Assert(name != null); if (name == MetadataReferenceProperties.GlobalAlias) { syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); return true; } NameSyntax nameSyntax; if (!SyntaxHelpers.TryParseDottedName(name, out nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName) { syntax = null; return false; } syntax = (IdentifierNameSyntax)nameSyntax; return true; } internal CommonMessageProvider MessageProvider { get { return this.Compilation.MessageProvider; } } private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local) { // CONSIDER: We might want to prevent the user from modifying pinned locals - // that's pretty dangerous. return local.IsConst ? DkmClrCompilationResultFlags.ReadOnlyResult : DkmClrCompilationResultFlags.None; } /// <summary> /// Generate the set of locals to use for binding. /// </summary> private static ImmutableArray<LocalSymbol> GetLocalsForBinding( ImmutableArray<LocalSymbol> locals, ImmutableArray<string> displayClassVariableNamesInOrder, ImmutableDictionary<string, DisplayClassVariable> displayClassVariables) { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in locals) { var name = local.Name; if (name == null) { continue; } if (GeneratedNames.GetKind(name) != GeneratedNameKind.None) { continue; } // Although Roslyn doesn't name synthesized locals unless they are well-known to EE, // Dev12 did so we need to skip them here. if (GeneratedNames.IsSynthesizedLocalName(name)) { continue; } builder.Add(local); } foreach (var variableName in displayClassVariableNamesInOrder) { var variable = displayClassVariables[variableName]; switch (variable.Kind) { case DisplayClassVariableKind.Local: case DisplayClassVariableKind.Parameter: builder.Add(new EEDisplayClassFieldLocalSymbol(variable)); break; } } return builder.ToImmutableAndFree(); } /// <summary> /// Return a mapping of captured variables (parameters, locals, and /// "this") to locals. The mapping is needed to expose the original /// local identifiers (those from source) in the binder. /// </summary> private static void GetDisplayClassVariables( MethodSymbol method, ImmutableArray<LocalSymbol> locals, InScopeHoistedLocals inScopeHoistedLocals, out ImmutableArray<string> displayClassVariableNamesInOrder, out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables, out ImmutableHashSet<string> hoistedParameterNames) { // Calculated the shortest paths from locals to instances of display // classes. There should not be two instances of the same display // class immediately within any particular method. var displayClassTypes = PooledHashSet<NamedTypeSymbol>.GetInstance(); var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); // Add any display class instances from locals (these will contain any hoisted locals). foreach (var local in locals) { var name = local.Name; if ((name != null) && (GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField)) { var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } foreach (var parameter in method.Parameters) { if (GeneratedNames.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier) { var instance = new DisplayClassInstanceFromParameter(parameter); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } } var containingType = method.ContainingType; bool isIteratorOrAsyncMethod = false; if (IsDisplayClassType(containingType)) { if (!method.IsStatic) { // Add "this" display class instance. var instance = new DisplayClassInstanceFromParameter(method.ThisParameter); displayClassTypes.Add(instance.Type); displayClassInstances.Add(new DisplayClassInstanceAndFields(instance)); } isIteratorOrAsyncMethod = GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType; } if (displayClassInstances.Any()) { // Find any additional display class instances breadth first. for (int depth = 0; GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0; depth++) { } // The locals are the set of all fields from the display classes. var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance(); var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance(); var parameterNames = PooledHashSet<string>.GetInstance(); if (isIteratorOrAsyncMethod) { Debug.Assert(IsDisplayClassType(containingType)); foreach (var field in containingType.GetMembers().OfType<FieldSymbol>()) { // All iterator and async state machine fields (including hoisted locals) have mangled names, except // for hoisted parameters (whose field names are always the same as the original source parameters). var fieldName = field.Name; if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None) { parameterNames.Add(fieldName); } } } else { foreach (var p in method.Parameters) { parameterNames.Add(p.Name); } } var pooledHoistedParameterNames = PooledHashSet<string>.GetInstance(); foreach (var instance in displayClassInstances) { GetDisplayClassVariables( displayClassVariableNamesInOrderBuilder, displayClassVariablesBuilder, parameterNames, inScopeHoistedLocals, instance, pooledHoistedParameterNames); } hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet<string>(); pooledHoistedParameterNames.Free(); parameterNames.Free(); displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree(); displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary(); displayClassVariablesBuilder.Free(); } else { hoistedParameterNames = ImmutableHashSet<string>.Empty; displayClassVariableNamesInOrder = ImmutableArray<string>.Empty; displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty; } displayClassTypes.Free(); displayClassInstances.Free(); } /// <summary> /// Return the set of display class instances that can be reached /// from the given local. A particular display class may be reachable /// from multiple locals. In those cases, the instance from the /// shortest path (fewest intermediate fields) is returned. /// </summary> private static int GetDisplayClassInstances( HashSet<NamedTypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, int depth) { Debug.Assert(displayClassInstances.All(p => p.Depth <= depth)); var atDepth = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance(); atDepth.AddRange(displayClassInstances.Where(p => p.Depth == depth)); Debug.Assert(atDepth.Count > 0); int n = 0; foreach (var instance in atDepth) { n += GetDisplayClassInstances(displayClassTypes, displayClassInstances, instance); } atDepth.Free(); return n; } private static int GetDisplayClassInstances( HashSet<NamedTypeSymbol> displayClassTypes, ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances, DisplayClassInstanceAndFields instance) { // Display class instance. The display class fields are variables. int n = 0; foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldType = field.Type; var fieldKind = GeneratedNames.GetKind(field.Name); if (fieldKind == GeneratedNameKind.DisplayClassLocalOrField || fieldKind == GeneratedNameKind.TransparentIdentifier || IsTransparentIdentifierFieldInAnonymousType(field) || (fieldKind == GeneratedNameKind.ThisProxyField && GeneratedNames.GetKind(fieldType.Name) == GeneratedNameKind.LambdaDisplayClass)) // Async lambda case. { Debug.Assert(!field.IsStatic); // A local that is itself a display class instance. if (displayClassTypes.Add((NamedTypeSymbol)fieldType)) { var other = instance.FromField(field); displayClassInstances.Add(other); n++; } } } return n; } private static bool IsTransparentIdentifierFieldInAnonymousType(FieldSymbol field) { string fieldName = field.Name; if (GeneratedNames.GetKind(fieldName) != GeneratedNameKind.AnonymousTypeField) { return false; } GeneratedNameKind kind; int openBracketOffset; int closeBracketOffset; if (!GeneratedNames.TryParseGeneratedName(fieldName, out kind, out openBracketOffset, out closeBracketOffset)) { return false; } fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); return GeneratedNames.GetKind(fieldName) == GeneratedNameKind.TransparentIdentifier; } private static void GetDisplayClassVariables( ArrayBuilder<string> displayClassVariableNamesInOrderBuilder, Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder, HashSet<string> parameterNames, InScopeHoistedLocals inScopeHoistedLocals, DisplayClassInstanceAndFields instance, HashSet<string> hoistedParameterNames) { // Display class instance. The display class fields are variables. foreach (var member in instance.Type.GetMembers()) { if (member.Kind != SymbolKind.Field) { continue; } var field = (FieldSymbol)member; var fieldName = field.Name; REPARSE: DisplayClassVariableKind variableKind; string variableName; GeneratedNameKind fieldKind; int openBracketOffset; int closeBracketOffset; GeneratedNames.TryParseGeneratedName(fieldName, out fieldKind, out openBracketOffset, out closeBracketOffset); switch (fieldKind) { case GeneratedNameKind.AnonymousTypeField: Debug.Assert(fieldName == field.Name); // This only happens once. fieldName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); goto REPARSE; case GeneratedNameKind.TransparentIdentifier: // A transparent identifier (field) in an anonymous type synthesized for a transparent identifier. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.DisplayClassLocalOrField: // A local that is itself a display class instance. Debug.Assert(!field.IsStatic); continue; case GeneratedNameKind.HoistedLocalField: // Filter out hoisted locals that are known to be out-of-scope at the current IL offset. // Hoisted locals with invalid indices will be included since more information is better // than less in error scenarios. if (!inScopeHoistedLocals.IsInScope(fieldName)) { continue; } variableName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); variableKind = DisplayClassVariableKind.Local; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.ThisProxyField: // A reference to "this". variableName = fieldName; variableKind = DisplayClassVariableKind.This; Debug.Assert(!field.IsStatic); break; case GeneratedNameKind.None: // A reference to a parameter or local. variableName = fieldName; if (parameterNames.Contains(variableName)) { variableKind = DisplayClassVariableKind.Parameter; hoistedParameterNames.Add(variableName); } else { variableKind = DisplayClassVariableKind.Local; } Debug.Assert(!field.IsStatic); break; default: continue; } if (displayClassVariablesBuilder.ContainsKey(variableName)) { // Only expecting duplicates for async state machine // fields (that should be at the top-level). Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1); Debug.Assert(instance.Fields.Count() >= 1); // greater depth Debug.Assert((variableKind == DisplayClassVariableKind.Parameter) || (variableKind == DisplayClassVariableKind.This)); if (variableKind == DisplayClassVariableKind.Parameter && GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.LambdaDisplayClass) { displayClassVariablesBuilder[variableName] = instance.ToVariable(variableName, variableKind, field); } } else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass) { // In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one. // In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one). displayClassVariableNamesInOrderBuilder.Add(variableName); displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field)); } } } private static bool IsDisplayClassType(NamedTypeSymbol type) { switch (GeneratedNames.GetKind(type.Name)) { case GeneratedNameKind.LambdaDisplayClass: case GeneratedNameKind.StateMachineType: return true; default: return false; } } private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type) { // 1) Display class and state machine types are always nested within the types // that use them (so that they can access private members of those types). // 2) The native compiler used to produce nested display classes for nested lambdas, // so we may have to walk out more than one level. while (IsDisplayClassType(type)) { type = type.ContainingType; } Debug.Assert((object)type != null); return type; } /// <summary> /// Identifies the method in which binding should occur. /// </summary> /// <param name="candidateSubstitutedSourceMethod"> /// The symbol of the method that is currently on top of the callstack, with /// EE type parameters substituted in place of the original type parameters. /// </param> /// <param name="sourceMethodMustBeInstance"> /// True if "this" is available via a display class in the current context. /// </param> /// <returns> /// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated, /// then we will attempt to determine which user-defined method caused it to be /// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/> /// is a state machine MoveNext method, then we will try to find the iterator or /// async method for which it was generated. If we are able to find the original /// method, then we will substitute in the EE type parameters. Otherwise, we will /// return <paramref name="candidateSubstitutedSourceMethod"/>. /// </returns> /// <remarks> /// In the event that the original method is overloaded, we may not be able to determine /// which overload actually corresponds to the state machine. In particular, we do not /// have information about the signature of the original method (i.e. number of parameters, /// parameter types and ref-kinds, return type). However, we conjecture that this /// level of uncertainty is acceptable, since parameters are managed by a separate binder /// in the synthesized binder chain and we have enough information to check the other method /// properties that are used during binding (e.g. static-ness, generic arity, type parameter /// constraints). /// </remarks> internal static MethodSymbol GetSubstitutedSourceMethod( MethodSymbol candidateSubstitutedSourceMethod, bool sourceMethodMustBeInstance) { var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType; string desiredMethodName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) || GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName) || GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LocalFunction, out desiredMethodName)) { // We could be in the MoveNext method of an async lambda. string tempMethodName; if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName) || GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LocalFunction, out tempMethodName)) { desiredMethodName = tempMethodName; var containing = candidateSubstitutedSourceType.ContainingType; Debug.Assert((object)containing != null); if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass) { candidateSubstitutedSourceType = containing; sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField); } } var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters; // Type containing the original iterator, async, or lambda-containing method. var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType); foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>()) { if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance)) { return desiredTypeParameters.Length == 0 ? candidateMethod : candidateMethod.Construct(candidateSubstitutedSourceType.TypeArguments); } } Debug.Assert(false, "Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?"); } return candidateSubstitutedSourceMethod; } private static bool IsViableSourceMethod( MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, bool desiredMethodMustBeInstance) { return !candidateMethod.IsAbstract && (!(desiredMethodMustBeInstance && candidateMethod.IsStatic)) && candidateMethod.Name == desiredMethodName && HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters); } private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters) { int arity = candidateTypeParameters.Length; if (arity != desiredTypeParameters.Length) { return false; } else if (arity == 0) { return true; } var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity); var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true); var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true); return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap); } private struct DisplayClassInstanceAndFields { internal readonly DisplayClassInstance Instance; internal readonly ConsList<FieldSymbol> Fields; internal DisplayClassInstanceAndFields(DisplayClassInstance instance) : this(instance, ConsList<FieldSymbol>.Empty) { Debug.Assert(IsDisplayClassType(instance.Type) || GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType); } private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields) { this.Instance = instance; this.Fields = fields; } internal NamedTypeSymbol Type { get { return this.Fields.Any() ? (NamedTypeSymbol)this.Fields.Head.Type : this.Instance.Type; } } internal int Depth { get { return this.Fields.Count(); } } internal DisplayClassInstanceAndFields FromField(FieldSymbol field) { Debug.Assert(IsDisplayClassType((NamedTypeSymbol)field.Type) || GeneratedNames.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType); return new DisplayClassInstanceAndFields(this.Instance, this.Fields.Prepend(field)); } internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field) { return new DisplayClassVariable(name, kind, this.Instance, this.Fields.Prepend(field)); } } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; namespace Microsoft.Zelig.Test { public class ClassClassTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); Log.Comment("These tests examine the conversion (casting) of classes at various levels of inheritance trees."); Log.Comment("The two trees are SDer : S : SBase and TDer : T : TBase."); Log.Comment("The names of the tests describe the tests by listing which two classes will be converted between"); Log.Comment("Followed by which (The source or the destination) will contain a cast definition"); Log.Comment("Followed further by 'i's or 'e's to indicate which of the cast definition and the actual cast are"); Log.Comment("implicit or explicit."); Log.Comment(""); Log.Comment("For example, SBase_T_Source_i_e tests the conversion of SBase to T, with an implicit definition"); Log.Comment("of the cast in the SBase class, and an explicit cast in the body of the method."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run( string[] args ) { TestResult result = TestResult.Pass; string testName = "ClassClass_"; int testNumber = 0; result |= Assert.CheckFailed( ClassClass_SBase_TBase_Source_i_e_Test(), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TBase_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TBase_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TBase_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Dest_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_T_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TDer_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TDer_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SBase_TDer_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TBase_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TBase_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TBase_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TBase_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Dest_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_T_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TDer_Source_i_i_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TDer_Source_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_S_TDer_Source_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SDer_TBase_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SDer_TBase_Dest_e_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SDer_T_Dest_i_e_Test( ), testName, ++testNumber ); result |= Assert.CheckFailed( ClassClass_SDer_T_Dest_e_e_Test( ), testName, ++testNumber ); return result; } //ClassClass Test methods //The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\ClassClass //SBase_TBase_Source_i_e,SBase_TBase_Source_e_e,SBase_TBase_Dest_i_e,SBase_TBase_Dest_e_e,SBase_T_Source_i_i,SBase_T_Source_i_e,SBase_T_Source_e_e,SBase_T_Dest_i_i,SBase_T_Dest_i_e,SBase_T_Dest_e_e,SBase_TDer_Source_i_i,SBase_TDer_Source_i_e,SBase_TDer_Source_e_e,S_TBase_Source_i_e,S_TBase_Source_e_e,S_TBase_Dest_i_e,S_TBase_Dest_e_e,S_T_Source_i_i,S_T_Source_i_e,S_T_Source_e_e,S_T_Dest_i_i,S_T_Dest_i_e,S_T_Dest_e_e,S_TDer_Source_i_i,S_TDer_Source_i_e,S_TDer_Source_e_e,SDer_TBase_Dest_i_e,SDer_TBase_Dest_e_e,SDer_T_Dest_i_e,SDer_T_Dest_e_e //Test Case Calls [TestMethod] public TestResult ClassClass_SBase_TBase_Source_i_e_Test() { if (ClassClassTestClass_SBase_TBase_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TBase_Source_e_e_Test() { if (ClassClassTestClass_SBase_TBase_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TBase_Dest_i_e_Test() { if (ClassClassTestClass_SBase_TBase_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TBase_Dest_e_e_Test() { if (ClassClassTestClass_SBase_TBase_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Source_i_i_Test() { if (ClassClassTestClass_SBase_T_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Source_i_e_Test() { if (ClassClassTestClass_SBase_T_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Source_e_e_Test() { if (ClassClassTestClass_SBase_T_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Dest_i_i_Test() { if (ClassClassTestClass_SBase_T_Dest_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Dest_i_e_Test() { if (ClassClassTestClass_SBase_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_T_Dest_e_e_Test() { if (ClassClassTestClass_SBase_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TDer_Source_i_i_Test() { if (ClassClassTestClass_SBase_TDer_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TDer_Source_i_e_Test() { if (ClassClassTestClass_SBase_TDer_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SBase_TDer_Source_e_e_Test() { if (ClassClassTestClass_SBase_TDer_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TBase_Source_i_e_Test() { if (ClassClassTestClass_S_TBase_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TBase_Source_e_e_Test() { if (ClassClassTestClass_S_TBase_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TBase_Dest_i_e_Test() { if (ClassClassTestClass_S_TBase_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TBase_Dest_e_e_Test() { if (ClassClassTestClass_S_TBase_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Source_i_i_Test() { if (ClassClassTestClass_S_T_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Source_i_e_Test() { if (ClassClassTestClass_S_T_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Source_e_e_Test() { if (ClassClassTestClass_S_T_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Dest_i_i_Test() { if (ClassClassTestClass_S_T_Dest_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Dest_i_e_Test() { if (ClassClassTestClass_S_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_T_Dest_e_e_Test() { if (ClassClassTestClass_S_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TDer_Source_i_i_Test() { if (ClassClassTestClass_S_TDer_Source_i_i.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TDer_Source_i_e_Test() { if (ClassClassTestClass_S_TDer_Source_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_S_TDer_Source_e_e_Test() { if (ClassClassTestClass_S_TDer_Source_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SDer_TBase_Dest_i_e_Test() { if (ClassClassTestClass_SDer_TBase_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SDer_TBase_Dest_e_e_Test() { if (ClassClassTestClass_SDer_TBase_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SDer_T_Dest_i_e_Test() { if (ClassClassTestClass_SDer_T_Dest_i_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult ClassClass_SDer_T_Dest_e_e_Test() { if (ClassClassTestClass_SDer_T_Dest_e_e.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } //Compiled Test Cases class ClassClassTestClass_SBase_TBase_Source_i_e_SBase { static public implicit operator ClassClassTestClass_SBase_TBase_Source_i_e_TBase(ClassClassTestClass_SBase_TBase_Source_i_e_SBase foo) { return new ClassClassTestClass_SBase_TBase_Source_i_e_TBase(); } } class ClassClassTestClass_SBase_TBase_Source_i_e_S: ClassClassTestClass_SBase_TBase_Source_i_e_SBase { } class ClassClassTestClass_SBase_TBase_Source_i_e_SDer: ClassClassTestClass_SBase_TBase_Source_i_e_S { } class ClassClassTestClass_SBase_TBase_Source_i_e_TBase { } class ClassClassTestClass_SBase_TBase_Source_i_e_T: ClassClassTestClass_SBase_TBase_Source_i_e_TBase { } class ClassClassTestClass_SBase_TBase_Source_i_e_TDer: ClassClassTestClass_SBase_TBase_Source_i_e_T { } class ClassClassTestClass_SBase_TBase_Source_i_e { public static bool testMethod() { ClassClassTestClass_SBase_TBase_Source_i_e_S s = new ClassClassTestClass_SBase_TBase_Source_i_e_S(); ClassClassTestClass_SBase_TBase_Source_i_e_T t; try { t = (ClassClassTestClass_SBase_TBase_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TBase_Source_e_e_SBase { static public explicit operator ClassClassTestClass_SBase_TBase_Source_e_e_TBase(ClassClassTestClass_SBase_TBase_Source_e_e_SBase foo) { return new ClassClassTestClass_SBase_TBase_Source_e_e_TBase(); } } class ClassClassTestClass_SBase_TBase_Source_e_e_S: ClassClassTestClass_SBase_TBase_Source_e_e_SBase { } class ClassClassTestClass_SBase_TBase_Source_e_e_SDer: ClassClassTestClass_SBase_TBase_Source_e_e_S { } class ClassClassTestClass_SBase_TBase_Source_e_e_TBase { } class ClassClassTestClass_SBase_TBase_Source_e_e_T: ClassClassTestClass_SBase_TBase_Source_e_e_TBase { } class ClassClassTestClass_SBase_TBase_Source_e_e_TDer: ClassClassTestClass_SBase_TBase_Source_e_e_T { } class ClassClassTestClass_SBase_TBase_Source_e_e { public static bool testMethod() { ClassClassTestClass_SBase_TBase_Source_e_e_S s = new ClassClassTestClass_SBase_TBase_Source_e_e_S(); ClassClassTestClass_SBase_TBase_Source_e_e_T t; try { t = (ClassClassTestClass_SBase_TBase_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TBase_Dest_i_e_SBase { } class ClassClassTestClass_SBase_TBase_Dest_i_e_S: ClassClassTestClass_SBase_TBase_Dest_i_e_SBase { } class ClassClassTestClass_SBase_TBase_Dest_i_e_SDer: ClassClassTestClass_SBase_TBase_Dest_i_e_S { } class ClassClassTestClass_SBase_TBase_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_SBase_TBase_Dest_i_e_TBase(ClassClassTestClass_SBase_TBase_Dest_i_e_SBase foo) { return new ClassClassTestClass_SBase_TBase_Dest_i_e_TBase(); } } class ClassClassTestClass_SBase_TBase_Dest_i_e_T: ClassClassTestClass_SBase_TBase_Dest_i_e_TBase { } class ClassClassTestClass_SBase_TBase_Dest_i_e_TDer: ClassClassTestClass_SBase_TBase_Dest_i_e_T { } class ClassClassTestClass_SBase_TBase_Dest_i_e { public static bool testMethod() { ClassClassTestClass_SBase_TBase_Dest_i_e_S s = new ClassClassTestClass_SBase_TBase_Dest_i_e_S(); ClassClassTestClass_SBase_TBase_Dest_i_e_T t; try { t = (ClassClassTestClass_SBase_TBase_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TBase_Dest_e_e_SBase { } class ClassClassTestClass_SBase_TBase_Dest_e_e_S: ClassClassTestClass_SBase_TBase_Dest_e_e_SBase { } class ClassClassTestClass_SBase_TBase_Dest_e_e_SDer: ClassClassTestClass_SBase_TBase_Dest_e_e_S { } class ClassClassTestClass_SBase_TBase_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_SBase_TBase_Dest_e_e_TBase(ClassClassTestClass_SBase_TBase_Dest_e_e_SBase foo) { return new ClassClassTestClass_SBase_TBase_Dest_e_e_TBase(); } } class ClassClassTestClass_SBase_TBase_Dest_e_e_T: ClassClassTestClass_SBase_TBase_Dest_e_e_TBase { } class ClassClassTestClass_SBase_TBase_Dest_e_e_TDer: ClassClassTestClass_SBase_TBase_Dest_e_e_T { } class ClassClassTestClass_SBase_TBase_Dest_e_e { public static bool testMethod() { ClassClassTestClass_SBase_TBase_Dest_e_e_S s = new ClassClassTestClass_SBase_TBase_Dest_e_e_S(); ClassClassTestClass_SBase_TBase_Dest_e_e_T t; try { t = (ClassClassTestClass_SBase_TBase_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Source_i_i_SBase { static public implicit operator ClassClassTestClass_SBase_T_Source_i_i_T(ClassClassTestClass_SBase_T_Source_i_i_SBase foo) { return new ClassClassTestClass_SBase_T_Source_i_i_T(); } } class ClassClassTestClass_SBase_T_Source_i_i_S: ClassClassTestClass_SBase_T_Source_i_i_SBase { } class ClassClassTestClass_SBase_T_Source_i_i_SDer: ClassClassTestClass_SBase_T_Source_i_i_S { } class ClassClassTestClass_SBase_T_Source_i_i_TBase { } class ClassClassTestClass_SBase_T_Source_i_i_T: ClassClassTestClass_SBase_T_Source_i_i_TBase { } class ClassClassTestClass_SBase_T_Source_i_i_TDer: ClassClassTestClass_SBase_T_Source_i_i_T { } class ClassClassTestClass_SBase_T_Source_i_i { public static bool testMethod() { ClassClassTestClass_SBase_T_Source_i_i_S s = new ClassClassTestClass_SBase_T_Source_i_i_S(); ClassClassTestClass_SBase_T_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Source_i_e_SBase { static public implicit operator ClassClassTestClass_SBase_T_Source_i_e_T(ClassClassTestClass_SBase_T_Source_i_e_SBase foo) { return new ClassClassTestClass_SBase_T_Source_i_e_T(); } } class ClassClassTestClass_SBase_T_Source_i_e_S: ClassClassTestClass_SBase_T_Source_i_e_SBase { } class ClassClassTestClass_SBase_T_Source_i_e_SDer: ClassClassTestClass_SBase_T_Source_i_e_S { } class ClassClassTestClass_SBase_T_Source_i_e_TBase { } class ClassClassTestClass_SBase_T_Source_i_e_T: ClassClassTestClass_SBase_T_Source_i_e_TBase { } class ClassClassTestClass_SBase_T_Source_i_e_TDer: ClassClassTestClass_SBase_T_Source_i_e_T { } class ClassClassTestClass_SBase_T_Source_i_e { public static bool testMethod() { ClassClassTestClass_SBase_T_Source_i_e_S s = new ClassClassTestClass_SBase_T_Source_i_e_S(); ClassClassTestClass_SBase_T_Source_i_e_T t; try { t = (ClassClassTestClass_SBase_T_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Source_e_e_SBase { static public explicit operator ClassClassTestClass_SBase_T_Source_e_e_T(ClassClassTestClass_SBase_T_Source_e_e_SBase foo) { return new ClassClassTestClass_SBase_T_Source_e_e_T(); } } class ClassClassTestClass_SBase_T_Source_e_e_S: ClassClassTestClass_SBase_T_Source_e_e_SBase { } class ClassClassTestClass_SBase_T_Source_e_e_SDer: ClassClassTestClass_SBase_T_Source_e_e_S { } class ClassClassTestClass_SBase_T_Source_e_e_TBase { } class ClassClassTestClass_SBase_T_Source_e_e_T: ClassClassTestClass_SBase_T_Source_e_e_TBase { } class ClassClassTestClass_SBase_T_Source_e_e_TDer: ClassClassTestClass_SBase_T_Source_e_e_T { } class ClassClassTestClass_SBase_T_Source_e_e { public static bool testMethod() { ClassClassTestClass_SBase_T_Source_e_e_S s = new ClassClassTestClass_SBase_T_Source_e_e_S(); ClassClassTestClass_SBase_T_Source_e_e_T t; try { t = (ClassClassTestClass_SBase_T_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Dest_i_i_SBase { } class ClassClassTestClass_SBase_T_Dest_i_i_S: ClassClassTestClass_SBase_T_Dest_i_i_SBase { } class ClassClassTestClass_SBase_T_Dest_i_i_SDer: ClassClassTestClass_SBase_T_Dest_i_i_S { } class ClassClassTestClass_SBase_T_Dest_i_i_TBase { } class ClassClassTestClass_SBase_T_Dest_i_i_T: ClassClassTestClass_SBase_T_Dest_i_i_TBase { static public implicit operator ClassClassTestClass_SBase_T_Dest_i_i_T(ClassClassTestClass_SBase_T_Dest_i_i_SBase foo) { return new ClassClassTestClass_SBase_T_Dest_i_i_T(); } } class ClassClassTestClass_SBase_T_Dest_i_i_TDer: ClassClassTestClass_SBase_T_Dest_i_i_T { } class ClassClassTestClass_SBase_T_Dest_i_i { public static bool testMethod() { ClassClassTestClass_SBase_T_Dest_i_i_S s = new ClassClassTestClass_SBase_T_Dest_i_i_S(); ClassClassTestClass_SBase_T_Dest_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Dest_i_e_SBase { } class ClassClassTestClass_SBase_T_Dest_i_e_S: ClassClassTestClass_SBase_T_Dest_i_e_SBase { } class ClassClassTestClass_SBase_T_Dest_i_e_SDer: ClassClassTestClass_SBase_T_Dest_i_e_S { } class ClassClassTestClass_SBase_T_Dest_i_e_TBase { } class ClassClassTestClass_SBase_T_Dest_i_e_T: ClassClassTestClass_SBase_T_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_SBase_T_Dest_i_e_T(ClassClassTestClass_SBase_T_Dest_i_e_SBase foo) { return new ClassClassTestClass_SBase_T_Dest_i_e_T(); } } class ClassClassTestClass_SBase_T_Dest_i_e_TDer: ClassClassTestClass_SBase_T_Dest_i_e_T { } class ClassClassTestClass_SBase_T_Dest_i_e { public static bool testMethod() { ClassClassTestClass_SBase_T_Dest_i_e_S s = new ClassClassTestClass_SBase_T_Dest_i_e_S(); ClassClassTestClass_SBase_T_Dest_i_e_T t; try { t = (ClassClassTestClass_SBase_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_T_Dest_e_e_SBase { } class ClassClassTestClass_SBase_T_Dest_e_e_S: ClassClassTestClass_SBase_T_Dest_e_e_SBase { } class ClassClassTestClass_SBase_T_Dest_e_e_SDer: ClassClassTestClass_SBase_T_Dest_e_e_S { } class ClassClassTestClass_SBase_T_Dest_e_e_TBase { } class ClassClassTestClass_SBase_T_Dest_e_e_T: ClassClassTestClass_SBase_T_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_SBase_T_Dest_e_e_T(ClassClassTestClass_SBase_T_Dest_e_e_SBase foo) { return new ClassClassTestClass_SBase_T_Dest_e_e_T(); } } class ClassClassTestClass_SBase_T_Dest_e_e_TDer: ClassClassTestClass_SBase_T_Dest_e_e_T { } class ClassClassTestClass_SBase_T_Dest_e_e { public static bool testMethod() { ClassClassTestClass_SBase_T_Dest_e_e_S s = new ClassClassTestClass_SBase_T_Dest_e_e_S(); ClassClassTestClass_SBase_T_Dest_e_e_T t; try { t = (ClassClassTestClass_SBase_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TDer_Source_i_i_SBase { static public implicit operator ClassClassTestClass_SBase_TDer_Source_i_i_TDer(ClassClassTestClass_SBase_TDer_Source_i_i_SBase foo) { return new ClassClassTestClass_SBase_TDer_Source_i_i_TDer(); } } class ClassClassTestClass_SBase_TDer_Source_i_i_S: ClassClassTestClass_SBase_TDer_Source_i_i_SBase { } class ClassClassTestClass_SBase_TDer_Source_i_i_SDer: ClassClassTestClass_SBase_TDer_Source_i_i_S { } class ClassClassTestClass_SBase_TDer_Source_i_i_TBase { } class ClassClassTestClass_SBase_TDer_Source_i_i_T: ClassClassTestClass_SBase_TDer_Source_i_i_TBase { } class ClassClassTestClass_SBase_TDer_Source_i_i_TDer: ClassClassTestClass_SBase_TDer_Source_i_i_T { } class ClassClassTestClass_SBase_TDer_Source_i_i { public static bool testMethod() { ClassClassTestClass_SBase_TDer_Source_i_i_S s= new ClassClassTestClass_SBase_TDer_Source_i_i_S(); ClassClassTestClass_SBase_TDer_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TDer_Source_i_e_SBase { static public implicit operator ClassClassTestClass_SBase_TDer_Source_i_e_TDer(ClassClassTestClass_SBase_TDer_Source_i_e_SBase foo) { return new ClassClassTestClass_SBase_TDer_Source_i_e_TDer(); } } class ClassClassTestClass_SBase_TDer_Source_i_e_S: ClassClassTestClass_SBase_TDer_Source_i_e_SBase { } class ClassClassTestClass_SBase_TDer_Source_i_e_SDer: ClassClassTestClass_SBase_TDer_Source_i_e_S { } class ClassClassTestClass_SBase_TDer_Source_i_e_TBase { } class ClassClassTestClass_SBase_TDer_Source_i_e_T: ClassClassTestClass_SBase_TDer_Source_i_e_TBase { } class ClassClassTestClass_SBase_TDer_Source_i_e_TDer: ClassClassTestClass_SBase_TDer_Source_i_e_T { } class ClassClassTestClass_SBase_TDer_Source_i_e { public static bool testMethod() { ClassClassTestClass_SBase_TDer_Source_i_e_S s = new ClassClassTestClass_SBase_TDer_Source_i_e_S(); ClassClassTestClass_SBase_TDer_Source_i_e_T t; try { t = (ClassClassTestClass_SBase_TDer_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SBase_TDer_Source_e_e_SBase { static public explicit operator ClassClassTestClass_SBase_TDer_Source_e_e_TDer(ClassClassTestClass_SBase_TDer_Source_e_e_SBase foo) { return new ClassClassTestClass_SBase_TDer_Source_e_e_TDer(); } } class ClassClassTestClass_SBase_TDer_Source_e_e_S: ClassClassTestClass_SBase_TDer_Source_e_e_SBase { } class ClassClassTestClass_SBase_TDer_Source_e_e_SDer: ClassClassTestClass_SBase_TDer_Source_e_e_S { } class ClassClassTestClass_SBase_TDer_Source_e_e_TBase { } class ClassClassTestClass_SBase_TDer_Source_e_e_T: ClassClassTestClass_SBase_TDer_Source_e_e_TBase { } class ClassClassTestClass_SBase_TDer_Source_e_e_TDer: ClassClassTestClass_SBase_TDer_Source_e_e_T { } class ClassClassTestClass_SBase_TDer_Source_e_e { public static bool testMethod() { ClassClassTestClass_SBase_TDer_Source_e_e_S s = new ClassClassTestClass_SBase_TDer_Source_e_e_S(); ClassClassTestClass_SBase_TDer_Source_e_e_T t; try { t = (ClassClassTestClass_SBase_TDer_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TBase_Source_i_e_SBase { } class ClassClassTestClass_S_TBase_Source_i_e_S: ClassClassTestClass_S_TBase_Source_i_e_SBase { static public implicit operator ClassClassTestClass_S_TBase_Source_i_e_TBase(ClassClassTestClass_S_TBase_Source_i_e_S foo) { return new ClassClassTestClass_S_TBase_Source_i_e_TBase(); } } class ClassClassTestClass_S_TBase_Source_i_e_SDer: ClassClassTestClass_S_TBase_Source_i_e_S { } class ClassClassTestClass_S_TBase_Source_i_e_TBase { } class ClassClassTestClass_S_TBase_Source_i_e_T: ClassClassTestClass_S_TBase_Source_i_e_TBase { } class ClassClassTestClass_S_TBase_Source_i_e_TDer: ClassClassTestClass_S_TBase_Source_i_e_T { } class ClassClassTestClass_S_TBase_Source_i_e { public static bool testMethod() { ClassClassTestClass_S_TBase_Source_i_e_S s = new ClassClassTestClass_S_TBase_Source_i_e_S(); ClassClassTestClass_S_TBase_Source_i_e_T t; try { t = (ClassClassTestClass_S_TBase_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TBase_Source_e_e_SBase { } class ClassClassTestClass_S_TBase_Source_e_e_S: ClassClassTestClass_S_TBase_Source_e_e_SBase { static public explicit operator ClassClassTestClass_S_TBase_Source_e_e_TBase(ClassClassTestClass_S_TBase_Source_e_e_S foo) { return new ClassClassTestClass_S_TBase_Source_e_e_TBase(); } } class ClassClassTestClass_S_TBase_Source_e_e_SDer: ClassClassTestClass_S_TBase_Source_e_e_S { } class ClassClassTestClass_S_TBase_Source_e_e_TBase { } class ClassClassTestClass_S_TBase_Source_e_e_T: ClassClassTestClass_S_TBase_Source_e_e_TBase { } class ClassClassTestClass_S_TBase_Source_e_e_TDer: ClassClassTestClass_S_TBase_Source_e_e_T { } class ClassClassTestClass_S_TBase_Source_e_e { public static bool testMethod() { ClassClassTestClass_S_TBase_Source_e_e_S s = new ClassClassTestClass_S_TBase_Source_e_e_S(); ClassClassTestClass_S_TBase_Source_e_e_T t; try { t = (ClassClassTestClass_S_TBase_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TBase_Dest_i_e_SBase { } class ClassClassTestClass_S_TBase_Dest_i_e_S: ClassClassTestClass_S_TBase_Dest_i_e_SBase { } class ClassClassTestClass_S_TBase_Dest_i_e_SDer: ClassClassTestClass_S_TBase_Dest_i_e_S { } class ClassClassTestClass_S_TBase_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_S_TBase_Dest_i_e_TBase(ClassClassTestClass_S_TBase_Dest_i_e_S foo) { return new ClassClassTestClass_S_TBase_Dest_i_e_TBase(); } } class ClassClassTestClass_S_TBase_Dest_i_e_T: ClassClassTestClass_S_TBase_Dest_i_e_TBase { } class ClassClassTestClass_S_TBase_Dest_i_e_TDer: ClassClassTestClass_S_TBase_Dest_i_e_T { } class ClassClassTestClass_S_TBase_Dest_i_e { public static bool testMethod() { ClassClassTestClass_S_TBase_Dest_i_e_S s = new ClassClassTestClass_S_TBase_Dest_i_e_S(); ClassClassTestClass_S_TBase_Dest_i_e_T t; try { t = (ClassClassTestClass_S_TBase_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TBase_Dest_e_e_SBase { } class ClassClassTestClass_S_TBase_Dest_e_e_S: ClassClassTestClass_S_TBase_Dest_e_e_SBase { } class ClassClassTestClass_S_TBase_Dest_e_e_SDer: ClassClassTestClass_S_TBase_Dest_e_e_S { } class ClassClassTestClass_S_TBase_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_S_TBase_Dest_e_e_TBase(ClassClassTestClass_S_TBase_Dest_e_e_S foo) { return new ClassClassTestClass_S_TBase_Dest_e_e_TBase(); } } class ClassClassTestClass_S_TBase_Dest_e_e_T: ClassClassTestClass_S_TBase_Dest_e_e_TBase { } class ClassClassTestClass_S_TBase_Dest_e_e_TDer: ClassClassTestClass_S_TBase_Dest_e_e_T { } class ClassClassTestClass_S_TBase_Dest_e_e { public static bool testMethod() { ClassClassTestClass_S_TBase_Dest_e_e_S s = new ClassClassTestClass_S_TBase_Dest_e_e_S(); ClassClassTestClass_S_TBase_Dest_e_e_T t; try { t = (ClassClassTestClass_S_TBase_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Source_i_i_SBase { } class ClassClassTestClass_S_T_Source_i_i_S: ClassClassTestClass_S_T_Source_i_i_SBase { static public implicit operator ClassClassTestClass_S_T_Source_i_i_T(ClassClassTestClass_S_T_Source_i_i_S foo) { return new ClassClassTestClass_S_T_Source_i_i_T(); } } class ClassClassTestClass_S_T_Source_i_i_SDer: ClassClassTestClass_S_T_Source_i_i_S { } class ClassClassTestClass_S_T_Source_i_i_TBase { } class ClassClassTestClass_S_T_Source_i_i_T: ClassClassTestClass_S_T_Source_i_i_TBase { } class ClassClassTestClass_S_T_Source_i_i_TDer: ClassClassTestClass_S_T_Source_i_i_T { } class ClassClassTestClass_S_T_Source_i_i { public static bool testMethod() { ClassClassTestClass_S_T_Source_i_i_S s = new ClassClassTestClass_S_T_Source_i_i_S(); ClassClassTestClass_S_T_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Source_i_e_SBase { } class ClassClassTestClass_S_T_Source_i_e_S: ClassClassTestClass_S_T_Source_i_e_SBase { static public implicit operator ClassClassTestClass_S_T_Source_i_e_T(ClassClassTestClass_S_T_Source_i_e_S foo) { return new ClassClassTestClass_S_T_Source_i_e_T(); } } class ClassClassTestClass_S_T_Source_i_e_SDer: ClassClassTestClass_S_T_Source_i_e_S { } class ClassClassTestClass_S_T_Source_i_e_TBase { } class ClassClassTestClass_S_T_Source_i_e_T: ClassClassTestClass_S_T_Source_i_e_TBase { } class ClassClassTestClass_S_T_Source_i_e_TDer: ClassClassTestClass_S_T_Source_i_e_T { } class ClassClassTestClass_S_T_Source_i_e { public static bool testMethod() { ClassClassTestClass_S_T_Source_i_e_S s = new ClassClassTestClass_S_T_Source_i_e_S(); ClassClassTestClass_S_T_Source_i_e_T t; try { t = (ClassClassTestClass_S_T_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Source_e_e_SBase { } class ClassClassTestClass_S_T_Source_e_e_S: ClassClassTestClass_S_T_Source_e_e_SBase { static public explicit operator ClassClassTestClass_S_T_Source_e_e_T(ClassClassTestClass_S_T_Source_e_e_S foo) { return new ClassClassTestClass_S_T_Source_e_e_T(); } } class ClassClassTestClass_S_T_Source_e_e_SDer: ClassClassTestClass_S_T_Source_e_e_S { } class ClassClassTestClass_S_T_Source_e_e_TBase { } class ClassClassTestClass_S_T_Source_e_e_T: ClassClassTestClass_S_T_Source_e_e_TBase { } class ClassClassTestClass_S_T_Source_e_e_TDer: ClassClassTestClass_S_T_Source_e_e_T { } class ClassClassTestClass_S_T_Source_e_e { public static bool testMethod() { ClassClassTestClass_S_T_Source_e_e_S s = new ClassClassTestClass_S_T_Source_e_e_S(); ClassClassTestClass_S_T_Source_e_e_T t; try { t = (ClassClassTestClass_S_T_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Dest_i_i_SBase { } class ClassClassTestClass_S_T_Dest_i_i_S: ClassClassTestClass_S_T_Dest_i_i_SBase { } class ClassClassTestClass_S_T_Dest_i_i_SDer: ClassClassTestClass_S_T_Dest_i_i_S { } class ClassClassTestClass_S_T_Dest_i_i_TBase { } class ClassClassTestClass_S_T_Dest_i_i_T: ClassClassTestClass_S_T_Dest_i_i_TBase { static public implicit operator ClassClassTestClass_S_T_Dest_i_i_T(ClassClassTestClass_S_T_Dest_i_i_S foo) { return new ClassClassTestClass_S_T_Dest_i_i_T(); } } class ClassClassTestClass_S_T_Dest_i_i_TDer: ClassClassTestClass_S_T_Dest_i_i_T { } class ClassClassTestClass_S_T_Dest_i_i { public static bool testMethod() { ClassClassTestClass_S_T_Dest_i_i_S s = new ClassClassTestClass_S_T_Dest_i_i_S(); ClassClassTestClass_S_T_Dest_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Dest_i_e_SBase { } class ClassClassTestClass_S_T_Dest_i_e_S: ClassClassTestClass_S_T_Dest_i_e_SBase { } class ClassClassTestClass_S_T_Dest_i_e_SDer: ClassClassTestClass_S_T_Dest_i_e_S { } class ClassClassTestClass_S_T_Dest_i_e_TBase { } class ClassClassTestClass_S_T_Dest_i_e_T: ClassClassTestClass_S_T_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_S_T_Dest_i_e_T(ClassClassTestClass_S_T_Dest_i_e_S foo) { return new ClassClassTestClass_S_T_Dest_i_e_T(); } } class ClassClassTestClass_S_T_Dest_i_e_TDer: ClassClassTestClass_S_T_Dest_i_e_T { } class ClassClassTestClass_S_T_Dest_i_e { public static bool testMethod() { ClassClassTestClass_S_T_Dest_i_e_S s = new ClassClassTestClass_S_T_Dest_i_e_S(); ClassClassTestClass_S_T_Dest_i_e_T t; try { t = (ClassClassTestClass_S_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_T_Dest_e_e_SBase { } class ClassClassTestClass_S_T_Dest_e_e_S: ClassClassTestClass_S_T_Dest_e_e_SBase { } class ClassClassTestClass_S_T_Dest_e_e_SDer: ClassClassTestClass_S_T_Dest_e_e_S { } class ClassClassTestClass_S_T_Dest_e_e_TBase { } class ClassClassTestClass_S_T_Dest_e_e_T: ClassClassTestClass_S_T_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_S_T_Dest_e_e_T(ClassClassTestClass_S_T_Dest_e_e_S foo) { return new ClassClassTestClass_S_T_Dest_e_e_T(); } } class ClassClassTestClass_S_T_Dest_e_e_TDer: ClassClassTestClass_S_T_Dest_e_e_T { } class ClassClassTestClass_S_T_Dest_e_e { public static bool testMethod() { ClassClassTestClass_S_T_Dest_e_e_S s = new ClassClassTestClass_S_T_Dest_e_e_S(); ClassClassTestClass_S_T_Dest_e_e_T t; try { t = (ClassClassTestClass_S_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TDer_Source_i_i_SBase { } class ClassClassTestClass_S_TDer_Source_i_i_S: ClassClassTestClass_S_TDer_Source_i_i_SBase { static public implicit operator ClassClassTestClass_S_TDer_Source_i_i_TDer(ClassClassTestClass_S_TDer_Source_i_i_S foo) { return new ClassClassTestClass_S_TDer_Source_i_i_TDer(); } } class ClassClassTestClass_S_TDer_Source_i_i_SDer: ClassClassTestClass_S_TDer_Source_i_i_S { } class ClassClassTestClass_S_TDer_Source_i_i_TBase { } class ClassClassTestClass_S_TDer_Source_i_i_T: ClassClassTestClass_S_TDer_Source_i_i_TBase { } class ClassClassTestClass_S_TDer_Source_i_i_TDer: ClassClassTestClass_S_TDer_Source_i_i_T { } class ClassClassTestClass_S_TDer_Source_i_i { public static bool testMethod() { ClassClassTestClass_S_TDer_Source_i_i_S s = new ClassClassTestClass_S_TDer_Source_i_i_S(); ClassClassTestClass_S_TDer_Source_i_i_T t; try { t = s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TDer_Source_i_e_SBase { } class ClassClassTestClass_S_TDer_Source_i_e_S: ClassClassTestClass_S_TDer_Source_i_e_SBase { static public implicit operator ClassClassTestClass_S_TDer_Source_i_e_TDer(ClassClassTestClass_S_TDer_Source_i_e_S foo) { return new ClassClassTestClass_S_TDer_Source_i_e_TDer(); } } class ClassClassTestClass_S_TDer_Source_i_e_SDer: ClassClassTestClass_S_TDer_Source_i_e_S { } class ClassClassTestClass_S_TDer_Source_i_e_TBase { } class ClassClassTestClass_S_TDer_Source_i_e_T: ClassClassTestClass_S_TDer_Source_i_e_TBase { } class ClassClassTestClass_S_TDer_Source_i_e_TDer: ClassClassTestClass_S_TDer_Source_i_e_T { } class ClassClassTestClass_S_TDer_Source_i_e { public static bool testMethod() { ClassClassTestClass_S_TDer_Source_i_e_S s = new ClassClassTestClass_S_TDer_Source_i_e_S(); ClassClassTestClass_S_TDer_Source_i_e_T t; try { t = (ClassClassTestClass_S_TDer_Source_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_S_TDer_Source_e_e_SBase { } class ClassClassTestClass_S_TDer_Source_e_e_S: ClassClassTestClass_S_TDer_Source_e_e_SBase { static public explicit operator ClassClassTestClass_S_TDer_Source_e_e_TDer(ClassClassTestClass_S_TDer_Source_e_e_S foo) { return new ClassClassTestClass_S_TDer_Source_e_e_TDer(); } } class ClassClassTestClass_S_TDer_Source_e_e_SDer: ClassClassTestClass_S_TDer_Source_e_e_S { } class ClassClassTestClass_S_TDer_Source_e_e_TBase { } class ClassClassTestClass_S_TDer_Source_e_e_T: ClassClassTestClass_S_TDer_Source_e_e_TBase { } class ClassClassTestClass_S_TDer_Source_e_e_TDer: ClassClassTestClass_S_TDer_Source_e_e_T { } class ClassClassTestClass_S_TDer_Source_e_e { public static bool testMethod() { ClassClassTestClass_S_TDer_Source_e_e_S s = new ClassClassTestClass_S_TDer_Source_e_e_S(); ClassClassTestClass_S_TDer_Source_e_e_T t; try { t = (ClassClassTestClass_S_TDer_Source_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SDer_TBase_Dest_i_e_SBase { } class ClassClassTestClass_SDer_TBase_Dest_i_e_S: ClassClassTestClass_SDer_TBase_Dest_i_e_SBase { } class ClassClassTestClass_SDer_TBase_Dest_i_e_SDer: ClassClassTestClass_SDer_TBase_Dest_i_e_S { } class ClassClassTestClass_SDer_TBase_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_SDer_TBase_Dest_i_e_TBase(ClassClassTestClass_SDer_TBase_Dest_i_e_SDer foo) { return new ClassClassTestClass_SDer_TBase_Dest_i_e_TBase(); } } class ClassClassTestClass_SDer_TBase_Dest_i_e_T: ClassClassTestClass_SDer_TBase_Dest_i_e_TBase { } class ClassClassTestClass_SDer_TBase_Dest_i_e_TDer: ClassClassTestClass_SDer_TBase_Dest_i_e_T { } class ClassClassTestClass_SDer_TBase_Dest_i_e { public static bool testMethod() { ClassClassTestClass_SDer_TBase_Dest_i_e_S s = new ClassClassTestClass_SDer_TBase_Dest_i_e_S(); ClassClassTestClass_SDer_TBase_Dest_i_e_T t; try { t = (ClassClassTestClass_SDer_TBase_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SDer_TBase_Dest_e_e_SBase { } class ClassClassTestClass_SDer_TBase_Dest_e_e_S: ClassClassTestClass_SDer_TBase_Dest_e_e_SBase { } class ClassClassTestClass_SDer_TBase_Dest_e_e_SDer: ClassClassTestClass_SDer_TBase_Dest_e_e_S { } class ClassClassTestClass_SDer_TBase_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_SDer_TBase_Dest_e_e_TBase(ClassClassTestClass_SDer_TBase_Dest_e_e_SDer foo) { return new ClassClassTestClass_SDer_TBase_Dest_e_e_TBase(); } } class ClassClassTestClass_SDer_TBase_Dest_e_e_T: ClassClassTestClass_SDer_TBase_Dest_e_e_TBase { } class ClassClassTestClass_SDer_TBase_Dest_e_e_TDer: ClassClassTestClass_SDer_TBase_Dest_e_e_T { } class ClassClassTestClass_SDer_TBase_Dest_e_e { public static bool testMethod() { ClassClassTestClass_SDer_TBase_Dest_e_e_S s = new ClassClassTestClass_SDer_TBase_Dest_e_e_S(); ClassClassTestClass_SDer_TBase_Dest_e_e_T t; try { t = (ClassClassTestClass_SDer_TBase_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SDer_T_Dest_i_e_SBase { } class ClassClassTestClass_SDer_T_Dest_i_e_S: ClassClassTestClass_SDer_T_Dest_i_e_SBase { } class ClassClassTestClass_SDer_T_Dest_i_e_SDer: ClassClassTestClass_SDer_T_Dest_i_e_S { } class ClassClassTestClass_SDer_T_Dest_i_e_TBase { } class ClassClassTestClass_SDer_T_Dest_i_e_T: ClassClassTestClass_SDer_T_Dest_i_e_TBase { static public implicit operator ClassClassTestClass_SDer_T_Dest_i_e_T(ClassClassTestClass_SDer_T_Dest_i_e_SDer foo) { return new ClassClassTestClass_SDer_T_Dest_i_e_T(); } } class ClassClassTestClass_SDer_T_Dest_i_e_TDer: ClassClassTestClass_SDer_T_Dest_i_e_T { } class ClassClassTestClass_SDer_T_Dest_i_e { public static bool testMethod() { ClassClassTestClass_SDer_T_Dest_i_e_S s = new ClassClassTestClass_SDer_T_Dest_i_e_S(); ClassClassTestClass_SDer_T_Dest_i_e_T t; try { t = (ClassClassTestClass_SDer_T_Dest_i_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } class ClassClassTestClass_SDer_T_Dest_e_e_SBase { } class ClassClassTestClass_SDer_T_Dest_e_e_S: ClassClassTestClass_SDer_T_Dest_e_e_SBase { } class ClassClassTestClass_SDer_T_Dest_e_e_SDer: ClassClassTestClass_SDer_T_Dest_e_e_S { } class ClassClassTestClass_SDer_T_Dest_e_e_TBase { } class ClassClassTestClass_SDer_T_Dest_e_e_T: ClassClassTestClass_SDer_T_Dest_e_e_TBase { static public explicit operator ClassClassTestClass_SDer_T_Dest_e_e_T(ClassClassTestClass_SDer_T_Dest_e_e_SDer foo) { return new ClassClassTestClass_SDer_T_Dest_e_e_T(); } } class ClassClassTestClass_SDer_T_Dest_e_e_TDer: ClassClassTestClass_SDer_T_Dest_e_e_T { } class ClassClassTestClass_SDer_T_Dest_e_e { public static bool testMethod() { ClassClassTestClass_SDer_T_Dest_e_e_S s = new ClassClassTestClass_SDer_T_Dest_e_e_S(); ClassClassTestClass_SDer_T_Dest_e_e_T t; try { t = (ClassClassTestClass_SDer_T_Dest_e_e_T)s; } catch (System.Exception) { Log.Comment("System.Exception caught"); } return true; } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <[email protected]> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using System.Data; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Net; namespace fyiReporting.Data { /// <summary> /// LogDataReader handles reading log files /// </summary> public class LogDataReader : IDataReader { LogConnection _lconn; LogCommand _lcmd; System.Data.CommandBehavior _behavior; Hashtable _CompressStrings; // we keep hashtable of strings so that we can reuse to save memory // most web sites won't have huge duplicates. MultipleStreamReader _sr; // StreamReader for _Url string _Domain; // domain name from LogCommand string _IndexFile; // index file name object[] _Data; // data values of the columns // column information: is fixed for all instances // names of all the columns static string[] _Names= new string[] {"host","client_identifier","user","datetime", "request_cmd","request_url","request_type", "request_parameters","status_code", "bytes", "referrer", "user_agent", "cookie"}; // types of all the columns static Type _dttype = DateTime.MinValue.GetType(); // work variable for getting the type static Type _tstring = "".GetType(); static Type _dtype = Double.MinValue.GetType(); static Type[] _Types = new Type[] {_tstring,_tstring,_tstring,_dttype, _tstring,_tstring,_tstring,_tstring,_tstring, _dtype,_tstring,_tstring,_tstring}; const int DATETIME_FIELD=3; // the date time field const int REQUEST_FIELD=4; // the request field const int BYTES_FIELD=9; // the bytes field public LogDataReader(System.Data.CommandBehavior behavior, LogConnection conn, LogCommand cmd) { _lconn = conn; _lcmd = cmd; _behavior = behavior; _CompressStrings = new Hashtable(10000); // compress strings to save memory string fname = _lcmd.Url; _Domain = _lcmd.Domain; if (_Domain == null) _Domain = ""; _IndexFile = _lcmd.IndexFile; if (_IndexFile == null) _IndexFile = ""; if (behavior != CommandBehavior.SchemaOnly) _sr = new MultipleStreamReader(_lcmd.Url); // get the main stream _Data = new object[_Names.Length]; // allocate enough room for data } #region IDataReader Members public int RecordsAffected { get { return 0; } } public bool IsClosed { get { return _sr == null; } } public bool NextResult() { return false; } public void Close() { _CompressStrings = null; if (_sr != null) { _sr.Close(); _sr = null; } _Data = null; } public bool Read() { if (this._sr == null) return false; // read a line of the log string line = _sr.ReadLine(); if (line == null) return false; // obtain the data from each column and put the data array Lexer l = new Lexer(new StringReader(line)); LexTokenList ll = l.Lex(); int ci=0; // start at first column if (ll.Count > 11) ci = 0; foreach (LexToken lt in ll) { if (ci >= _Data.Length || lt.Type == LexTokenTypes.EOF) break; if (ci == DATETIME_FIELD) { _Data[ci] =GetDateTime(lt.Value); } else if (ci == REQUEST_FIELD) { // break the request into multiple fields; command, url, http type string[] reqs = lt.Value.Split(' '); string req_cmd=null; string req_url=null; string req_type=null; string req_parameters=null; if (reqs == null) {} else if (reqs.Length >= 3) { req_cmd = reqs[0]; req_url = reqs[1]; req_type = reqs[2]; } else if (reqs.Length == 2) { req_cmd = reqs[0]; req_url = reqs[1]; } else if (reqs.Length == 1) req_url = reqs[0]; if (req_url != null) { string [] up = req_url.Split('?'); if (up.Length > 1) { req_url = up[0]; req_parameters = up[1]; } } _Data[ci++] = req_type; if (req_url != null && req_url.Length > 0) { if (req_url[0] == '/') req_url = _Domain + req_url; if (req_url[req_url.Length-1] == '/') req_url += _IndexFile; } _Data[ci++] = CompressString(req_url); _Data[ci++] = req_type == "HTTP/1.1"? "HTTP/1.1": CompressString(req_type); _Data[ci++] = req_parameters; continue; } else if (ci == BYTES_FIELD) { double v=0; if (lt.Value.Length == 0 || lt.Value == "-") {} else { try { v = Convert.ToDouble(lt.Value); } catch { } } _Data[ci] = v; } else _Data[ci] = CompressString(lt.Value); ci++; // go to next column } while (ci < _Data.Length) _Data[ci++] = null; return true; } string CompressString(string v) { if (v == null) return null; string sv = _CompressStrings[v] as string; if (sv != null) return sv; _CompressStrings.Add(v, v); return v; } object GetDateTime(string v) { object result; if (v.Length != 26) return null; try { string dd = v.Substring(0,2); // the day of the month string MMM = v.Substring(3,3); // the month int month=1; switch (MMM.ToLower()) { case "jan": month=1; break; case "feb": month=2; break; case "mar": month=3; break; case "apr": month=4; break; case "may": month=5; break; case "jun": month=6; break; case "jul": month=7; break; case "aug": month=8; break; case "sep": month=9; break; case "oct": month=10; break; case "nov": month=11; break; case "dec": month=12; break; default: break; } string yyyy = v.Substring(7,4); // the year string hh = v.Substring(12,2); // the hour string mm = v.Substring(15,2); // the minute string ss = v.Substring(18,2); // the seconds bool bPlus = v[21] == '+'; int thh = Convert.ToInt32(v.Substring(22,2)); // the time zone (hh) int tmm = Convert.ToInt32(v.Substring(24,2)); // the time zone (mm) int tzdiff = thh * 60 + tmm; // time zone difference in minutes if (!bPlus) tzdiff = - tzdiff; DateTime dt = new DateTime(Convert.ToInt32(yyyy), month, Convert.ToInt32(dd), Convert.ToInt32(hh), Convert.ToInt32(mm), Convert.ToInt32(ss), 0); result = dt.AddMinutes(tzdiff); } catch { result = null; } return result; } public int Depth { get { return 0; } } public DataTable GetSchemaTable() { return null; } #endregion #region IDisposable Members public void Dispose() { this.Close(); } #endregion #region IDataRecord Members public int GetInt32(int i) { return Convert.ToInt32(_Data[i]); } public object this[string name] { get { int ci = this.GetOrdinal(name); return _Data[ci]; } } object System.Data.IDataRecord.this[int i] { get { return _Data[i]; } } public object GetValue(int i) { return _Data[i]; } public bool IsDBNull(int i) { return _Data[i] == null; } public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { throw new NotImplementedException("GetBytes not implemented."); } public byte GetByte(int i) { return Convert.ToByte(_Data[i]); } public Type GetFieldType(int i) { return _Types[i]; } public decimal GetDecimal(int i) { return Convert.ToDecimal(_Data[i]); } public int GetValues(object[] values) { int i; for (i=0; i < values.Length; i++) { values[i] = i >= _Data.Length? System.DBNull.Value: _Data[i]; } return Math.Min(values.Length, _Data.Length); } public string GetName(int i) { return _Names[i] as string; } public int FieldCount { get { return _Data.Length; } } public long GetInt64(int i) { return Convert.ToInt64(_Data[i]); } public double GetDouble(int i) { return Convert.ToDouble(_Data[i]); } public bool GetBoolean(int i) { return Convert.ToBoolean(_Data[i]); } public Guid GetGuid(int i) { throw new NotImplementedException("GetGuid not implemented."); } public DateTime GetDateTime(int i) { return Convert.ToDateTime(_Data[i]); } public int GetOrdinal(string name) { int ci=0; // do case sensitive lookup foreach (string cname in _Names) { if (cname == name) return ci; ci++; } // do case insensitive lookup ci=0; name = name.ToLower(); foreach (string cname in _Names) { if (cname.ToLower() == name) return ci; ci++; } throw new ArgumentException(string.Format("Column '{0}' not known.", name)); } public string GetDataTypeName(int i) { Type t = _Types[i] as Type; return t.ToString(); } public float GetFloat(int i) { return Convert.ToSingle(_Data[i]); } public IDataReader GetData(int i) { throw new NotImplementedException("GetData not implemented."); } public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { throw new NotImplementedException("GetChars not implemented."); } public string GetString(int i) { return Convert.ToString(_Data[i]); } public char GetChar(int i) { return Convert.ToChar(_Data[i]); } public short GetInt16(int i) { return Convert.ToInt16(_Data[i]); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Orleans; using Orleans.Configuration; using Orleans.Messaging; using Orleans.Runtime; using Orleans.Runtime.Configuration; using TestGrainInterfaces; using UnitTests.DtosRefOrleans; using Xunit; namespace NonSilo.Tests { public class NoOpGatewaylistProvider : IGatewayListProvider { public TimeSpan MaxStaleness => throw new NotImplementedException(); public bool IsUpdatable => throw new NotImplementedException(); public Task<IList<Uri>> GetGateways() { throw new NotImplementedException(); } public Task InitializeGatewayListProvider() { throw new NotImplementedException(); } } /// <summary> /// Tests for <see cref="ClientBuilder"/>. /// </summary> [TestCategory("BVT")] [TestCategory("ClientBuilder")] public class ClientBuilderTests { /// <summary> /// Tests that a client cannot be created without specifying a ClusterId and a ServiceId. /// </summary> [Fact] public void ClientBuilder_ClusterOptionsTest() { Assert.Throws<OrleansConfigurationException>(() => new ClientBuilder() .ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>()) .Build()); Assert.Throws<OrleansConfigurationException>(() => new ClientBuilder() .Configure<ClusterOptions>(options => options.ClusterId = "someClusterId") .ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>()) .Build()); Assert.Throws<OrleansConfigurationException>(() => new ClientBuilder() .Configure<ClusterOptions>(options => options.ServiceId = "someServiceId") .ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>()) .Build()); var builder = new ClientBuilder() .Configure<ClusterOptions>(options => { options.ClusterId = "someClusterId"; options.ServiceId = "someServiceId"; }) .ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>()); using (var client = builder.Build()) { Assert.NotNull(client); } } /// <summary> /// Tests that a client can be created without specifying configuration. /// </summary> [Fact] public void ClientBuilder_NoSpecifiedConfigurationTest() { var builder = new ClientBuilder() .ConfigureDefaults() .ConfigureServices(RemoveConfigValidators) .ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>()); using (var client = builder.Build()) { Assert.NotNull(client); } } [Fact] public void ClientBuilder_ThrowsDuringStartupIfNoGrainInterfacesAdded() { // Add only an assembly with generated serializers but no grain interfaces var clientBuilder = new ClientBuilder() .UseLocalhostClustering() .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(ClassReferencingOrleansTypeDto).Assembly)) .ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>()); Assert.Throws<OrleansConfigurationException>(() => clientBuilder.Build()); } /// <summary> /// Tests that a builder can not be used to build more than one client. /// </summary> [Fact] public void ClientBuilder_DoubleBuildTest() { var builder = new ClientBuilder() .ConfigureDefaults() .ConfigureServices(RemoveConfigValidators) .ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>()); using (builder.Build()) { Assert.Throws<InvalidOperationException>(() => builder.Build()); } } /// <summary> /// Tests that configuration cannot be specified twice. /// </summary> [Fact] public void ClientBuilder_DoubleSpecifyConfigurationTest() { var builder = new ClientBuilder() .ConfigureDefaults() .ConfigureServices(RemoveConfigValidators) .UseConfiguration(new ClientConfiguration()) .UseConfiguration(new ClientConfiguration()); Assert.Throws<InvalidOperationException>(() => builder.Build()); } /// <summary> /// Tests that a client can be created without specifying configuration. /// </summary> [Fact] public void ClientBuilder_NullConfigurationTest() { var builder = new ClientBuilder() .ConfigureDefaults() .ConfigureServices(RemoveConfigValidators); Assert.Throws<ArgumentNullException>(() => builder.UseConfiguration(null)); } /// <summary> /// Tests that the <see cref="IClientBuilder.ConfigureServices"/> delegate works as expected. /// </summary> [Fact] public void ClientBuilder_ServiceProviderTest() { var builder = new ClientBuilder() .ConfigureDefaults() .ConfigureServices(RemoveConfigValidators) .ConfigureServices(services => services.AddSingleton<IGatewayListProvider, NoOpGatewaylistProvider>()); Assert.Throws<ArgumentNullException>(() => builder.ConfigureServices(null)); var registeredFirst = new int[1]; var one = new MyService { Id = 1 }; builder.ConfigureServices( services => { Interlocked.CompareExchange(ref registeredFirst[0], 1, 0); services.AddSingleton(one); }); var two = new MyService { Id = 2 }; builder.ConfigureServices( services => { Interlocked.CompareExchange(ref registeredFirst[0], 2, 0); services.AddSingleton(two); }); using (var client = builder.Build()) { var services = client.ServiceProvider.GetServices<MyService>()?.ToList(); Assert.NotNull(services); // Both services should be registered. Assert.Equal(2, services.Count); Assert.NotNull(services.FirstOrDefault(svc => svc.Id == 1)); Assert.NotNull(services.FirstOrDefault(svc => svc.Id == 2)); // Service 1 should have been registered first - the pipeline order should be preserved. Assert.Equal(1, registeredFirst[0]); // The last registered service should be provided by default. Assert.Equal(2, client.ServiceProvider.GetRequiredService<MyService>().Id); } } private static void RemoveConfigValidators(IServiceCollection services) { var validators = services.Where(descriptor => descriptor.ServiceType == typeof(IConfigurationValidator)).ToList(); foreach (var validator in validators) services.Remove(validator); } private class MyService { public int Id { get; set; } } } }
using System.Collections.Generic; using GitTools.Testing; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using GitVersionCore.Tests.Helpers; using LibGit2Sharp; using NUnit.Framework; namespace GitVersionCore.Tests.IntegrationTests { [TestFixture] public class DevelopScenarios : TestBase { [Test] public void WhenDevelopHasMultipleCommitsSpecifyExistingCommitId() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); var thirdCommit = fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.3", commitId: thirdCommit.Sha); } [Test] public void WhenDevelopHasMultipleCommitsSpecifyNonExistingCommitId() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.5", commitId: "nonexistingcommitid"); } [Test] public void WhenDevelopBranchedFromTaggedCommitOnMasterVersionDoesNotChange() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.AssertFullSemver("1.0.0"); } [Test] public void CanChangeDevelopTagViaConfig() { var config = new Config { Branches = { { "develop", new BranchConfig { Tag = "alpha", SourceBranches = new HashSet<string>() } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1", config); } [Test] public void WhenDeveloperBranchExistsDontTreatAsDevelop() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("developer")); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.0.1-developer.1+1"); // this tag should be the branch name by default, not unstable } [Test] public void WhenDevelopBranchedFromMasterMinorIsIncreased() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.0-alpha.1"); } [Test] public void MergingReleaseBranchBackIntoDevelopWithMergingToMasterDoesBumpDevelopVersion() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("release-2.0.0")); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "master"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MergeNoFF("release-2.0.0", Generate.SignatureNow()); fixture.AssertFullSemver("2.1.0-alpha.2"); } [Test] public void CanHandleContinuousDelivery() { var config = new Config { Branches = { { "develop", new BranchConfig { VersioningMode = VersioningMode.ContinuousDelivery } } } }; using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeATaggedCommit("1.1.0-alpha7"); fixture.AssertFullSemver("1.1.0-alpha.7", config); } [Test] public void WhenDevelopBranchedFromMasterDetachedHeadMinorIsIncreased() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); Commands.Checkout(fixture.Repository, fixture.Repository.CreateBranch("develop")); fixture.Repository.MakeACommit(); var commit = fixture.Repository.Head.Tip; fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, commit); fixture.AssertFullSemver("1.1.0-alpha.1", onlyTrackedBranches: false); } [Test] public void InheritVersionFromReleaseBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.MakeATaggedCommit("1.0.0"); fixture.BranchTo("develop"); fixture.MakeACommit(); fixture.BranchTo("release/2.0.0"); fixture.MakeACommit(); fixture.MakeACommit(); fixture.Checkout("develop"); fixture.AssertFullSemver("1.1.0-alpha.1"); fixture.MakeACommit(); fixture.AssertFullSemver("2.1.0-alpha.1"); fixture.MergeNoFF("release/2.0.0"); fixture.AssertFullSemver("2.1.0-alpha.4"); fixture.BranchTo("feature/MyFeature"); fixture.MakeACommit(); fixture.AssertFullSemver("2.1.0-MyFeature.1+5"); } [Test] public void WhenMultipleDevelopBranchesExistAndCurrentBranchHasIncrementInheritPolicyAndCurrentCommitIsAMerge() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("bob_develop"); fixture.Repository.CreateBranch("develop"); fixture.Repository.CreateBranch("feature/x"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); Commands.Checkout(fixture.Repository, "feature/x"); fixture.Repository.MakeACommit(); fixture.Repository.MergeNoFF("develop"); fixture.AssertFullSemver("1.1.0-x.1+3"); } [Test] public void TagOnHotfixShouldNotAffectDevelop() { using var fixture = new BaseGitFlowRepositoryFixture("1.2.0"); Commands.Checkout(fixture.Repository, "master"); var hotfix = fixture.Repository.CreateBranch("hotfix-1.2.1"); Commands.Checkout(fixture.Repository, hotfix); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.2.1-beta.1+1"); fixture.Repository.ApplyTag("1.2.1-beta.1"); fixture.AssertFullSemver("1.2.1-beta.1"); Commands.Checkout(fixture.Repository, "develop"); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.3.0-alpha.2"); } [Test] public void CommitsSinceVersionSourceShouldNotGoDownUponGitFlowReleaseFinish() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); fixture.ApplyTag("1.1.0"); fixture.BranchTo("develop"); fixture.MakeACommit("commit in develop - 1"); fixture.AssertFullSemver("1.2.0-alpha.1"); fixture.BranchTo("release/1.2.0"); fixture.AssertFullSemver("1.2.0-beta.1+0"); fixture.Checkout("develop"); fixture.MakeACommit("commit in develop - 2"); fixture.MakeACommit("commit in develop - 3"); fixture.MakeACommit("commit in develop - 4"); fixture.MakeACommit("commit in develop - 5"); fixture.AssertFullSemver("1.3.0-alpha.4"); fixture.Checkout("release/1.2.0"); fixture.MakeACommit("commit in release/1.2.0 - 1"); fixture.MakeACommit("commit in release/1.2.0 - 2"); fixture.MakeACommit("commit in release/1.2.0 - 3"); fixture.AssertFullSemver("1.2.0-beta.1+3"); fixture.Checkout("master"); fixture.MergeNoFF("release/1.2.0"); fixture.ApplyTag("1.2.0"); fixture.Checkout("develop"); fixture.MergeNoFF("release/1.2.0"); fixture.MakeACommit("commit in develop - 6"); fixture.AssertFullSemver("1.3.0-alpha.9"); fixture.SequenceDiagram.Destroy("release/1.2.0"); fixture.Repository.Branches.Remove("release/1.2.0"); var expectedFullSemVer = "1.3.0-alpha.9"; fixture.AssertFullSemver(expectedFullSemVer, config); } [Test] public void CommitsSinceVersionSourceShouldNotGoDownUponMergingFeatureOnlyToDevelop() { var config = new Config { VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit("commit in master - 1"); fixture.ApplyTag("1.1.0"); fixture.BranchTo("develop"); fixture.MakeACommit("commit in develop - 1"); fixture.AssertFullSemver("1.2.0-alpha.1"); fixture.BranchTo("release/1.2.0"); fixture.MakeACommit("commit in release - 1"); fixture.MakeACommit("commit in release - 2"); fixture.MakeACommit("commit in release - 3"); fixture.AssertFullSemver("1.2.0-beta.1+3"); fixture.ApplyTag("1.2.0"); fixture.Checkout("develop"); fixture.MakeACommit("commit in develop - 2"); fixture.AssertFullSemver("1.3.0-alpha.1"); fixture.MergeNoFF("release/1.2.0"); fixture.AssertFullSemver("1.3.0-alpha.5"); fixture.SequenceDiagram.Destroy("release/1.2.0"); fixture.Repository.Branches.Remove("release/1.2.0"); var expectedFullSemVer = "1.3.0-alpha.5"; fixture.AssertFullSemver(expectedFullSemVer, config); } [Test] public void PreviousPreReleaseTagShouldBeRespectedWhenCountingCommits() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); fixture.BranchTo("develop"); fixture.MakeATaggedCommit("1.0.0-alpha.3"); // manual bump version fixture.MakeACommit(); fixture.MakeACommit(); fixture.AssertFullSemver("1.0.0-alpha.5"); } } }
using Gtk; using System; using System.Data; using System.Collections.Generic; using Valle.GtkUtilidades; using Valle.SqlGestion; using Valle.ToolsTpv; namespace Valle.TpvFinal { public partial class ListadoCierres : FormularioBase { string nomImp; string rutFicherosImp; public ListadoCierres (IGesSql ges, int id, string nomImp, string rutFicherosImp) { this.Init (); this.nomImp = nomImp; this.rutFicherosImp = rutFicherosImp; this.LblTituloBase = this.lblTitulo; if(ges is GesMSSQL){ SELECT_TOP_LIMIT = SELECT_TOP_LIMIT.Replace("@TOP","TOP @MAXIMO"); SELECT_TOP_LIMIT = SELECT_TOP_LIMIT.Replace("@LIMIT",""); }else{ SELECT_TOP_LIMIT = SELECT_TOP_LIMIT.Replace("@LIMIT","LIMIT @MAXIMO"); SELECT_TOP_LIMIT = SELECT_TOP_LIMIT.Replace("@TOP",""); } Titulo = "Listado de cierres de TPV"; SalirAlPulsar = false; this.btnDesglose.Visible = false; gesBase = ges; idTpv = id; tbTpv = gesBase.ExtraerTabla("TPVs",null); Gtk.ListStore ls = new Gtk.ListStore(typeof(string),typeof(string),typeof(string),typeof(DataRow)); lstCierres.Model = ls; CellRendererText cell = new CellRendererText(); cell.FontDesc = Pango.FontDescription.FromString("monospace 12"); cell.SetFixedSize(110,50); lstCierres.AppendColumn("Fecha",cell,"text",0); cell = new CellRendererText(); cell.FontDesc = Pango.FontDescription.FromString("monospace 12"); cell.SetFixedSize(60,50); lstCierres.AppendColumn("Hora",cell,"text",1); cell = new CellRendererText(); cell.FontDesc = Pango.FontDescription.FromString("monospace 12"); cell.SetFixedSize(80,50); lstCierres.AppendColumn("Nombre Tpv",cell,"text",2); this.lblInfOriginal.Texto = "Lista de cierres de caja"; } delegate void MetodoSimuladorAcc(int tiempo); public event EventHandler salirListadoCierres; IGesSql gesBase; int idTpv; //Filtro filtro; DataTable tbTpv; DataTable tbCierres; DesgloseCierre desInv = null; int modo = 0; int maximo = 20; string SELECT_TOP_LIMIT = "Select @TOP * FROM CierreDeCaja WHERE IDTpv = @IDTpv ORDER BY fechaCierre DESC, horaCierre DESC @LIMIT"; List<string> ListaVentaCamareros = new List<string>(); List<string> ListaVentaHoras = new List<string>(); void RellenarCierres(){ Gtk.ListStore lStr = (Gtk.ListStore)lstCierres.Model; lStr.Clear(); foreach(DataRow r in tbCierres.Rows){ lStr.AppendValues(Utilidades.CadenasTexto.RotarFecha(r["fechaCierre"].ToString()), r["horaCierre"].ToString(), this.tbTpv.Select("IDTpv = "+r["IDTpv"].ToString())[0]["Nombre"].ToString(),r); } } /*void btnFiltros_Click(object sender, EventArgs e) { FiltrosCierres fil = new FiltrosCierres(filtro); fil.MiVista.MostrarFormulario(true, true, ModoSombra.control); string consultaTpv = ""; if(fil.filtro.tpv.Tag != null) consultaTpv = "IDTpv = "+ ((DataRow)fil.filtro.tpv.Tag)["IDTpv"].ToString()+" AND "; if((fil.filtro.FechaHasta!=null)&&(fil.filtro.FechaDesde !=null)){ tbCierres = gesBase.EjecutarSqlSelect("MisCierres", "SELECT * FROM CierreDeCaja WHERE "+consultaTpv+" FechaCierre >= '"+Utilidades.CadenasTexto.RotarFecha(fil.filtro.FechaDesde.ToShortDateString())+ "' AND FechaCierre <= '"+ Utilidades.CadenasTexto.RotarFecha(fil.filtro.FechaHasta.ToShortDateString())+"' ORDER BY FechaCierre DESC, horaCierre DESC"); this.RellenarCierres(); } }*/ void lstCierres_SelectedIndexChanged(object o, EventArgs args) { if (lstCierres.Selection.CountSelectedRows() > 0){ switch(modo){ case 0: new MetodosAsync(new MetodoSinArg(CalcularCierre)).GtkFuncAsync(); break; case 1: new MetodosAsync(new MetodoSinArg(VentaPorCamareros)).GtkFuncAsync(); break; case 2: new MetodosAsync(new MetodoSinArg(VentaPorHoras)).GtkFuncAsync(); break; } }else{ lblInfSelcecionados.Texto = "No hay cierres seleccionados"; ListaVentaHoras.Clear(); ListaVentaCamareros.Clear(); desInv = null; ((Gtk.ListStore)lstCierres.Model).Clear(); txtTicketInf.Buffer.Clear(); } } void VentaPorHoras(){ this.barImformacion.Visible = true; this.barImformacion.Text = "Calculando la venta por horas..."; Gtk.TreeIter item; lstCierres.Selection.GetSelected(out item); this.barImformacion.Fraction = 1/3; DataRow r = (DataRow)lstCierres.Model.GetValue(item,3); this.barImformacion.Fraction = 2/3; ListaVentaHoras = new GesVentas().CalcularVentaHoras(gesBase, (int)r["IDCierre"]); lblInfSelcecionados.Texto = "Fecha = " + Utilidades.CadenasTexto.RotarFecha(r["FechaCierre"].ToString()); this.barImformacion.Fraction = 3/3; VisorDeInformes.mostrarInforme(txtTicketInf.Buffer, ListaVentaHoras.ToArray()); this.barImformacion.Visible = false; } void VentaPorCamareros(){ this.barImformacion.Visible = true; this.barImformacion.Text = "Calculando la venta por camareros..."; Gtk.TreeIter item; lstCierres.Selection.GetSelected(out item); DataRow r = (DataRow)lstCierres.Model.GetValue(item,3); ListaVentaCamareros = new GesVentas().CalcularVentaCamareros(gesBase, (int)r["IDCierre"], new BarraProgreso(this.barImformacion)); lblInfSelcecionados.Texto = "Fecha = " + Utilidades.CadenasTexto.RotarFecha(r["FechaCierre"].ToString()) ; VisorDeInformes.mostrarInforme(txtTicketInf.Buffer, ListaVentaCamareros.ToArray()); this.barImformacion.Visible = false; } void CalcularCierre(){ this.barImformacion.Visible = true; this.barImformacion.Text = "Calculando el desglose de cierre"; Gtk.TreeIter item; lstCierres.Selection.GetSelected(out item); this.barImformacion.Fraction = 1/4; DataRow r = (DataRow)lstCierres.Model.GetValue(item,3); this.barImformacion.Fraction = 2/4; desInv = new GesVentas().CalcularCierre(gesBase, (int)r["IDTpv"], (int)r["DesdeTicket"], (int)r["HastaTicket"]); desInv.fechaCierre = r["FechaCierre"].ToString(); desInv.HoraCierre = r["HoraCierre"].ToString(); this.barImformacion.Fraction = 3/4; this.lblInfSelcecionados.Texto = " Num ticket = " + desInv.numTicket + " Media = " +String.Format("{0:##0.00}", desInv.totalCierre / desInv.numTicket); List<string> listado = new List<string>(); listado.Add(String.Format("Total del dia: {0:c}", desInv.totalCierre)); listado.Add(String.Format("Numero de ticket: {0}", desInv.numTicket)); listado.Add(String.Format("Media por ticket: {0:#0.00}", desInv.totalCierre / desInv.numTicket)); listado.Add("Fecha " + desInv.fechaCierre + " Hora " + desInv.HoraCierre); listado.Add(""); foreach (string s in desInv.lienasArticulos) { s.Trim(':',' '); listado.Add(s); } this.barImformacion.Fraction = 4/4; VisorDeInformes.mostrarInforme(txtTicketInf.Buffer, listado.ToArray()); this.barImformacion.Visible = false; } public void MostrarCierres(int idTpv){ this.idTpv = idTpv;this.Show(); ListaLosPrimerosCierres(); } void ListaLosPrimerosCierres(){ maximo = 20; string consulta = SELECT_TOP_LIMIT.Replace("@IDTpv",idTpv.ToString()) .Replace("@MAXIMO" ,maximo.ToString()); tbCierres = gesBase.EjecutarSqlSelect("ListadoCierre",consulta); this.RellenarCierres(); } protected virtual void OnBtnAbrirCajonClicked (object sender, System.EventArgs e) { ImpresoraTicket.AbrirCajon(rutFicherosImp,nomImp); } protected virtual void OnBtnDesgloseClicked (object sender, System.EventArgs e) { this.btnHoras.Visible = true; this.btnDesglose.Visible = false; this.btnCamareros.Visible = true; modo = 0; this.lstCierres_SelectedIndexChanged(sender,e); } protected virtual void OnBtnCamarerosClicked (object sender, System.EventArgs e) { this.btnCamareros.Visible = false; this.btnDesglose.Visible = true; this.btnHoras.Visible = true; modo = 1; this.lstCierres_SelectedIndexChanged(sender,e); } protected virtual void OnBtnHorasClicked (object sender, System.EventArgs e) { this.btnHoras.Visible = false; this.btnDesglose.Visible = true; this.btnCamareros.Visible = true; modo = 2; this.lstCierres_SelectedIndexChanged(sender,e); } protected virtual void OnBtnImprimirClicked (object sender, System.EventArgs e) { switch(modo){ case 0: if (desInv != null) { List<string> listado = new List<string>(); listado.Add(String.Format("Total del dia: {0:c}", desInv.totalCierre)); listado.Add(String.Format("Numero de ticket: {0}", desInv.numTicket)); listado.Add(String.Format("Media por ticket: {0:#0.00}", desInv.totalCierre / desInv.numTicket)); listado.Add("Fecha " + desInv.fechaCierre + " Hora " + desInv.HoraCierre); listado.Add(""); foreach (string s in desInv.lienasArticulos) { s.Replace(':',' '); listado.Add(s); } ImpresoraTicket.ImprimeResumen(rutFicherosImp,nomImp, listado.ToArray(), "Cierre de caja"); } break; case 1: if (ListaVentaCamareros != null) { ImpresoraTicket.ImprimeResumen(rutFicherosImp,nomImp, ListaVentaCamareros.ToArray(), "Venta por camareros "); } break; case 2: if(ListaVentaHoras!=null){ ImpresoraTicket.ImprimeResumen(rutFicherosImp,nomImp, ListaVentaHoras.ToArray(), "Venta por horas "); } break; } } protected virtual void OnBtnMasClicked (object sender, System.EventArgs e) { maximo += 20; tbCierres = gesBase.EjecutarSqlSelect("ListadoCierre",SELECT_TOP_LIMIT.Replace("@IDTpv",idTpv.ToString()) .Replace("@MAXIMO" , maximo.ToString())); this.RellenarCierres(); } protected virtual void OnBtnCierreClicked (object sender, System.EventArgs e) { String[] lineas = new GesVentas().CalcularCierre(gesBase, idTpv); if (lineas != null) { new MetodosAsync(new MetodoSinArg(ListaLosPrimerosCierres)).GtkFuncAsync(); } else { new DialogoTactil("Aviso en caja diaria", "No hay ticket nuevos desde el ultimo cierre." + " No se puede hacer un cierre de caja", TipoRes.aceptar); } } protected virtual void OnBtnSalirClicked (object sender, System.EventArgs e) { if(salirListadoCierres != null) salirListadoCierres(this,new EventArgs()); this.CerrarFormulario(); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Data; using System.Configuration; using System.Globalization; using System.Web; using System.Web.Caching; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Xml; namespace WebsitePanel.WebPortal { /// <summary> /// Summary description for ModuleDefinitions /// </summary> public class PortalConfiguration { private const string ROLES_DELIMITERS = ";,"; private const string APP_DATA_FOLDER = "~/App_Data"; private const string THEMES_FOLDER = "~/App_Themes"; private const string MODULES_PATTERN = "*_Modules.config"; private const string PAGES_PATTERN = "*_Pages.config"; private const string SITE_SETTINGS_FILE = "SiteSettings.config"; private const string MODULE_DEFINITIONS_KEY = "PortalModuleDefinitionsCacheKey"; private const string SITE_STRUCTURE_KEY = "SiteStructureCacheKey"; private const string SITE_SETTINGS_KEY = "SiteSettingsCacheKey"; public static Dictionary<string, ModuleDefinition> ModuleDefinitions { get { Dictionary<string, ModuleDefinition> modules = (Dictionary<string, ModuleDefinition>)HttpContext.Current.Cache[MODULE_DEFINITIONS_KEY]; if (modules == null) { // create list modules = new Dictionary<string, ModuleDefinition>(); // load modules string appData = HttpContext.Current.Server.MapPath(APP_DATA_FOLDER); FileInfo[] files = new DirectoryInfo(appData).GetFiles(MODULES_PATTERN); foreach (FileInfo file in files) LoadModulesFromXml(modules, file.FullName); // place to cache HttpContext.Current.Cache.Insert(MODULE_DEFINITIONS_KEY, modules, new System.Web.Caching.CacheDependency(appData)); } return modules; } } public static SiteStructure Site { get { SiteStructure site = (SiteStructure)HttpContext.Current.Cache[SITE_STRUCTURE_KEY]; if (site == null) { // create list site = new SiteStructure(); // load pages string appData = HttpContext.Current.Server.MapPath(APP_DATA_FOLDER); FileInfo[] files = new DirectoryInfo(appData).GetFiles(PAGES_PATTERN); foreach (FileInfo file in files) LoadPagesFromXml(site, file.FullName); // place to cache HttpContext.Current.Cache.Insert(SITE_STRUCTURE_KEY, site, new System.Web.Caching.CacheDependency(appData)); } return site; } } public static SiteSettings SiteSettings { get { SiteSettings settings = (SiteSettings)HttpContext.Current.Cache[SITE_SETTINGS_KEY]; if (settings == null) { // create list settings = new SiteSettings(); // load pages string appData = HttpContext.Current.Server.MapPath(APP_DATA_FOLDER); string path = Path.Combine(appData, SITE_SETTINGS_FILE); // load site settings XmlDocument xml = new XmlDocument(); xml.Load(path); XmlNodeList nodes = xml.SelectNodes("SiteSettings/*"); foreach(XmlNode node in nodes) { settings[node.LocalName] = node.InnerText; } // place to cache HttpContext.Current.Cache.Insert(SITE_SETTINGS_KEY, settings, new System.Web.Caching.CacheDependency(path)); } return settings; } } public static bool SaveSiteSettings() { // load pages string appData = HttpContext.Current.Server.MapPath(APP_DATA_FOLDER); string path = Path.Combine(appData, SITE_SETTINGS_FILE); try { // build and save site settings XmlDocument xml = new XmlDocument(); XmlElement root = xml.CreateElement("SiteSettings"); xml.AppendChild(root); foreach (string keyName in SiteSettings.AllKeys) { XmlElement elem = xml.CreateElement(keyName); elem.InnerText = SiteSettings[keyName]; root.AppendChild(elem); } xml.Save(path); } catch { return false; } return true; } private static void LoadModulesFromXml(Dictionary<string, ModuleDefinition> modules, string path) { // open xml document XmlDocument xml = new XmlDocument(); xml.Load(path); // select nodes XmlNodeList xmlModules = xml.SelectNodes("ModuleDefinitions/ModuleDefinition"); foreach (XmlNode xmlModule in xmlModules) { ModuleDefinition module = new ModuleDefinition(); if (xmlModule.Attributes["id"] == null) throw new Exception(String.Format("Module ID is not specified. File: {0}, Node: {1}", path, xmlModule.OuterXml)); module.Id = xmlModule.Attributes["id"].Value.ToLower(CultureInfo.InvariantCulture); modules.Add(module.Id, module); // controls XmlNodeList xmlControls = xmlModule.SelectNodes("Controls/Control"); foreach (XmlNode xmlControl in xmlControls) { ModuleControl control = new ModuleControl(); if (xmlControl.Attributes["icon"] != null) control.IconFile = xmlControl.Attributes["icon"].Value; if(xmlControl.Attributes["key"] != null) control.Key = xmlControl.Attributes["key"].Value.ToLower(CultureInfo.InvariantCulture); if (xmlControl.Attributes["src"] == null) throw new Exception(String.Format("Control 'src' is not specified. File: {0}, Node: {1}", path, xmlControl.ParentNode.OuterXml)); control.Src = xmlControl.Attributes["src"].Value; if (xmlControl.Attributes["title"] == null) throw new Exception(String.Format("Control 'title' is not specified. File: {0}, Node: {1}", path, xmlControl.ParentNode.OuterXml)); control.Title = xmlControl.Attributes["title"].Value; if (xmlControl.Attributes["type"] != null) control.ControlType = (ModuleControlType)Enum.Parse(typeof(ModuleControlType), xmlControl.Attributes["type"].Value, true); else control.ControlType = ModuleControlType.View; if (String.IsNullOrEmpty(control.Key)) module.DefaultControl = control; module.Controls.Add(control.Key, control); } } } private static void LoadPagesFromXml(SiteStructure site, string path) { // open xml document XmlDocument xml = new XmlDocument(); xml.Load(path); // select nodes XmlNodeList xmlPages = xml.SelectNodes("Pages/Page"); // process includes ProcessXmlIncludes(xml, path); // parse root nodes ParsePagesRecursively(path, site, xmlPages, null); } private static void ProcessXmlIncludes(XmlDocument xml, string parentPath) { // working dir string path = Path.GetDirectoryName(parentPath); // get all <includes> XmlNodeList nodes = xml.SelectNodes("//include"); foreach (XmlNode node in nodes) { if (node.Attributes["file"] == null) continue; string incPath = Path.Combine(path, node.Attributes["file"].Value); XmlDocument inc = new XmlDocument(); inc.Load(incPath); XmlElement incNode = xml.CreateElement(inc.DocumentElement.Name); incNode.InnerXml = inc.DocumentElement.InnerXml; // replace original node node.ParentNode.ReplaceChild(incNode, node); } } private static void ParsePagesRecursively(string path, SiteStructure site, XmlNodeList xmlPages, PortalPage parentPage) { foreach (XmlNode xmlPage in xmlPages) { PortalPage page = new PortalPage(); page.ParentPage = parentPage; // page properties if (xmlPage.Attributes["name"] == null) throw new Exception(String.Format("Page name is not specified. File: {0}, Node: {1}", path, xmlPage.OuterXml)); page.Name = xmlPage.Attributes["name"].Value; if (xmlPage.Attributes["roles"] == null) page.Roles.Add("*"); else page.Roles.AddRange(xmlPage.Attributes["roles"].Value.Split(ROLES_DELIMITERS.ToCharArray())); if (xmlPage.Attributes["selectedUserContext"] != null) page.Roles.AddRange(xmlPage.Attributes["selectedUserContext"].Value.Split(ROLES_DELIMITERS.ToCharArray())); page.Enabled = (xmlPage.Attributes["enabled"] != null) ? Boolean.Parse(xmlPage.Attributes["enabled"].Value) : true; page.Hidden = (xmlPage.Attributes["hidden"] != null) ? Boolean.Parse(xmlPage.Attributes["hidden"].Value) : false; page.Align = (xmlPage.Attributes["align"] != null) ? xmlPage.Attributes["align"].Value : null; page.SkinSrc = (xmlPage.Attributes["skin"] != null) ? xmlPage.Attributes["skin"].Value : null; page.AdminSkinSrc = (xmlPage.Attributes["adminskin"] != null) ? xmlPage.Attributes["adminskin"].Value : null; if (xmlPage.Attributes["url"] != null) page.Url = xmlPage.Attributes["url"].Value; if (xmlPage.Attributes["target"] != null) page.Target = xmlPage.Attributes["target"].Value; // content panes XmlNodeList xmlContentPanes = xmlPage.SelectNodes("Content"); foreach (XmlNode xmlContentPane in xmlContentPanes) { ContentPane pane = new ContentPane(); if (xmlContentPane.Attributes["id"] == null) throw new Exception(String.Format("ContentPane ID is not specified. File: {0}, Node: {1}", path, xmlContentPane.ParentNode.OuterXml)); pane.Id = xmlContentPane.Attributes["id"].Value; page.ContentPanes.Add(pane.Id, pane); // page modules XmlNodeList xmlModules = xmlContentPane.SelectNodes("Module"); foreach (XmlNode xmlModule in xmlModules) { PageModule module = new PageModule(); module.ModuleId = site.Modules.Count + 1; module.Page = page; site.Modules.Add(module.ModuleId, module); if (xmlModule.Attributes["moduleDefinitionID"] == null) throw new Exception(String.Format("ModuleDefinition ID is not specified. File: {0}, Node: {1}", path, xmlModule.ParentNode.OuterXml)); module.ModuleDefinitionID = xmlModule.Attributes["moduleDefinitionID"].Value.ToLower(CultureInfo.InvariantCulture); if (xmlModule.Attributes["title"] != null) module.Title = xmlModule.Attributes["title"].Value; if (xmlModule.Attributes["icon"] != null) module.IconFile = xmlModule.Attributes["icon"].Value; if (xmlModule.Attributes["container"] != null) module.ContainerSrc = xmlModule.Attributes["container"].Value; if (xmlModule.Attributes["admincontainer"] != null) module.AdminContainerSrc = xmlModule.Attributes["admincontainer"].Value; if (xmlModule.Attributes["viewRoles"] == null) module.ViewRoles.Add("*"); else module.ViewRoles.AddRange(xmlModule.Attributes["viewRoles"].Value.Split(ROLES_DELIMITERS.ToCharArray())); if (xmlModule.Attributes["readOnlyRoles"] != null) module.ReadOnlyRoles.AddRange(xmlModule.Attributes["readOnlyRoles"].Value.Split(ROLES_DELIMITERS.ToCharArray())); if (xmlModule.Attributes["editRoles"] == null) module.EditRoles.Add("*"); else module.EditRoles.AddRange(xmlModule.Attributes["editRoles"].Value.Split(ROLES_DELIMITERS.ToCharArray())); // settings XmlNodeList xmlSettings = xmlModule.SelectNodes("Settings/Add"); foreach (XmlNode xmlSetting in xmlSettings) { module.Settings[xmlSetting.Attributes["name"].Value] = xmlSetting.Attributes["value"].Value; } XmlNode xmlModuleData = xmlModule.SelectSingleNode("ModuleData"); if (xmlModuleData != null) { // check reference if (xmlModuleData.Attributes["ref"] != null) { // load referenced module data xmlModuleData = xmlModule.OwnerDocument.SelectSingleNode( "Pages/ModulesData/ModuleData[@id='" + xmlModuleData.Attributes["ref"].Value + "']"); } module.LoadXmlModuleData(xmlModuleData.OuterXml); } pane.Modules.Add(module); } } // add page to te array if (parentPage != null) parentPage.Pages.Add(page); site.Pages.Add(page); // process children XmlNodeList xmlChildPages = xmlPage.SelectNodes("Pages/Page"); ParsePagesRecursively(path, site, xmlChildPages, page); } } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Xunit; using HETSAPI; using System.Text; using HETSAPI.Models; using Newtonsoft.Json; using System.Net; namespace HETSAPI.Test { public class RentalRequestIntegrationTest : ApiIntegrationTestBase { [Fact] /// <summary> /// Integration test for BulkPost /// </summary> public async Task TestBulkPost() { var request = new HttpRequestMessage(HttpMethod.Post, "/api/rentalrequests/bulk"); request.Content = new StringContent("[]", Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); } [Fact] /// <summary> /// Integration test /// </summary> public async Task TestBasic() { string initialName = "InitialName"; string changedName = "ChangedName"; // first test the POST. var request = new HttpRequestMessage(HttpMethod.Post, "/api/rentalrequests"); // create a new object. RentalRequest rentalRequest = new RentalRequest(); rentalRequest.Status = initialName; string jsonString = rentalRequest.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); rentalRequest = JsonConvert.DeserializeObject<RentalRequest>(jsonString); // get the id var id = rentalRequest.Id; // change the name rentalRequest.Status = changedName; // now do an update. request = new HttpRequestMessage(HttpMethod.Put, "/api/rentalrequests/" + id); request.Content = new StringContent(rentalRequest.ToJson(), Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // do a get. request = new HttpRequestMessage(HttpMethod.Get, "/api/rentalrequests/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); rentalRequest = JsonConvert.DeserializeObject<RentalRequest>(jsonString); // verify the change went through. Assert.Equal(rentalRequest.Status, changedName); // do a delete. request = new HttpRequestMessage(HttpMethod.Post, "/api/rentalrequests/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/rentalrequests/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } Equipment CreateEquipment (Equipment equipment) { var request = new HttpRequestMessage(HttpMethod.Post, "/api/equipment"); // create a new object. string jsonString = equipment.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); Task<HttpResponseMessage> responseTask = _client.SendAsync(request); responseTask.Wait(); HttpResponseMessage response = responseTask.Result; Task<string> stringTask = response.Content.ReadAsStringAsync(); stringTask.Wait(); jsonString = stringTask.Result; // parse as JSON. Equipment result = JsonConvert.DeserializeObject<Equipment>(jsonString); return result; } [Fact] /// <summary> /// Test the creation of the rotation list, a side effect of rental request record creation. /// </summary> public async Task TestRotationListNonDumpTruck() { string initialName = "InitialName"; // create a temporary region. var request = new HttpRequestMessage(HttpMethod.Post, "/api/regions"); Region region = new Region(); region.Name = initialName; request.Content = new StringContent(region.ToJson(), Encoding.UTF8, "application/json"); var response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. string jsonString = await response.Content.ReadAsStringAsync(); region = JsonConvert.DeserializeObject<Region>(jsonString); request = new HttpRequestMessage(HttpMethod.Post, "/api/districts"); // create a new District District district = new District(); district.Id = 0; district.Name = initialName; district.Region = region; jsonString = district.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); district = JsonConvert.DeserializeObject<District>(jsonString); // create a new Service Area request = new HttpRequestMessage(HttpMethod.Post, "/api/serviceareas"); ServiceArea serviceArea = new ServiceArea(); serviceArea.Id = 0; serviceArea.Name = initialName; serviceArea.District= district; jsonString = serviceArea.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); serviceArea = JsonConvert.DeserializeObject<ServiceArea>(jsonString); // create a new Local Area request = new HttpRequestMessage(HttpMethod.Post, "/api/localAreas"); LocalArea localArea = new LocalArea(); localArea.Id = 0; localArea.LocalAreaNumber = 1234; localArea.ServiceArea = serviceArea; jsonString = localArea.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); localArea = JsonConvert.DeserializeObject<LocalArea>(jsonString); // create a new Equipment Type request = new HttpRequestMessage(HttpMethod.Post, "/api/equipmentTypes"); // create a new equipment type EquipmentType equipmentType = new EquipmentType(); equipmentType.Id = 0; equipmentType.Name = initialName; equipmentType.IsDumpTruck = false; equipmentType.NumberOfBlocks = 2; jsonString = equipmentType.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); equipmentType = JsonConvert.DeserializeObject<EquipmentType>(jsonString); request = new HttpRequestMessage(HttpMethod.Post, "/api/districtEquipmentTypes"); // create a new District Equipment Type DistrictEquipmentType districtEquipmentType = new DistrictEquipmentType(); districtEquipmentType.Id = 0; districtEquipmentType.DistrictEquipmentName = initialName; districtEquipmentType.District = district; districtEquipmentType.EquipmentType = equipmentType; jsonString = districtEquipmentType.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); districtEquipmentType = JsonConvert.DeserializeObject<DistrictEquipmentType>(jsonString); // create equipment. int numberEquipment = 75; Equipment[] testEquipment = new Equipment[numberEquipment]; int blockCount = 0; int currentBlock = 1; for (int i = 0; i < numberEquipment; i++) { testEquipment[i] = new Equipment(); testEquipment[i].LocalArea = localArea; testEquipment[i].DistrictEquipmentType = districtEquipmentType; testEquipment[i].Seniority = (numberEquipment - i + 1) * 1.05F; testEquipment[i].IsSeniorityOverridden = true; testEquipment[i].BlockNumber = currentBlock; testEquipment[i] = CreateEquipment(testEquipment[i]); ++blockCount; if (blockCount >= 10 && currentBlock < 2) { currentBlock++; blockCount = 0; } // avoid database problems due to too many requests System.Threading.Thread.Sleep(200); } // Now create the rental request. request = new HttpRequestMessage(HttpMethod.Post, "/api/rentalrequests"); RentalRequest rentalRequest = new RentalRequest(); rentalRequest.Status = initialName; rentalRequest.LocalArea = localArea; rentalRequest.DistrictEquipmentType = districtEquipmentType; jsonString = rentalRequest.ToJson(); request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); rentalRequest = JsonConvert.DeserializeObject<RentalRequest>(jsonString); // get the id var id = rentalRequest.Id; // do a get. request = new HttpRequestMessage(HttpMethod.Get, "/api/rentalrequests/" + id); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // parse as JSON. jsonString = await response.Content.ReadAsStringAsync(); rentalRequest = JsonConvert.DeserializeObject<RentalRequest>(jsonString); // should be the same number of equipment. Assert.Equal(rentalRequest.RentalRequestRotationList.Count, numberEquipment); // do a delete. request = new HttpRequestMessage(HttpMethod.Post, "/api/rentalrequests/" + id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/rentalrequests/" + id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // remove equipment. for (int i = 0; i < numberEquipment; i++) { request = new HttpRequestMessage(HttpMethod.Post, "/api/equipment/" + testEquipment[i].Id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); // should get a 404 if we try a get now. request = new HttpRequestMessage(HttpMethod.Get, "/api/equipment/" + testEquipment[i].Id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } // now remove the other temporary objects. // districtEquipmentType request = new HttpRequestMessage(HttpMethod.Post, "/api/districtEquipmentTypes/" + districtEquipmentType.Id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); request = new HttpRequestMessage(HttpMethod.Get, "/api/districtEquipmentTypes/" + districtEquipmentType.Id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // equipmentType request = new HttpRequestMessage(HttpMethod.Post, "/api/equipmentTypes/" + equipmentType.Id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); request = new HttpRequestMessage(HttpMethod.Get, "/api/equipmentTypes/" + equipmentType.Id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // localArea request = new HttpRequestMessage(HttpMethod.Post, "/api/localAreas/" + localArea.Id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); request = new HttpRequestMessage(HttpMethod.Get, "/api/localAreas/" + localArea.Id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // Service Area request = new HttpRequestMessage(HttpMethod.Post, "/api/serviceareas/" + serviceArea.Id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); request = new HttpRequestMessage(HttpMethod.Get, "/api/serviceareas/" + serviceArea.Id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // District request = new HttpRequestMessage(HttpMethod.Post, "/api/districts/" + district.Id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); request = new HttpRequestMessage(HttpMethod.Get, "/api/districts/" + district.Id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // Region request = new HttpRequestMessage(HttpMethod.Post, "/api/regions/" + region.Id + "/delete"); response = await _client.SendAsync(request); response.EnsureSuccessStatusCode(); request = new HttpRequestMessage(HttpMethod.Get, "/api/regions/" + region.Id); response = await _client.SendAsync(request); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } } }
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Windows.Kinect { // // Windows.Kinect.ColorFrame // public sealed partial class ColorFrame : RootSystem.IDisposable, Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal ColorFrame(RootSystem.IntPtr pNative) { _pNative = pNative; Windows_Kinect_ColorFrame_AddRefObject(ref _pNative); } ~ColorFrame() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_ColorFrame_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_ColorFrame_AddRefObject(ref RootSystem.IntPtr pNative); private void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } Helper.NativeObjectCache.RemoveObject<ColorFrame>(_pNative); if (disposing) { Windows_Kinect_ColorFrame_Dispose(_pNative); } Windows_Kinect_ColorFrame_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrame_get_ColorCameraSettings(RootSystem.IntPtr pNative); public Windows.Kinect.ColorCameraSettings ColorCameraSettings { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrame_get_ColorCameraSettings(_pNative); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.ColorCameraSettings>(objectPointer, n => new Windows.Kinect.ColorCameraSettings(n)); } } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrame_get_ColorFrameSource(RootSystem.IntPtr pNative); public Windows.Kinect.ColorFrameSource ColorFrameSource { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrame_get_ColorFrameSource(_pNative); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.ColorFrameSource>(objectPointer, n => new Windows.Kinect.ColorFrameSource(n)); } } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrame_get_FrameDescription(RootSystem.IntPtr pNative); public Windows.Kinect.FrameDescription FrameDescription { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrame_get_FrameDescription(_pNative); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.FrameDescription>(objectPointer, n => new Windows.Kinect.FrameDescription(n)); } } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern Windows.Kinect.ColorImageFormat Windows_Kinect_ColorFrame_get_RawColorImageFormat(RootSystem.IntPtr pNative); public Windows.Kinect.ColorImageFormat RawColorImageFormat { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } return Windows_Kinect_ColorFrame_get_RawColorImageFormat(_pNative); } } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern long Windows_Kinect_ColorFrame_get_RelativeTime(RootSystem.IntPtr pNative); public RootSystem.TimeSpan RelativeTime { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } return RootSystem.TimeSpan.FromMilliseconds(Windows_Kinect_ColorFrame_get_RelativeTime(_pNative)); } } // Public Methods [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_ColorFrame_CopyRawFrameDataToArray(RootSystem.IntPtr pNative, RootSystem.IntPtr frameData, int frameDataSize); public void CopyRawFrameDataToArray(byte[] frameData) { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } var frameDataSmartGCHandle = new Helper.SmartGCHandle(RootSystem.Runtime.InteropServices.GCHandle.Alloc(frameData, RootSystem.Runtime.InteropServices.GCHandleType.Pinned)); var _frameData = frameDataSmartGCHandle.AddrOfPinnedObject(); Windows_Kinect_ColorFrame_CopyRawFrameDataToArray(_pNative, _frameData, frameData.Length); } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrame_LockRawImageBuffer(RootSystem.IntPtr pNative); public Windows.Storage.Streams.IBuffer LockRawImageBuffer() { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrame_LockRawImageBuffer(_pNative); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Storage.Streams.IBuffer_Internal>(objectPointer, n => new Windows.Storage.Streams.IBuffer_Internal(n)); } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_ColorFrame_CopyConvertedFrameDataToArray(RootSystem.IntPtr pNative, RootSystem.IntPtr frameData, int frameDataSize, Windows.Kinect.ColorImageFormat colorFormat); public void CopyConvertedFrameDataToArray(byte[] frameData, Windows.Kinect.ColorImageFormat colorFormat) { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } var frameDataSmartGCHandle = new Helper.SmartGCHandle(RootSystem.Runtime.InteropServices.GCHandle.Alloc(frameData, RootSystem.Runtime.InteropServices.GCHandleType.Pinned)); var _frameData = frameDataSmartGCHandle.AddrOfPinnedObject(); Windows_Kinect_ColorFrame_CopyConvertedFrameDataToArray(_pNative, _frameData, frameData.Length, colorFormat); } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrame_CreateFrameDescription(RootSystem.IntPtr pNative, Windows.Kinect.ColorImageFormat format); public Windows.Kinect.FrameDescription CreateFrameDescription(Windows.Kinect.ColorImageFormat format) { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrame_CreateFrameDescription(_pNative, format); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.FrameDescription>(objectPointer, n => new Windows.Kinect.FrameDescription(n)); } [RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private static extern void Windows_Kinect_ColorFrame_Dispose(RootSystem.IntPtr pNative); public void Dispose() { if (_pNative == RootSystem.IntPtr.Zero) { return; } Dispose(true); RootSystem.GC.SuppressFinalize(this); } } }
using UnityEngine; using System.Collections.Generic; using System; public class Chatty : MonoBehaviour { // The font to use. public Font font; // The object that displays the sprites. public GameObject background; // The backgrounds to display. private Sprite[] sprites; // Questions/answers/moods private string[] questions; private string[] answers; private int[] moods; private int questionIdx; // [0,1] // The current mood. private float mood = 1; // Whether the buttons are being hovered over. private bool[] hoverOnButton; // The last stable mood. private int lastStableSpriteIndex; // The temporary mood. private int temporarySpriteIndex; // The time for the transition between moods. private float transitionPeriod = .75f; // The time in the current transition, or 0 if there is no transition at the moment. private float transitionTime = 0; void Start() { questions = new string[]{ "Hello, my prince.", "What do you think about the new flowers in the garden?", "They're imported from Westeros... the flowers, I mean.", "And the bedsheets... I think I prefer the silk ones over the Egyptian cotton ones.", "Did you want to attend the Eriksen dinner party next week? I hear they're serving Kobe lobster.", "It's been a while since we've gone riding together. Would you like to go later this evening?", "Does this robe make me look fat?", "The oracle says she sees many offspring in our future.", "We don't even talk any more. We don't even know what we argue about.", "Are you happy?", }; answers = new string[]{ "Hello, my darling.", "Hey.", "(Head Nod)", "What was that, darling?", "They seem nice.", "The blue ones are quite striking, but pale in comparison to your beautiful eyes.", "Nice.", "Nice!", "Noice!", "Then we should go with the silk ones. They do seem warmer.", "Cool with me.", "Honestly, I could not care less.", "Do I have a choice?", "Of course! I know you and the Eriksens are like besties.", "You know how I feel about crustaceans. How is that not like eating giant insects?", "Yes.", "No.", "Well, we kind of did when we visited your aunt last week...", "Yes.", "Not more than usual.", "You make the robe look good.", "That's wonderful, darling!", "That bitch crazy.", "...", "Some people work things out and some just don't know how to change.", "Let's don't wait 'til the water runs dry.", "This stream dried up a long time ago, baby.", "Yes.", "No.", "Define \"happy\".", }; moods = new int[]{ 2, 1, 0, 0, 1, 2, 0, 1, 2, 2, 1, 0, 0, 2, 1, 2, 0, 1, 1, 0, 2, 2, 0, 1, 2, 0, 1, 2, 0, 1, }; sprites = new Sprite[]{ Resources.Load<Sprite>("chatty/chatty-0"), Resources.Load<Sprite>("chatty/chatty-1"), Resources.Load<Sprite>("chatty/chatty-2"), Resources.Load<Sprite>("chatty/chatty-3"), Resources.Load<Sprite>("chatty/chatty-4"), }; hoverOnButton = new bool[]{false, false, false}; // Set the initial color. var spriteRenderer = gameObject.GetComponent<SpriteRenderer>(); var spriteIndex = getStableSpriteIndex(); lastStableSpriteIndex = spriteIndex; spriteRenderer.sprite = sprites[spriteIndex]; } // Returns the sprite index of the stable sprite for the current mood. private int getStableSpriteIndex() { return 2 * (int)(Mathf.Max(1, Mathf.Ceil(mood*3)) - 1); } private void commonAnswerUpdate(int answerOffset) { var moodToDelta = new Dictionary<int, float>{ {0, -.25f}, {1, -.1f}, {2, .25f}, }; var oldMood = mood; var oldSpriteIndex = getStableSpriteIndex(); // Update the mood. mood = Mathf.Min(1, Mathf.Max(0, mood + moodToDelta[moods[questionIdx*3 + answerOffset]])); // Determine which transition to use. if (mood >= oldMood) { temporarySpriteIndex = Math.Min(4, oldSpriteIndex + 1); } else { temporarySpriteIndex = Math.Max(0, oldSpriteIndex - 1); } //Debug.Log("mood:" + mood); transitionTime = transitionPeriod; var moodIndex = getStableSpriteIndex(); if (++questionIdx > questions.Length - 1) { // Move right to the stable mood for the end of the game. temporarySpriteIndex = moodIndex; if (moodIndex == 4) { // Happy LevelState.levelState = LevelState.State.ChattyHappy; // Indifferent } else if (moodIndex == 2) { LevelState.levelState = LevelState.State.ChattyIndifferent; } else { // Sad LevelState.levelState = LevelState.State.ChattySad; } Application.LoadLevel(5); } } void OnGUI() { if (questionIdx > questions.Length - 1) { return; } GUI.skin.button.wordWrap = true; // Clear button backgrounds. GUI.backgroundColor = new Color(1,1,1,0); // Make the font GUI.skin.label.fontSize = Screen.width / 31; GUI.skin.button.fontSize = Screen.width / 40; GUI.skin.label.font = font; GUI.skin.button.font = GUI.skin.label.font; // Default text color. var labelAndHighlightColor = new Color(0.184f, 0.341f, 0.498f, 1); GUI.contentColor = labelAndHighlightColor; // Text alignment. GUI.skin.label.alignment = TextAnchor.MiddleCenter; GUI.skin.button.alignment = TextAnchor.MiddleLeft; // Pad the label and buttons. int padding = Screen.width/25; GUI.skin.label.padding = new RectOffset(padding, padding, 0, 0); GUI.skin.button.padding = new RectOffset(padding, padding, 0, 0); // Display the question label. var buttonAreaSize = new Vector2(Screen.width*.575f, Screen.height*.45f); GUI.Label(new Rect(0, Screen.height - buttonAreaSize.y, Screen.width - buttonAreaSize.x - Screen.width * .05f, buttonAreaSize.y - padding/2), questions[questionIdx]); // Display/update the buttons. var buttonIndex = -1; GUILayout.BeginArea(new Rect(Screen.width - buttonAreaSize.x, Screen.height - buttonAreaSize.y, buttonAreaSize.x, buttonAreaSize.y)); GUI.skin.button.margin = new RectOffset(0,0,0,0); GUILayout.BeginVertical(); var numButtons = 3; for (int i=0; i<numButtons; i++) { // Sets the hover color of a button. if (hoverOnButton[i]) { GUI.contentColor = labelAndHighlightColor; } else { GUI.contentColor = new Color(0.427f,0.431f,0.439f,1); } if (GUILayout.Button(answers[questionIdx*numButtons+i], GUILayout.Height(buttonAreaSize.y/3))) { buttonIndex = i; } if (Event.current.type == EventType.Repaint) { hoverOnButton[i] = GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition); } } GUILayout.EndVertical(); GUILayout.EndArea(); if (buttonIndex >= 0) { commonAnswerUpdate(buttonIndex); } } void Update() { var moodState = getStableSpriteIndex(); var spriteRenderer = gameObject.GetComponent<SpriteRenderer>(); ResizeSpriteToScreen(background, Camera.main, 1, 1); Action<int> render = state => spriteRenderer.sprite = sprites[state]; if (transitionTime > 0) { transitionTime -= Time.deltaTime; render(temporarySpriteIndex); } else { render(moodState); } } private void ResizeSpriteToScreen(GameObject theSprite, Camera theCamera, int fitToScreenWidth, int fitToScreenHeight) { SpriteRenderer sr = theSprite.GetComponent<SpriteRenderer>(); theSprite.transform.localScale = new Vector3(1,1,1); float width = sr.sprite.bounds.size.x; float height = sr.sprite.bounds.size.y; float worldScreenHeight = (float)(theCamera.orthographicSize * 2.0); float worldScreenWidth = (float)(worldScreenHeight / Screen.height * Screen.width); if (fitToScreenWidth != 0) { Vector2 sizeX = new Vector2(worldScreenWidth / width / fitToScreenWidth,theSprite.transform.localScale.y); theSprite.transform.localScale = sizeX; } if (fitToScreenHeight != 0) { Vector2 sizeY = new Vector2(theSprite.transform.localScale.x, worldScreenHeight / height / fitToScreenHeight); theSprite.transform.localScale = sizeY; } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Equationator { /// <summary> /// This is a single node of the equation. /// All the other node types inherit from this one. /// </summary> public abstract class BaseNode { #region Properties /// <summary> /// Gets or sets the previous node. /// </summary> /// <value>The previous.</value> protected BaseNode Prev { get; set; } /// <summary> /// Gets or sets the next node. /// </summary> /// <value>The next.</value> protected BaseNode Next { get; set; } /// <summary> /// The value of this node for order of operations. /// This is set in all teh chlid nodes. /// </summary> /// <value>The pembas value.</value> protected PemdasValue OrderOfOperationsValue { get; set; } #endregion Properties #region Methods #region Constructor /// <summary> /// Initializes a new instance of the <see cref="Equationator.EquationNode"/> class. /// </summary> /// <param name="prev">Previous node in the list, or null if this is head</param> /// <param name="next">Next node in the list, or null if this is tail.</param> public BaseNode() { this.Prev = null; this.Next = null; } #endregion //Constructor #region Linked List Functionality /// <summary> /// Make this node into a head node. /// </summary> protected void MakeHead() { //note that if there is a prev node, it has to take care of it's own pointers! Prev = null; } /// <summary> /// Makes this node into a tail node. /// </summary> protected void MakeTail() { //note that if there is a next node, it has to take care of it's own pointers! Next = null; } /// <summary> /// Appends the next node. /// </summary> /// <param name="nextNode">Next node.</param> public void AppendNextNode(BaseNode nextNode) { if (null == nextNode) { throw new ArgumentNullException("nextNode"); } nextNode.Prev = this; this.Next = nextNode; } /// <summary> /// Add the ability for any node in a list to get the head node of the list. /// </summary> /// <returns>The head.</returns> public BaseNode GetHead() { //If there is a previous node, recurse into it to get the head node. if (null != Prev) { return Prev.GetHead(); } else { //If there is no prev node, this dude is the head return this; } } #endregion //Linked List Functionality #region Token Parsing Functionality /// <summary> /// Parse a list of tokens into a linked list of equation nodes. /// This will sort it out into a flat equation /// </summary> /// <param name="tokenList">Token list.</param> /// <param name="curIndex">Current index. When this function exits, will be incremented to the past any tokens consumed by this method</param> /// <param name="owner">the equation that this node is part of. required to pull function delegates out of the dictionary</param> /// <returns>A basenode pointing at the head of a linked list parsed by this method</returns> static public BaseNode Parse(List<Token> tokenList, ref int curIndex, Equation owner) { if (null == tokenList) { throw new ArgumentNullException("tokenList"); } if (null == owner) { throw new ArgumentNullException("owner"); } Debug.Assert(curIndex < tokenList.Count); //TODO: throw exceptions //first get a value, which will be a number, function, param, or equation node BaseNode myNumNode = BaseNode.ParseValueNode(tokenList, ref curIndex, owner); Debug.Assert(null != myNumNode); //TODO: throw exceptions //if there are any tokens left, get an operator if (curIndex < tokenList.Count) { BaseNode myOperNode = BaseNode.ParseOperNode(tokenList, ref curIndex, owner); if (null != myOperNode) { //add that node to the end of the list myNumNode.AppendNextNode(myOperNode); //If it was able to pull an operator out, there has to be a number after it. if (curIndex >= tokenList.Count) { throw new FormatException("Can't end an equation with an operator."); } //Recurse into the parse function and sort out the rest of the tokens BaseNode nextNode = BaseNode.Parse(tokenList, ref curIndex, owner); Debug.Assert(null != nextNode); //TODO: throw exceptions //add that node to the end of the list myOperNode.AppendNextNode(nextNode); } } //return the head node that I found return myNumNode; } /// <summary> /// Given a list of tokens and the index, get a node based on whatever is at that index /// </summary> /// <returns>The value node, will be a number, function, param, or equation node</returns> /// <param name="tokenList">Token list.</param> /// <param name="curIndex">Current index.</param> /// <param name="owner">the equation that this node is part of. required to pull function delegates out of the dictionary</param> static protected BaseNode ParseValueNode(List<Token> tokenList, ref int curIndex, Equation owner) { if (null == tokenList) { throw new ArgumentNullException("tokenList"); } if (null == owner) { throw new ArgumentNullException("owner"); } Debug.Assert(curIndex < tokenList.Count); //TODO: throw exceptions //what kind of token do I have at that index? switch (tokenList[curIndex].TypeOfToken) { case TokenType.Number: { //awesome, that's nice and easy... just shove the text into a node as a number //create the number node NumberNode valueNode = new NumberNode(); //parse the text into the number node valueNode.ParseToken(tokenList, ref curIndex, owner); //return the number node as our result return valueNode; } case TokenType.Param: { //also not bad, grab the text as a parameter index and put in a node //create the param node ParamNode valueNode = new ParamNode(); //parse the parameter index into the node valueNode.ParseToken(tokenList, ref curIndex, owner); //return it as our result return valueNode; } case TokenType.Function: { //hmmm... need to get the delegate and put in a node? //create the function node FunctionNode valueNode = new FunctionNode(); //parse the function delegate into the node valueNode.ParseToken(tokenList, ref curIndex, owner); //return it as our result return valueNode; } case TokenType.OpenParen: { //ok don't panic... //verify that this is not the last token if (curIndex >= (tokenList.Count - 1)) { throw new FormatException("Can't end an equation with an open paranthesis"); } //move past this token, cuz nothing else to do with it curIndex++; //starting at the next token, start an equation node EquationNode valueNode = new EquationNode(); //start parsing into the equation node valueNode.ParseToken(tokenList, ref curIndex, owner); //return it as the result return valueNode; } case TokenType.Operator: { //whoa, how did an operator get in here? it better be a minus sign return EquationNode.ParseNegativeToken(tokenList, ref curIndex, owner); } default: { //should just be close paren nodes in here, which we should never get throw new FormatException("Expected a \"value\" token, but got a " + tokenList[curIndex].TypeOfToken.ToString()); } } } /// <summary> /// Given a list of tokens and the index, get an operator node based on whatever is at that index. /// </summary> /// <returns>The oper node, or null if it hit the end of the equation.</returns> /// <param name="tokenList">Token list.</param> /// <param name="curIndex">Current index.</param> /// <param name="owner">the equation that this node is part of. required to pull function delegates out of the dictionary</param> static protected BaseNode ParseOperNode(List<Token> tokenList, ref int curIndex, Equation owner) { if (null == tokenList) { throw new ArgumentNullException("tokenList"); } if (null == owner) { throw new ArgumentNullException("owner"); } Debug.Assert(curIndex < tokenList.Count); //TODO: throw exceptions //what kind of token do I have at that index? switch (tokenList[curIndex].TypeOfToken) { case TokenType.Operator: { //ok create an operator node OperatorNode operNode = new OperatorNode(); //parse into that node operNode.ParseToken(tokenList, ref curIndex, owner); //return the thing return operNode; } case TokenType.CloseParen: { //close paren, just eat it and return null. It means this equation is finished parsing curIndex++; return null; } default: { //should just be close paren nodes in here, which we should never get throw new FormatException("Expected a \"operator\" token, but got a " + tokenList[curIndex].TypeOfToken.ToString()); } } } /// <summary> /// Parse the specified tokenList and curIndex. /// overloaded by child types to do there own specific parsing. /// </summary> /// <param name="tokenList">Token list.</param> /// <param name="curIndex">Current index.</param> /// <param name="owner">the equation that this node is part of. required to pull function delegates out of the dictionary</param> protected abstract void ParseToken(List<Token> tokenList, ref int curIndex, Equation owner); #endregion //Token Parsing Functionality #region Treeifying Functionality /// <summary> /// This method takes a node from a linked list, and folds it into a binary tree. /// The root node will have the highest pemdas value and the tree will be solved breadth first, ensuring that the root node is solved last. /// </summary> public BaseNode Treeify() { if (null != Prev) { throw new Exception("BaseNode.Treeify() should only ever be called on head nodes."); } //If this is a leaf node, there is nothing to do here! if (null == Next) { return this; } //find the node with the highest pemdas value (or the first add/subtract node, those are always highest) BaseNode rootNode = GetHighestPemdas(); //by this point nodes are either leaf or binary nodes with a node at each end Debug.Assert(null != rootNode.Prev); //TODO: throw exceptions Debug.Assert(null != rootNode.Next); //TODO: throw exceptions //set the next node to be the head of it's own list rootNode.Next.MakeHead(); //set the prev node to be the tail of it's own list rootNode.Prev.MakeTail(); //set the prev of our root node to the head of the prev list rootNode.Prev = rootNode.Prev.GetHead(); //set the prev node to the treeifyication result of the "previous" linked list rootNode.Prev = rootNode.Prev.Treeify(); //set the next node to treeification result of the "next" linked list rootNode.Next = rootNode.Next.Treeify(); //that's it, the whole equation below the root node is treeified now return rootNode; } /// <summary> /// Gets the highest pemdas. /// </summary> /// <returns>The highest pemdas.</returns> private BaseNode GetHighestPemdas() { Debug.Assert(null != Next); //TODO: throw exceptions //First, navigate to the end of the list. var current = this; while (null != current.Next) { current = current.Next; } //Now go backwards through the list to find the highest pemdas. var rootNode = current; for (var iter = current.Prev; iter != null; iter = iter.Prev) { //if we found an addition or subtraction node, that is the highest value if (PemdasValue.Addition <= rootNode.OrderOfOperationsValue) { break; } else if (iter.OrderOfOperationsValue > rootNode.OrderOfOperationsValue) { //The next node has a higher value than the current champion rootNode = iter; } } //ok, return the node we found with the highest value. return rootNode; } #endregion //Treeifying Functionality #region Solve Functionality /// <summary> /// Solve the equation! /// This method recurses into the whole tree and returns a result from the equation. /// </summary> /// <param name="paramCallback">Parameter callback that will be used to get teh values of parameter nodes.</param> /// <returns>The solution of this node and all its subnodes!</returns> public abstract double Solve(ParamDelegate paramCallback); #endregion //Solve Functionality #endregion Methods } }
// <copyright file="ReaderWriterSynchronizedBase.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Threading; using IX.StandardExtensions.ComponentModel; using IX.StandardExtensions.Contracts; using IX.System.Threading; using JetBrains.Annotations; using ReaderWriterLockSlim = IX.System.Threading.ReaderWriterLockSlim; namespace IX.StandardExtensions.Threading { /// <summary> /// A base class for a reader/writer synchronized class. /// </summary> /// <seealso cref="IX.StandardExtensions.ComponentModel.DisposableBase" /> [DataContract(Namespace = Constants.DataContractNamespace)] [PublicAPI] public abstract partial class ReaderWriterSynchronizedBase : DisposableBase { private readonly bool lockInherited; [SuppressMessage( "IDisposableAnalyzers.Correctness", "IDISP008:Don't assign member with injected and created disposables.", Justification = "We can't do that here, as doing exactly that is the purpose of this class.")] [SuppressMessage( "IDisposableAnalyzers.Correctness", "IDISP002:Dispose member.", Justification = "It is.")] [SuppressMessage( "IDisposableAnalyzers.Correctness", "IDISP006:Implement IDisposable.", Justification = "It is.")] private IReaderWriterLock locker; [DataMember] private TimeSpan lockerTimeout; /// <summary> /// Initializes a new instance of the <see cref="ReaderWriterSynchronizedBase" /> class. /// </summary> protected ReaderWriterSynchronizedBase() { this.locker = new ReaderWriterLockSlim(); this.lockerTimeout = EnvironmentSettings.LockAcquisitionTimeout; } /// <summary> /// Initializes a new instance of the <see cref="ReaderWriterSynchronizedBase" /> class. /// </summary> /// <param name="locker">The locker.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="locker" /> /// is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> protected ReaderWriterSynchronizedBase(IReaderWriterLock locker) { Contract.RequiresNotNull(ref this.locker, locker, nameof(locker)); this.lockInherited = true; this.lockerTimeout = EnvironmentSettings.LockAcquisitionTimeout; } /// <summary> /// Initializes a new instance of the <see cref="ReaderWriterSynchronizedBase" /> class. /// </summary> /// <param name="timeout">The lock timeout duration.</param> protected ReaderWriterSynchronizedBase(TimeSpan timeout) { this.locker = new ReaderWriterLockSlim(); this.lockerTimeout = timeout; } /// <summary> /// Initializes a new instance of the <see cref="ReaderWriterSynchronizedBase" /> class. /// </summary> /// <param name="locker">The locker.</param> /// <param name="timeout">The lock timeout duration.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="locker" /> /// is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic). /// </exception> protected ReaderWriterSynchronizedBase( IReaderWriterLock locker, TimeSpan timeout) { Contract.RequiresNotNull(ref this.locker, locker, nameof(locker)); this.lockInherited = true; this.lockerTimeout = timeout; } /// <summary> /// Called when the object is being deserialized, in order to set the locker to a new value. /// </summary> /// <param name="context">The streaming context.</param> [OnDeserializing] internal void OnDeserializingMethod(StreamingContext context) => Interlocked.Exchange( ref this.locker, new ReaderWriterLockSlim()); /// <summary> /// Produces a reader lock in concurrent collections. /// </summary> /// <returns>A disposable object representing the lock.</returns> protected ReadOnlySynchronizationLocker ReadLock() { this.ThrowIfCurrentObjectDisposed(); return new ReadOnlySynchronizationLocker( this.locker, this.lockerTimeout); } /// <summary> /// Invokes using a reader lock. /// </summary> /// <param name="action">An action that is called.</param> protected void ReadLock(Action action) { this.ThrowIfCurrentObjectDisposed(); using (new ReadOnlySynchronizationLocker( this.locker, this.lockerTimeout)) { action(); } } /// <summary> /// Gets a result from an invoker using a reader lock. /// </summary> /// <param name="action">An action that is called to get the result.</param> /// <typeparam name="T">The type of the object to return.</typeparam> /// <returns>A disposable object representing the lock.</returns> protected T ReadLock<T>(Func<T> action) { this.ThrowIfCurrentObjectDisposed(); using (new ReadOnlySynchronizationLocker( this.locker, this.lockerTimeout)) { return action(); } } /// <summary> /// Produces a writer lock in concurrent collections. /// </summary> /// <returns>A disposable object representing the lock.</returns> protected WriteOnlySynchronizationLocker WriteLock() { this.ThrowIfCurrentObjectDisposed(); return new WriteOnlySynchronizationLocker( this.locker, this.lockerTimeout); } /// <summary> /// Invokes using a writer lock. /// </summary> /// <param name="action">An action that is called.</param> protected void WriteLock(Action action) { this.ThrowIfCurrentObjectDisposed(); using (new WriteOnlySynchronizationLocker( this.locker, this.lockerTimeout)) { action(); } } /// <summary> /// Invokes using a writer lock. /// </summary> /// <typeparam name="T">The type of item to return.</typeparam> /// <param name="action">An action that is called.</param> /// <returns>The generated item.</returns> protected T WriteLock<T>(Func<T> action) { this.ThrowIfCurrentObjectDisposed(); using (new WriteOnlySynchronizationLocker( this.locker, this.lockerTimeout)) { return action(); } } /// <summary> /// Produces an upgradeable reader lock in concurrent collections. /// </summary> /// <returns>A disposable object representing the lock.</returns> protected ReadWriteSynchronizationLocker ReadWriteLock() { this.ThrowIfCurrentObjectDisposed(); return new ReadWriteSynchronizationLocker( this.locker, this.lockerTimeout); } /// <summary> /// Disposes in the managed context. /// </summary> protected override void DisposeManagedContext() { if (!this.lockInherited) { this.locker.Dispose(); } base.DisposeManagedContext(); } /// <summary> /// Spawns an atomic enumerator tied to this instance's locking mechanisms. /// </summary> /// <typeparam name="TItem">The type of the item within the atomic enumerator.</typeparam> /// <typeparam name="TEnumerator">The type of the enumerator to spawn the atomic enumerator from.</typeparam> /// <param name="sourceEnumerator">The source enumerator.</param> /// <returns>An tied-in atomic enumerator.</returns> protected AtomicEnumerator<TItem, TEnumerator> SpawnAtomicEnumerator<TItem, TEnumerator>( in TEnumerator sourceEnumerator) where TEnumerator : IEnumerator<TItem> { this.ThrowIfCurrentObjectDisposed(); return new AtomicEnumerator<TItem, TEnumerator>( sourceEnumerator, this.ReadLock); } } }
/** * STUFF DOWNLOADED FROM http://wiki.unity3d.com/index.php/Hermite_Spline_Controller * AUTHOR: Benoit FOULETIER (http://wiki.unity3d.com/index.php/User:Benblo) * MODIFIED BY F. Montorsi */ using UnityEngine; using System.Collections; using System.Collections.Generic; public class SplineNodeBreak { internal string Name; internal Vector3 Point; internal Quaternion Rot; internal float ArrivalTime; internal float BreakTime; internal Vector2 EaseIO; internal SplineNodeBreak(string n, Vector3 p, Quaternion q, float tArrival, float tBreak, Vector2 io) { Name = n; Point = p; Rot = q; ArrivalTime = tArrival; BreakTime = tBreak; EaseIO = io; } internal SplineNodeBreak(SplineNodeBreak o) { Name = o.Name; Point = o.Point; Rot = o.Rot; ArrivalTime = o.ArrivalTime; BreakTime = o.BreakTime; EaseIO = o.EaseIO; } // this is the constructor used by SplineController: internal SplineNodeBreak(string n, Transform t, float tBreak) { Name = n; Point = t.position; Rot = t.rotation; BreakTime = tBreak; } public float GetLeaveTime() { return ArrivalTime + BreakTime; } } public delegate void OnPathEndCallback(); public delegate void OnNodeArrivalCallback(int idxArrival, SplineNodeBreak nodeArrival); public delegate void OnNodeLeavingCallback(int idxLeaving, SplineNodeBreak nodeLeaving); public class SplineInterpolatorBreak : MonoBehaviour { List<SplineNodeBreak> mNodes = new List<SplineNodeBreak>(); eEndPointsMode mEndPointsMode = eEndPointsMode.AUTO; string mState = ""; // can be "Reset", "Stopped", "Once" or "Loop" bool mRotations; float mCurrentTime; int mCurrentIdx = 1; OnPathEndCallback mOnPathEndCallback; OnNodeArrivalCallback mOnNodeArrivalCallback; OnNodeLeavingCallback mOnNodeLeavingCallback; int mLastNodeCallback = 0; // -------------------------------------------------------------------------------------------- // UNITY CALLBACKS // -------------------------------------------------------------------------------------------- void Awake() { Reset(); } void Update() { if (mState == "Reset" || mState == "Stopped" || mNodes.Count < 4) return; mCurrentTime += Time.deltaTime; if (mCurrentTime >= mNodes[mCurrentIdx + 1].ArrivalTime) { // advance to next point in the path if (mCurrentIdx < mNodes.Count - 3) { mCurrentIdx++; // Inform that we have just arrived to the mCurrentIdx -th node! if (mOnNodeArrivalCallback != null) mOnNodeArrivalCallback(mCurrentIdx, mNodes[mCurrentIdx]); } else { if (mState != "Loop") { mState = "Stopped"; // We stop right in the end point transform.position = mNodes[mNodes.Count - 2].Point; if (mRotations) transform.rotation = mNodes[mNodes.Count - 2].Rot; // We call back to inform that we are ended if (mOnNodeArrivalCallback != null) mOnNodeArrivalCallback(mCurrentIdx+1, mNodes[mCurrentIdx+1]); if (mOnPathEndCallback != null) mOnPathEndCallback(); } else { mCurrentIdx = 1; mCurrentTime = 0; } } } if (mState != "Stopped") { if (mCurrentTime >= mNodes[mCurrentIdx].GetLeaveTime()) { if (mLastNodeCallback < mCurrentIdx && mOnNodeLeavingCallback != null) { // Inform that we have just left the mCurrentIdx-th node! mOnNodeLeavingCallback(mCurrentIdx, mNodes[mCurrentIdx]); mLastNodeCallback++; } //else: callback has already been called // Calculates the t param between 0 and 1 float param = GetNormalizedTime(mCurrentIdx, mCurrentTime, mCurrentIdx+1); // Smooth the param param = MathUtils.Ease(param, mNodes[mCurrentIdx].EaseIO.x, mNodes[mCurrentIdx].EaseIO.y); // Move attached transform transform.position = GetHermiteInternal(mCurrentIdx, param); /* // simulate human walking (FIXME) Vector3 tmp = new Vector3(transform.position.x, transform.position.y, transform.position.z); tmp.y += 0.7f * Mathf.Sin (7*mCurrentTime); transform.position = tmp;*/ if (mRotations) { // Rotate attached transform transform.rotation = GetSquad(mCurrentIdx, param); } } // else: we are in the "stop time" for the mCurrentIdx-th node } } // -------------------------------------------------------------------------------------------- // PUBLIC MEMBERS // -------------------------------------------------------------------------------------------- public void StartInterpolation(OnPathEndCallback endCallback, OnNodeArrivalCallback nodeArrival, OnNodeLeavingCallback nodeCallback, bool bRotations, eWrapMode mode) { if (mState != "Reset") throw new System.Exception("First reset, add points and then call here"); mState = mode == eWrapMode.ONCE ? "Once" : "Loop"; mRotations = bRotations; mOnPathEndCallback = endCallback; mOnNodeArrivalCallback = nodeArrival; mOnNodeLeavingCallback = nodeCallback; SetInput(); } public void Reset() { mNodes.Clear(); mState = "Reset"; mCurrentIdx = 1; mCurrentTime = 0; mRotations = false; mEndPointsMode = eEndPointsMode.AUTO; } public void AddPoint(string name, Vector3 pos, Quaternion quat, float timeInSeconds, float timeStop, Vector2 easeInOut) { if (mState != "Reset") throw new System.Exception("Cannot add points after start"); mNodes.Add(new SplineNodeBreak(name, pos, quat, timeInSeconds, timeStop, easeInOut)); } public void SetAutoCloseMode(float joiningPointTime) { if (mState != "Reset") throw new System.Exception("Cannot change mode after start"); mEndPointsMode = eEndPointsMode.AUTOCLOSED; mNodes.Add(new SplineNodeBreak(mNodes[0] as SplineNodeBreak)); mNodes[mNodes.Count - 1].ArrivalTime = joiningPointTime; Vector3 vInitDir = (mNodes[1].Point - mNodes[0].Point).normalized; Vector3 vEndDir = (mNodes[mNodes.Count - 2].Point - mNodes[mNodes.Count - 1].Point).normalized; float firstLength = (mNodes[1].Point - mNodes[0].Point).magnitude; float lastLength = (mNodes[mNodes.Count - 2].Point - mNodes[mNodes.Count - 1].Point).magnitude; SplineNodeBreak firstNode = new SplineNodeBreak(mNodes[0] as SplineNodeBreak); firstNode.Point = mNodes[0].Point + vEndDir * firstLength; SplineNodeBreak lastNode = new SplineNodeBreak(mNodes[mNodes.Count - 1] as SplineNodeBreak); lastNode.Point = mNodes[0].Point + vInitDir * lastLength; mNodes.Insert(0, firstNode); mNodes.Add(lastNode); } public Vector3 GetHermiteAtTime(float t) { // find the indices of the two nodes used for spline interpolation // at time t int c; for (c = 0; c < mNodes.Count - 1 /* - 1 because we look at c+1 */; c++) { if (mNodes[c].ArrivalTime <= t && t <= mNodes[c+1].ArrivalTime) break; } // ensure c is in the correct range if (c == mNodes.Count - 1) return mNodes[c].Point; float param = GetNormalizedTime(c, t, c+1); // c+1 is safe here thanks to prev check param = MathUtils.Ease(param, mNodes[c].EaseIO.x, mNodes[c].EaseIO.y); return GetHermiteInternal(c, param); } // -------------------------------------------------------------------------------------------- // PRIVATE MEMBERS // -------------------------------------------------------------------------------------------- void SetInput() { if (mNodes.Count < 2) throw new System.Exception("Invalid number of points"); if (mRotations) { for (int c = 1; c < mNodes.Count; c++) { SplineNodeBreak node = mNodes[c]; SplineNodeBreak prevNode = mNodes[c - 1]; // Always interpolate using the shortest path -> Selective negation if (Quaternion.Dot(node.Rot, prevNode.Rot) < 0) { node.Rot.x = -node.Rot.x; node.Rot.y = -node.Rot.y; node.Rot.z = -node.Rot.z; node.Rot.w = -node.Rot.w; } } } if (mEndPointsMode == eEndPointsMode.AUTO) { mNodes.Insert(0, mNodes[0]); mNodes.Add(mNodes[mNodes.Count - 1]); } else if (mEndPointsMode == eEndPointsMode.EXPLICIT && (mNodes.Count < 4)) throw new System.Exception("Invalid number of points"); } void SetExplicitMode() { if (mState != "Reset") throw new System.Exception("Cannot change mode after start"); mEndPointsMode = eEndPointsMode.EXPLICIT; } float GetNormalizedTime(int idxPrev, float t, int idxNext) { //DebugUtils.Assert(idxNext - idxPrev == 1); // we take two params just for clariness, but idxNext must be idxPrev+1 always if (t > mNodes[idxPrev].ArrivalTime && t < mNodes[idxPrev].GetLeaveTime()) return 0; float ret = (t - mNodes[idxPrev].GetLeaveTime()) / (mNodes[idxNext].ArrivalTime - mNodes[idxPrev].GetLeaveTime()); //DebugUtils.Assert(ret >= 0 && ret <= 1); return ret; } Quaternion GetSquad(int idxFirstPoint, float t) { Quaternion Q0 = mNodes[idxFirstPoint - 1].Rot; Quaternion Q1 = mNodes[idxFirstPoint].Rot; Quaternion Q2 = mNodes[idxFirstPoint + 1].Rot; Quaternion Q3 = mNodes[idxFirstPoint + 2].Rot; Quaternion T1 = MathUtils.GetSquadIntermediate(Q0, Q1, Q2); Quaternion T2 = MathUtils.GetSquadIntermediate(Q1, Q2, Q3); return MathUtils.GetQuatSquad(t, Q1, Q2, T1, T2); } Vector3 GetHermiteInternal(int idxFirstPoint, float t) { //DebugUtils.Assert(idxFirstPoint > 0 && idxFirstPoint < mNodes.Count - 2); // the spline can be computed only from the second node up to the penultimate node! if (idxFirstPoint == 0) return mNodes[0].Point; else if (idxFirstPoint == mNodes.Count - 1 || idxFirstPoint == mNodes.Count - 2) return mNodes[idxFirstPoint].Point; else if (idxFirstPoint > 0 && idxFirstPoint < mNodes.Count - 2) { float t2 = t * t; float t3 = t2 * t; Vector3 P0 = mNodes[idxFirstPoint - 1].Point; // take previous node Vector3 P1 = mNodes[idxFirstPoint].Point; Vector3 P2 = mNodes[idxFirstPoint + 1].Point; // take following node Vector3 P3 = mNodes[idxFirstPoint + 2].Point; // take the following of the following!! float tension = 0.5f; // 0.5 equivale a catmull-rom Vector3 T1 = tension * (P2 - P0); Vector3 T2 = tension * (P3 - P1); float Blend1 = 2 * t3 - 3 * t2 + 1; float Blend2 = -2 * t3 + 3 * t2; float Blend3 = t3 - 2 * t2 + t; float Blend4 = t3 - t2; return Blend1 * P1 + Blend2 * P2 + Blend3 * T1 + Blend4 * T2; } throw new System.Exception("logic error"); //return new Vector3(); // to avoid warnings } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.Framework.Scenes.Animation { /// <summary> /// Handle all animation duties for a scene presence /// </summary> public class Animator : IAnimator { private static AvatarAnimations m_defaultAnimations; protected int SLOWFLY_DELAY = 10; private float m_animTickFall; private float m_animTickStandup; protected AnimationSet m_animations; protected string m_movementAnimation = "DEFAULT"; /// <value> /// The scene presence that this animator applies to /// </value> protected IScenePresence m_scenePresence; private int m_timesBeforeSlowFlyIsOff; protected bool m_useSplatAnimation = true; public bool NeedsAnimationResent { get; set; } public Animator(IScenePresence sp) { m_scenePresence = sp; IConfig animationConfig = sp.Scene.Config.Configs["Animations"]; if (animationConfig != null) { SLOWFLY_DELAY = animationConfig.GetInt("SlowFlyDelay", SLOWFLY_DELAY); m_useSplatAnimation = animationConfig.GetBoolean("enableSplatAnimation", m_useSplatAnimation); } //This step makes sure that we don't waste almost 2.5! seconds on incoming agents m_animations = new AnimationSet(DefaultAnimations); } public static AvatarAnimations DefaultAnimations { get { if (m_defaultAnimations == null) m_defaultAnimations = new AvatarAnimations(); return m_defaultAnimations; } } #region IAnimator Members public AnimationSet Animations { get { return m_animations; } } /// <value> /// The current movement animation /// </value> public string CurrentMovementAnimation { get { return m_movementAnimation; } } public void AddAnimation(UUID animID, UUID objectID) { if (m_scenePresence.IsChildAgent) return; if (m_animations.Add(animID, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, objectID)) SendAnimPack(); } // Called from scripts public bool AddAnimation(string name, UUID objectID) { if (m_scenePresence.IsChildAgent) return false; UUID animID = m_scenePresence.ControllingClient.GetDefaultAnimation(name); if (animID == UUID.Zero) return false; AddAnimation(animID, objectID); return true; } /// <summary> /// Remove the given animation from the list of current animations /// </summary> /// <param name = "animID"></param> public void RemoveAnimation(UUID animID) { if (m_scenePresence.IsChildAgent) return; if (m_animations.Remove(animID)) SendAnimPack(); } /// <summary> /// Remove the given animation from the list of current animations /// </summary> /// <param name = "name"></param> public bool RemoveAnimation(string name) { if (m_scenePresence.IsChildAgent) return false; UUID animID = m_scenePresence.ControllingClient.GetDefaultAnimation(name); if (animID == UUID.Zero) { if (DefaultAnimations.AnimsUUID.ContainsKey(name.ToUpper())) animID = DefaultAnimations.AnimsUUID[name]; else return false; } RemoveAnimation(animID); return true; } /// <summary> /// Clear out all animations /// </summary> public void ResetAnimations() { m_animations.Clear(); } /// <summary> /// The movement animation is reserved for "main" animations /// that are mutually exclusive, e.g. flying and sitting. /// </summary> public void TrySetMovementAnimation(string anim) { TrySetMovementAnimation(anim, false); } /// <summary> /// The movement animation is reserved for "main" animations /// that are mutually exclusive, e.g. flying and sitting. /// </summary> public void TrySetMovementAnimation(string anim, bool sendTerseUpdateIfNotSending) { //MainConsole.Instance.DebugFormat("Updating movement animation to {0}", anim); if (!m_useSplatAnimation && anim == "STANDUP") anim = "LAND"; if (!m_scenePresence.IsChildAgent) { if (m_animations.TrySetDefaultAnimation( anim, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, m_scenePresence.UUID)) { // 16384 is CHANGED_ANIMATION IAttachmentsModule attMod = m_scenePresence.Scene.RequestModuleInterface<IAttachmentsModule>(); if (attMod != null) attMod.SendScriptEventToAttachments(m_scenePresence.UUID, "changed", new Object[] {(int) Changed.ANIMATION}); SendAnimPack(); } else if (sendTerseUpdateIfNotSending) m_scenePresence.SendTerseUpdateToAllClients(); //Send the terse update alone then } } /// <summary> /// This method determines the proper movement related animation /// </summary> public string GetMovementAnimation() { const float STANDUP_TIME = 2f; const float BRUSH_TIME = 3.5f; const float SOFTLAND_FORCE = 80; #region Inputs if (m_scenePresence.SitGround) { return "SIT_GROUND_CONSTRAINED"; } AgentManager.ControlFlags controlFlags = (AgentManager.ControlFlags) m_scenePresence.AgentControlFlags; PhysicsCharacter actor = m_scenePresence.PhysicsActor; // Create forward and left vectors from the current avatar rotation Vector3 fwd = Vector3.UnitX*m_scenePresence.Rotation; Vector3 left = Vector3.UnitY*m_scenePresence.Rotation; // Check control flags bool heldForward = (((controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) == AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) || ((controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) == AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS)); bool yawPos = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) == AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS; bool yawNeg = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG; bool heldBack = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG; bool heldLeft = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) == AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS; bool heldRight = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG; bool heldTurnLeft = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT) == AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT; bool heldTurnRight = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT) == AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT; bool heldUp = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) == AgentManager.ControlFlags.AGENT_CONTROL_UP_POS; bool heldDown = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG; //bool flying = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) == AgentManager.ControlFlags.AGENT_CONTROL_FLY; //bool mouselook = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) == AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK; // Direction in which the avatar is trying to move Vector3 move = Vector3.Zero; if (heldForward) { move.X += fwd.X; move.Y += fwd.Y; } if (heldBack) { move.X -= fwd.X; move.Y -= fwd.Y; } if (heldLeft) { move.X += left.X; move.Y += left.Y; } if (heldRight) { move.X -= left.X; move.Y -= left.Y; } if (heldUp) { move.Z += 1; } if (heldDown) { move.Z -= 1; } float fallVelocity = (actor != null) ? actor.Velocity.Z : 0.0f; if (heldTurnLeft && yawPos && !heldForward && !heldBack && actor != null && !actor.IsJumping && !actor.Flying && move.Z == 0 && fallVelocity == 0.0f && !heldUp && !heldDown && move.CompareTo(Vector3.Zero) == 0) { return "TURNLEFT"; } if (heldTurnRight && yawNeg && !heldForward && !heldBack && actor != null && !actor.IsJumping && !actor.Flying && move.Z == 0 && fallVelocity == 0.0f && !heldUp && !heldDown && move.CompareTo(Vector3.Zero) == 0) { return "TURNRIGHT"; } // Is the avatar trying to move? // bool moving = (move != Vector3.Zero); #endregion Inputs #region Standup float standupElapsed = (Util.EnvironmentTickCount() - m_animTickStandup)/1000f; if (m_scenePresence.PhysicsActor != null && standupElapsed < STANDUP_TIME && m_useSplatAnimation) { // Falling long enough to trigger the animation m_scenePresence.FallenStandUp = true; m_scenePresence.PhysicsActor.Velocity = Vector3.Zero; return "STANDUP"; } else if (standupElapsed < BRUSH_TIME && m_useSplatAnimation) { m_scenePresence.FallenStandUp = true; return "BRUSH"; } else if (m_animTickStandup != 0 || m_scenePresence.FallenStandUp) { m_scenePresence.FallenStandUp = false; m_animTickStandup = 0; } #endregion Standup #region Flying // if (actor != null && actor.Flying) if (actor != null && (m_scenePresence.AgentControlFlags & (uint) AgentManager.ControlFlags.AGENT_CONTROL_FLY) == (uint) AgentManager.ControlFlags.AGENT_CONTROL_FLY) { m_animTickFall = 0; if (move.X != 0f || move.Y != 0f) { if (move.Z == 0) { if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) { return "SWIM_FORWARD"; } else { if (m_timesBeforeSlowFlyIsOff < SLOWFLY_DELAY) { m_timesBeforeSlowFlyIsOff++; return "FLYSLOW"; } else return "FLY"; } } else if (move.Z > 0) { if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_UP"; else return "FLYSLOW"; } if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_DOWN"; else return "FLY"; } else if (move.Z > 0f) { //This is for the slow fly timer m_timesBeforeSlowFlyIsOff = 0; if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_UP"; else return "HOVER_UP"; } else if (move.Z < 0f) { //This is for the slow fly timer m_timesBeforeSlowFlyIsOff = 0; if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_DOWN"; else { ITerrainChannel channel = m_scenePresence.Scene.RequestModuleInterface<ITerrainChannel>(); if (channel != null) { float groundHeight = channel.GetNormalizedGroundHeight((int) m_scenePresence.AbsolutePosition.X, (int) m_scenePresence.AbsolutePosition.Y); if (actor != null && (m_scenePresence.AbsolutePosition.Z - groundHeight) < 2) return "LAND"; else return "HOVER_DOWN"; } else return "HOVER_DOWN"; } } else { //This is for the slow fly timer m_timesBeforeSlowFlyIsOff = 0; if (m_scenePresence.Scene.PhysicsScene.UseUnderWaterPhysics && actor.Position.Z < m_scenePresence.Scene.RegionInfo.RegionSettings.WaterHeight) return "SWIM_HOVER"; else return "HOVER"; } } m_timesBeforeSlowFlyIsOff = 0; #endregion Flying #region Falling/Floating/Landing if (actor != null && actor.IsPhysical && !actor.IsJumping && (!actor.IsColliding) && actor.Velocity.Z < -2) { //Always return falldown immediately as there shouldn't be a waiting period if (m_animTickFall == 0) m_animTickFall = Util.EnvironmentTickCount(); return "FALLDOWN"; } #endregion Falling/Floating/Landing #region Ground Movement if (actor != null && actor.IsJumping) { return "JUMP"; } if (actor != null && actor.IsPreJumping) { return "PREJUMP"; } if (m_movementAnimation == "FALLDOWN") { float fallElapsed = (Util.EnvironmentTickCount() - m_animTickFall)/1000f; if (fallElapsed < 0.75) { m_animTickFall = Util.EnvironmentTickCount(); return "SOFT_LAND"; } else if (fallElapsed < 1.1) { m_animTickFall = Util.EnvironmentTickCount(); return "LAND"; } else { if (m_useSplatAnimation) { m_animTickStandup = Util.EnvironmentTickCount(); return "STANDUP"; } else return "LAND"; } } else if (m_movementAnimation == "LAND") { if (actor != null && actor.Velocity.Z != 0) { if (actor.Velocity.Z < SOFTLAND_FORCE) return "LAND"; return "SOFT_LAND"; } //return "LAND"; } m_animTickFall = 0; if (move.Z <= 0f) { if (actor != null && (move.X != 0f || move.Y != 0f || actor.Velocity.X != 0 && actor.Velocity.Y != 0)) { // Walking / crouchwalking / running if (move.Z < 0f) return "CROUCHWALK"; else if (m_scenePresence.SetAlwaysRun) return "RUN"; else return "WALK"; } else { // Not walking if (move.Z < 0f) return "CROUCH"; else return "STAND"; } } #endregion Ground Movement return m_movementAnimation; } /// <summary> /// Update the movement animation of this avatar according to its current state /// </summary> public void UpdateMovementAnimations(bool sendTerseUpdate) { string oldanimation = m_movementAnimation; m_movementAnimation = GetMovementAnimation(); if (NeedsAnimationResent || oldanimation != m_movementAnimation || sendTerseUpdate) { NeedsAnimationResent = false; TrySetMovementAnimation(m_movementAnimation, sendTerseUpdate); } } /// <summary> /// Gets a list of the animations that are currently in use by this avatar /// </summary> /// <returns></returns> public UUID[] GetAnimationArray() { UUID[] animIDs; int[] sequenceNums; UUID[] objectIDs; m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs); return animIDs; } /// <summary> /// Sends all clients the given information for this avatar /// </summary> /// <param name = "animations"></param> /// <param name = "seqs"></param> /// <param name = "objectIDs"></param> public void SendAnimPack(UUID[] animations, int[] sequenceNums, UUID[] objectIDs) { if (m_scenePresence.IsChildAgent) return; AnimationGroup anis = new AnimationGroup { Animations = animations, SequenceNums = sequenceNums, ObjectIDs = objectIDs, AvatarID = m_scenePresence.UUID }; #if (!ISWIN) m_scenePresence.Scene.ForEachScenePresence( delegate(IScenePresence presence) { presence.SceneViewer.QueuePresenceForAnimationUpdate(m_scenePresence, anis); }); #else m_scenePresence.Scene.ForEachScenePresence( presence => presence.SceneViewer.QueuePresenceForAnimationUpdate(presence, anis)); #endif } /// <summary> /// Send an animation update to the given client /// </summary> /// <param name = "client"></param> public void SendAnimPackToClient(IClientAPI client) { if (m_scenePresence.IsChildAgent) return; UUID[] animations; int[] sequenceNums; UUID[] objectIDs; m_animations.GetArrays(out animations, out sequenceNums, out objectIDs); AnimationGroup anis = new AnimationGroup { Animations = animations, SequenceNums = sequenceNums, ObjectIDs = objectIDs, AvatarID = m_scenePresence.ControllingClient.AgentId }; m_scenePresence.Scene.GetScenePresence(client.AgentId).SceneViewer.QueuePresenceForAnimationUpdate( m_scenePresence, anis); } /// <summary> /// Send animation information about this avatar to all clients. /// </summary> public void SendAnimPack() { //MainConsole.Instance.Debug("Sending animation pack to all"); if (m_scenePresence.IsChildAgent) return; UUID[] animIDs; int[] sequenceNums; UUID[] objectIDs; m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs); SendAnimPack(animIDs, sequenceNums, objectIDs); } /// <summary> /// Close out and remove any current data /// </summary> public void Close() { m_animations = null; m_scenePresence = null; } #endregion } }
#region license // Copyright (c) 2005 - 2007 Ayende Rahien ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; //using System.Linq; using System.Text; using System.Collections; using Rhino.Mocks.Constraints; using System.Reflection; namespace Rhino.Mocks { /// <summary> /// Used to manage the static state of the Arg&lt;T&gt; class"/> /// </summary> internal class ArgManager { [ThreadStatic] private static List<ArgumentDefinition> args; internal static bool HasBeenUsed { get { if (args == null) return false; return args.Count > 0; } } /// <summary> /// Resets the static state /// </summary> internal static void Clear() { args = new List<ArgumentDefinition>(); } internal static void AddInArgument(AbstractConstraint constraint) { InitializeThreadStatic(); args.Add(new ArgumentDefinition(constraint)); } internal static void AddOutArgument(object returnValue) { InitializeThreadStatic(); args.Add(new ArgumentDefinition(returnValue)); } internal static void AddRefArgument(AbstractConstraint constraint, object returnValue) { InitializeThreadStatic(); args.Add(new ArgumentDefinition(constraint, returnValue)); } /// <summary> /// Returns return values for the out and ref parameters /// Note: the array returned has the size of the number of out and ref /// argument definitions /// </summary> /// <returns></returns> internal static object[] GetAllReturnValues() { InitializeThreadStatic(); List<object> returnValues = new List<object>(); foreach (ArgumentDefinition arg in args) { if (arg.InOutRef == InOutRefArgument.OutArg || arg.InOutRef == InOutRefArgument.RefArg) { returnValues.Add(arg.returnValue); } } return returnValues.ToArray(); } /// <summary> /// Returns the constraints for all arguments. /// Out arguments have an Is.Anything constraint and are also in the list. /// </summary> /// <returns></returns> internal static AbstractConstraint[] GetAllConstraints() { InitializeThreadStatic(); List<AbstractConstraint> constraints = new List<AbstractConstraint>(); foreach (ArgumentDefinition arg in args) { constraints.Add(arg.constraint); } return constraints.ToArray(); } internal static void CheckMethodSignature(MethodInfo method) { InitializeThreadStatic(); ParameterInfo[] parameters = method.GetParameters(); AbstractConstraint[] constraints = new AbstractConstraint[parameters.Length]; if (args.Count < parameters.Length) { throw new InvalidOperationException( string.Format("When using Arg<T>, all arguments must be defined using Arg<T>.Is, Arg<T>.Text, Arg<T>.List, Arg<T>.Ref or Arg<T>.Out. {0} arguments expected, {1} have been defined.", parameters.Length, args.Count)); } if (args.Count > parameters.Length) { throw new InvalidOperationException( string.Format("Use Arg<T> ONLY within a mock method call while recording. {0} arguments expected, {1} have been defined.", parameters.Length, args.Count)); } for (int i = 0; i < parameters.Length; i++) { if (parameters[i].IsOut) { if (args[i].InOutRef != InOutRefArgument.OutArg) { throw new InvalidOperationException( string.Format("Argument {0} must be defined as: out Arg<T>.Out(returnvalue).Dummy", i)); } } else if (parameters[i].ParameterType.IsByRef) { if (args[i].InOutRef != InOutRefArgument.RefArg) { throw new InvalidOperationException( string.Format("Argument {0} must be defined as: ref Arg<T>.Ref(constraint, returnvalue).Dummy", i)); } } else if (args[i].InOutRef != InOutRefArgument.InArg) { throw new InvalidOperationException( string.Format("Argument {0} must be defined using: Arg<T>.Is, Arg<T>.Text or Arg<T>.List", i)); } } } private static void InitializeThreadStatic() { if (args == null) { args = new List<ArgumentDefinition>(); } } private struct ArgumentDefinition { public InOutRefArgument InOutRef; public AbstractConstraint constraint; public object returnValue; public ArgumentDefinition(AbstractConstraint constraint) { this.InOutRef = InOutRefArgument.InArg; this.constraint = constraint; this.returnValue = null; } public ArgumentDefinition(AbstractConstraint constraint, object returnValue) { this.InOutRef = InOutRefArgument.RefArg; this.constraint = constraint; this.returnValue = returnValue; } public ArgumentDefinition(object returnValue) { this.InOutRef = InOutRefArgument.OutArg; this.returnValue = returnValue; this.constraint = Is.Anything(); } } private enum InOutRefArgument { InArg, OutArg, RefArg } } }
// 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.Runtime.CompilerServices; using Xunit; namespace System.Threading.Tasks.Tests { public class AsyncValueTaskMethodBuilderTests { [Fact] public void Create_ReturnsDefaultInstance() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); Assert.Equal(default(AsyncValueTaskMethodBuilder<int>), b); // implementation detail being verified } [Fact] public void SetResult_BeforeAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); b.SetResult(42); ValueTask<int> vt = b.Task; Assert.True(vt.IsCompletedSuccessfully); Assert.False(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetResult_AfterAccessTask_ValueTaskContainsValue() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); ValueTask<int> vt = b.Task; b.SetResult(42); Assert.True(vt.IsCompletedSuccessfully); Assert.True(WrapsTask(vt)); Assert.Equal(42, vt.Result); } [Fact] public void SetException_BeforeAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new FormatException(); b.SetException(e); ValueTask<int> vt = b.Task; Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_AfterAccessTask_FaultsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new FormatException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsFaulted); Assert.Same(e, Assert.Throws<FormatException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void SetException_OperationCanceledException_CancelsTask() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var e = new OperationCanceledException(); ValueTask<int> vt = b.Task; b.SetException(e); Assert.True(vt.IsCanceled); Assert.Same(e, Assert.Throws<OperationCanceledException>(() => vt.GetAwaiter().GetResult())); } [Fact] public void Start_InvokesMoveNext() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); int invokes = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => invokes++ }; b.Start(ref dsm); Assert.Equal(1, invokes); } [Theory] [InlineData(false)] [InlineData(true)] public async Task AwaitOnCompleted_InvokesStateMachineMethods(bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var ignored = b.Task; var callbackCompleted = new TaskCompletionSource<bool>(); IAsyncStateMachine foundSm = null; var dsm = new DelegateStateMachine { MoveNextDelegate = () => callbackCompleted.SetResult(true), SetStateMachineDelegate = sm => foundSm = sm }; TaskAwaiter t = Task.CompletedTask.GetAwaiter(); if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } await callbackCompleted.Task; Assert.Equal(dsm, foundSm); } [Theory] [InlineData(1, false)] [InlineData(2, false)] [InlineData(1, true)] [InlineData(2, true)] public void AwaitOnCompleted_ForcesTaskCreation(int numAwaits, bool awaitUnsafe) { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); var dsm = new DelegateStateMachine(); TaskAwaiter<int> t = new TaskCompletionSource<int>().Task.GetAwaiter(); Assert.InRange(numAwaits, 1, int.MaxValue); for (int i = 1; i <= numAwaits; i++) { if (awaitUnsafe) { b.AwaitUnsafeOnCompleted(ref t, ref dsm); } else { b.AwaitOnCompleted(ref t, ref dsm); } } b.SetResult(42); Assert.True(WrapsTask(b.Task)); Assert.Equal(42, b.Task.Result); } [Fact] public void SetStateMachine_InvalidArgument_ThrowsException() { AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null)); b.SetStateMachine(new DelegateStateMachine()); } [Fact] public void Start_ExecutionContextChangesInMoveNextDontFlowOut() { var al = new AsyncLocal<int> { Value = 0 }; int calls = 0; var dsm = new DelegateStateMachine { MoveNextDelegate = () => { al.Value++; calls++; } }; dsm.MoveNext(); Assert.Equal(1, al.Value); Assert.Equal(1, calls); dsm.MoveNext(); Assert.Equal(2, al.Value); Assert.Equal(2, calls); AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder(); b.Start(ref dsm); Assert.Equal(2, al.Value); // change should not be visible Assert.Equal(3, calls); // Make sure we've not caused the Task to be allocated b.SetResult(42); ValueTask<int> vt = b.Task; Assert.False(WrapsTask(vt)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(10)] public static async Task UsedWithAsyncMethod_CompletesSuccessfully(int yields) { Assert.Equal(42, await ValueTaskReturningAsyncMethod(42)); ValueTask<int> vt = ValueTaskReturningAsyncMethod(84); Assert.Equal(yields > 0, WrapsTask(vt)); Assert.Equal(84, await vt); async ValueTask<int> ValueTaskReturningAsyncMethod(int result) { for (int i = 0; i < yields; i++) await Task.Yield(); return result; } } /// <summary>Gets whether the ValueTask has a non-null Task.</summary> private static bool WrapsTask<T>(ValueTask<T> vt) => ReferenceEquals(vt.AsTask(), vt.AsTask()); private struct DelegateStateMachine : IAsyncStateMachine { internal Action MoveNextDelegate; public void MoveNext() => MoveNextDelegate?.Invoke(); internal Action<IAsyncStateMachine> SetStateMachineDelegate; public void SetStateMachine(IAsyncStateMachine stateMachine) => SetStateMachineDelegate?.Invoke(stateMachine); } } }
//------------------------------------------------------------------------------ // <copyright file="SimpleWebHandlerParser.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Implements the parser for simple web handler files * * Copyright (c) 2000 Microsoft Corporation */ namespace System.Web.UI { using System.Runtime.Serialization.Formatters; using System.Text; using System.Runtime.Serialization; using System; using System.Reflection; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Text.RegularExpressions; using System.CodeDom.Compiler; using System.Web; using System.Web.Hosting; using System.Web.Caching; using System.Web.Compilation; using System.CodeDom; using System.Web.Util; using Debug=System.Web.Util.Debug; using System.Web.RegularExpressions; using System.Globalization; using System.Security.Permissions; /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract class SimpleWebHandlerParser : IAssemblyDependencyParser { private readonly static Regex directiveRegex = new SimpleDirectiveRegex(); private SimpleHandlerBuildProvider _buildProvider; private TextReader _reader; private VirtualPath _virtualPath; // The line number in file currently being parsed private int _lineNumber; // The column number in file currently being parsed private int _startColumn; private bool _fFoundMainDirective; private string _typeName; internal string TypeName { get { return _typeName; } } private CompilerType _compilerType; // The string containing the code to be compiled private string _sourceString; // Assemblies to be linked with private AssemblySet _linkedAssemblies; // The set of assemblies that the build system is telling us we will be linked with private ICollection _referencedAssemblies; private static char[] s_newlineChars = new char[] { '\r', '\n' }; private bool _ignoreParseErrors; internal bool IgnoreParseErrors { get { return _ignoreParseErrors; } set { _ignoreParseErrors = value; } } internal void SetBuildProvider(SimpleHandlerBuildProvider buildProvider) { _buildProvider = buildProvider; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> // Only allowed in full trust (ASURT 124397) [SecurityPermission(SecurityAction.Demand, Unrestricted=true)] protected SimpleWebHandlerParser(HttpContext context, string virtualPath, string physicalPath) { // These obsolete parameters should never be set Debug.Assert(context == null); Debug.Assert(physicalPath == null); Debug.Assert(virtualPath != null); _virtualPath = VirtualPath.Create(virtualPath); } /* * Compile a web handler file into a Type. Result is cached. */ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected Type GetCompiledTypeFromCache() { // // This method is practically useless, but cannot be removed to avoid a breaking change // BuildResultCompiledType result = (BuildResultCompiledType) BuildManager.GetVPathBuildResult(_virtualPath); return result.ResultType; } internal void Parse(ICollection referencedAssemblies) { _referencedAssemblies = referencedAssemblies; AddSourceDependency(_virtualPath); // Open a TextReader for the virtualPath we're parsing using (_reader = _buildProvider.OpenReaderInternal()) { ParseReader(); } } internal CompilerType CompilerType { get { return _compilerType; } } internal ICollection AssemblyDependencies { get { return _linkedAssemblies; } } private StringSet _sourceDependencies; internal ICollection SourceDependencies { get { return _sourceDependencies; } } internal CodeCompileUnit GetCodeModel() { // Do we have something to compile? if (_sourceString == null) return null; CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(_sourceString); // Put in some context so that the file can be debugged. snippetCompileUnit.LinePragma = BaseCodeDomTreeGenerator.CreateCodeLinePragmaHelper( _virtualPath.VirtualPathString, _lineNumber); return snippetCompileUnit; } internal IDictionary GetLinePragmasTable() { LinePragmaCodeInfo codeInfo = new LinePragmaCodeInfo(); codeInfo._startLine = _lineNumber; codeInfo._startColumn = _startColumn; codeInfo._startGeneratedColumn = 1; codeInfo._codeLength = -1; codeInfo._isCodeNugget = false; IDictionary linePragmasTable = new Hashtable(); linePragmasTable[_lineNumber] = codeInfo; return linePragmasTable; } internal bool HasInlineCode { get { return (_sourceString != null); } } internal Type GetTypeToCache(Assembly builtAssembly) { Type t = null; // First, try to get the type from the assembly that has been built (if any) if (builtAssembly != null) t = builtAssembly.GetType(_typeName); // If not, try to get it from other assemblies if (t == null) t = GetType(_typeName); // Make sure the type derives from what we expect try { ValidateBaseType(t); } catch (Exception e) { throw new HttpParseException(e.Message, e, _virtualPath, _sourceString, _lineNumber); } return t; } internal virtual void ValidateBaseType(Type t) { // No restriction on the base type by default } /* * Parse the contents of the TextReader */ private void ParseReader() { string s = _reader.ReadToEnd(); try { ParseString(s); } catch (Exception e) { throw new HttpParseException(e.Message, e, _virtualPath, s, _lineNumber); } } /* * Parse the contents of the string */ private void ParseString(string text) { int textPos = 0; Match match; _lineNumber = 1; // First, parse all the <%@ ... %> directives for (;;) { match = directiveRegex.Match(text, textPos); // Done with the directives? if (!match.Success) break; _lineNumber += Util.LineCount(text, textPos, match.Index); textPos = match.Index; // Get all the directives into a bag IDictionary directive = CollectionsUtil.CreateCaseInsensitiveSortedList(); string directiveName = ProcessAttributes(match, directive); ProcessDirective(directiveName, directive); _lineNumber += Util.LineCount(text, textPos, match.Index + match.Length); textPos = match.Index + match.Length; int newlineIndex = text.LastIndexOfAny(s_newlineChars, textPos-1); _startColumn = textPos - newlineIndex; } if (!_fFoundMainDirective && !IgnoreParseErrors) { throw new HttpException( SR.GetString(SR.Missing_directive, DefaultDirectiveName)); } // skip the directive string remainingText = text.Substring(textPos); // If there is something else in the file, it needs to be compiled if (!Util.IsWhiteSpaceString(remainingText)) _sourceString = remainingText; } private string ProcessAttributes(Match match, IDictionary attribs) { string ret = String.Empty; CaptureCollection attrnames = match.Groups["attrname"].Captures; CaptureCollection attrvalues = match.Groups["attrval"].Captures; CaptureCollection equalsign = null; equalsign = match.Groups["equal"].Captures; for (int i = 0; i < attrnames.Count; i++) { string attribName = attrnames[i].ToString(); string attribValue = attrvalues[i].ToString(); // Check if there is an equal sign. bool fHasEqual = (equalsign[i].ToString().Length > 0); if (attribName != null) { // A <%@ %> block can have two formats: // <%@ directive foo=1 bar=hello %> // <%@ foo=1 bar=hello %> // Check if we have the first format if (!fHasEqual && i==0) { ret = attribName; continue; } try { if (attribs != null) attribs.Add(attribName, attribValue); } catch (ArgumentException) { // Ignore the duplicate attributes when called from CBM if (IgnoreParseErrors) continue; throw new HttpException( SR.GetString(SR.Duplicate_attr_in_tag, attribName)); } } } return ret; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected abstract string DefaultDirectiveName { get; } private static void ProcessCompilationParams(IDictionary directive, CompilerParameters compilParams) { bool fDebug = false; if (Util.GetAndRemoveBooleanAttribute(directive, "debug", ref fDebug)) compilParams.IncludeDebugInformation = fDebug; if (compilParams.IncludeDebugInformation && !HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) { throw new HttpException(SR.GetString(SR.Insufficient_trust_for_attribute, "debug")); } int warningLevel=0; if (Util.GetAndRemoveNonNegativeIntegerAttribute(directive, "warninglevel", ref warningLevel)) { compilParams.WarningLevel = warningLevel; if (warningLevel > 0) compilParams.TreatWarningsAsErrors = true; } string compilerOptions = Util.GetAndRemoveNonEmptyAttribute( directive, "compileroptions"); if (compilerOptions != null) { CompilationUtil.CheckCompilerOptionsAllowed(compilerOptions, false /*config*/, null, 0); compilParams.CompilerOptions = compilerOptions; } } /* * Process a <%@ %> block */ internal virtual void ProcessDirective(string directiveName, IDictionary directive) { // Empty means default if (directiveName.Length == 0) directiveName = DefaultDirectiveName; // Check for the main directive if (IsMainDirective(directiveName)) { // Make sure the main directive was not already specified if (_fFoundMainDirective && !IgnoreParseErrors) { throw new HttpException( SR.GetString(SR.Only_one_directive_allowed, DefaultDirectiveName)); } _fFoundMainDirective = true; // Since description is a no op, just remove it if it's there directive.Remove("description"); // Similarily, ignore 'codebehind' attribute (ASURT 4591) directive.Remove("codebehind"); string language = Util.GetAndRemoveNonEmptyAttribute(directive, "language"); // Get the compiler for the specified language (if any) if (language != null) { _compilerType = _buildProvider.GetDefaultCompilerTypeForLanguageInternal(language); } else { // Get a default from config _compilerType = _buildProvider.GetDefaultCompilerTypeInternal(); } _typeName = Util.GetAndRemoveRequiredAttribute(directive, "class"); if (_compilerType.CompilerParameters != null) ProcessCompilationParams(directive, _compilerType.CompilerParameters); } else if (StringUtil.EqualsIgnoreCase(directiveName, "assembly")) { // Assembly directive // Remove the attributes as we get them from the dictionary string assemblyName = Util.GetAndRemoveNonEmptyAttribute(directive, "name"); VirtualPath src = Util.GetAndRemoveVirtualPathAttribute(directive, "src"); if (assemblyName != null && src != null && !IgnoreParseErrors) { throw new HttpException( SR.GetString(SR.Attributes_mutually_exclusive, "Name", "Src")); } if (assemblyName != null) { AddAssemblyDependency(assemblyName); } // Is it a source file that needs to be compiled on the fly else if (src != null) { ImportSourceFile(src); } else if (!IgnoreParseErrors) { throw new HttpException(SR.GetString(SR.Missing_attr, "name")); } } else if (!IgnoreParseErrors) { throw new HttpException( SR.GetString(SR.Unknown_directive, directiveName)); } // If there are some attributes left, fail Util.CheckUnknownDirectiveAttributes(directiveName, directive); } internal virtual bool IsMainDirective(string directiveName) { return (string.Compare(directiveName, DefaultDirectiveName, StringComparison.OrdinalIgnoreCase) == 0); } /* * Compile a source file into an assembly, and import it */ private void ImportSourceFile(VirtualPath virtualPath) { // Get a full path to the source file VirtualPath baseVirtualDir = _virtualPath.Parent; VirtualPath fullVirtualPath = baseVirtualDir.Combine(virtualPath); // Add the source file to the list of files we depend on AddSourceDependency(fullVirtualPath); // CompilationUtil.GetCompilerInfoFromVirtualPath(fullVirtualPath); // Compile it into an assembly BuildResultCompiledAssembly result = (BuildResultCompiledAssembly) BuildManager.GetVPathBuildResult( fullVirtualPath); Assembly a = result.ResultAssembly; // Add a dependency to the assembly AddAssemblyDependency(a); } /* * Add a file as a dependency for the DLL we're building */ internal void AddSourceDependency(VirtualPath fileName) { if (_sourceDependencies == null) _sourceDependencies = new CaseInsensitiveStringSet(); _sourceDependencies.Add(fileName.VirtualPathString); } private void AddAssemblyDependency(string assemblyName) { // Load and keep track of the assembly Assembly a = Assembly.Load(assemblyName); AddAssemblyDependency(a); } private void AddAssemblyDependency(Assembly assembly) { if (_linkedAssemblies == null) _linkedAssemblies = new AssemblySet(); _linkedAssemblies.Add(assembly); } /* * Look for a type by name in the assemblies available to this page */ private Type GetType(string typeName) { Type t; // If it contains an assembly name, just call Type.GetType (ASURT 53589) if (Util.TypeNameContainsAssembly(typeName)) { try { t = Type.GetType(typeName, true); } catch (Exception e) { throw new HttpParseException(null, e, _virtualPath, _sourceString, _lineNumber); } return t; } t = Util.GetTypeFromAssemblies(_referencedAssemblies, typeName, false /*ignoreCase*/); if (t != null) return t; t = Util.GetTypeFromAssemblies(_linkedAssemblies, typeName, false /*ignoreCase*/); if (t != null) return t; throw new HttpParseException( SR.GetString(SR.Could_not_create_type, typeName), null, _virtualPath, _sourceString, _lineNumber); } /// <internalonly/> ICollection IAssemblyDependencyParser.AssemblyDependencies { get { return AssemblyDependencies; } } } /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal class WebHandlerParser: SimpleWebHandlerParser { internal WebHandlerParser(string virtualPath) : base(null /*context*/, virtualPath, null /*physicalPath*/) {} /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override string DefaultDirectiveName { get { return "webhandler"; } } internal override void ValidateBaseType(Type t) { // Make sure the type has the correct base class Util.CheckAssignableType(typeof(IHttpHandler), t); } } /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class WebServiceParser: SimpleWebHandlerParser { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> // Only allowed in full trust (ASURT 123890) [SecurityPermission(SecurityAction.Demand, Unrestricted=true)] public static Type GetCompiledType(string inputFile, HttpContext context) { // NOTE: the inputFile parameter should be named virtualPath, but cannot be changed // as it would be a minor breaking change! (VSWhidbey 80997). BuildResultCompiledType result = (BuildResultCompiledType) BuildManager.GetVPathBuildResult( context, VirtualPath.Create(inputFile)); return result.ResultType; } internal WebServiceParser(string virtualPath) : base(null /*context*/, virtualPath, null /*physicalPath*/) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override string DefaultDirectiveName { get { return "webservice"; } } } }
/* * Copyright 2021 Google LLC All Rights Reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/usage.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/usage.proto</summary> public static partial class UsageReflection { #region Descriptor /// <summary>File descriptor for google/api/usage.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static UsageReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZnb29nbGUvYXBpL3VzYWdlLnByb3RvEgpnb29nbGUuYXBpImoKBVVzYWdl", "EhQKDHJlcXVpcmVtZW50cxgBIAMoCRIkCgVydWxlcxgGIAMoCzIVLmdvb2ds", "ZS5hcGkuVXNhZ2VSdWxlEiUKHXByb2R1Y2VyX25vdGlmaWNhdGlvbl9jaGFu", "bmVsGAcgASgJIl0KCVVzYWdlUnVsZRIQCghzZWxlY3RvchgBIAEoCRIgChhh", "bGxvd191bnJlZ2lzdGVyZWRfY2FsbHMYAiABKAgSHAoUc2tpcF9zZXJ2aWNl", "X2NvbnRyb2wYAyABKAhCbAoOY29tLmdvb2dsZS5hcGlCClVzYWdlUHJvdG9Q", "AVpFZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkv", "c2VydmljZWNvbmZpZztzZXJ2aWNlY29uZmlnogIER0FQSWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Usage), global::Google.Api.Usage.Parser, new[]{ "Requirements", "Rules", "ProducerNotificationChannel" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.UsageRule), global::Google.Api.UsageRule.Parser, new[]{ "Selector", "AllowUnregisteredCalls", "SkipServiceControl" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// Configuration controlling usage of a service. /// </summary> public sealed partial class Usage : pb::IMessage<Usage> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Usage> _parser = new pb::MessageParser<Usage>(() => new Usage()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Usage> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.UsageReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Usage() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Usage(Usage other) : this() { requirements_ = other.requirements_.Clone(); rules_ = other.rules_.Clone(); producerNotificationChannel_ = other.producerNotificationChannel_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Usage Clone() { return new Usage(this); } /// <summary>Field number for the "requirements" field.</summary> public const int RequirementsFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_requirements_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> requirements_ = new pbc::RepeatedField<string>(); /// <summary> /// Requirements that must be satisfied before a consumer project can use the /// service. Each requirement is of the form &lt;service.name>/&lt;requirement-id>; /// for example 'serviceusage.googleapis.com/billing-enabled'. /// /// For Google APIs, a Terms of Service requirement must be included here. /// Google Cloud APIs must include "serviceusage.googleapis.com/tos/cloud". /// Other Google APIs should include /// "serviceusage.googleapis.com/tos/universal". Additional ToS can be /// included based on the business needs. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Requirements { get { return requirements_; } } /// <summary>Field number for the "rules" field.</summary> public const int RulesFieldNumber = 6; private static readonly pb::FieldCodec<global::Google.Api.UsageRule> _repeated_rules_codec = pb::FieldCodec.ForMessage(50, global::Google.Api.UsageRule.Parser); private readonly pbc::RepeatedField<global::Google.Api.UsageRule> rules_ = new pbc::RepeatedField<global::Google.Api.UsageRule>(); /// <summary> /// A list of usage rules that apply to individual API methods. /// /// **NOTE:** All service configuration rules follow "last one wins" order. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.UsageRule> Rules { get { return rules_; } } /// <summary>Field number for the "producer_notification_channel" field.</summary> public const int ProducerNotificationChannelFieldNumber = 7; private string producerNotificationChannel_ = ""; /// <summary> /// The full resource name of a channel used for sending notifications to the /// service producer. /// /// Google Service Management currently only supports /// [Google Cloud Pub/Sub](https://cloud.google.com/pubsub) as a notification /// channel. To use Google Cloud Pub/Sub as the channel, this must be the name /// of a Cloud Pub/Sub topic that uses the Cloud Pub/Sub topic name format /// documented in https://cloud.google.com/pubsub/docs/overview. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ProducerNotificationChannel { get { return producerNotificationChannel_; } set { producerNotificationChannel_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Usage); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Usage other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!requirements_.Equals(other.requirements_)) return false; if(!rules_.Equals(other.rules_)) return false; if (ProducerNotificationChannel != other.ProducerNotificationChannel) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= requirements_.GetHashCode(); hash ^= rules_.GetHashCode(); if (ProducerNotificationChannel.Length != 0) hash ^= ProducerNotificationChannel.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else requirements_.WriteTo(output, _repeated_requirements_codec); rules_.WriteTo(output, _repeated_rules_codec); if (ProducerNotificationChannel.Length != 0) { output.WriteRawTag(58); output.WriteString(ProducerNotificationChannel); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { requirements_.WriteTo(ref output, _repeated_requirements_codec); rules_.WriteTo(ref output, _repeated_rules_codec); if (ProducerNotificationChannel.Length != 0) { output.WriteRawTag(58); output.WriteString(ProducerNotificationChannel); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += requirements_.CalculateSize(_repeated_requirements_codec); size += rules_.CalculateSize(_repeated_rules_codec); if (ProducerNotificationChannel.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ProducerNotificationChannel); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Usage other) { if (other == null) { return; } requirements_.Add(other.requirements_); rules_.Add(other.rules_); if (other.ProducerNotificationChannel.Length != 0) { ProducerNotificationChannel = other.ProducerNotificationChannel; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { requirements_.AddEntriesFrom(input, _repeated_requirements_codec); break; } case 50: { rules_.AddEntriesFrom(input, _repeated_rules_codec); break; } case 58: { ProducerNotificationChannel = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { requirements_.AddEntriesFrom(ref input, _repeated_requirements_codec); break; } case 50: { rules_.AddEntriesFrom(ref input, _repeated_rules_codec); break; } case 58: { ProducerNotificationChannel = input.ReadString(); break; } } } } #endif } /// <summary> /// Usage configuration rules for the service. /// /// NOTE: Under development. /// /// Use this rule to configure unregistered calls for the service. Unregistered /// calls are calls that do not contain consumer project identity. /// (Example: calls that do not contain an API key). /// By default, API methods do not allow unregistered calls, and each method call /// must be identified by a consumer project identity. Use this rule to /// allow/disallow unregistered calls. /// /// Example of an API that wants to allow unregistered calls for entire service. /// /// usage: /// rules: /// - selector: "*" /// allow_unregistered_calls: true /// /// Example of a method that wants to allow unregistered calls. /// /// usage: /// rules: /// - selector: "google.example.library.v1.LibraryService.CreateBook" /// allow_unregistered_calls: true /// </summary> public sealed partial class UsageRule : pb::IMessage<UsageRule> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<UsageRule> _parser = new pb::MessageParser<UsageRule>(() => new UsageRule()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<UsageRule> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.UsageReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UsageRule() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UsageRule(UsageRule other) : this() { selector_ = other.selector_; allowUnregisteredCalls_ = other.allowUnregisteredCalls_; skipServiceControl_ = other.skipServiceControl_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public UsageRule Clone() { return new UsageRule(this); } /// <summary>Field number for the "selector" field.</summary> public const int SelectorFieldNumber = 1; private string selector_ = ""; /// <summary> /// Selects the methods to which this rule applies. Use '*' to indicate all /// methods in all APIs. /// /// Refer to [selector][google.api.DocumentationRule.selector] for syntax details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Selector { get { return selector_; } set { selector_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "allow_unregistered_calls" field.</summary> public const int AllowUnregisteredCallsFieldNumber = 2; private bool allowUnregisteredCalls_; /// <summary> /// If true, the selected method allows unregistered calls, e.g. calls /// that don't identify any user or application. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool AllowUnregisteredCalls { get { return allowUnregisteredCalls_; } set { allowUnregisteredCalls_ = value; } } /// <summary>Field number for the "skip_service_control" field.</summary> public const int SkipServiceControlFieldNumber = 3; private bool skipServiceControl_; /// <summary> /// If true, the selected method should skip service control and the control /// plane features, such as quota and billing, will not be available. /// This flag is used by Google Cloud Endpoints to bypass checks for internal /// methods, such as service health check methods. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool SkipServiceControl { get { return skipServiceControl_; } set { skipServiceControl_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as UsageRule); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(UsageRule other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Selector != other.Selector) return false; if (AllowUnregisteredCalls != other.AllowUnregisteredCalls) return false; if (SkipServiceControl != other.SkipServiceControl) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Selector.Length != 0) hash ^= Selector.GetHashCode(); if (AllowUnregisteredCalls != false) hash ^= AllowUnregisteredCalls.GetHashCode(); if (SkipServiceControl != false) hash ^= SkipServiceControl.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Selector.Length != 0) { output.WriteRawTag(10); output.WriteString(Selector); } if (AllowUnregisteredCalls != false) { output.WriteRawTag(16); output.WriteBool(AllowUnregisteredCalls); } if (SkipServiceControl != false) { output.WriteRawTag(24); output.WriteBool(SkipServiceControl); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Selector.Length != 0) { output.WriteRawTag(10); output.WriteString(Selector); } if (AllowUnregisteredCalls != false) { output.WriteRawTag(16); output.WriteBool(AllowUnregisteredCalls); } if (SkipServiceControl != false) { output.WriteRawTag(24); output.WriteBool(SkipServiceControl); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Selector.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Selector); } if (AllowUnregisteredCalls != false) { size += 1 + 1; } if (SkipServiceControl != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(UsageRule other) { if (other == null) { return; } if (other.Selector.Length != 0) { Selector = other.Selector; } if (other.AllowUnregisteredCalls != false) { AllowUnregisteredCalls = other.AllowUnregisteredCalls; } if (other.SkipServiceControl != false) { SkipServiceControl = other.SkipServiceControl; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Selector = input.ReadString(); break; } case 16: { AllowUnregisteredCalls = input.ReadBool(); break; } case 24: { SkipServiceControl = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Selector = input.ReadString(); break; } case 16: { AllowUnregisteredCalls = input.ReadBool(); break; } case 24: { SkipServiceControl = input.ReadBool(); break; } } } } #endif } #endregion } #endregion Designer generated code
// 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; using System.Linq; using System.Text.Json; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ToolPackage; using Microsoft.DotNet.Tools.Tool.Install; using Microsoft.Extensions.EnvironmentAbstractions; using NuGet.Versioning; namespace Microsoft.DotNet.Tools.Tests.ComponentMocks { internal class ProjectRestorerMock : IProjectRestorer { public const string FakeEntrypointName = "SimulatorEntryPoint.dll"; public const string DefaultToolCommandName = "SimulatorCommand"; public const string DefaultPackageName = "global.tool.console.demo"; public const string DefaultPackageVersion = "1.0.4"; public const string FakeCommandSettingsFileName = "FakeDotnetToolSettings.json"; private readonly IFileSystem _fileSystem; private readonly IReporter _reporter; private readonly List<MockFeed> _feeds; public ProjectRestorerMock( IFileSystem fileSystem, IReporter reporter = null, List<MockFeed> feeds = null) { _fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); _reporter = reporter; if (feeds == null) { _feeds = new List<MockFeed>(); _feeds.Add(new MockFeed { Type = MockFeedType.FeedFromGlobalNugetConfig, Packages = new List<MockFeedPackage> { new MockFeedPackage { PackageId = DefaultPackageName, Version = DefaultPackageVersion, ToolCommandName = DefaultToolCommandName, } } }); } else { _feeds = feeds; } } public void Restore(FilePath project, PackageLocation packageLocation, string verbosity = null) { string packageId; VersionRange versionRange; string targetFramework; DirectoryPath assetJsonOutput; try { // The mock installer wrote a mock project file containing id;version;framework;stageDirectory var contents = _fileSystem.File.ReadAllText(project.Value); var tokens = contents.Split(';'); if (tokens.Length != 4) { throw new ToolPackageException(LocalizableStrings.ToolInstallationRestoreFailed); } packageId = tokens[0]; versionRange = VersionRange.Parse(tokens[1]); targetFramework = tokens[2]; assetJsonOutput = new DirectoryPath(tokens[3]); } catch (IOException) { throw new ToolPackageException(LocalizableStrings.ToolInstallationRestoreFailed); } if (string.IsNullOrEmpty(packageId)) { throw new ToolPackageException(LocalizableStrings.ToolInstallationRestoreFailed); } var feedPackage = GetPackage( packageId, versionRange, packageLocation.NugetConfig, packageLocation.RootConfigDirectory); var packageVersion = feedPackage.Version; targetFramework = string.IsNullOrEmpty(targetFramework) ? "targetFramework" : targetFramework; var fakeExecutableSubDirectory = Path.Combine( packageId.ToLowerInvariant(), packageVersion.ToLowerInvariant(), "tools", targetFramework, Constants.AnyRid); var fakeExecutablePath = Path.Combine(fakeExecutableSubDirectory, FakeEntrypointName); _fileSystem.Directory.CreateDirectory(Path.Combine(assetJsonOutput.Value, fakeExecutableSubDirectory)); _fileSystem.File.CreateEmptyFile(Path.Combine(assetJsonOutput.Value, fakeExecutablePath)); _fileSystem.File.WriteAllText( assetJsonOutput.WithFile("project.assets.json").Value, fakeExecutablePath); _fileSystem.File.WriteAllText( assetJsonOutput.WithFile(FakeCommandSettingsFileName).Value, JsonSerializer.Serialize(new {Name = feedPackage.ToolCommandName})); } public MockFeedPackage GetPackage( string packageId, VersionRange versionRange, FilePath? nugetConfig = null, DirectoryPath? rootConfigDirectory = null) { var allPackages = _feeds .Where(feed => { if (nugetConfig == null) { return SimulateNugetSearchNugetConfigAndMatch( rootConfigDirectory, feed); } else { return ExcludeOtherFeeds(nugetConfig.Value, feed); } }) .SelectMany(f => f.Packages) .Where(f => f.PackageId == packageId) .ToList(); var bestVersion = versionRange.FindBestMatch(allPackages.Select(p => NuGetVersion.Parse(p.Version))); var package = allPackages.FirstOrDefault(p => NuGetVersion.Parse(p.Version).Equals(bestVersion)); if (package == null) { _reporter?.WriteLine($"Error: failed to restore package {packageId}."); throw new ToolPackageException(LocalizableStrings.ToolInstallationRestoreFailed); } return package; } /// <summary> /// Simulate NuGet search nuget config from parent directories. /// Assume all nuget.config has Clear /// And then filter against mock feed /// </summary> private bool SimulateNugetSearchNugetConfigAndMatch( DirectoryPath? rootConfigDirectory, MockFeed feed) { if (rootConfigDirectory != null) { var probedNugetConfig = EnumerateDefaultAllPossibleNuGetConfig(rootConfigDirectory.Value) .FirstOrDefault(possibleNugetConfig => _fileSystem.File.Exists(possibleNugetConfig.Value)); if (!Equals(probedNugetConfig, default(FilePath))) { return (feed.Type == MockFeedType.FeedFromLookUpNugetConfig) || (feed.Type == MockFeedType.ImplicitAdditionalFeed) || (feed.Type == MockFeedType.FeedFromLookUpNugetConfig && feed.Uri == probedNugetConfig.Value); } } return feed.Type != MockFeedType.ExplicitNugetConfig && feed.Type != MockFeedType.FeedFromLookUpNugetConfig; } private static IEnumerable<FilePath> EnumerateDefaultAllPossibleNuGetConfig(DirectoryPath probStart) { DirectoryPath? currentSearchDirectory = probStart; while (currentSearchDirectory.HasValue) { var tryNugetConfig = currentSearchDirectory.Value.WithFile("nuget.config"); yield return tryNugetConfig; currentSearchDirectory = currentSearchDirectory.Value.GetParentPathNullable(); } } private static bool ExcludeOtherFeeds(FilePath nugetConfig, MockFeed f) { return f.Type == MockFeedType.ImplicitAdditionalFeed || (f.Type == MockFeedType.ExplicitNugetConfig && f.Uri == nugetConfig.Value); } } }
// // Application.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using Mono.Unix; using Hyena; using Banshee.Library; using Banshee.Playlist; using Banshee.SmartPlaylist; using Banshee.Sources; using Banshee.Base; namespace Banshee.ServiceStack { public delegate bool ShutdownRequestHandler (); public delegate bool TimeoutHandler (); public delegate bool IdleHandler (); public delegate bool IdleTimeoutRemoveHandler (uint id); public delegate uint TimeoutImplementationHandler (uint milliseconds, TimeoutHandler handler); public delegate uint IdleImplementationHandler (IdleHandler handler); public delegate bool IdleTimeoutRemoveImplementationHandler (uint id); public static class Application { public static event ShutdownRequestHandler ShutdownRequested; public static event Action<Client> ClientAdded; private static event Action<Client> client_started; public static event Action<Client> ClientStarted { add { lock (running_clients) { foreach (Client client in running_clients) { if (client.IsStarted) { OnClientStarted (client); } } } client_started += value; } remove { client_started -= value; } } private static Stack<Client> running_clients = new Stack<Client> (); private static bool shutting_down; public static void Initialize () { ServiceManager.DefaultInitialize (); } #if WIN32 [DllImport("msvcrt.dll") /* willfully unmapped */] public static extern int _putenv (string varName); #endif public static void Run () { Banshee.Base.PlatformHacks.TrapMonoJitSegv (); #if WIN32 // There are two sets of environement variables we need to impact with our LANG. // refer to : http://article.gmane.org/gmane.comp.gnu.mingw.user/8272 CultureInfo current_ci = CultureInfo.CurrentUICulture; string env = String.Concat ("LANG=", current_ci.TwoLetterISOLanguageName); Environment.SetEnvironmentVariable ("LANG", current_ci.TwoLetterISOLanguageName); _putenv (env); #endif Catalog.Init (Application.InternalName, System.IO.Path.Combine ( Hyena.Paths.InstalledApplicationDataRoot, "locale")); ApplicationInstance.Create (); ServiceManager.Run (); ServiceManager.SourceManager.AddSource (new MusicLibrarySource (), true); ServiceManager.SourceManager.AddSource (new VideoLibrarySource (), false); ServiceManager.SourceManager.LoadExtensionSources (); Banshee.Base.PlatformHacks.RestoreMonoJitSegv (); } public static bool ShuttingDown { get { return shutting_down; } } public static void Shutdown () { shutting_down = true; if (Banshee.Kernel.Scheduler.IsScheduled (typeof (Banshee.Kernel.IInstanceCriticalJob)) || ServiceManager.JobScheduler.HasAnyDataLossJobs || Banshee.Kernel.Scheduler.CurrentJob is Banshee.Kernel.IInstanceCriticalJob) { if (shutdown_prompt_handler != null && !shutdown_prompt_handler ()) { shutting_down = false; return; } } if (OnShutdownRequested ()) { Dispose (); } shutting_down = false; } public static void PushClient (Client client) { lock (running_clients) { running_clients.Push (client); client.Started += OnClientStarted; } Action<Client> handler = ClientAdded; if (handler != null) { handler (client); } } public static Client PopClient () { lock (running_clients) { return running_clients.Pop (); } } public static Client ActiveClient { get { lock (running_clients) { return running_clients.Peek (); } } } private static void OnClientStarted (Client client) { client.Started -= OnClientStarted; Action<Client> handler = client_started; if (handler != null) { handler (client); } } [DllImport ("libglib-2.0-0.dll")] static extern IntPtr g_get_language_names (); public static void DisplayHelp (string page) { DisplayHelp ("banshee", page); } private static void DisplayHelp (string project, string page) { bool shown = false; foreach (var lang in GLib.Marshaller.NullTermPtrToStringArray (g_get_language_names (), false)) { string path = String.Format ("{0}/gnome/help/{1}/{2}", Paths.InstalledApplicationDataRoot, project, lang); if (System.IO.Directory.Exists (path)) { shown = Banshee.Web.Browser.Open (String.Format ("ghelp:/{0}", path), false); break; } } if (!shown) { Banshee.Web.Browser.Open (String.Format ("http://library.gnome.org/users/{0}/{1}/", project, Version)); } } private static bool OnShutdownRequested () { ShutdownRequestHandler handler = ShutdownRequested; if (handler != null) { foreach (ShutdownRequestHandler del in handler.GetInvocationList ()) { if (!del ()) { return false; } } } return true; } public static void Invoke (InvokeHandler handler) { RunIdle (delegate { handler (); return false; }); } public static uint RunIdle (IdleHandler handler) { if (idle_handler == null) { throw new NotImplementedException ("The application client must provide an IdleImplementationHandler"); } return idle_handler (handler); } public static uint RunTimeout (uint milliseconds, TimeoutHandler handler) { if (timeout_handler == null) { throw new NotImplementedException ("The application client must provide a TimeoutImplementationHandler"); } return timeout_handler (milliseconds, handler); } public static bool IdleTimeoutRemove (uint id) { if (idle_timeout_remove_handler == null) { throw new NotImplementedException ("The application client must provide a IdleTimeoutRemoveImplementationHandler"); } return idle_timeout_remove_handler (id); } private static void Dispose () { ServiceManager.JobScheduler.CancelAll (true); ServiceManager.Shutdown (); lock (running_clients) { while (running_clients.Count > 0) { running_clients.Pop ().Dispose (); } } } private static ShutdownRequestHandler shutdown_prompt_handler = null; public static ShutdownRequestHandler ShutdownPromptHandler { get { return shutdown_prompt_handler; } set { shutdown_prompt_handler = value; } } private static TimeoutImplementationHandler timeout_handler = null; public static TimeoutImplementationHandler TimeoutHandler { get { return timeout_handler; } set { timeout_handler = value; } } private static IdleImplementationHandler idle_handler = null; public static IdleImplementationHandler IdleHandler { get { return idle_handler; } set { idle_handler = value; } } private static IdleTimeoutRemoveImplementationHandler idle_timeout_remove_handler = null; public static IdleTimeoutRemoveImplementationHandler IdleTimeoutRemoveHandler { get { return idle_timeout_remove_handler; } set { idle_timeout_remove_handler = value; } } public static string InternalName { get { return "banshee-1"; } } public static string IconName { get { return "media-player-banshee"; } } public static string ApplicationPath { get { #if WIN32 // TODO: Full installation path using registry key. return "Banshee.exe"; #else return "banshee-1"; #endif // WIN32 } } private static string api_version; public static string ApiVersion { get { if (api_version != null) { return api_version; } try { AssemblyName name = Assembly.GetEntryAssembly ().GetName (); api_version = String.Format ("{0}.{1}.{2}", name.Version.Major, name.Version.Minor, name.Version.Build); } catch { api_version = "unknown"; } return api_version; } } private static string version; public static string Version { get { return version ?? (version = GetVersion ("ReleaseVersion")); } } private static string display_version; public static string DisplayVersion { get { return display_version ?? (display_version = GetVersion ("DisplayVersion")); } } private static string build_time; public static string BuildTime { get { return build_time ?? (build_time = GetBuildInfo ("BuildTime")); } } private static string build_host_os; public static string BuildHostOperatingSystem { get { return build_host_os ?? (build_host_os = GetBuildInfo ("HostOperatingSystem")); } } private static string build_host_cpu; public static string BuildHostCpu { get { return build_host_cpu ?? (build_host_cpu = GetBuildInfo ("HostCpu")); } } private static string build_vendor; public static string BuildVendor { get { return build_vendor ?? (build_vendor = GetBuildInfo ("Vendor")); } } private static string build_display_info; public static string BuildDisplayInfo { get { if (build_display_info != null) { return build_display_info; } build_display_info = String.Format ("{0} ({1}, {2}) @ {3}", BuildVendor, BuildHostOperatingSystem, BuildHostCpu, BuildTime); return build_display_info; } } internal static bool IsMSDotNet { get { try { return Type.GetType ("Mono.Runtime") == null; } catch { return true; } } } private static string GetVersion (string versionName) { return GetCustomAssemblyMetadata ("ApplicationVersionAttribute", versionName) ?? Catalog.GetString ("Unknown"); } private static string GetBuildInfo (string buildField) { return GetCustomAssemblyMetadata ("ApplicationBuildInformationAttribute", buildField); } private static string GetCustomAssemblyMetadata (string attrName, string field) { Assembly assembly = Assembly.GetEntryAssembly (); if (assembly == null) { return null; } foreach (Attribute attribute in assembly.GetCustomAttributes (false)) { Type type = attribute.GetType (); PropertyInfo property = type.GetProperty (field); if (type.Name == attrName && property != null && property.PropertyType == typeof (string)) { return (string)property.GetValue (attribute, null); } } return null; } } }
// 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.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; namespace System.Data.SqlClient { abstract internal class SqlInternalConnection : DbConnectionInternal { private readonly SqlConnectionString _connectionOptions; // if connection is not open: null // if connection is open: currently active database internal string CurrentDatabase { get; set; } // if connection is not open yet, CurrentDataSource is null // if connection is open: // * for regular connections, it is set to Data Source value from connection string // * for connections with FailoverPartner, it is set to the FailoverPartner value from connection string if the connection was opened to it. internal string CurrentDataSource { get; set; } internal enum TransactionRequest { Begin, Commit, Rollback, IfRollback, Save }; internal SqlInternalConnection(SqlConnectionString connectionOptions) : base() { Debug.Assert(null != connectionOptions, "null connectionOptions?"); _connectionOptions = connectionOptions; } internal SqlConnection Connection { get { return (SqlConnection)Owner; } } internal SqlConnectionString ConnectionOptions { get { return _connectionOptions; } } abstract internal SqlInternalTransaction CurrentTransaction { get; } // Get the internal transaction that should be hooked to a new outer transaction // during a BeginTransaction API call. In some cases (i.e. connection is going to // be reset), CurrentTransaction should not be hooked up this way. virtual internal SqlInternalTransaction AvailableInternalTransaction { get { return CurrentTransaction; } } internal bool HasLocalTransaction { get { SqlInternalTransaction currentTransaction = CurrentTransaction; bool result = (null != currentTransaction && currentTransaction.IsLocal); return result; } } internal bool HasLocalTransactionFromAPI { get { SqlInternalTransaction currentTransaction = CurrentTransaction; bool result = (null != currentTransaction && currentTransaction.HasParentTransaction); return result; } } abstract internal bool IsLockedForBulkCopy { get; } abstract internal bool IsKatmaiOrNewer { get; } override public DbTransaction BeginTransaction(IsolationLevel iso) { return BeginSqlTransaction(iso, null, false); } virtual internal SqlTransaction BeginSqlTransaction(IsolationLevel iso, string transactionName, bool shouldReconnect) { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Connection.Statistics); ValidateConnectionForExecute(null); if (HasLocalTransactionFromAPI) throw ADP.ParallelTransactionsNotSupported(Connection); if (iso == IsolationLevel.Unspecified) { iso = IsolationLevel.ReadCommitted; // Default to ReadCommitted if unspecified. } SqlTransaction transaction = new SqlTransaction(this, Connection, iso, AvailableInternalTransaction); transaction.InternalTransaction.RestoreBrokenConnection = shouldReconnect; ExecuteTransaction(TransactionRequest.Begin, transactionName, iso, transaction.InternalTransaction); transaction.InternalTransaction.RestoreBrokenConnection = false; return transaction; } finally { SqlStatistics.StopTimer(statistics); } } override public void ChangeDatabase(string database) { if (string.IsNullOrEmpty(database)) { throw ADP.EmptyDatabaseName(); } ValidateConnectionForExecute(null); ChangeDatabaseInternal(database); // do the real work... } abstract protected void ChangeDatabaseInternal(string database); override protected DbReferenceCollection CreateReferenceCollection() { return new SqlReferenceCollection(); } override protected void Deactivate() { try { SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection; if (null != referenceCollection) { referenceCollection.Deactivate(); } // Invoke subclass-specific deactivation logic InternalDeactivate(); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } // if an exception occurred, the inner connection will be // marked as unusable and destroyed upon returning to the // pool DoomThisConnection(); } } abstract internal void DisconnectTransaction(SqlInternalTransaction internalTransaction); override public void Dispose() { base.Dispose(); } abstract internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction); internal SqlDataReader FindLiveReader(SqlCommand command) { SqlDataReader reader = null; SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection; if (null != referenceCollection) { reader = referenceCollection.FindLiveReader(command); } return reader; } internal SqlCommand FindLiveCommand(TdsParserStateObject stateObj) { SqlCommand command = null; SqlReferenceCollection referenceCollection = (SqlReferenceCollection)ReferenceCollection; if (null != referenceCollection) { command = referenceCollection.FindLiveCommand(stateObj); } return command; } virtual protected void InternalDeactivate() { } // If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter // The close action also supports being run asynchronously internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction = null) { if (breakConnection) { DoomThisConnection(); } var connection = Connection; if (null != connection) { connection.OnError(exception, breakConnection, wrapCloseInAction); } else if (exception.Class >= TdsEnums.MIN_ERROR_CLASS) { // It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS // or above is an error, below TdsEnums.MIN_ERROR_CLASS denotes an info message. throw exception; } } abstract internal void ValidateConnectionForExecute(SqlCommand command); } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 11/17/2008 8:41:13 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Drawing; using DotSpatial.Serialization; using GeoAPI.Geometries; namespace DotSpatial.Symbology { public class LabelSymbolizer : Descriptor, ILabelSymbolizer { #region Constructors /// <summary> /// Creates a new instance of TextSymbolizer /// </summary> public LabelSymbolizer() { Angle = 0; UseAngle = false; LabelAngleField = null; UseLabelAngleField = false; BorderVisible = false; BorderColor = Color.Black; BackColor = Color.AntiqueWhite; BackColorEnabled = false; DropShadowColor = Color.FromArgb(20, 0, 0, 0); DropShadowEnabled = false; DropShadowGeographicOffset = new Coordinate(0, 0); DropShadowPixelOffset = new PointF(2F, 2F); FontSize = 10F; FontFamily = "Arial Unicode MS"; FontStyle = FontStyle.Regular; FontColor = Color.Black; HaloColor = Color.White; HaloEnabled = false; ScaleMode = ScaleMode.Symbolic; LabelPlacementMethod = LabelPlacementMethod.Centroid; PartsLabelingMethod = PartLabelingMethod.LabelLargestPart; PreventCollisions = true; PriorityField = "FID"; Orientation = ContentAlignment.MiddleCenter; } #endregion #region Properties /// <summary> /// Gets or sets the multi-line text alignment in the box. I.e., Control the positioning of the text within the rectangular bounds. /// </summary> [Serialize("Alignment")] public StringAlignment Alignment { get; set; } /// <summary> /// Gets or set the angle that the font should be drawn in /// </summary> [Serialize("Angle")] public double Angle { get; set; } /// <summary> /// Gets or sets the background color /// </summary> [Category("General"), Description("Gets or sets the background color of a rectangle around the label"), Serialize("BackColor")] public Color BackColor { get; set; } /// <summary> /// Gets or sets a boolean indicating whether or not a background color should be used /// </summary> [Category("General"), Description("Gets or sets a boolean indicating whether or not a background color should be used"), Serialize("BackColorEnabled")] public bool BackColorEnabled { get; set; } /// <summary> /// Gets or sets the border color /// </summary> [Category("Border"), Description("Gets or sets the border color"), Serialize("BorderColor")] public Color BorderColor { get; set; } /// <summary> /// Gets or sets a boolean indicating whether or not a border should be drawn around the label. /// </summary> [Category("Border"), Description("Gets or sets a boolean indicating whether or not a border should be drawn around the label."), Serialize("BorderVisible")] public bool BorderVisible { get; set; } /// <summary> /// Gets or sets the color of the actual shadow. Use the alpha channel to specify opacity. /// </summary> [Serialize("DropShadowColor")] public Color DropShadowColor { get; set; } /// <summary> /// Gets or sets a boolean that will force a shadow to be drawn if this is true. /// </summary> [Serialize("DropShadowEnabled")] public bool DropShadowEnabled { get; set; } /// <summary> /// Gets or sets an X and Y geographic offset that is only used if ScaleMode is set to Geographic /// </summary> [Serialize("DropShadowGeographicOffset")] public Coordinate DropShadowGeographicOffset { get; set; } /// <summary> /// Gets or sets an X and Y pixel offset that is used if the ScaleMode is set to Symbolic or Simple. /// </summary> [Serialize("DropShadowPixelOffset")] public PointF DropShadowPixelOffset { get; set; } /// <summary> /// Gets or sets format string used to draw float fields. E.g.: /// #.##, 0.000. If empty - then format not used. /// </summary> [Serialize("FloatingFormat")] public string FloatingFormat { get; set; } /// <summary> /// Gets or set the color that the font should be drawn in. /// </summary> [Serialize("FontColor")] public Color FontColor { get; set; } /// <summary> /// Gets or sets the string font family name /// </summary> [Serialize("FontFamily")] public string FontFamily { get; set; } /// <summary> /// Gets or sets the font size /// </summary> [Serialize("FontSize")] public float FontSize { get; set; } /// <summary> /// Gets or sets the font style. /// </summary> [Serialize("FontStyle")] public FontStyle FontStyle { get; set; } /// <summary> /// Gets or sets the color of the halo that surrounds the text. /// </summary> [Serialize("HaloColor")] public Color HaloColor { get; set; } /// <summary> /// Gets or sets a boolean that governs whether or not to draw a halo. /// </summary> [Serialize("HaloEnabled")] public bool HaloEnabled { get; set; } /// <summary> /// Gets or set the field with angle to draw label /// </summary> [Serialize("LabelAngleField")] public string LabelAngleField { get; set; } /// <summary> /// Gets or sets the labeling method /// </summary> [Serialize("LabelMethod")] public LabelPlacementMethod LabelPlacementMethod { get; set; } /// <summary> /// Gets or sets the labeling method for line labels. /// </summary> [Serialize("LineLabelPlacementMethod")] public LineLabelPlacementMethod LineLabelPlacementMethod { get; set; } /// <summary> /// Gets or sets the orientation of line labels. /// </summary> [Serialize("LineOrientation")] public LineOrientation LineOrientation { get; set; } /// <summary> /// Gets or sets the X offset in pixels from the center of each feature. /// </summary> [Serialize("OffsetX")] public float OffsetX { get; set; } /// <summary> /// Gets or sets the Y offset in pixels from the center of each feature. /// </summary> [Serialize("OffsetY")] public float OffsetY { get; set; } /// <summary> /// Gets or sets the orientation relative to the placement point. I.e., Controls the position of the label relative to the feature. /// </summary> [Serialize("Orientation")] public ContentAlignment Orientation { get; set; } /// <summary> /// Gets or sets the way features with multiple parts are labeled. /// </summary> [Serialize("LabelParts")] public PartLabelingMethod PartsLabelingMethod { get; set; } /// <summary> /// Gets or sets a boolean. If true, as high priority labels are placed, they /// take up space and will not allow low priority labels that conflict for the /// space to be placed. /// </summary> [Serialize("PreventCollisions")] public bool PreventCollisions { get; set; } /// <summary> /// Gets or sets a boolean. Normally high values from the field are given /// a higher priority. If this is true, low values are given priority instead. /// </summary> [Serialize("PrioritizeLowValues")] public bool PrioritizeLowValues { get; set; } /// <summary> /// Gets or sets the string field name for the field that controls which labels /// get placed first. If collision detection is on, a higher priority means /// will get placed first. If it is off, higher priority will be labeled /// on top of lower priority. /// </summary> [Serialize("PriorityField")] public string PriorityField { get; set; } /// <summary> /// Gets or sets the scaling behavior for the text /// </summary> [Serialize("ScaleMode")] public ScaleMode ScaleMode { get; set; } /// <summary> /// Gets or set a boolean indicating whether or not <see cref="Angle"/> should be used /// </summary> [Serialize("UseAngle")] public bool UseAngle { get; set; } /// <summary> /// Gets or set a boolean indicating whether or not <see cref="LabelAngleField"/> should be used /// </summary> [Serialize("UseLabelAngleField")] public bool UseLabelAngleField { get; set; } /// <summary> /// Gets or sets a boolean indicating whether or not the LineOrientation gets used. /// </summary> [Serialize("UseLineOrientation")] public bool UseLineOrientation { get; set; } #endregion #region Methods /// <summary> /// Uses the properties defined on this symbolizer to return a font. /// </summary> /// <returns>A new font</returns> public Font GetFont() { return new Font(FontFamily, FontSize, FontStyle); } #endregion } }