context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ---------------------------------------------------------------------------------- // // Copyright Microsoft 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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Tools.Vhd { using System; using System.Collections.Generic; using System.IO; using Tools.Vhd.Model; using Tools.Vhd.Model.Persistence; /// <summary> /// Provides a logical stream over a virtual hard disk (VHD). /// </summary> /// <remarks> /// This stream implementation provides a "view" over a VHD, such that the /// VHD appears to be an ordinary fixed VHD file, regardless of the true physical layout. /// This stream supports any combination of differencing, dynamic disks, and fixed disks. /// </remarks> public class VirtualDiskStream : SparseStream { private long position; private VhdFile vhdFile; private IBlockFactory blockFactory; private IndexRange footerRange; private IndexRange fileDataRange; public VirtualDiskStream(string vhdPath) { this.vhdFile = new VhdFileFactory().Create(vhdPath); this.blockFactory = vhdFile.GetBlockFactory(); footerRange = this.blockFactory.GetFooterRange(); fileDataRange = IndexRange.FromLength(0, this.Length - footerRange.Length); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override void Flush() { } public override sealed long Length { get { return this.footerRange.EndIndex + 1; } } public override long Position { get { return this.position; } set { if (value < 0) throw new ArgumentException(); if (value >= this.Length) throw new EndOfStreamException(); this.position = value; } } /// <summary> /// Gets the extents of the stream that contain data. /// </summary> public override IEnumerable<StreamExtent> Extents { get { for (uint index = 0; index < blockFactory.BlockCount; index++ ) { var block = blockFactory.Create(index); if(!block.Empty) { yield return new StreamExtent { Owner = block.VhdUniqueId, StartOffset = block.LogicalRange.StartIndex, EndOffset = block.LogicalRange.EndIndex, Range = block.LogicalRange }; } } yield return new StreamExtent { Owner = vhdFile.Footer.UniqueId, StartOffset = this.footerRange.StartIndex, EndOffset = this.footerRange.EndIndex, Range = this.footerRange }; } } public DiskType DiskType { get { return this.vhdFile.DiskType; } } public DiskType RootDiskType { get { var diskType = this.vhdFile.DiskType; for(var parent = this.vhdFile.Parent; parent != null; parent = parent.Parent) { diskType = parent.DiskType; } return diskType; } } /// <summary> /// Reads the specified number of bytes from the current position. /// </summary> public override int Read(byte[] buffer, int offset, int count) { if (count <= 0) { return 0; } try { var rangeToRead = IndexRange.FromLength(this.position, count); int writtenCount = 0; if (fileDataRange.Intersection(rangeToRead) == null) { int readCountFromFooter; if (TryReadFromFooter(rangeToRead, buffer, offset, out readCountFromFooter)) { writtenCount += readCountFromFooter; } return writtenCount; } rangeToRead = fileDataRange.Intersection(rangeToRead); var startingBlock = ByteToBlock(rangeToRead.StartIndex); var endingBlock = ByteToBlock(rangeToRead.EndIndex); for(var blockIndex = startingBlock; blockIndex <= endingBlock; blockIndex++) { var currentBlock = blockFactory.Create(blockIndex); var rangeToReadInBlock = currentBlock.LogicalRange.Intersection(rangeToRead); var copyStartIndex = rangeToReadInBlock.StartIndex % blockFactory.GetBlockSize(); Buffer.BlockCopy(currentBlock.Data, (int) copyStartIndex, buffer, offset + writtenCount, (int) rangeToReadInBlock.Length); writtenCount += (int)rangeToReadInBlock.Length; } this.position += writtenCount; return writtenCount; } catch (Exception e) { throw new VhdParsingException("Invalid or Corrupted VHD file", e); } } public bool TryReadFromFooter(IndexRange rangeToRead, byte[] buffer, int offset, out int readCount) { readCount = 0; var rangeToReadFromFooter = this.footerRange.Intersection(rangeToRead); if (rangeToReadFromFooter != null) { var footerData = GenerateFooter(); var copyStartIndex = rangeToReadFromFooter.StartIndex - footerRange.StartIndex; Buffer.BlockCopy(footerData, (int)copyStartIndex, buffer, offset, (int)rangeToReadFromFooter.Length); this.position += (int)rangeToReadFromFooter.Length; readCount = (int)rangeToReadFromFooter.Length; return true; } return false; } private uint ByteToBlock(long position) { uint sectorsPerBlock = (uint) (this.blockFactory.GetBlockSize() / VhdConstants.VHD_SECTOR_LENGTH); return (uint)Math.Floor((position / VhdConstants.VHD_SECTOR_LENGTH) * 1.0m / sectorsPerBlock); } private byte[] GenerateFooter() { var footer = vhdFile.Footer.CreateCopy(); if(vhdFile.Footer.DiskType != DiskType.Fixed) { footer.HeaderOffset = VhdConstants.VHD_NO_DATA_LONG; footer.DiskType = DiskType.Fixed; footer.CreatorApplication = VhdFooterFactory.WindowsAzureCreatorApplicationName; } var serializer = new VhdFooterSerializer(footer); return serializer.ToByteArray(); } public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: this.Position = offset; break; case SeekOrigin.Current: this.Position += offset; break; case SeekOrigin.End: this.Position -= offset; break; default: throw new NotSupportedException(); } return this.Position; } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override void Close() { this.vhdFile.Dispose(); } } }
// Copyright 2016, Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Longrunning { /// <summary> /// Settings for a <see cref="OperationsClient"/>. /// </summary> public sealed partial class OperationsSettings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="OperationsSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="OperationsSettings"/>. /// </returns> public static OperationsSettings GetDefault() => new OperationsSettings(); /// <summary> /// Constructs a new <see cref="OperationsSettings"/> object with default settings. /// </summary> public OperationsSettings() { } private OperationsSettings(OperationsSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetOperationSettings = existing.GetOperationSettings; ListOperationsSettings = existing.ListOperationsSettings; CancelOperationSettings = existing.CancelOperationSettings; DeleteOperationSettings = existing.DeleteOperationSettings; } /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="OperationsClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="OperationsClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="OperationsClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="OperationsClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="OperationsClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="OperationsClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="OperationsClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="OperationsClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 20000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(20000), maxDelay: TimeSpan.FromMilliseconds(20000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>OperationsClient.GetOperation</c> and <c>OperationsClient.GetOperationAsync</c>. /// </summary> /// <remarks> /// The default <c>OperationsClient.GetOperation</c> and /// <c>OperationsClient.GetOperationAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings GetOperationSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>OperationsClient.ListOperations</c> and <c>OperationsClient.ListOperationsAsync</c>. /// </summary> /// <remarks> /// The default <c>OperationsClient.ListOperations</c> and /// <c>OperationsClient.ListOperationsAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings ListOperationsSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>OperationsClient.CancelOperation</c> and <c>OperationsClient.CancelOperationAsync</c>. /// </summary> /// <remarks> /// The default <c>OperationsClient.CancelOperation</c> and /// <c>OperationsClient.CancelOperationAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings CancelOperationSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>OperationsClient.DeleteOperation</c> and <c>OperationsClient.DeleteOperationAsync</c>. /// </summary> /// <remarks> /// The default <c>OperationsClient.DeleteOperation</c> and /// <c>OperationsClient.DeleteOperationAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings DeleteOperationSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="OperationsSettings"/> object.</returns> public OperationsSettings Clone() => new OperationsSettings(this); } /// <summary> /// Operations client wrapper, for convenient use. /// </summary> public abstract partial class OperationsClient { /// <summary> /// The default endpoint for the Operations service, which is a host of "longrunning.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("longrunning.googleapis.com", 443); /// <summary> /// The default Operations scopes. /// </summary> /// <remarks> /// The default Operations scopes are: /// <list type="bullet"> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); /// <summary> /// Path template for a operation_path resource. Parameters: /// <list type="bullet"> /// <item><description>operationPath</description></item> /// </list> /// </summary> public static PathTemplate OperationPathTemplate { get; } = new PathTemplate("operations/{operation_path=**}"); /// <summary> /// Creates a operation_path resource name from its component IDs. /// </summary> /// <param name="operationPathId">The operationPath ID.</param> /// <returns> /// The full operation_path resource name. /// </returns> public static string FormatOperationPathName(string operationPathId) => OperationPathTemplate.Expand(operationPathId); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="OperationsClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="OperationsSettings"/>.</param> /// <returns>The task representing the created <see cref="OperationsClient"/>.</returns> public static async Task<OperationsClient> CreateAsync(ServiceEndpoint endpoint = null, OperationsSettings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="OperationsClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="OperationsSettings"/>.</param> /// <returns>The created <see cref="OperationsClient"/>.</returns> public static OperationsClient Create(ServiceEndpoint endpoint = null, OperationsSettings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="OperationsClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="OperationsSettings"/>.</param> /// <returns>The created <see cref="OperationsClient"/>.</returns> public static OperationsClient Create(Channel channel, OperationsSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); Operations.OperationsClient grpcClient = new Operations.OperationsClient(channel); return new OperationsClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, OperationsSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, OperationsSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, OperationsSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, OperationsSettings)"/> 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 Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC Operations client. /// </summary> public virtual Operations.OperationsClient GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="name"> /// The name of the operation resource. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Operation> GetOperationAsync( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="name"> /// The name of the operation resource. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Operation> GetOperationAsync( string name, CancellationToken cancellationToken) => GetOperationAsync( name, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="name"> /// The name of the operation resource. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Operation GetOperation( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists operations that match the specified filter in the request. If the /// server doesn't support this method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding below allows API services to override the binding /// to use different resource name schemes, such as `users/*/operations`. /// </summary> /// <param name="name"> /// The name of the operation collection. /// </param> /// <param name="filter"> /// The standard list filter. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="Operation"/> resources. /// </returns> public virtual IPagedAsyncEnumerable<ListOperationsResponse, Operation> ListOperationsAsync( string name, string filter, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Lists operations that match the specified filter in the request. If the /// server doesn't support this method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding below allows API services to override the binding /// to use different resource name schemes, such as `users/*/operations`. /// </summary> /// <param name="name"> /// The name of the operation collection. /// </param> /// <param name="filter"> /// The standard list filter. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="Operation"/> resources. /// </returns> public virtual IPagedEnumerable<ListOperationsResponse, Operation> ListOperations( string name, string filter, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be cancelled. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task CancelOperationAsync( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be cancelled. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task CancelOperationAsync( string name, CancellationToken cancellationToken) => CancelOperationAsync( name, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be cancelled. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void CancelOperation( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be deleted. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteOperationAsync( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be deleted. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task DeleteOperationAsync( string name, CancellationToken cancellationToken) => DeleteOperationAsync( name, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be deleted. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual void DeleteOperation( string name, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// Operations client wrapper implementation, for convenient use. /// </summary> public sealed partial class OperationsClientImpl : OperationsClient { private readonly ClientHelper _clientHelper; private readonly ApiCall<GetOperationRequest, Operation> _callGetOperation; private readonly ApiCall<ListOperationsRequest, ListOperationsResponse> _callListOperations; private readonly ApiCall<CancelOperationRequest, Empty> _callCancelOperation; private readonly ApiCall<DeleteOperationRequest, Empty> _callDeleteOperation; /// <summary> /// Constructs a client wrapper for the Operations service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="OperationsSettings"/> used within this client </param> public OperationsClientImpl(Operations.OperationsClient grpcClient, OperationsSettings settings) { this.GrpcClient = grpcClient; OperationsSettings effectiveSettings = settings ?? OperationsSettings.GetDefault(); _clientHelper = new ClientHelper(effectiveSettings); _callGetOperation = _clientHelper.BuildApiCall<GetOperationRequest, Operation>( GrpcClient.GetOperationAsync, GrpcClient.GetOperation, effectiveSettings.GetOperationSettings); _callListOperations = _clientHelper.BuildApiCall<ListOperationsRequest, ListOperationsResponse>( GrpcClient.ListOperationsAsync, GrpcClient.ListOperations, effectiveSettings.ListOperationsSettings); _callCancelOperation = _clientHelper.BuildApiCall<CancelOperationRequest, Empty>( GrpcClient.CancelOperationAsync, GrpcClient.CancelOperation, effectiveSettings.CancelOperationSettings); _callDeleteOperation = _clientHelper.BuildApiCall<DeleteOperationRequest, Empty>( GrpcClient.DeleteOperationAsync, GrpcClient.DeleteOperation, effectiveSettings.DeleteOperationSettings); } /// <summary> /// The underlying gRPC Operations client. /// </summary> public override Operations.OperationsClient GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_GetOperationRequest(ref GetOperationRequest request, ref CallSettings settings); partial void Modify_ListOperationsRequest(ref ListOperationsRequest request, ref CallSettings settings); partial void Modify_CancelOperationRequest(ref CancelOperationRequest request, ref CallSettings settings); partial void Modify_DeleteOperationRequest(ref DeleteOperationRequest request, ref CallSettings settings); /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="name"> /// The name of the operation resource. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<Operation> GetOperationAsync( string name, CallSettings callSettings = null) { GetOperationRequest request = new GetOperationRequest { Name = name, }; Modify_GetOperationRequest(ref request, ref callSettings); return _callGetOperation.Async(request, callSettings); } /// <summary> /// Gets the latest state of a long-running operation. Clients can use this /// method to poll the operation result at intervals as recommended by the API /// service. /// </summary> /// <param name="name"> /// The name of the operation resource. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Operation GetOperation( string name, CallSettings callSettings = null) { GetOperationRequest request = new GetOperationRequest { Name = name, }; Modify_GetOperationRequest(ref request, ref callSettings); return _callGetOperation.Sync(request, callSettings); } /// <summary> /// Lists operations that match the specified filter in the request. If the /// server doesn't support this method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding below allows API services to override the binding /// to use different resource name schemes, such as `users/*/operations`. /// </summary> /// <param name="name"> /// The name of the operation collection. /// </param> /// <param name="filter"> /// The standard list filter. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="Operation"/> resources. /// </returns> public override IPagedAsyncEnumerable<ListOperationsResponse, Operation> ListOperationsAsync( string name, string filter, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { ListOperationsRequest request = new ListOperationsRequest { Name = name, Filter = filter, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }; Modify_ListOperationsRequest(ref request, ref callSettings); return new PagedAsyncEnumerable<ListOperationsRequest, ListOperationsResponse, Operation>(_callListOperations, request, callSettings); } /// <summary> /// Lists operations that match the specified filter in the request. If the /// server doesn't support this method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding below allows API services to override the binding /// to use different resource name schemes, such as `users/*/operations`. /// </summary> /// <param name="name"> /// The name of the operation collection. /// </param> /// <param name="filter"> /// The standard list filter. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="Operation"/> resources. /// </returns> public override IPagedEnumerable<ListOperationsResponse, Operation> ListOperations( string name, string filter, string pageToken = null, int? pageSize = null, CallSettings callSettings = null) { ListOperationsRequest request = new ListOperationsRequest { Name = name, Filter = filter, PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }; Modify_ListOperationsRequest(ref request, ref callSettings); return new PagedEnumerable<ListOperationsRequest, ListOperationsResponse, Operation>(_callListOperations, request, callSettings); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be cancelled. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task CancelOperationAsync( string name, CallSettings callSettings = null) { CancelOperationRequest request = new CancelOperationRequest { Name = name, }; Modify_CancelOperationRequest(ref request, ref callSettings); return _callCancelOperation.Async(request, callSettings); } /// <summary> /// Starts asynchronous cancellation on a long-running operation. The server /// makes a best effort to cancel the operation, but success is not /// guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use /// [Operations.GetOperation][google.longrunning.Operations.GetOperation] or /// other methods to check whether the cancellation succeeded or whether the /// operation completed despite cancellation. On successful cancellation, /// the operation is not deleted; instead, it becomes an operation with /// an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, /// corresponding to `Code.CANCELLED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be cancelled. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override void CancelOperation( string name, CallSettings callSettings = null) { CancelOperationRequest request = new CancelOperationRequest { Name = name, }; Modify_CancelOperationRequest(ref request, ref callSettings); _callCancelOperation.Sync(request, callSettings); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be deleted. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task DeleteOperationAsync( string name, CallSettings callSettings = null) { DeleteOperationRequest request = new DeleteOperationRequest { Name = name, }; Modify_DeleteOperationRequest(ref request, ref callSettings); return _callDeleteOperation.Async(request, callSettings); } /// <summary> /// Deletes a long-running operation. This method indicates that the client is /// no longer interested in the operation result. It does not cancel the /// operation. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. /// </summary> /// <param name="name"> /// The name of the operation resource to be deleted. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override void DeleteOperation( string name, CallSettings callSettings = null) { DeleteOperationRequest request = new DeleteOperationRequest { Name = name, }; Modify_DeleteOperationRequest(ref request, ref callSettings); _callDeleteOperation.Sync(request, callSettings); } } // Partial classes to enable page-streaming public partial class ListOperationsRequest : IPageRequest { } public partial class ListOperationsResponse : IPageResponse<Operation> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public IEnumerator<Operation> GetEnumerator() => Operations.GetEnumerator(); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.Collections; using System.Collections.Generic; namespace Anima2D { [DisallowMultipleComponent] [CanEditMultipleObjects] [CustomEditor(typeof(SpriteMeshInstance))] public class SpriteMeshInstanceEditor : Editor { SpriteMeshInstance m_SpriteMeshInstance; SpriteMeshData m_SpriteMeshData; ReorderableList mBoneList = null; SerializedProperty m_SortingOrder; SerializedProperty m_SortingLayerID; SerializedProperty m_SpriteMeshProperty; SerializedProperty m_ColorProperty; SerializedProperty m_MaterialsProperty; SerializedProperty m_BonesProperty; SerializedProperty m_BoneTransformsProperty; int m_UndoGroup = -1; void OnEnable() { m_SpriteMeshInstance = target as SpriteMeshInstance; m_SortingOrder = serializedObject.FindProperty("m_SortingOrder"); m_SortingLayerID = serializedObject.FindProperty("m_SortingLayerID"); m_SpriteMeshProperty = serializedObject.FindProperty("m_SpriteMesh"); m_ColorProperty = serializedObject.FindProperty("m_Color"); m_MaterialsProperty = serializedObject.FindProperty("m_Materials.Array"); m_BonesProperty = serializedObject.FindProperty("m_Bones.Array"); m_BoneTransformsProperty = serializedObject.FindProperty("m_BoneTransforms.Array"); UpgradeToMaterials(); UpgradeToBoneTransforms(); UpdateSpriteMeshData(); SetupBoneList(); #if UNITY_5_5_OR_NEWER #else EditorUtility.SetSelectedWireframeHidden(m_SpriteMeshInstance.cachedRenderer, !m_SpriteMeshInstance.cachedSkinnedRenderer); #endif } void UpgradeToMaterials() { if(Selection.transforms.Length == 1 && m_MaterialsProperty.arraySize == 0) { serializedObject.Update(); m_MaterialsProperty.InsertArrayElementAtIndex(0); m_MaterialsProperty.GetArrayElementAtIndex(0).objectReferenceValue = SpriteMeshUtils.defaultMaterial; serializedObject.ApplyModifiedProperties(); } } void UpgradeToBoneTransforms() { if(Selection.transforms.Length == 1 && m_BoneTransformsProperty.arraySize == 0 && m_BonesProperty.arraySize > 0) { serializedObject.Update(); m_BoneTransformsProperty.arraySize = m_BonesProperty.arraySize; for(int i = 0; i < m_BonesProperty.arraySize; ++i) { SerializedProperty boneElement = m_BonesProperty.GetArrayElementAtIndex(i); SerializedProperty transformElement = m_BoneTransformsProperty.GetArrayElementAtIndex(i); if(boneElement.objectReferenceValue) { Bone2D bone = boneElement.objectReferenceValue as Bone2D; transformElement.objectReferenceValue = bone.transform; } } m_BonesProperty.arraySize = 0; serializedObject.ApplyModifiedProperties(); } } public void OnDisable() { if(target) { #if UNITY_5_5_OR_NEWER #else EditorUtility.SetSelectedWireframeHidden(m_SpriteMeshInstance.cachedRenderer, false); #endif } } bool HasBindPoses() { bool hasBindPoses = false; if(m_SpriteMeshData && m_SpriteMeshData.bindPoses != null && m_SpriteMeshData.bindPoses.Length > 0) { hasBindPoses = true; } return hasBindPoses; } void SetupBoneList() { if(HasBindPoses() && m_BoneTransformsProperty.arraySize != m_SpriteMeshData.bindPoses.Length) { int oldSize = m_BoneTransformsProperty.arraySize; serializedObject.Update(); m_BoneTransformsProperty.arraySize = m_SpriteMeshData.bindPoses.Length; for(int i = oldSize; i < m_BoneTransformsProperty.arraySize; ++i) { SerializedProperty element = m_BoneTransformsProperty.GetArrayElementAtIndex(i); element.objectReferenceValue = null; } serializedObject.ApplyModifiedProperties(); } mBoneList = new ReorderableList(serializedObject,m_BoneTransformsProperty,!HasBindPoses(),true,!HasBindPoses(),!HasBindPoses()); mBoneList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { SerializedProperty boneProperty = mBoneList.serializedProperty.GetArrayElementAtIndex(index); rect.y += 1.5f; float labelWidth = 0f; if(HasBindPoses() && index < m_SpriteMeshData.bindPoses.Length) { labelWidth = EditorGUIUtility.labelWidth; EditorGUI.LabelField( new Rect(rect.x, rect.y, labelWidth, EditorGUIUtility.singleLineHeight), new GUIContent(m_SpriteMeshData.bindPoses[index].name)); } EditorGUI.BeginChangeCheck(); EditorGUI.PropertyField( new Rect(rect.x + labelWidth, rect.y, rect.width - labelWidth, EditorGUIUtility.singleLineHeight), boneProperty, GUIContent.none); if(EditorGUI.EndChangeCheck()) { Transform l_NewTransform = boneProperty.objectReferenceValue as Transform; if(l_NewTransform && !l_NewTransform.GetComponent<Bone2D>()) { boneProperty.objectReferenceValue = null; } } }; mBoneList.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, "Bones"); }; mBoneList.onSelectCallback = (ReorderableList list) => {}; } public override void OnInspectorGUI() { #if UNITY_5_5_OR_NEWER #else EditorUtility.SetSelectedWireframeHidden(m_SpriteMeshInstance.cachedRenderer, !m_SpriteMeshInstance.cachedSkinnedRenderer); #endif EditorGUI.BeginChangeCheck(); serializedObject.Update(); EditorGUILayout.PropertyField(m_SpriteMeshProperty); serializedObject.ApplyModifiedProperties(); if(EditorGUI.EndChangeCheck()) { UpdateSpriteMeshData(); UpdateRenderers(); SetupBoneList(); } serializedObject.Update(); EditorGUILayout.PropertyField(m_ColorProperty); if(m_MaterialsProperty.arraySize == 0) { m_MaterialsProperty.InsertArrayElementAtIndex(0); } EditorGUILayout.PropertyField(m_MaterialsProperty.GetArrayElementAtIndex(0), new GUIContent("Material"), true, new GUILayoutOption[0]); EditorGUILayout.Space(); EditorGUIExtra.SortingLayerField(new GUIContent("Sorting Layer"), m_SortingLayerID, EditorStyles.popup, EditorStyles.label); EditorGUILayout.PropertyField(m_SortingOrder, new GUIContent("Order in Layer")); EditorGUILayout.Space(); if(!HasBindPoses()) { List<Bone2D> bones = new List<Bone2D>(); EditorGUI.BeginChangeCheck(); Transform root = EditorGUILayout.ObjectField("Set bones",null,typeof(Transform),true) as Transform; if(EditorGUI.EndChangeCheck()) { if(root) { root.GetComponentsInChildren<Bone2D>(bones); } Undo.RegisterCompleteObjectUndo(m_SpriteMeshInstance,"set bones"); m_BoneTransformsProperty.arraySize = bones.Count; for(int i = 0; i < bones.Count; ++i) { m_BoneTransformsProperty.GetArrayElementAtIndex(i).objectReferenceValue = bones[i].transform; } UpdateRenderers(); } } EditorGUI.BeginChangeCheck(); if(mBoneList != null) { mBoneList.DoLayoutList(); } serializedObject.ApplyModifiedProperties(); if(EditorGUI.EndChangeCheck()) { UpdateRenderers(); } if(m_SpriteMeshInstance.spriteMesh) { if(SpriteMeshUtils.HasNullBones(m_SpriteMeshInstance)) { EditorGUILayout.HelpBox("Warning:\nBone list contains null references.", MessageType.Warning); } if(m_SpriteMeshInstance.spriteMesh.sharedMesh.bindposes.Length != m_SpriteMeshInstance.bones.Count) { EditorGUILayout.HelpBox("Warning:\nNumber of SpriteMesh Bind Poses and number of Bones does not match.", MessageType.Warning); } } } void UpdateSpriteMeshData() { m_SpriteMeshData = null; if(m_SpriteMeshProperty != null && m_SpriteMeshProperty.objectReferenceValue) { m_SpriteMeshData = SpriteMeshUtils.LoadSpriteMeshData(m_SpriteMeshProperty.objectReferenceValue as SpriteMesh); } } void UpdateRenderers() { m_UndoGroup = Undo.GetCurrentGroup(); EditorApplication.delayCall += DoUpdateRenderer; } void DoUpdateRenderer() { SpriteMeshUtils.UpdateRenderer(m_SpriteMeshInstance); #if UNITY_5_5_OR_NEWER #else EditorUtility.SetSelectedWireframeHidden(m_SpriteMeshInstance.cachedRenderer, !m_SpriteMeshInstance.cachedSkinnedRenderer); #endif Undo.CollapseUndoOperations(m_UndoGroup); SceneView.RepaintAll(); } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CrystalDecisions.Shared; namespace WebApplication2 { /// <summary> /// Summary description for Main. /// </summary> public partial class MainOrgs : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; protected System.Web.UI.WebControls.Button lblResME; public SqlConnection epsDbConn = new SqlConnection(strDB); private int GetIndexOfCountries(string s) { return (lstCountries.Items.IndexOf(lstCountries.Items.FindByValue(s))); } private int GetIndexOfStates(string s) { return (lstStates.Items.IndexOf(lstStates.Items.FindByValue(s))); } private int GetIndexOfLocs(string s) { return (lstLocs.Items.IndexOf(lstLocs.Items.FindByValue(s))); } /************************************************************************************************************ * I. Page Load and Exit * **********************************************************************************************************/ protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!IsPostBack) { if (Session["CHH"] != null) { btnOK.Visible = true; } loadHome(); } } /*************************************************************************************************** * btnOK: Provides exit to calling form (with btnOK displayed only if accessed from another form) ***************************************************************************************************/ protected void btnOK_Click(object sender, EventArgs e) { if (Session["CHH"] != null) { if ((Session["CHH"].ToString() == "frmMainMgr")||(Session["CHH"].ToString() == "frmStart")) { Response.Redirect(strURL + Session["CHH"].ToString() + ".aspx?"); } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion /******************************************************* * II. Home Page Load * *****************************************************/ private void loadHome() { DataGrid1.Visible = false; DataGrid2.Visible = false; DataGrid3.Visible = false; btnPlan.Visible = true; btnRes.Visible = true; btnHome.Visible = false; btnOK2.Visible = false; lblIntro1.Text = "Welcome to EcoSys<sup>&copy;</sup>." ; lblIntro2.Text = "The buttons above provide you with customized information that" + " geared to help you protect yourself and your household from various types of natural and man-made hazards. Specifically:"; cleanAbout(); } /******************************************************* * Returns to home page * *****************************************************/ protected void btnHome_Click(object sender, EventArgs e) { Response.Redirect(strURL + "frmMainHH.aspx?"); } private void cleanHome() { btnPlan.Visible = false; btnHome.Text = "Cancel"; btnHome.Visible = true; btnOKPlan1.Visible = true; lblIntro3.Visible = false; lblIntro3a.Visible = false; lblIntro4.Visible = false; lblIntro4a.Visible = false; lblIntro5.Visible = false; lblIntro5a.Visible = false; } /******************************************************************************************************************************* * III. btnPlan: Generates Emergency Preparedness Checklist * *****************************************************************************************************************************/ protected void btnPlan_Click(object sender, EventArgs e) { cleanHome();//Erase Home Page content cleanAbout(); btnRes.Visible = false; btnAbout.Visible = false; loadData1();//Display household profiles - step 1 to generate checklist lblIntro1.Text = "Household Emergency Checklist"; lblIntro2.Text = "You will now generate an emergency plan checklist that" + " is customized to your household characteristics and to your concerns. Thus, for example, a household with small children will have" + " different needs compared to a household comprising an adult couple only. Similarly, a household located inland will" + " have somewhat different concerns than one that is located in a coastal area. You will therefore first select" + " the household characterists for which the report is to be customized in Step 1 below. After you have made your" + " selections, click on 'Continue to Step 2'"; DataGrid1.Visible = true; btnOKPlan1.Visible = true; } private void loadData1() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_RetrieveProfilesAll"; cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "ProfilesAll"); Session["ds"] = ds; DataGrid1.DataSource = ds; DataGrid1.DataBind(); refreshGrid1(); } private void refreshGrid1() { foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[3].FindControl("cbxSel")); if (i.Cells[4].Text == "1") { i.BackColor = Color.Black; i.ForeColor = Color.Black; cb.Visible = false; } } } protected void btnOKPlan1_Click(object sender, EventArgs e) { if (btnOKPlan1.Text == "Continue to Step 2") { DataGrid1.Visible = false; btnOKPlan1.Text = "Return to Step 1"; loadData2();//Display risks - step 2 to generate checklist DataGrid2.Visible = true; btnOKPlan2.Visible = true; lblIntro1.Text = "Household Emergency Checklist: Step 2"; lblIntro2.Text = "In Step 2 below, select the types of emergency events for which you wish to make preparations." + " Once you have made your selections, click on 'Generate Report' and wait for the report to be prepared. You may wish to print out the" + " report for easy reference once it is prepared. If you wish to continue to work on this website after you have " + " generated the report, use the browser button to return to this page. Alternatively, you may simply select this web-site" + " address again."; } else { btnOKPlan1.Text = "Continue to Step 2"; DataGrid1.Visible = true; DataGrid2.Visible = false; btnOKPlan2.Visible = false; lblIntro1.Text = "Household Emergency Checklist: Step 1"; lblIntro2.Text = "You will now generate an emergency plan checklist that" + " is customized to your household characteristics and to your concerns. Thus, for example, a household with small children will have" + " different needs compared to a household comprising an adult couple only. Similarly, a household located inland will" + " have somewhat different concerns than one that is located in a coastal area. You will therefore first select" + " the household characterists for which the report is to be customized in Step 1 below. After you have made your" + " selections, click on 'Continue to Step 2'"; } } private void loadData2() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_RetrieveEventsAll"; cmd.Parameters.Add("@HHFlag", SqlDbType.Int); cmd.Parameters["@HHFlag"].Value = "1"; cmd.Connection = this.epsDbConn; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "EventsAll"); Session["ds"] = ds; DataGrid2.DataSource = ds; DataGrid2.DataBind(); refreshGrid2(); } private void refreshGrid2() { foreach (DataGridItem i in DataGrid2.Items) { CheckBox cb = (CheckBox)(i.Cells[3].FindControl("cbxSel0")); if (i.Cells[4].Text == "1") { i.BackColor = Color.Maroon; i.ForeColor = Color.Maroon; cb.Visible = false; } } } /******************************************************* * btnOKPlan2: Generates Emergency Preparedness Checklist * *****************************************************/ protected void btnOKPlan2_Click(object sender, EventArgs e) { prepareReport(); } private void rpts() { Session["cRG"] = "frmMainHH"; Response.Redirect(strURL + "frmReportGen.aspx?"); } private void prepareReport() { ParameterFields myParams = new ParameterFields(); ParameterField myParam = new ParameterField(); myParam.ParameterFieldName = "ProfilesId"; int Check1 = 0; foreach (DataGridItem i in DataGrid1.Items) { CheckBox cb = (CheckBox)(i.Cells[3].FindControl("cbxSel")); if (cb.Checked) { Check1 = 1; ParameterDiscreteValue myDiscreteValue = new ParameterDiscreteValue(); myDiscreteValue.Value = Int32.Parse(i.Cells[0].Text); myParam.CurrentValues.Add(myDiscreteValue); } else { if (i.Cells[4].Text == "1") { ParameterDiscreteValue myDiscreteValue = new ParameterDiscreteValue(); myDiscreteValue.Value = Int32.Parse(i.Cells[0].Text); myParam.CurrentValues.Add(myDiscreteValue); } } } if (Check1 == 0) { lblIntro1.ForeColor = Color.Orange; lblIntro1.Text = "In order to generate a report, you must select at least one household characteristic."; } else { ParameterField myParam1 = new ParameterField(); myParam1.ParameterFieldName = "EventsId"; int Check2 = 0; foreach (DataGridItem j in DataGrid2.Items) { CheckBox cb1 = (CheckBox)(j.Cells[3].FindControl("cbxSel0")); if (cb1.Checked) { Check2 = 1; ParameterDiscreteValue myDiscreteValue1 = new ParameterDiscreteValue(); myDiscreteValue1.Value = Int32.Parse(j.Cells[0].Text); myParam1.CurrentValues.Add(myDiscreteValue1); } else { if (j.Cells[4].Text == "1") { ParameterDiscreteValue myDiscreteValue1 = new ParameterDiscreteValue(); myDiscreteValue1.Value = Int32.Parse(j.Cells[0].Text); myParam1.CurrentValues.Add(myDiscreteValue1); } } } if (Check2 == 0) { lblIntro1.ForeColor = Color.Orange; lblIntro1.Text = "In order to generate a report, you must select at least one emergency event."; } else { myParams.Add(myParam1); myParams.Add(myParam); Session["ReportParameters"] = myParams; Session["ReportName"] = "rptHouseholdPlan.rpt"; rpts(); } } } /******************************************************* * IV. btnRes (Button Emergency Services): displays location, displays services in a given location * *****************************************************/ /******************************************************* * IVa. btnRes (Button Emergency Services): displays locations * *****************************************************/ protected void btnRes_Click(object sender, EventArgs e) { cleanHome(); cleanAbout(); cleanCheck(); btnHome.Visible = true; btnAbout.Visible = false; lblIntro1.Text = "Emergency Services"; lblIntro2.Text = "You will now generate list of " + " emergency services available in your area. You will therefore first identify" + " the area you live in below, then click on 'Show Services'."; btnRes.Visible = false; btnOK2.Visible = true; loadCountries(); loadStates(); loadLocs(); lblCountry.Visible = true; lblState.Visible = true; lblLoc.Visible = true; lstCountries.Visible = true; lstLocs.Visible = true; lstStates.Visible = true; } private void loadCountries() { SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_RetrieveCountries"; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Countries"); lstCountries.DataSource = ds; lstCountries.DataMember = "Countries"; lstCountries.DataTextField = "Name"; lstCountries.DataValueField = "Id"; lstCountries.DataBind(); } protected void lstCountries_SelectedIndexChanged(object sender, EventArgs e) { loadStates(); loadLocs(); if (lstLocs.SelectedItem == null) { btnOK2.Visible = false; lblIntro2.Text = "Sorry. There are no emergency services identified in our database for this country." + "Would you like to help maintain a list of emergency services" + " in this country?" + " If so, please contact me by sending an email to tauheedahmed@hotmail.com."; } else { if (lstStates.SelectedItem != null) { lblIntro2.Text = "You will now generate list of " + " emergency services available in your area. You will therefore first identify" + " the area you live in below, then click on 'Show Services'."; } if (lstLocs.SelectedItem != null) { lblIntro2.Text = "You will now generate list of " + " emergency services available in your area. You will therefore first identify" + " the area you live in below, then click on 'Show Services'."; } } } protected void lstStates_SelectedIndexChanged(object sender, EventArgs e) { loadLocs(); } private void loadStates() { SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@CountriesId", SqlDbType.Int); cmd.Parameters["@CountriesId"].Value = Int32.Parse(lstCountries.SelectedItem.Value); cmd.CommandText = "wms_RetrieveStates"; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "States"); if (ds.Tables["States"].Rows.Count == 0) { lblState.Visible = false; lstStates.Visible = false; lstLocs.Visible = false; lblLoc.Visible = false; } else { lblState.Visible = true; lstStates.Visible = true; lstLocs.Visible = true; lblLoc.Visible = true; } lstStates.DataSource = ds; lstStates.DataMember = "States"; lstStates.DataTextField = "Name"; lstStates.DataValueField = "Id"; lstStates.DataBind(); } private void loadLocs() { SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.StoredProcedure; if (lstStates.SelectedItem != null) { cmd.Parameters.Add("@StatesId", SqlDbType.Int); cmd.Parameters["@StatesId"].Value = Int32.Parse(lstStates.SelectedItem.Value); } else { cmd.Parameters.Add("@CountriesId", SqlDbType.Int); cmd.Parameters["@CountriesId"].Value = Int32.Parse(lstCountries.SelectedItem.Value); } cmd.CommandText = "wms_RetrieveLocs"; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Locations"); if (ds.Tables["Locations"].Rows.Count == 0) { lstLocs.Visible = false; lblLoc.Visible = false; } else { lstLocs.Visible = true; lblLoc.Visible = true; } lstLocs.DataSource = ds; lstLocs.DataMember = "Locations"; lstLocs.DataTextField = "Name"; lstLocs.DataValueField = "Id"; lstLocs.DataBind(); } /******************************************************* * IVb. btnRes (Button Emergency Services): displays services in a given location * *****************************************************/ protected void btnOK2_Click(object sender, EventArgs e) { btnHome.Text = "Home"; SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_RetrieveHHContractSupplies"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@CountriesId", SqlDbType.Int); cmd.Parameters["@CountriesId"].Value = Int32.Parse(lstCountries.SelectedValue); if (lstStates.SelectedItem !=null) { cmd.Parameters.Add("@StatesId", SqlDbType.Int); cmd.Parameters["@StatesId"].Value = Int32.Parse(lstStates.SelectedValue); } if (lstLocs.SelectedItem != null) { cmd.Parameters.Add("@LocsId", SqlDbType.Int); cmd.Parameters["@LocsId"].Value = Int32.Parse(lstLocs.SelectedValue); } DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "HHRes"); if (ds.Tables["HHRes"].Rows.Count == 0) { lblIntro1.Text = "There are no services in the area below that have been identified."; lblIntro2.Text = "Would you like to help maintain contact information for basic fire, security and emergency services" + " in your area?" + " Do you know of other organizations that might be interested in participating in " + " strengthening local community efforts at emergency preparedness?" + " If so, please contact me by sending an email to tauheedahmed@hotmail.com."; } else { Session["ds"] = ds; DataGrid3.DataSource = ds; DataGrid3.DataBind(); btnOK2.Visible = false; lblCountry.Visible = false; lblState.Visible = false; lblLoc.Visible = false; lstCountries.Visible = false; lstLocs.Visible = false; lstStates.Visible = false; lblIntro1.Text = "Emergency Services"; lblIntro2.Text = "Given below is a list of emergency services in your area."; DataGrid3.Visible = true; } } private void cleanAbout() { lblAbout1.Visible = false; lblAbout2.Visible = false; lblAbout3.Visible = false; lblAbout4.Visible = false; } private void cleanCheck() { btnPlan.Visible = false; btnOKPlan1.Visible = false; btnOKPlan2.Visible = false; } protected void btnAbout_Click(object sender, EventArgs e) { lblIntro1.Visible = false; lblIntro2.Visible=false; lblAbout1.Visible=true; lblAbout2.Visible=true; lblAbout3.Visible = true; lblAbout4.Visible = true; bltAbout.Visible = true; cleanHome(); cleanCheck(); btnHome.Visible = true; btnHome.Text = "Home"; btnAbout.Visible = false; btnRes.Visible = false; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Storage { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for StorageAccountsOperations. /// </summary> public static partial class StorageAccountsOperationsExtensions { /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static CheckNameAvailabilityResult CheckNameAvailability(this IStorageAccountsOperations operations, StorageAccountCheckNameAvailabilityParameters accountName) { return operations.CheckNameAvailabilityAsync(accountName).GetAwaiter().GetResult(); } /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CheckNameAvailabilityResult> CheckNameAvailabilityAsync(this IStorageAccountsOperations operations, StorageAccountCheckNameAvailabilityParameters accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> public static StorageAccount Create(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> CreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static void Delete(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { operations.DeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Returns the properties for the specified storage account including but not /// limited to name, account type, location, and account status. The ListKeys /// operation should be used to retrieve storage keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static StorageAccount GetProperties(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { return operations.GetPropertiesAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Returns the properties for the specified storage account including but not /// limited to name, account type, location, and account status. The ListKeys /// operation should be used to retrieve storage keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> GetPropertiesAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPropertiesWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the account type or tags for a storage account. It can also be used /// to add a custom domain (note that custom domains cannot be added via the /// Create operation). Only one custom domain is supported per storage account. /// In order to replace a custom domain, the old value must be cleared before a /// new value may be set. To clear a custom domain, simply update the custom /// domain with empty string. Then call update again with the new cutsom domain /// name. The update API can only be used to update one of tags, accountType, /// or customDomain per call. To update multiple of these properties, call the /// API multiple times with one change per call. This call does not change the /// storage keys for the account. If you want to change storage account keys, /// use the RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one property can be /// changed at a time using this API. /// </param> public static StorageAccount Update(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates the account type or tags for a storage account. It can also be used /// to add a custom domain (note that custom domains cannot be added via the /// Create operation). Only one custom domain is supported per storage account. /// In order to replace a custom domain, the old value must be cleared before a /// new value may be set. To clear a custom domain, simply update the custom /// domain with empty string. Then call update again with the new cutsom domain /// name. The update API can only be used to update one of tags, accountType, /// or customDomain per call. To update multiple of these properties, call the /// API multiple times with one change per call. This call does not change the /// storage keys for the account. If you want to change storage account keys, /// use the RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one property can be /// changed at a time using this API. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> UpdateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> public static StorageAccountKeys ListKeys(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { return operations.ListKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountKeys> ListKeysAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the subscription. Note that /// storage keys are not returned; use the ListKeys operation for this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IEnumerable<StorageAccount> List(this IStorageAccountsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the subscription. Note that /// storage keys are not returned; use the ListKeys operation for this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListAsync(this IStorageAccountsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the given resource group. /// Note that storage keys are not returned; use the ListKeys operation for /// this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> public static IEnumerable<StorageAccount> ListByResourceGroup(this IStorageAccountsOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the given resource group. /// Note that storage keys are not returned; use the ListKeys operation for /// this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListByResourceGroupAsync(this IStorageAccountsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or key2 for the /// default keys /// </param> public static StorageAccountKeys RegenerateKey(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey) { return operations.RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey).GetAwaiter().GetResult(); } /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or key2 for the /// default keys /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountKeys> RegenerateKeyAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, regenerateKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> public static StorageAccount BeginCreate(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.BeginCreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> BeginCreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElasticTranscoder.Model { /// <summary> /// Container for the parameters to the UpdatePipeline operation. /// /// </summary> /// <seealso cref="Amazon.ElasticTranscoder.AmazonElasticTranscoder.UpdatePipeline"/> public class UpdatePipelineRequest : AmazonWebServiceRequest { private string id; private string name; private string inputBucket; private string role; private Notifications notifications; private PipelineOutputConfig contentConfig; private PipelineOutputConfig thumbnailConfig; /// <summary> /// /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Pattern</term> /// <description>^\d{13}-\w{6}$</description> /// </item> /// </list> /// </para> /// </summary> public string Id { get { return this.id; } set { this.id = value; } } /// <summary> /// Sets the Id property /// </summary> /// <param name="id">The value to set for the Id property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdatePipelineRequest WithId(string id) { this.id = id; return this; } // Check to see if Id property is set internal bool IsSetId() { return this.id != null; } /// <summary> /// /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 40</description> /// </item> /// </list> /// </para> /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// Sets the Name property /// </summary> /// <param name="name">The value to set for the Name property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdatePipelineRequest WithName(string name) { this.name = name; return this; } // Check to see if Name property is set internal bool IsSetName() { return this.name != null; } /// <summary> /// /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Pattern</term> /// <description>^(\w|\.|-){1,255}$</description> /// </item> /// </list> /// </para> /// </summary> public string InputBucket { get { return this.inputBucket; } set { this.inputBucket = value; } } /// <summary> /// Sets the InputBucket property /// </summary> /// <param name="inputBucket">The value to set for the InputBucket property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdatePipelineRequest WithInputBucket(string inputBucket) { this.inputBucket = inputBucket; return this; } // Check to see if InputBucket property is set internal bool IsSetInputBucket() { return this.inputBucket != null; } /// <summary> /// /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Pattern</term> /// <description>^arn:aws:iam::\w{12}:role/.+$</description> /// </item> /// </list> /// </para> /// </summary> public string Role { get { return this.role; } set { this.role = value; } } /// <summary> /// Sets the Role property /// </summary> /// <param name="role">The value to set for the Role property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdatePipelineRequest WithRole(string role) { this.role = role; return this; } // Check to see if Role property is set internal bool IsSetRole() { return this.role != null; } /// <summary> /// The Amazon Simple Notification Service (Amazon SNS) topic or topics to notify in order to report job status. <important>To receive /// notifications, you must also subscribe to the new topic in the Amazon SNS console.</important> /// /// </summary> public Notifications Notifications { get { return this.notifications; } set { this.notifications = value; } } /// <summary> /// Sets the Notifications property /// </summary> /// <param name="notifications">The value to set for the Notifications property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdatePipelineRequest WithNotifications(Notifications notifications) { this.notifications = notifications; return this; } // Check to see if Notifications property is set internal bool IsSetNotifications() { return this.notifications != null; } /// <summary> /// /// /// </summary> public PipelineOutputConfig ContentConfig { get { return this.contentConfig; } set { this.contentConfig = value; } } /// <summary> /// Sets the ContentConfig property /// </summary> /// <param name="contentConfig">The value to set for the ContentConfig property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdatePipelineRequest WithContentConfig(PipelineOutputConfig contentConfig) { this.contentConfig = contentConfig; return this; } // Check to see if ContentConfig property is set internal bool IsSetContentConfig() { return this.contentConfig != null; } /// <summary> /// /// /// </summary> public PipelineOutputConfig ThumbnailConfig { get { return this.thumbnailConfig; } set { this.thumbnailConfig = value; } } /// <summary> /// Sets the ThumbnailConfig property /// </summary> /// <param name="thumbnailConfig">The value to set for the ThumbnailConfig property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public UpdatePipelineRequest WithThumbnailConfig(PipelineOutputConfig thumbnailConfig) { this.thumbnailConfig = thumbnailConfig; return this; } // Check to see if ThumbnailConfig property is set internal bool IsSetThumbnailConfig() { return this.thumbnailConfig != null; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; public class Telltale { public int doNotTellTheTruth(int n, int[] a, string[] parties) { //int[] person = new int[n]; //for (int i = 0; i < n; i++) //{ // person[i] = 1 << 0; //} //for (int i = 0; i < a.Length; i++) //{ // person[a[i]] = 1 << 1; //} //int soFar = 0; //for (int i = 0; i < parties.Length; i++) //{ // int t = 0; // string[] p = parties[i].Split(' '); // for (int j = 0; j < p.Length; j++) // { // t = t | person[int.Parse(p[j])]; // } // bool tr = (t & (1 << 1)) != 0; // bool fa = (t & (1 << 2)) != 0; // bool dn = (t & (1 << 0)) != 0; // if (tr && fa) // { // return -1; // } // else if (tr) // { // soFar += 0; // for (int j = 0; j < p.Length; j++) // { // person[int.Parse(p[j])] = (1 << 1); // } // } // else if (fa) // { // soFar += 1; // for (int j = 0; j < p.Length; j++) // { // person[int.Parse(p[j])] = (1 << 2); // } // } // else // { // for (int j = 0; j < p.Length; j++) // { // person[int.Parse(p[j])] = (1 << 1); // } // int aa = foo(person, i+1); // for (int j = 0; j < p.Length; j++) // { // person[int.Parse(p[j])] = (1 << 2); // } // int bb = foo(person, i+1); // if (aa > bb) // { // soFar += aa; // for (int j = 0; j < p.Length; j++) // { // person[int.Parse(p[j])] = (1 << 1); // } // } // else // { // soFar += bb; // for (int j = 0; j < p.Length; j++) // { // person[int.Parse(p[j])] = (1 << 2); // } // } // } //} //return soFar; return 0; } // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof #region Testing code generated by KawigiEdit [STAThread] private static Boolean KawigiEdit_RunTest(int testNum, int p0, int[] p1, string[] p2, Boolean hasAnswer, int p3) { Console.Write("Test " + testNum + ": [" + p0 + "," + "{"); for (int i = 0; p1.Length > i; ++i) { if (i > 0) { Console.Write(","); } Console.Write(p1[i]); } Console.Write("}" + "," + "{"); for (int i = 0; p2.Length > i; ++i) { if (i > 0) { Console.Write(","); } Console.Write("\"" + p2[i] + "\""); } Console.Write("}"); Console.WriteLine("]"); Telltale obj; int answer; obj = new Telltale(); DateTime startTime = DateTime.Now; answer = obj.doNotTellTheTruth(p0, p1, p2); DateTime endTime = DateTime.Now; Boolean res; res = true; Console.WriteLine("Time: " + (endTime - startTime).TotalSeconds + " seconds"); if (hasAnswer) { Console.WriteLine("Desired answer:"); Console.WriteLine("\t" + p3); } Console.WriteLine("Your answer:"); Console.WriteLine("\t" + answer); if (hasAnswer) { res = answer == p3; } if (!res) { Console.WriteLine("DOESN'T MATCH!!!!"); } else if ((endTime - startTime).TotalSeconds >= 2) { Console.WriteLine("FAIL the timeout"); res = false; } else if (hasAnswer) { Console.WriteLine("Match :-)"); } else { Console.WriteLine("OK, but is it right?"); } Console.WriteLine(""); return res; } public static void m1(string[] args) { Boolean all_right; all_right = true; int p0; int[] p1; string[] p2; int p3; // ----- test 0 ----- p0 = 4; p1 = new int[]{}; p2 = new string[]{"1 2","3","2 3 4"}; p3 = 3; all_right = KawigiEdit_RunTest(0, p0, p1, p2, true, p3) && all_right; // ------------------ // ----- test 1 ----- p0 = 4; p1 = new int[]{1}; p2 = new string[]{"1 2 3 4"}; p3 = 0; all_right = KawigiEdit_RunTest(1, p0, p1, p2, true, p3) && all_right; // ------------------ // ----- test 2 ----- p0 = 4; p1 = new int[]{}; p2 = new string[]{"1 2 3 4"}; p3 = 1; all_right = KawigiEdit_RunTest(2, p0, p1, p2, true, p3) && all_right; // ------------------ // ----- test 3 ----- p0 = 4; p1 = new int[]{1}; p2 = new string[]{"1","2","3","4","4 1"}; p3 = 2; all_right = KawigiEdit_RunTest(3, p0, p1, p2, true, p3) && all_right; // ------------------ // ----- test 4 ----- p0 = 10; p1 = new int[]{1,2,3,4}; p2 = new string[]{"1 5","2 6","7","8","7 8","9","10","3 10","4"}; p3 = 4; all_right = KawigiEdit_RunTest(4, p0, p1, p2, true, p3) && all_right; // ------------------ // ----- test 5 ----- p0 = 8; p1 = new int[]{1,2,7}; p2 = new string[]{"3 4","5","5 6","6 8","8"}; p3 = 5; all_right = KawigiEdit_RunTest(5, p0, p1, p2, true, p3) && all_right; // ------------------ // ----- test 6 ----- p0 = 3; p1 = new int[]{3}; p2 = new string[]{"1","2","1 2","1 2 3"}; p3 = 0; all_right = KawigiEdit_RunTest(6, p0, p1, p2, true, p3) && all_right; // ------------------ if (all_right) { Console.WriteLine("You're a stud (at least on the example cases)!"); } else { Console.WriteLine("Some of the test cases had errors."); } } #endregion // END KAWIGIEDIT TESTING } //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
namespace XenAdmin.Dialogs.HealthCheck { partial class HealthCheckSettingsDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HealthCheckSettingsDialog)); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.decentGroupBox2 = new XenAdmin.Controls.DecentGroupBox(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this.frequencyLabel = new System.Windows.Forms.Label(); this.frequencyNumericBox = new System.Windows.Forms.NumericUpDown(); this.weeksLabel = new System.Windows.Forms.Label(); this.dayOfweekLabel = new System.Windows.Forms.Label(); this.timeOfDayLabel = new System.Windows.Forms.Label(); this.timeOfDayComboBox = new System.Windows.Forms.ComboBox(); this.dayOfWeekComboBox = new System.Windows.Forms.ComboBox(); this.decentGroupBox1 = new XenAdmin.Controls.DecentGroupBox(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.authenticationRubricTextBox = new System.Windows.Forms.RichTextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBoxMyCitrixPassword = new System.Windows.Forms.TextBox(); this.textBoxMyCitrixUsername = new System.Windows.Forms.TextBox(); this.existingAuthenticationRadioButton = new System.Windows.Forms.RadioButton(); this.newAuthenticationRadioButton = new System.Windows.Forms.RadioButton(); this.rubricLabel = new System.Windows.Forms.Label(); this.PolicyStatementLinkLabel = new System.Windows.Forms.LinkLabel(); this.m_ctrlError = new XenAdmin.Controls.Common.PasswordFailure(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.enrollmentCheckBox = new System.Windows.Forms.CheckBox(); this.decentGroupBoxXSCredentials = new XenAdmin.Controls.DecentGroupBox(); this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this.errorLabel = new System.Windows.Forms.Label(); this.testCredentialsStatusImage = new System.Windows.Forms.PictureBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.textboxXSPassword = new System.Windows.Forms.TextBox(); this.textboxXSUserName = new System.Windows.Forms.TextBox(); this.currentXsCredentialsRadioButton = new System.Windows.Forms.RadioButton(); this.newXsCredentialsRadioButton = new System.Windows.Forms.RadioButton(); this.testCredentialsButton = new System.Windows.Forms.Button(); this.tableLayoutPanel1.SuspendLayout(); this.decentGroupBox2.SuspendLayout(); this.tableLayoutPanel4.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.frequencyNumericBox)).BeginInit(); this.decentGroupBox1.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.decentGroupBoxXSCredentials.SuspendLayout(); this.tableLayoutPanel3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.testCredentialsStatusImage)).BeginInit(); this.SuspendLayout(); // // okButton // resources.ApplyResources(this.okButton, "okButton"); this.okButton.Name = "okButton"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // resources.ApplyResources(this.cancelButton, "cancelButton"); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Name = "cancelButton"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.decentGroupBox2, 0, 3); this.tableLayoutPanel1.Controls.Add(this.decentGroupBox1, 0, 8); this.tableLayoutPanel1.Controls.Add(this.rubricLabel, 0, 0); this.tableLayoutPanel1.Controls.Add(this.PolicyStatementLinkLabel, 0, 1); this.tableLayoutPanel1.Controls.Add(this.m_ctrlError, 0, 10); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 1, 10); this.tableLayoutPanel1.Controls.Add(this.enrollmentCheckBox, 0, 2); this.tableLayoutPanel1.Controls.Add(this.decentGroupBoxXSCredentials, 0, 7); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // decentGroupBox2 // resources.ApplyResources(this.decentGroupBox2, "decentGroupBox2"); this.tableLayoutPanel1.SetColumnSpan(this.decentGroupBox2, 2); this.decentGroupBox2.Controls.Add(this.tableLayoutPanel4); this.decentGroupBox2.Name = "decentGroupBox2"; this.decentGroupBox2.TabStop = false; // // tableLayoutPanel4 // resources.ApplyResources(this.tableLayoutPanel4, "tableLayoutPanel4"); this.tableLayoutPanel4.Controls.Add(this.frequencyLabel, 0, 0); this.tableLayoutPanel4.Controls.Add(this.frequencyNumericBox, 1, 0); this.tableLayoutPanel4.Controls.Add(this.weeksLabel, 2, 0); this.tableLayoutPanel4.Controls.Add(this.dayOfweekLabel, 0, 2); this.tableLayoutPanel4.Controls.Add(this.timeOfDayLabel, 0, 1); this.tableLayoutPanel4.Controls.Add(this.timeOfDayComboBox, 1, 1); this.tableLayoutPanel4.Controls.Add(this.dayOfWeekComboBox, 1, 2); this.tableLayoutPanel4.Name = "tableLayoutPanel4"; // // frequencyLabel // resources.ApplyResources(this.frequencyLabel, "frequencyLabel"); this.frequencyLabel.Name = "frequencyLabel"; // // frequencyNumericBox // resources.ApplyResources(this.frequencyNumericBox, "frequencyNumericBox"); this.frequencyNumericBox.Maximum = new decimal(new int[] { 52, 0, 0, 0}); this.frequencyNumericBox.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.frequencyNumericBox.Name = "frequencyNumericBox"; this.frequencyNumericBox.Value = new decimal(new int[] { 1, 0, 0, 0}); // // weeksLabel // resources.ApplyResources(this.weeksLabel, "weeksLabel"); this.weeksLabel.Name = "weeksLabel"; // // dayOfweekLabel // resources.ApplyResources(this.dayOfweekLabel, "dayOfweekLabel"); this.dayOfweekLabel.Name = "dayOfweekLabel"; // // timeOfDayLabel // resources.ApplyResources(this.timeOfDayLabel, "timeOfDayLabel"); this.timeOfDayLabel.Name = "timeOfDayLabel"; // // timeOfDayComboBox // this.tableLayoutPanel4.SetColumnSpan(this.timeOfDayComboBox, 2); this.timeOfDayComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.timeOfDayComboBox, "timeOfDayComboBox"); this.timeOfDayComboBox.FormattingEnabled = true; this.timeOfDayComboBox.Name = "timeOfDayComboBox"; // // dayOfWeekComboBox // this.tableLayoutPanel4.SetColumnSpan(this.dayOfWeekComboBox, 2); this.dayOfWeekComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.dayOfWeekComboBox, "dayOfWeekComboBox"); this.dayOfWeekComboBox.FormattingEnabled = true; this.dayOfWeekComboBox.Name = "dayOfWeekComboBox"; // // decentGroupBox1 // resources.ApplyResources(this.decentGroupBox1, "decentGroupBox1"); this.tableLayoutPanel1.SetColumnSpan(this.decentGroupBox1, 2); this.decentGroupBox1.Controls.Add(this.tableLayoutPanel2); this.decentGroupBox1.Name = "decentGroupBox1"; this.decentGroupBox1.TabStop = false; // // tableLayoutPanel2 // resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2"); this.tableLayoutPanel2.Controls.Add(this.authenticationRubricTextBox, 0, 0); this.tableLayoutPanel2.Controls.Add(this.label1, 0, 3); this.tableLayoutPanel2.Controls.Add(this.label2, 0, 4); this.tableLayoutPanel2.Controls.Add(this.textBoxMyCitrixPassword, 1, 4); this.tableLayoutPanel2.Controls.Add(this.textBoxMyCitrixUsername, 1, 3); this.tableLayoutPanel2.Controls.Add(this.existingAuthenticationRadioButton, 0, 1); this.tableLayoutPanel2.Controls.Add(this.newAuthenticationRadioButton, 0, 2); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; // // authenticationRubricTextBox // resources.ApplyResources(this.authenticationRubricTextBox, "authenticationRubricTextBox"); this.authenticationRubricTextBox.BackColor = System.Drawing.SystemColors.Control; this.authenticationRubricTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; this.tableLayoutPanel2.SetColumnSpan(this.authenticationRubricTextBox, 2); this.authenticationRubricTextBox.Cursor = System.Windows.Forms.Cursors.Default; this.authenticationRubricTextBox.Name = "authenticationRubricTextBox"; this.authenticationRubricTextBox.ShortcutsEnabled = false; this.authenticationRubricTextBox.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.authenticationRubricTextBox_LinkClicked); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // textBoxMyCitrixPassword // resources.ApplyResources(this.textBoxMyCitrixPassword, "textBoxMyCitrixPassword"); this.textBoxMyCitrixPassword.Name = "textBoxMyCitrixPassword"; this.textBoxMyCitrixPassword.UseSystemPasswordChar = true; this.textBoxMyCitrixPassword.TextChanged += new System.EventHandler(this.credentials_TextChanged); // // textBoxMyCitrixUsername // resources.ApplyResources(this.textBoxMyCitrixUsername, "textBoxMyCitrixUsername"); this.textBoxMyCitrixUsername.Name = "textBoxMyCitrixUsername"; this.textBoxMyCitrixUsername.TextChanged += new System.EventHandler(this.credentials_TextChanged); // // existingAuthenticationRadioButton // resources.ApplyResources(this.existingAuthenticationRadioButton, "existingAuthenticationRadioButton"); this.tableLayoutPanel2.SetColumnSpan(this.existingAuthenticationRadioButton, 2); this.existingAuthenticationRadioButton.Name = "existingAuthenticationRadioButton"; this.existingAuthenticationRadioButton.TabStop = true; this.existingAuthenticationRadioButton.UseVisualStyleBackColor = true; // // newAuthenticationRadioButton // resources.ApplyResources(this.newAuthenticationRadioButton, "newAuthenticationRadioButton"); this.tableLayoutPanel2.SetColumnSpan(this.newAuthenticationRadioButton, 2); this.newAuthenticationRadioButton.Name = "newAuthenticationRadioButton"; this.newAuthenticationRadioButton.TabStop = true; this.newAuthenticationRadioButton.UseVisualStyleBackColor = true; this.newAuthenticationRadioButton.CheckedChanged += new System.EventHandler(this.newAuthenticationRadioButton_CheckedChanged); // // rubricLabel // resources.ApplyResources(this.rubricLabel, "rubricLabel"); this.tableLayoutPanel1.SetColumnSpan(this.rubricLabel, 2); this.rubricLabel.Name = "rubricLabel"; // // PolicyStatementLinkLabel // resources.ApplyResources(this.PolicyStatementLinkLabel, "PolicyStatementLinkLabel"); this.tableLayoutPanel1.SetColumnSpan(this.PolicyStatementLinkLabel, 2); this.PolicyStatementLinkLabel.Name = "PolicyStatementLinkLabel"; this.PolicyStatementLinkLabel.TabStop = true; this.PolicyStatementLinkLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.PolicyStatementLinkLabel_LinkClicked); // // m_ctrlError // resources.ApplyResources(this.m_ctrlError, "m_ctrlError"); this.m_ctrlError.Name = "m_ctrlError"; // // flowLayoutPanel1 // resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.Controls.Add(this.cancelButton); this.flowLayoutPanel1.Controls.Add(this.okButton); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // enrollmentCheckBox // resources.ApplyResources(this.enrollmentCheckBox, "enrollmentCheckBox"); this.tableLayoutPanel1.SetColumnSpan(this.enrollmentCheckBox, 2); this.enrollmentCheckBox.Name = "enrollmentCheckBox"; this.enrollmentCheckBox.UseVisualStyleBackColor = true; this.enrollmentCheckBox.CheckedChanged += new System.EventHandler(this.enrollmentCheckBox_CheckedChanged); // // decentGroupBoxXSCredentials // resources.ApplyResources(this.decentGroupBoxXSCredentials, "decentGroupBoxXSCredentials"); this.tableLayoutPanel1.SetColumnSpan(this.decentGroupBoxXSCredentials, 2); this.decentGroupBoxXSCredentials.Controls.Add(this.tableLayoutPanel3); this.decentGroupBoxXSCredentials.Name = "decentGroupBoxXSCredentials"; this.decentGroupBoxXSCredentials.TabStop = false; // // tableLayoutPanel3 // resources.ApplyResources(this.tableLayoutPanel3, "tableLayoutPanel3"); this.tableLayoutPanel3.Controls.Add(this.errorLabel, 3, 5); this.tableLayoutPanel3.Controls.Add(this.testCredentialsStatusImage, 2, 5); this.tableLayoutPanel3.Controls.Add(this.label3, 0, 0); this.tableLayoutPanel3.Controls.Add(this.label4, 0, 3); this.tableLayoutPanel3.Controls.Add(this.label5, 0, 4); this.tableLayoutPanel3.Controls.Add(this.textboxXSPassword, 1, 4); this.tableLayoutPanel3.Controls.Add(this.textboxXSUserName, 1, 3); this.tableLayoutPanel3.Controls.Add(this.currentXsCredentialsRadioButton, 0, 1); this.tableLayoutPanel3.Controls.Add(this.newXsCredentialsRadioButton, 0, 2); this.tableLayoutPanel3.Controls.Add(this.testCredentialsButton, 1, 5); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; // // errorLabel // this.errorLabel.AutoEllipsis = true; resources.ApplyResources(this.errorLabel, "errorLabel"); this.errorLabel.ForeColor = System.Drawing.Color.Red; this.errorLabel.Name = "errorLabel"; // // testCredentialsStatusImage // resources.ApplyResources(this.testCredentialsStatusImage, "testCredentialsStatusImage"); this.testCredentialsStatusImage.Name = "testCredentialsStatusImage"; this.testCredentialsStatusImage.TabStop = false; // // label3 // resources.ApplyResources(this.label3, "label3"); this.tableLayoutPanel3.SetColumnSpan(this.label3, 4); this.label3.Name = "label3"; // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // textboxXSPassword // this.tableLayoutPanel3.SetColumnSpan(this.textboxXSPassword, 3); resources.ApplyResources(this.textboxXSPassword, "textboxXSPassword"); this.textboxXSPassword.Name = "textboxXSPassword"; this.textboxXSPassword.UseSystemPasswordChar = true; this.textboxXSPassword.TextChanged += new System.EventHandler(this.xsCredentials_TextChanged); // // textboxXSUserName // this.tableLayoutPanel3.SetColumnSpan(this.textboxXSUserName, 3); resources.ApplyResources(this.textboxXSUserName, "textboxXSUserName"); this.textboxXSUserName.Name = "textboxXSUserName"; this.textboxXSUserName.TextChanged += new System.EventHandler(this.xsCredentials_TextChanged); // // currentXsCredentialsRadioButton // resources.ApplyResources(this.currentXsCredentialsRadioButton, "currentXsCredentialsRadioButton"); this.currentXsCredentialsRadioButton.Checked = true; this.tableLayoutPanel3.SetColumnSpan(this.currentXsCredentialsRadioButton, 4); this.currentXsCredentialsRadioButton.Name = "currentXsCredentialsRadioButton"; this.currentXsCredentialsRadioButton.TabStop = true; this.currentXsCredentialsRadioButton.UseVisualStyleBackColor = true; // // newXsCredentialsRadioButton // resources.ApplyResources(this.newXsCredentialsRadioButton, "newXsCredentialsRadioButton"); this.tableLayoutPanel3.SetColumnSpan(this.newXsCredentialsRadioButton, 4); this.newXsCredentialsRadioButton.Name = "newXsCredentialsRadioButton"; this.newXsCredentialsRadioButton.UseVisualStyleBackColor = true; this.newXsCredentialsRadioButton.CheckedChanged += new System.EventHandler(this.radioButton2_CheckedChanged); // // testCredentialsButton // resources.ApplyResources(this.testCredentialsButton, "testCredentialsButton"); this.testCredentialsButton.Name = "testCredentialsButton"; this.testCredentialsButton.UseVisualStyleBackColor = true; this.testCredentialsButton.Click += new System.EventHandler(this.testCredentialsButton_Click); // // HealthCheckSettingsDialog // this.AcceptButton = this.okButton; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.CancelButton = this.cancelButton; this.Controls.Add(this.tableLayoutPanel1); this.Name = "HealthCheckSettingsDialog"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.decentGroupBox2.ResumeLayout(false); this.decentGroupBox2.PerformLayout(); this.tableLayoutPanel4.ResumeLayout(false); this.tableLayoutPanel4.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.frequencyNumericBox)).EndInit(); this.decentGroupBox1.ResumeLayout(false); this.decentGroupBox1.PerformLayout(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.decentGroupBoxXSCredentials.ResumeLayout(false); this.decentGroupBoxXSCredentials.PerformLayout(); this.tableLayoutPanel3.ResumeLayout(false); this.tableLayoutPanel3.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.testCredentialsStatusImage)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private Controls.DecentGroupBox decentGroupBox2; protected System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; private System.Windows.Forms.Label frequencyLabel; private System.Windows.Forms.NumericUpDown frequencyNumericBox; private System.Windows.Forms.Label weeksLabel; private System.Windows.Forms.Label dayOfweekLabel; private System.Windows.Forms.Label timeOfDayLabel; private System.Windows.Forms.ComboBox timeOfDayComboBox; private System.Windows.Forms.ComboBox dayOfWeekComboBox; private Controls.DecentGroupBox decentGroupBox1; protected System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; protected System.Windows.Forms.Label label1; protected System.Windows.Forms.Label label2; protected System.Windows.Forms.TextBox textBoxMyCitrixPassword; protected System.Windows.Forms.TextBox textBoxMyCitrixUsername; private System.Windows.Forms.RadioButton existingAuthenticationRadioButton; private System.Windows.Forms.RadioButton newAuthenticationRadioButton; private System.Windows.Forms.LinkLabel PolicyStatementLinkLabel; private System.Windows.Forms.Label rubricLabel; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; private System.Windows.Forms.CheckBox enrollmentCheckBox; private Controls.DecentGroupBox decentGroupBoxXSCredentials; protected System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; private System.Windows.Forms.Label label3; protected System.Windows.Forms.Label label4; protected System.Windows.Forms.Label label5; protected System.Windows.Forms.TextBox textboxXSPassword; protected System.Windows.Forms.TextBox textboxXSUserName; private System.Windows.Forms.RadioButton currentXsCredentialsRadioButton; private System.Windows.Forms.RadioButton newXsCredentialsRadioButton; private Controls.Common.PasswordFailure m_ctrlError; private System.Windows.Forms.Button testCredentialsButton; private System.Windows.Forms.PictureBox testCredentialsStatusImage; private System.Windows.Forms.Label errorLabel; private System.Windows.Forms.RichTextBox authenticationRubricTextBox; } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.IO; using System.Collections; using System.Reflection; using NUnit.Core.Extensibility; namespace NUnit.Core.Builders { /// <summary> /// Class that builds a TestSuite from an assembly /// </summary> public class TestAssemblyBuilder { static Logger log = InternalTrace.GetLogger("TestAssemblyBuilder"); #region Instance Fields /// <summary> /// The loaded assembly /// </summary> Assembly assembly; /// <summary> /// Our LegacySuite builder, which is only used when a /// fixture has been passed by name on the command line. /// </summary> ISuiteBuilder legacySuiteBuilder; private TestAssemblyInfo assemblyInfo = null; #endregion #region Properties public Assembly Assembly { get { return assembly; } } public TestAssemblyInfo AssemblyInfo { get { if ( assemblyInfo == null && assembly != null ) { AssemblyReader rdr = new AssemblyReader( assembly ); Version imageRuntimeVersion = new Version( rdr.ImageRuntimeVersion.Substring( 1 ) ); IList frameworks = CoreExtensions.Host.TestFrameworks.GetReferencedFrameworks( assembly ); assemblyInfo = new TestAssemblyInfo( rdr.AssemblyPath, imageRuntimeVersion, RuntimeFramework.CurrentFramework, frameworks ); } return assemblyInfo; } } #endregion #region Constructor public TestAssemblyBuilder() { // TODO: Keeping this separate till we can make //it work in all situations. legacySuiteBuilder = new NUnit.Core.Builders.LegacySuiteBuilder(); } #endregion #region Build Methods public Test Build( string assemblyName, string testName, bool autoSuites ) { if ( testName == null || testName == string.Empty ) return Build( assemblyName, autoSuites ); // Change currentDirectory in case assembly references unmanaged dlls // and so that any addins are able to access the directory easily. using (new DirectorySwapper(Path.GetDirectoryName(assemblyName))) { this.assembly = Load(assemblyName); if (assembly == null) return null; // If provided test name is actually the name of // a type, we handle it specially Type testType = assembly.GetType(testName); if (testType != null) return Build(assemblyName, testType, autoSuites); // Assume that testName is a namespace and get all fixtures in it IList fixtures = GetFixtures(assembly, testName); if (fixtures.Count > 0) return BuildTestAssembly(assemblyName, fixtures, autoSuites); return null; } } public TestSuite Build( string assemblyName, bool autoSuites ) { // Change currentDirectory in case assembly references unmanaged dlls // and so that any addins are able to access the directory easily. using (new DirectorySwapper(Path.GetDirectoryName(assemblyName))) { this.assembly = Load(assemblyName); if (this.assembly == null) return null; IList fixtures = GetFixtures(assembly, null); return BuildTestAssembly(assemblyName, fixtures, autoSuites); } } private Test Build( string assemblyName, Type testType, bool autoSuites ) { // TODO: This is the only situation in which we currently // recognize and load legacy suites. We need to determine // whether to allow them in more places. if ( legacySuiteBuilder.CanBuildFrom( testType ) ) return legacySuiteBuilder.BuildFrom( testType ); else if ( TestFixtureBuilder.CanBuildFrom( testType ) ) return BuildTestAssembly( assemblyName, new Test[] { TestFixtureBuilder.BuildFrom( testType ) }, autoSuites ); return null; } private TestSuite BuildTestAssembly( string assemblyName, IList fixtures, bool autoSuites ) { TestSuite testAssembly = new TestAssembly( assemblyName ); if ( autoSuites ) { NamespaceTreeBuilder treeBuilder = new NamespaceTreeBuilder( testAssembly ); treeBuilder.Add( fixtures ); testAssembly = treeBuilder.RootSuite; } else foreach( TestSuite fixture in fixtures ) { if (fixture != null) { if (fixture is SetUpFixture) { fixture.RunState = RunState.NotRunnable; fixture.IgnoreReason = "SetUpFixture cannot be used when loading tests as a flat list of fixtures"; } testAssembly.Add(fixture); } } if ( fixtures.Count == 0 ) { testAssembly.RunState = RunState.NotRunnable; testAssembly.IgnoreReason = "Has no TestFixtures"; } NUnitFramework.ApplyCommonAttributes( assembly, testAssembly ); testAssembly.Properties["_PID"] = System.Diagnostics.Process.GetCurrentProcess().Id; testAssembly.Properties["_APPDOMAIN"] = AppDomain.CurrentDomain.FriendlyName; // TODO: Make this an option? Add Option to sort assemblies as well? testAssembly.Sort(); return testAssembly; } #endregion #region Helper Methods private Assembly Load(string path) { Assembly assembly = null; // Throws if this isn't a managed assembly or if it was built // with a later version of the same assembly. AssemblyName assemblyName = AssemblyName.GetAssemblyName( Path.GetFileName( path ) ); assembly = Assembly.Load(assemblyName); if ( assembly != null ) CoreExtensions.Host.InstallAdhocExtensions( assembly ); log.Info( "Loaded assembly " + assembly.FullName ); return assembly; } private IList GetFixtures( Assembly assembly, string ns ) { ArrayList fixtures = new ArrayList(); log.Debug("Examining assembly for test fixtures"); IList testTypes = GetCandidateFixtureTypes( assembly, ns ); log.Debug("Found {0} classes to examine", testTypes.Count); #if NET_2_0 System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); timer.Start(); #endif foreach(Type testType in testTypes) { if( TestFixtureBuilder.CanBuildFrom( testType ) ) fixtures.Add( TestFixtureBuilder.BuildFrom( testType ) ); } #if NET_2_0 log.Debug("Found {0} fixtures in {1} seconds", fixtures.Count, timer.Elapsed); #else log.Debug("Found {0} fixtures", fixtures.Count); #endif return fixtures; } private IList GetCandidateFixtureTypes( Assembly assembly, string ns ) { IList types = assembly.GetTypes(); if ( ns == null || ns == string.Empty || types.Count == 0 ) return types; string prefix = ns + "." ; ArrayList result = new ArrayList(); foreach( Type type in types ) if ( type.FullName.StartsWith( prefix ) ) result.Add( type ); return result; } #endregion } }
// Sassy 1.3 // By Jookia under the GPL v3 license. // // Update 1.1 // Cleaned up the code style. // Added error stacks. // Added a pref array feature. // Added a shared isValue function. // // Update 1.2 // Removed getData function. // Added dataID variable. // Fixed a pref array bug. // Removed need for names. // Fixed up some more code style stuff. // // Update 1.3 // SassyData added. // Optimization. Lots of it. // Fixed up even more code style. // Made the pref array less hacky. // // Todo // Blank line checking. // SassyData is like a file header. $EywaData = "1.3"; // Version. function Eywa::onAdd(%this) { %errorStack = ""; if($server::LAN == true) %errorStack = "ERROR: Eywa::onAdd(): Eywa does not support LAN servers!"; if(%this.dataFile $= "") %errorStack = %errorStack @ ((%errorStack !$= "") ? "\n" : "") @ "ERROR: Eywa::onAdd(): Eywa needs a dataFile variable!"; if(%errorStack !$= "") { if(%this.Debug) { warn("WorldRP Debug (Database): " @ %errorStack); } %this.schedule(0, "delete"); return false; } %this.valueCount = 0; %this.dataCount = 0; if(isFile(%this.dataFile) == true) { if(%this.Debug) { warn("WorldRP Debug (DB ERROR): Eywa::onAdd(): Previous save file found. Loading.."); } %this.loadData(); } return true; } function Eywa::onRemove(%this) { for(%a = 1; %a <= %this.dataCount; %a++) { if(%this.Debug) { warn("WorldRP Debug (Database): " @ %this.data[%a] @ " Deleted"); } %this.data[%a].delete(); } return true; } function Eywa::saveData(%this) { %file = new fileObject(); %file.openForWrite(%this.dataFile); %file.writeLine(":" @ $EywaData @ "\n"); %file.writeLine("VALUES"); for(%a = 1; %a <= %this.valueCount; %a++) %file.writeLine(" " @ %this.value[%a] SPC %this.defaultValue[%a]); if(%this.dataCount > 0) %file.writeLine(""); for(%b = 1; %b <= %this.dataCount; %b++) { if(isObject(%this.data[%b]) == false) continue; %file.writeLine("ID " @ %this.data[%b].ID); for(%c = 1; %c <= %this.valueCount; %c++) %file.writeLine(" " @ %this.value[%c] SPC %this.data[%b].value[%this.value[%c]]); if(%b < %this.dataCount) %file.writeLine(""); } %file.close(); %file.delete(); return true; } function Eywa::loadData(%this) { if(isFile(%this.dataFile) == false) { if(%this.Debug) { warn("WorldRP Debug (Database): Eywa::loadData(): Data file not found!"); } return false; } %file = new fileObject(); %file.openForRead(%this.dataFile); %currentState = ""; %fileVersion = 0; %EywaVersion = getWord($EywaData, 0); %this.valuecount = 0; while(%file.isEOF() == false) { %line = %file.readLine(); if(strReplace(%line, " ", "") $= "") continue; if(getSubStr(%line, 0, 1) $= ":") { %line = getSubStr(%line, 1, strLen(%line) - 1); %version = getWord(%line, 0); if(%version > %EywaVersion) { if(%this.Debug) { warn("WorldRP Debug (Database): Eywa_loadPrefArray([%dataFile: " @ %dataFile @ "]): Attempting to read file from the future!"); } return false; } continue; } if(getSubStr(%line, 0, 1) $= " ") { %line = getSubStr(%line, 1, strLen(%line) - 1); if(%currentState $= "values") { %this.valueCount++; %this.value[%this.valueCount] = getWord(%line, 0); %this.defaultValue[%this.valueCount] = getWords(%line, 1, getWordCount(%line) - 1); } else if(%currentState $= "id" && %this.isValue(getWord(%line, 0)) == true) %this.data[%this.dataCount].value[getWord(%line, 0)] = getWords(%line, 1, getWordCount(%line) - 1); continue; } %currentState = strLwr(getWord(%line, 0)); if(%currentState $= "id" && isObject(%this.dataID[%ID]) == false) %this.addData(getWord(%line, 1)); } %file.close(); %file.delete(); return true; } function Eywa::addValue(%this, %value, %defaultValue) { %errorStack = ""; if(%value $= "" || %defaultValue $= "") %errorStack = "ERROR: Eywa::addValue([value: " @ %value @ "], [defaultValue: " @ %defaultValue @ "]): Incorrect amount of arguments!"; if(%this.isValue(%value) == true) %errorStack = %errorStack @ ((%errorStack !$= "") ? "\n" : "") @ "ERROR: Eywa::addValue([value: " @ %value @ "], [defaultValue: " @ %defaultValue @ "]): Value '" @ %value @ "' is already in the database!"; if(getWordCount(%value) > 1) %errorStack = %errorStack @ ((%errorStack !$= "") ? "\n" : "") @ "ERROR: Eywa::addValue([value: " @ %value @ "], [defaultValue: " @ %defaultValue @ "]): Values can't be longer then one word!"; if(%errorStack !$= "") { if(%this.Debug) { warn("WorldRP Debug (Database): " @ %errorStack); } return false; } %this.valueCount++; %this.value[%this.valueCount] = %value; %this.defaultValue[%this.valueCount] = %defaultValue; for(%a = 1; %a <= %this.dataCount; %a++) %this.data[%a].value[%value] = %defaultValue; return true; } function Eywa::removeValue(%this, %value) { %errorStack = ""; if(%value $= "") %errorStack = "ERROR: Eywa::removeValue(): Incorrect amount of arguments!"; if(%this.isValue(%value) == false) %errorStack = %errorStack @ ((%errorStack !$= "") ? "\n" : "") @ "ERROR: Eywa::removeValue(): Value '" @ %value @ "' is not found in the database!"; if(%errorStack !$= "") { if(%this.Debug) { warn("WorldRP Debug (Database): " @ %errorStack); } return false; } %foundValue = false; for(%a = 0; %a < %this.valueCount; %a++) { if(%this.value[%a] $= %value) { %foundValue = true; %this.value[%a] = ""; %this.defaultValue[%a] = ""; continue; } if(%foundValue == true) { %this.value[%a - 1] = %this.value[%a]; %this.defaultValue[%a - 1] = %this.defaultValue[%a]; %this.value[%a] = ""; %this.defaultValue[%a] = ""; } } %this.valueCount--; for(%b = 1; %b <= %this.dataCount; %b++) %this.data[%b].value[%value] = ""; return true; } function Eywa::isValue(%this, %value) { for(%a = 0; %a <= %this.valueCount; %a++) if(%this.value[%a] $= %value) return true; return false; } function Eywa::addData(%this, %ID) { %errorStack = ""; if(%ID $= "") %errorStack = "ERROR: Eywa::addData([ID: " @ %ID @ "]): Incorrect amount of arguments!"; if(isObject(%this.dataID[%ID]) == true) %errorStack = %errorStack @ ((%errorStack !$= "") ? "\n" : "") @ "ERROR: Eywa::addData([ID: " @ %ID @ "]): Data for ID '" @ %ID @ "' is already in the database!"; if(%errorStack !$= "") { if(%this.Debug) { warn("WorldRP Debug (Database): " @ %errorStack); } return false; } %data = new scriptObject() { class = EywaData; ID = %ID; parent = %this; }; %this.dataCount++; %this.data[%this.dataCount] = %data; %this.dataID[%ID] = %data; return true; } function Eywa::removeData(%this, %ID) { %errorStack = ""; if(%ID $= "") %errorStack = "ERROR: Eywa::removeData([ID: " @ %ID @ "]): Incorrect amount of arguments!"; if(isObject(%this.dataID[%ID]) == false) %errorStack = %errorStack @ ((%errorStack !$= "") ? "\n" : "") @ "ERROR: Eywa::removeData([ID: " @ %ID @ "]): Data for ID '" @ %ID @ "' is not found in the database!"; if(%errorStack !$= "") { if(%this.Debug) { warn("WorldRP Debug (Database): " @ %errorStack); } return false; } %foundID = false; for(%a = 1; %a <= %this.dataCount; %a++) { if(%this.data[%a].ID == %ID) { %foundID = true; %this.data[%a].delete(); %this.data[%a] = ""; continue; } if(%foundID == true) { %this.data[%a - 1] = %this.data[%a]; %this.data[%a] = ""; } } %this.dataCount--; return true; } function Eywa::getData(%this, %ID) { for(%a = 0; %a <= %this.dataCount; %a++) { if(%this.data[%a].ID == %ID) { return %this.data[%a]; } } return false; } function EywaData::onAdd(%this) { %errorStack = ""; if(%this.ID $= "") %errorStack = "ERROR: EywaData::onAdd(): ID variable not specified!"; if(!isObject(%this.parent)) %errorStack = %errorStack @ ((%errorStack !$= "") ? "\n" : "") @ "ERROR: EywaData::onAdd(): Parent object not found!"; if(%errorStack !$= "") { if(%this.Debug) { warn("WorldRP Debug (Database): " @ %errorStack); } return false; } for(%a = 1; %a <= %this.parent.valueCount; %a++) %this.value[%this.parent.value[%a]] = %this.parent.defaultValue[%a]; return true; } function Eywa_loadPrefArray(%dataFile) { if(isFile(%dataFile) == false) { echo("ERROR: Eywa_loadPrefArray::loadData(): File not found!"); return false; } %file = new fileObject(); %file.openForRead(%dataFile); %currentState = ""; %prefCount = 0; %defaultPref = ""; %countPref = ""; %ID = 0; %fileVersion = 0; %EywaVersion = getWord($EywaData, 0); while(%file.isEOF() == false) { %line = %file.readLine(); if(strReplace(%line, " ", "") $= "") continue; if(getSubStr(%line, 0, 1) $= ":") { %line = getSubStr(%line, 1, strLen(%line) - 1); %version = getWord(%line, 0); if(%version > %EywaVersion) { echo("ERROR: Eywa_loadPrefArray([%dataFile: " @ %dataFile @ "]): Attempting to read file from the future!"); return false; } continue; } if(getSubStr(%line, 0, 1) $= " ") { %line = getSubStr(%line, 1, strLen(%line) - 1); if(%version == 0) // Before 1.3 or no header. { if(%currentState $= "prefs") { %prefTag[getWord(%line, 0)] = %prefCount++; %pref[%prefCount] = getWord(%line, 1); %defaultPref[%prefCount] = getWords(%line, 2, getWordCount(%line) - 1); } else if(%currentState $= "id") { %pref = %pref[%prefTag[getWord(%line, 0)]]; %value = getWords(%line, 1, getWordCount(%line) - 1); eval(strReplace(%pref, "%ID", %ID) @ " = \"" @ %value @ "\";"); } } else { if(%currentState $= "prefs") { %tag = getWord(%line, 0); if(%tag $= "Eywa_PREFCOUNT") %countPref = getWord(%line, 1); else if(%tag $= "Eywa_STARTCOUNT") %ID = getWord(%line, 1) - 1; else { %prefTag[%tag] = %prefCount++; %pref[%prefCount] = getWord(%line, 1); %defaultPref[%prefCount] = getWords(%line, 2, getWordCount(%line) - 1); } } else if(%currentState $= "pref") { %pref = %pref[%prefTag[getWord(%line, 0)]]; %value = getWords(%line, 1, getWordCount(%line) - 1); eval(%pref @ "[" @ %ID @ "] = \"" @ %value @ "\";"); } } continue; } %currentState = strLwr(getWord(%line, 0)); if(%version == 0 && %currentState $= "id") // Before 1.3. { %ID = getWord(%line, 1); for(%a = 1; %a <= %prefCount; %a++) eval(strReplace(%pref[%a], "%ID", %ID) @ " = \"" @ (%value = %defaultPref[%a]) @ "\";"); } else if(%currentState $= "pref") eval(%countPref @ " = " @ %ID++ @ ";"); } %file.close(); %file.delete(); return true; } function SeedOfEywa(%req,%genName,%file) { if(isObject(eval(%gen))) eval(%gen @ ".delete()"); warn(%gen @ ".delete() Executed via SeedOfEywa eval"); // Default DB(s) %gen = new scriptObject(%genName) { class = "Eywa"; dataFile = "config/server/WorldRP/" @ %file @ ".dat"; Debug = false; }; if(fileexists(%gen.DataFile)) switch$(strlwr(%req)) { case "population": %gen.addValue("Name", "NONE"); %gen.addValue("Online", "0"); %gen.addValue("Gender", "NONE"); %gen.addValue("Rank", "1"); %gen.addValue("Money", "0"); %gen.addValue("Bank", "0"); %gen.addValue("Exp", "0"); // %gen.addValue("Scale", "1 1 1"); %gen.addValue("Hunger", "100"); %gen.addValue("Ore", "0" SPC "0" SPC "0" SPC "0"); // Minerals, Wood, Fish, Plastic %gen.addValue("Items", "NONE"); %gen.addValue("Garage", "EMPTY"); case "rank": return; case "crop": return; case "drugs": %gen.AddValue("Weed","BUZZCODEEVALHERE"); } if(EywaPopulation.Debug) { warn("WorldRP Debug: Population Database Booted"); } } SeedOfEywa("population","EywaPopulation","Users");
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using MLifter.Properties; using MLifter.Components; namespace MLifter { /// <summary> /// Used to set the number of cards in each box. /// </summary> /// <remarks>Documented by Dev03, 2007-07-19</remarks> public class SetupBoxesForm : System.Windows.Forms.Form { private bool Loading = false; private System.Windows.Forms.GroupBox GBBoxes; private System.Windows.Forms.Label LInfo; private System.Windows.Forms.Button btnOkay; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.Label[] BoxLabels = new Label[MainForm.LearnLogic.Dictionary.Boxes.Count]; private System.Windows.Forms.Label[] BoxSize = new Label[MainForm.LearnLogic.Dictionary.Boxes.Count]; private ColorProgressBar[] BoxIndicator = new ColorProgressBar[MainForm.LearnLogic.Dictionary.Boxes.Count]; private System.Windows.Forms.NumericUpDown[] BoxMaxSize = new NumericUpDown[MainForm.LearnLogic.Dictionary.Boxes.Count - 2]; private System.Windows.Forms.Button btnDefault; private System.Windows.Forms.Label BoxLabelSizePool = new Label(); private System.Windows.Forms.HelpProvider MainHelp; private System.Windows.Forms.Label BoxLabelSizePark = new Label(); private CheckBox checkBoxAutoBoxSize; private Color[,] barColors = new Color[,] { { Color.Chocolate, Color.Orange }, { Color.Red, Color.OrangeRed }, { Color.Orange, Color.Coral }, { Color.Gold, Color.Khaki }, { Color.Yellow, Color.LightGoldenrodYellow }, { Color.Chartreuse, Color.Aquamarine }, { Color.LimeGreen, Color.LightGreen }, { Color.DarkTurquoise, Color.Turquoise }, { Color.PaleTurquoise, Color.SkyBlue }, { Color.DodgerBlue, Color.DeepSkyBlue }, { Color.MediumBlue, Color.RoyalBlue } }; private MLifter.BusinessLayer.Dictionary Dictionary { get { return MainForm.LearnLogic.Dictionary; } } /// <summary> /// Constructor /// </summary> public SetupBoxesForm() { // // Required for Windows Form Designer support // InitializeComponent(); // MLifter.Classes.Help.SetHelpNameSpace(MainHelp); Loading = true; checkBoxAutoBoxSize.Checked = Dictionary.AutoBoxSize; // Create labels and meters } for (int i = 0; i < Dictionary.Boxes.Count; i++) { BoxLabels[i] = new Label(); BoxLabels[i].Parent = GBBoxes; BoxLabels[i].Left = 7; BoxLabels[i].Top = 19 * i + LInfo.Top + LInfo.Height + 5; BoxLabels[i].Height = 14; BoxLabels[i].Width = 95; BoxLabels[i].AutoSize = true; BoxSize[i] = new Label(); BoxSize[i].Parent = GBBoxes; BoxSize[i].TextAlign = ContentAlignment.MiddleRight; BoxSize[i].Anchor = AnchorStyles.Right; BoxSize[i].Left = GBBoxes.Width - 120; BoxSize[i].Top = BoxLabels[i].Top; BoxSize[i].Width = 50; BoxSize[i].Height = 14; if (i > 0 && i < Dictionary.Boxes.Count - 1) { BoxMaxSize[i - 1] = new NumericUpDown(); BoxMaxSize[i - 1].Parent = GBBoxes; BoxMaxSize[i - 1].Maximum = 64000; BoxMaxSize[i - 1].Minimum = 2; BoxMaxSize[i - 1].Size = new System.Drawing.Size(58, 14); BoxMaxSize[i - 1].Value = BoxMaxSize[i - 1].Minimum; BoxMaxSize[i - 1].ValueChanged += new EventHandler(SEMax_ValueChanged); BoxMaxSize[i - 1].LostFocus += new EventHandler(SEMax_TextChanged); BoxMaxSize[i - 1].Tag = i; BoxMaxSize[i - 1].Top = BoxLabels[i].Top - 3; BoxMaxSize[i - 1].Left = GBBoxes.Width - 65; } BoxIndicator[i] = new ColorProgressBar(); BoxIndicator[i].Parent = GBBoxes; BoxIndicator[i].Left = BoxLabels[i].Left + BoxLabels[i].Width + 5; BoxIndicator[i].Top = BoxLabels[i].Top; BoxIndicator[i].Step = 1; BoxIndicator[i].Width = GBBoxes.Width - BoxIndicator[i].Left - 120; BoxIndicator[i].Height = 14; BoxIndicator[i].BarColor = Color.SteelBlue; BoxIndicator[i].FillStyle = ColorProgressBar.FillStyles.Solid; } BoxLabelSizePool.Parent = GBBoxes; BoxLabelSizePool.Top = BoxLabels[0].Top; BoxLabelSizePool.Left = GBBoxes.Width - 65; BoxLabelSizePool.TextAlign = ContentAlignment.MiddleLeft; BoxLabelSizePool.Size = new System.Drawing.Size(58, 14); BoxLabelSizePark.Parent = GBBoxes; BoxLabelSizePark.Top = BoxLabels[10].Top; BoxLabelSizePark.Left = GBBoxes.Width - 65; BoxLabelSizePark.TextAlign = ContentAlignment.MiddleLeft; BoxLabelSizePark.Size = new System.Drawing.Size(58, 14); int lastBox = Dictionary.Boxes.Count - 1; for (int i = lastBox - 1; i >= 0; i--) { BoxIndicator[i].DataBindings.Add(new Binding("Left", BoxIndicator[lastBox], "Left")); BoxIndicator[i].DataBindings.Add(new Binding("Width", BoxIndicator[lastBox], "Width")); } BoxLabels[0].Text = Resources.SETUPBOXES_BOXLABEL0_TEXT; for (int i = 1; i < Dictionary.Boxes.Count; i++) BoxLabels[i].Text = Resources.SETUPBOXES_BOXLABELI_TEXT + " " + i.ToString(); BoxIndicator[lastBox].Left = BoxLabels[lastBox].Left + BoxLabels[lastBox].Width + 5; BoxIndicator[lastBox].Width = GBBoxes.Width - BoxIndicator[lastBox].Left - 120; Loading = false; UpdateMeters(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SetupBoxesForm)); this.GBBoxes = new System.Windows.Forms.GroupBox(); this.LInfo = new System.Windows.Forms.Label(); this.btnOkay = new System.Windows.Forms.Button(); this.btnDefault = new System.Windows.Forms.Button(); this.MainHelp = new System.Windows.Forms.HelpProvider(); this.checkBoxAutoBoxSize = new System.Windows.Forms.CheckBox(); this.GBBoxes.SuspendLayout(); this.SuspendLayout(); // // GBBoxes // resources.ApplyResources(this.GBBoxes, "GBBoxes"); this.GBBoxes.Controls.Add(this.LInfo); this.GBBoxes.Name = "GBBoxes"; this.MainHelp.SetShowHelp(this.GBBoxes, ((bool)(resources.GetObject("GBBoxes.ShowHelp")))); this.GBBoxes.TabStop = false; // // LInfo // resources.ApplyResources(this.LInfo, "LInfo"); this.LInfo.Name = "LInfo"; this.MainHelp.SetShowHelp(this.LInfo, ((bool)(resources.GetObject("LInfo.ShowHelp")))); // // btnOkay // resources.ApplyResources(this.btnOkay, "btnOkay"); this.btnOkay.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnOkay.Name = "btnOkay"; this.MainHelp.SetShowHelp(this.btnOkay, ((bool)(resources.GetObject("btnOkay.ShowHelp")))); this.btnOkay.Click += new System.EventHandler(this.btnOkay_Click); // // btnDefault // resources.ApplyResources(this.btnDefault, "btnDefault"); this.btnDefault.Name = "btnDefault"; this.MainHelp.SetShowHelp(this.btnDefault, ((bool)(resources.GetObject("btnDefault.ShowHelp")))); this.btnDefault.Click += new System.EventHandler(this.btnDefault_Click); // // checkBoxAutoBoxSize // resources.ApplyResources(this.checkBoxAutoBoxSize, "checkBoxAutoBoxSize"); this.checkBoxAutoBoxSize.Name = "checkBoxAutoBoxSize"; this.MainHelp.SetShowHelp(this.checkBoxAutoBoxSize, ((bool)(resources.GetObject("checkBoxAutoBoxSize.ShowHelp")))); this.checkBoxAutoBoxSize.UseVisualStyleBackColor = true; this.checkBoxAutoBoxSize.CheckedChanged += new System.EventHandler(this.checkBoxAutoBoxSize_CheckedChanged); // // SetupBoxesForm // this.AcceptButton = this.btnOkay; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnOkay; this.Controls.Add(this.btnDefault); this.Controls.Add(this.btnOkay); this.Controls.Add(this.GBBoxes); this.Controls.Add(this.checkBoxAutoBoxSize); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MainHelp.SetHelpKeyword(this, resources.GetString("$this.HelpKeyword")); this.MainHelp.SetHelpNavigator(this, ((System.Windows.Forms.HelpNavigator)(resources.GetObject("$this.HelpNavigator")))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SetupBoxesForm"; this.MainHelp.SetShowHelp(this, ((bool)(resources.GetObject("$this.ShowHelp")))); this.ShowInTaskbar = false; this.Closing += new System.ComponentModel.CancelEventHandler(this.SetupBoxesForm_Closing); this.GBBoxes.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void SEMax_ValueChanged(object sender, System.EventArgs e) { int box_id = (int)(sender as NumericUpDown).Tag; Dictionary.Boxes[box_id].MaximalSize = (int)BoxMaxSize[box_id - 1].Value; UpdateMeters(); } private void SEMax_TextChanged(object sender, System.EventArgs e) { int box_id = (int)(sender as NumericUpDown).Tag; if (BoxMaxSize[box_id - 1].Value > BoxMaxSize[box_id - 1].Maximum) BoxMaxSize[box_id - 1].Value = BoxMaxSize[box_id - 1].Maximum; if (BoxMaxSize[box_id - 1].Value < BoxMaxSize[box_id - 1].Minimum) BoxMaxSize[box_id - 1].Value = BoxMaxSize[box_id - 1].Minimum; SEMax_ValueChanged(sender, e); } private void btnOkay_Click(object sender, System.EventArgs e) { this.Close(); } /// <summary> /// Used to update and visualize the number of cards in each box. /// Updates the ColorProgressBar controls. /// </summary> /// <remarks>Documented by Dev03, 2007-07-19</remarks> private void UpdateMeters() { if (!Loading) { int size = 0, total = 0; // Find out numbers in boxes, pool = total number of cards - cards in boxes } for (int i = 1; i < Dictionary.Boxes.Count - 1; i++) { BoxIndicator[i].BarColor = barColors[i, (i == Dictionary.CurrentBox ? 1 : 0)]; size = Dictionary.Boxes[i].Size; BoxSize[i].Text = size.ToString() + " / "; BoxIndicator[i].Minimum = 0; BoxMaxSize[i - 1].Enabled = !Dictionary.AutoBoxSize; if (i < Dictionary.Boxes.Count) { BoxIndicator[i].Maximum = Dictionary.Boxes[i].MaximalSize; try { BoxMaxSize[i - 1].Value = BoxIndicator[i].Maximum; } catch (ArgumentOutOfRangeException) { BoxMaxSize[i - 1].Value = BoxMaxSize[i - 1].Minimum; } if (BoxIndicator[i].Maximum < size) BoxIndicator[i].Maximum = size; int min = BoxIndicator[i].Minimum; int max = BoxIndicator[i].Maximum; BoxIndicator[i].Value = size > max ? max : (size < min ? min : size); } } size = Dictionary.Boxes[Dictionary.Boxes.Count - 1].Size; total = Dictionary.Cards.ActiveCardsCount; BoxLabelSizePark.Text = total.ToString(); BoxSize[Dictionary.Boxes.Count - 1].Text = size.ToString() + " / "; BoxIndicator[Dictionary.Boxes.Count - 1].Maximum = total; BoxIndicator[Dictionary.Boxes.Count - 1].Minimum = 0; int minL = BoxIndicator[Dictionary.Boxes.Count - 1].Minimum; int maxL = BoxIndicator[Dictionary.Boxes.Count - 1].Maximum; BoxIndicator[Dictionary.Boxes.Count - 1].Value = size > maxL ? maxL : (size < minL ? minL : size); size = Dictionary.Boxes[0].Size; BoxLabelSizePool.Text = total.ToString(); BoxSize[0].Text = size.ToString() + " / "; BoxIndicator[0].Maximum = total; BoxIndicator[0].Minimum = 0; BoxIndicator[0].Value = size; btnDefault.Enabled = !Dictionary.AutoBoxSize; } } /// <summary> /// Handles the Closing event of the SetupBoxesForm control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-01-04</remarks> private void SetupBoxesForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (!Loading) Dictionary.Save(); } /// <summary> /// Handles the Click event of the btnDefault control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-01-04</remarks> private void btnDefault_Click(object sender, System.EventArgs e) { if (!Loading && !Dictionary.AutoBoxSize) { for (int i = 1; i < Dictionary.Boxes.Count - 1; i++) BoxMaxSize[i - 1].Value = Dictionary.Boxes[i].DefaultSize; } } /// <summary> /// Handles the CheckedChanged event of the checkBoxAutoBoxSize control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2008-01-04</remarks> private void checkBoxAutoBoxSize_CheckedChanged(object sender, EventArgs e) { if (!Loading) { Dictionary.AutoBoxSize = checkBoxAutoBoxSize.Checked; UpdateMeters(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal delegate BoundStatement GenerateMethodBody(EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals); /// <summary> /// Synthesized expression evaluation method. /// </summary> internal sealed class EEMethodSymbol : MethodSymbol { // We only create a single EE method (per EE type) that represents an arbitrary expression, // whose lowering may produce synthesized members (lambdas, dynamic sites, etc). // We may thus assume that the method ordinal is always 0. // // Consider making the implementation more flexible in order to avoid this assumption. // In future we might need to compile multiple expression and then we'll need to assign // a unique method ordinal to each of them to avoid duplicate synthesized member names. private const int _methodOrdinal = 0; internal readonly TypeMap TypeMap; internal readonly MethodSymbol SubstitutedSourceMethod; internal readonly ImmutableArray<LocalSymbol> Locals; internal readonly ImmutableArray<LocalSymbol> LocalsForBinding; private readonly EENamedTypeSymbol _container; private readonly string _name; private readonly ImmutableArray<Location> _locations; private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<ParameterSymbol> _parameters; private readonly ParameterSymbol _thisParameter; private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables; /// <summary> /// Invoked at most once to generate the method body. /// (If the compilation has no errors, it will be invoked /// exactly once, otherwise it may be skipped.) /// </summary> private readonly GenerateMethodBody _generateMethodBody; private TypeSymbol _lazyReturnType; // NOTE: This is only used for asserts, so it could be conditional on DEBUG. private readonly ImmutableArray<TypeParameterSymbol> _allTypeParameters; internal EEMethodSymbol( EENamedTypeSymbol container, string name, Location location, MethodSymbol sourceMethod, ImmutableArray<LocalSymbol> sourceLocals, ImmutableArray<LocalSymbol> sourceLocalsForBinding, ImmutableDictionary<string, DisplayClassVariable> sourceDisplayClassVariables, GenerateMethodBody generateMethodBody) { Debug.Assert(sourceMethod.IsDefinition); Debug.Assert(sourceMethod.ContainingSymbol == container.SubstitutedSourceType.OriginalDefinition); Debug.Assert(sourceLocals.All(l => l.ContainingSymbol == sourceMethod)); _container = container; _name = name; _locations = ImmutableArray.Create(location); // What we want is to map all original type parameters to the corresponding new type parameters // (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: // 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. // 2) The map cannot be constructed until all new type parameters exist. // Our solution is to pass each new type parameter a lazy reference to the type map. We then // initialize the map as soon as the new type parameters are available - and before they are // handed out - so that there is never a period where they can require the type map and find // it uninitialized. var sourceMethodTypeParameters = sourceMethod.TypeParameters; var allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters); var getTypeMap = new Func<TypeMap>(() => this.TypeMap); _typeParameters = sourceMethodTypeParameters.SelectAsArray( (tp, i, arg) => (TypeParameterSymbol)new EETypeParameterSymbol(this, tp, i, getTypeMap), (object)null); _allTypeParameters = container.TypeParameters.Concat(_typeParameters); this.TypeMap = new TypeMap(allSourceTypeParameters, _allTypeParameters); EENamedTypeSymbol.VerifyTypeParameters(this, _typeParameters); var substitutedSourceType = container.SubstitutedSourceType; this.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType); if (sourceMethod.Arity > 0) { this.SubstitutedSourceMethod = this.SubstitutedSourceMethod.Construct(_typeParameters.As<TypeSymbol>()); } TypeParameterChecker.Check(this.SubstitutedSourceMethod, _allTypeParameters); // Create a map from original parameter to target parameter. var parameterBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(); var substitutedSourceThisParameter = this.SubstitutedSourceMethod.ThisParameter; var substitutedSourceHasThisParameter = (object)substitutedSourceThisParameter != null; if (substitutedSourceHasThisParameter) { _thisParameter = MakeParameterSymbol(0, GeneratedNames.ThisProxyFieldName(), substitutedSourceThisParameter); Debug.Assert(_thisParameter.Type == this.SubstitutedSourceMethod.ContainingType); parameterBuilder.Add(_thisParameter); } var ordinalOffset = (substitutedSourceHasThisParameter ? 1 : 0); foreach (var substitutedSourceParameter in this.SubstitutedSourceMethod.Parameters) { var ordinal = substitutedSourceParameter.Ordinal + ordinalOffset; Debug.Assert(ordinal == parameterBuilder.Count); var parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter); parameterBuilder.Add(parameter); } _parameters = parameterBuilder.ToImmutableAndFree(); var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var localsMap = PooledDictionary<LocalSymbol, LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocals) { var local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); localsBuilder.Add(local); } this.Locals = localsBuilder.ToImmutableAndFree(); localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var sourceLocal in sourceLocalsForBinding) { LocalSymbol local; if (!localsMap.TryGetValue(sourceLocal, out local)) { local = sourceLocal.ToOtherMethod(this, this.TypeMap); localsMap.Add(sourceLocal, local); } localsBuilder.Add(local); } this.LocalsForBinding = localsBuilder.ToImmutableAndFree(); // Create a map from variable name to display class field. var displayClassVariables = PooledDictionary<string, DisplayClassVariable>.GetInstance(); foreach (var pair in sourceDisplayClassVariables) { var variable = pair.Value; var oldDisplayClassInstance = variable.DisplayClassInstance; // Note: we don't call ToOtherMethod in the local case because doing so would produce // a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding. var oldDisplayClassInstanceFromLocal = oldDisplayClassInstance as DisplayClassInstanceFromLocal; var newDisplayClassInstance = (oldDisplayClassInstanceFromLocal == null) ? oldDisplayClassInstance.ToOtherMethod(this, this.TypeMap) : new DisplayClassInstanceFromLocal((EELocalSymbol)localsMap[oldDisplayClassInstanceFromLocal.Local]); variable = variable.SubstituteFields(newDisplayClassInstance, this.TypeMap); displayClassVariables.Add(pair.Key, variable); } _displayClassVariables = displayClassVariables.ToImmutableDictionary(); displayClassVariables.Free(); localsMap.Free(); _generateMethodBody = generateMethodBody; } private ParameterSymbol MakeParameterSymbol(int ordinal, string name, ParameterSymbol sourceParameter) { return new SynthesizedParameterSymbol(this, sourceParameter.Type, ordinal, sourceParameter.RefKind, name, sourceParameter.CustomModifiers, sourceParameter.CountOfCustomModifiersPrecedingByRef); } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.Ordinary; } } public override string Name { get { return _name; } } public override int Arity { get { return _typeParameters.Length; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return true; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData GetDllImportData() { return null; } internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } internal override bool TryGetThisParameter(out ParameterSymbol thisParameter) { thisParameter = null; return true; } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return this.SubstitutedSourceMethod.IsVararg; } } internal override RefKind RefKind { get { return this.SubstitutedSourceMethod.RefKind; } } public override bool ReturnsVoid { get { return this.ReturnType.SpecialType == SpecialType.System_Void; } } public override bool IsAsync { get { return false; } } public override TypeSymbol ReturnType { get { if (_lazyReturnType == null) { throw new InvalidOperationException(); } return _lazyReturnType; } } public override ImmutableArray<TypeSymbol> TypeArguments { get { return _typeParameters.Cast<TypeParameterSymbol, TypeSymbol>(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { throw ExceptionUtilities.Unreachable; } internal override Cci.CallingConvention CallingConvention { get { Debug.Assert(this.IsStatic); var cc = Cci.CallingConvention.Default; if (this.IsVararg) { cc |= Cci.CallingConvention.ExtraArguments; } if (this.IsGenericMethod) { cc |= Cci.CallingConvention.Generic; } return cc; } } internal override bool GenerateDebugInfo { get { return false; } } public override Symbol ContainingSymbol { get { return _container; } } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { throw ExceptionUtilities.Unreachable; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.Internal; } } public override bool IsStatic { get { return true; } } public override bool IsVirtual { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } internal override ObsoleteAttributeData ObsoleteAttributeData { get { throw ExceptionUtilities.Unreachable; } } internal override void GenerateMethodBody(TypeCompilationState compilationState, DiagnosticBag diagnostics) { ImmutableArray<LocalSymbol> declaredLocalsArray; var body = _generateMethodBody(this, diagnostics, out declaredLocalsArray); var compilation = compilationState.Compilation; _lazyReturnType = CalculateReturnType(compilation, body); // Can't do this until the return type has been computed. TypeParameterChecker.Check(this, _allTypeParameters); if (diagnostics.HasAnyErrors()) { return; } DiagnosticsPass.IssueDiagnostics(compilation, body, diagnostics, this); if (diagnostics.HasAnyErrors()) { return; } // Check for use-site diagnostics (e.g. missing types in the signature). DiagnosticInfo useSiteDiagnosticInfo = null; this.CalculateUseSiteDiagnostic(ref useSiteDiagnosticInfo); if (useSiteDiagnosticInfo != null && useSiteDiagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnosticInfo, this.Locations[0]); return; } try { var declaredLocals = PooledHashSet<LocalSymbol>.GetInstance(); try { // Rewrite local declaration statement. body = (BoundStatement)LocalDeclarationRewriter.Rewrite(compilation, _container, declaredLocals, body, declaredLocalsArray); // Verify local declaration names. foreach (var local in declaredLocals) { Debug.Assert(local.Locations.Length > 0); var name = local.Name; if (name.StartsWith("$", StringComparison.Ordinal)) { diagnostics.Add(ErrorCode.ERR_UnexpectedCharacter, local.Locations[0], name[0]); return; } } // Rewrite references to placeholder "locals". body = (BoundStatement)PlaceholderLocalRewriter.Rewrite(compilation, _container, declaredLocals, body, diagnostics); if (diagnostics.HasAnyErrors()) { return; } } finally { declaredLocals.Free(); } var syntax = body.Syntax; var statementsBuilder = ArrayBuilder<BoundStatement>.GetInstance(); statementsBuilder.Add(body); // Insert an implicit return statement if necessary. if (body.Kind != BoundKind.ReturnStatement) { statementsBuilder.Add(new BoundReturnStatement(syntax, RefKind.None, expressionOpt: null)); } var localsBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var localsSet = PooledHashSet<LocalSymbol>.GetInstance(); foreach (var local in this.LocalsForBinding) { Debug.Assert(!localsSet.Contains(local)); localsBuilder.Add(local); localsSet.Add(local); } foreach (var local in this.Locals) { if (!localsSet.Contains(local)) { Debug.Assert(!localsSet.Contains(local)); localsBuilder.Add(local); localsSet.Add(local); } } localsSet.Free(); body = new BoundBlock(syntax, localsBuilder.ToImmutableAndFree(), statementsBuilder.ToImmutableAndFree()) { WasCompilerGenerated = true }; Debug.Assert(!diagnostics.HasAnyErrors()); Debug.Assert(!body.HasErrors); bool sawLambdas; bool sawLocalFunctions; bool sawAwaitInExceptionHandler; ImmutableArray<SourceSpan> dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty; body = LocalRewriter.Rewrite( compilation: this.DeclaringCompilation, method: this, methodOrdinal: _methodOrdinal, containingType: _container, statement: body, compilationState: compilationState, previousSubmissionFields: null, allowOmissionOfConditionalCalls: false, instrumentForDynamicAnalysis: false, debugDocumentProvider: null, dynamicAnalysisSpans: ref dynamicAnalysisSpans, diagnostics: diagnostics, sawLambdas: out sawLambdas, sawLocalFunctions: out sawLocalFunctions, sawAwaitInExceptionHandler: out sawAwaitInExceptionHandler); Debug.Assert(!sawAwaitInExceptionHandler); Debug.Assert(dynamicAnalysisSpans.Length == 0); if (body.HasErrors) { return; } // Variables may have been captured by lambdas in the original method // or in the expression, and we need to preserve the existing values of // those variables in the expression. This requires rewriting the variables // in the expression based on the closure classes from both the original // method and the expression, and generating a preamble that copies // values into the expression closure classes. // // Consider the original method: // static void M() // { // int x, y, z; // ... // F(() => x + y); // } // and the expression in the EE: "F(() => x + z)". // // The expression is first rewritten using the closure class and local <1> // from the original method: F(() => <1>.x + z) // Then lambda rewriting introduces a new closure class that includes // the locals <1> and z, and a corresponding local <2>: F(() => <2>.<1>.x + <2>.z) // And a preamble is added to initialize the fields of <2>: // <2> = new <>c__DisplayClass0(); // <2>.<1> = <1>; // <2>.z = z; // Rewrite "this" and "base" references to parameter in this method. // Rewrite variables within body to reference existing display classes. body = (BoundStatement)CapturedVariableRewriter.Rewrite( this.SubstitutedSourceMethod.IsStatic ? null : _parameters[0], compilation.Conversions, _displayClassVariables, body, diagnostics); if (body.HasErrors) { Debug.Assert(false, "Please add a test case capturing whatever caused this assert."); return; } if (diagnostics.HasAnyErrors()) { return; } if (sawLambdas || sawLocalFunctions) { var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance(); var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance(); body = LambdaRewriter.Rewrite( loweredBody: body, thisType: this.SubstitutedSourceMethod.ContainingType, thisParameter: _thisParameter, method: this, methodOrdinal: _methodOrdinal, substitutedSourceMethod: this.SubstitutedSourceMethod.OriginalDefinition, closureDebugInfoBuilder: closureDebugInfoBuilder, lambdaDebugInfoBuilder: lambdaDebugInfoBuilder, slotAllocatorOpt: null, compilationState: compilationState, diagnostics: diagnostics, assignLocals: true); // we don't need this information: closureDebugInfoBuilder.Free(); lambdaDebugInfoBuilder.Free(); } // Insert locals from the original method, // followed by any new locals. var block = (BoundBlock)body; var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var local in this.Locals) { Debug.Assert(!(local is EELocalSymbol) || (((EELocalSymbol)local).Ordinal == localBuilder.Count)); localBuilder.Add(local); } foreach (var local in block.Locals) { var oldLocal = local as EELocalSymbol; if (oldLocal != null) { Debug.Assert(localBuilder[oldLocal.Ordinal] == oldLocal); continue; } localBuilder.Add(local); } body = block.Update(localBuilder.ToImmutableAndFree(), block.LocalFunctions, block.Statements); TypeParameterChecker.Check(body, _allTypeParameters); compilationState.AddSynthesizedMethod(this, body); } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); } } private static TypeSymbol CalculateReturnType(CSharpCompilation compilation, BoundStatement bodyOpt) { if (bodyOpt == null) { // If the method doesn't do anything, then it doesn't return anything. return compilation.GetSpecialType(SpecialType.System_Void); } switch (bodyOpt.Kind) { case BoundKind.ReturnStatement: return ((BoundReturnStatement)bodyOpt).ExpressionOpt.Type; case BoundKind.ExpressionStatement: case BoundKind.LocalDeclaration: case BoundKind.MultipleLocalDeclarations: case BoundKind.LocalDeconstructionDeclaration: return compilation.GetSpecialType(SpecialType.System_Void); default: throw ExceptionUtilities.UnexpectedValue(bodyOpt.Kind); } } internal override void AddSynthesizedReturnTypeAttributes(ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedReturnTypeAttributes(ref attributes); var compilation = this.DeclaringCompilation; var returnType = this.ReturnType; if (returnType.ContainsDynamic() && compilation.HasDynamicEmitAttributes()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(returnType, ReturnTypeCustomModifiers.Length)); } if (returnType.ContainsTupleNames() && compilation.HasTupleNamesAttributes) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(returnType)); } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return localPosition; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertVector128Int321() { var test = new ImmBinaryOpTest__InsertVector128Int321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__InsertVector128Int321 { private struct TestStruct { public Vector256<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__InsertVector128Int321 testClass) { var result = Avx.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static ImmBinaryOpTest__InsertVector128Int321() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmBinaryOpTest__InsertVector128Int321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.InsertVector128( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.InsertVector128( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.InsertVector128( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.InsertVector128( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Avx.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__InsertVector128Int321(); var result = Avx.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != left[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (i < 4 ? left[i] : right[i-4])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.InsertVector128)}<Int32>(Vector256<Int32>.1, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using gView.Framework.Data; using gView.Framework.UI; namespace gView.Plugins.MapTools.Dialogs { internal partial class FormSplitLayerWithFilter : Form { private ILayer _layer = null; public FormSplitLayerWithFilter(IMapDocument doc, ILayer layer) { InitializeComponent(); if (!(layer.Class is IFeatureClass)) return; _layer = layer; cmbOperator.SelectedIndex = 0; foreach (IField field in ((IFeatureClass)layer.Class).Fields.ToEnumerable()) { if (field == null) continue; cmbFilterField.Items.Add(new FieldItem(field)); } if (cmbFilterField.Items.Count > 0) cmbFilterField.SelectedIndex = 0; string title = _layer.Title; if (doc != null && doc.FocusMap != null && doc.FocusMap.TOC != null) { ITOCElement tocElement = doc.FocusMap.TOC.GetTOCElement(_layer); if (tocElement != null) title = tocElement.Name; } txtTemplate.Text = title + " [VALUE]"; } #region Properties public List<FilterExpessionItem> FilterExpressions { get { List<FilterExpessionItem> expressions = new List<FilterExpessionItem>(); foreach (FilterExpessionItem item in lstLayerNames.CheckedItems) { expressions.Add(item); } return expressions; } } #endregion #region ItemClasses private class FieldItem { IField _field; public FieldItem(IField field) { _field = field; } public IField Field { get { return _field; } } public override string ToString() { return gView.Framework.Data.Field.WhereClauseFieldName(Field.name); } } public class FilterExpessionItem { string _text, _filter; public FilterExpessionItem(string text, string filter) { _text = text; _filter = filter; } public string Text { get { return _text; } } public string Filter { get { return _filter; } } public override string ToString() { return _text; } } #endregion #region Events private void cmbFilterField_SelectedIndexChanged(object sender, EventArgs e) { cmbOperator.Visible = numOperator.Visible = false; if (cmbFilterField.SelectedItem is FieldItem) { switch (((FieldItem)cmbFilterField.SelectedItem).Field.type) { case FieldType.integer: case FieldType.smallinteger: case FieldType.biginteger: case FieldType.Double: case FieldType.Float: case FieldType.ID: cmbOperator.Visible = numOperator.Visible = true; break; } } } private void btnApply_Click(object sender, EventArgs e) { if (!txtTemplate.Text.Contains("[VALUE]")) { txtTemplate.Text += "[VALUE]"; } lstLayerNames.Items.Clear(); string fieldName = cmbFilterField.Text.Replace("[", String.Empty).Replace("]", String.Empty); // Joined fields [...]. Dont need brackets in Distinctfilter... DistinctFilter filter = new DistinctFilter(fieldName); filter.OrderBy = fieldName; using (IFeatureCursor cursor = ((IFeatureClass)_layer.Class).Search(filter) as IFeatureCursor) { if (cursor == null) return; IFeature feature; while ((feature = cursor.NextFeature) != null) { object oobj; object obj = oobj = feature[fieldName]; if (obj == null && fieldName.Contains(":")) obj = oobj = feature[fieldName.Split(':')[1]]; if (obj == null || obj == DBNull.Value) continue; if (numOperator.Visible) { try { double d = Convert.ToDouble(obj); switch (cmbOperator.Text) { case "+": d += (double)numOperator.Value; break; case "-": d -= (double)numOperator.Value; break; case "*": d *= (double)numOperator.Value; break; case "/": d /= (double)numOperator.Value; break; } obj = d; } catch (Exception ex) { MessageBox.Show("ERROR: " + ex.Message); return; } } lstLayerNames.Items.Add( new FilterExpessionItem( txtTemplate.Text.Replace("[VALUE]", obj.ToString()), cmbFilterField.Text + "=" + Quote(oobj.ToString())), true); } } } private void btnCheckAll_Click(object sender, EventArgs e) { for (int i = 0; i < lstLayerNames.Items.Count; i++) lstLayerNames.SetItemChecked(i, true); } private void btnUncheckAll_Click(object sender, EventArgs e) { for (int i = 0; i < lstLayerNames.Items.Count; i++) lstLayerNames.SetItemChecked(i, false); } #endregion #region Helper private string Quote(string str) { if (cmbFilterField.SelectedItem is FieldItem) { switch (((FieldItem)cmbFilterField.SelectedItem).Field.type) { case FieldType.character: case FieldType.String: case FieldType.Date: return "'" + str + "'"; } } return str; } #endregion } }
// http://www.darkfader.net/toolbox/convert/ test units using libaxolotl; using libaxolotl.protocol; using libaxolotl.state; using System; using System.Collections.Generic; using System.Linq; // for ExtraFunctions using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using libaxolotl.ecc; using libaxolotl.util; using System.Security.Cryptography; // temporary oly for testing using libaxolotl.state.impl; namespace WhatsAppApi.Helper { public class AxolotlManager : WhatsAppBase, AxolotlStore { Dictionary<string, List<ProtocolTreeNode>> pending_nodes = new Dictionary<string, List<ProtocolTreeNode>>(); Dictionary<string, ProtocolTreeNode> retryNodes = new Dictionary<string, ProtocolTreeNode>(); Dictionary<string, int> retryCounters = new Dictionary<string,int>(); Dictionary<string, SessionCipher> sessionCiphers = new Dictionary<string, SessionCipher>(); List<string> cipherKeys = new List<string>(); List<string> v2Jids = new List<string>(); bool replaceKey = false; /// <summary> /// /// </summary> public AxolotlManager() { } /// <summary> /// intercept iq and precess the keys /// </summary> /// <param name="node"></param> public ProtocolTreeNode[] ProcessIqTreeNode(ProtocolTreeNode node) { try { if (cipherKeys.Contains(node.GetAttribute("id"))) { cipherKeys.Remove(node.GetAttribute("id")); foreach (var child in node.children) { string jid = child.GetChild("user").GetAttribute("jid"); uint registrationId = deAdjustId(child.GetChild("registration").GetData()); IdentityKey identityKey = new IdentityKey(new DjbECPublicKey(child.GetChild("identity").GetData())); uint signedPreKeyId = deAdjustId(child.GetChild("skey").GetChild("id").GetData()); DjbECPublicKey signedPreKeyPub = new DjbECPublicKey(child.GetChild("skey").GetChild("value").GetData()); byte[] signedPreKeySig = child.GetChild("skey").GetChild("signature").GetData(); uint preKeyId = deAdjustId(child.GetChild("key").GetChild("id").GetData()); DjbECPublicKey preKeyPublic = new DjbECPublicKey(child.GetChild("key").GetChild("value").GetData()); PreKeyBundle preKeyBundle = new PreKeyBundle(registrationId, 1, preKeyId, preKeyPublic, signedPreKeyId, signedPreKeyPub, signedPreKeySig, identityKey); SessionBuilder sessionBuilder = new SessionBuilder(this, this, this, this, new AxolotlAddress(ExtractNumber(jid), 1)); // now do the work return nodelist sessionBuilder.process(preKeyBundle); if (pending_nodes.ContainsKey(ExtractNumber(jid))){ var pendingNodes = pending_nodes[ExtractNumber(jid)].ToArray(); pending_nodes.Remove(ExtractNumber(jid)); return pendingNodes; } } } } catch (Exception e) { } finally { } return null; } /// <summary> /// /// </summary> /// <param name="node"></param> /// <returns></returns> public ProtocolTreeNode processEncryptedNode(ProtocolTreeNode node) { string from = node.GetAttribute("from"); string author = string.Empty; string version = string.Empty; string encType = string.Empty; byte[] encMsg = null; ProtocolTreeNode rtnNode = null; if (from.IndexOf("s.whatsapp.net", 0) > -1) { author = ExtractNumber(node.GetAttribute("from")); version = node.GetChild("enc").GetAttribute("v"); encType = node.GetChild("enc").GetAttribute("type"); encMsg = node.GetChild("enc").GetData(); if (!ContainsSession(new AxolotlAddress(author, 1))) { //we don't have the session to decrypt, save it in pending and process it later addPendingNode(node); Helper.DebugAdapter.Instance.fireOnPrintDebug("info : Requesting cipher keys from " + author); sendGetCipherKeysFromUser(author); } else { string id = node.GetAttribute("id"); //decrypt the message with the session if (String.IsNullOrEmpty(node.GetChild("enc").GetAttribute("count"))) setRetryCounter(id, 1); if (version == "2"){ if (!v2Jids.Contains(author)) v2Jids.Add(author); } object plaintext = decryptMessage(from, encMsg, encType, id, node.GetAttribute("t")); if (plaintext.GetType() == typeof(bool) && false == (bool)plaintext) { if (!retryCounters.ContainsKey(id) || retryCounters[id] <= 2) { sendRetry(node, from, id, node.GetAttribute("t")); Helper.DebugAdapter.Instance.fireOnPrintDebug("info : " + string.Format("Couldn't decrypt message id {0} from {1}. Retrying.", id, author)); } else { Helper.DebugAdapter.Instance.fireOnPrintDebug("info : " + string.Format("Couldn't decrypt message id {0} from {1}. too many retries.", id, author)); } return node; // could not decrypt } // success now lets clear all setting and return node if (retryCounters.ContainsKey(id)) retryCounters.Remove(id); if (retryNodes.ContainsKey(id)) retryNodes.Remove(id); switch (node.GetAttribute("type")) { case "text": { //Convert to list. List<ProtocolTreeNode> children = (from q in node.children where !string.Equals(q.tag, "enc") select q).ToList(); List<KeyValue> attributeHash = node.attributeHash.ToList(); byte[] data = null; if (plaintext.GetType() == typeof(string)) { data = System.Text.Encoding.UTF8.GetBytes((string)plaintext); } children.Add(new ProtocolTreeNode("body", null, null, data)); rtnNode = new ProtocolTreeNode(node.tag, attributeHash.ToArray(), children.ToArray(), node.data); } break; case "media": { /* id = node.GetAttribute("id"); from = node.GetAttribute("from"); UserName = node.GetAttribute("notify"); switch (media.GetAttribute("type")) { case "image": url = media.GetAttribute("url"); file = media.GetAttribute("file"); size = Int32.Parse(media.GetAttribute("size")); */ //Convert to list. List<ProtocolTreeNode> children = (from q in node.children where !string.Equals(q.tag, "enc") select q).ToList(); List<KeyValue> attributeHash = node.attributeHash.ToList(); byte[] data = null; if (plaintext.GetType() == typeof(string)) { data = System.Text.Encoding.UTF8.GetBytes((string)plaintext); } children.Add(new ProtocolTreeNode("media", null, null, data)); rtnNode = new ProtocolTreeNode(node.tag, attributeHash.ToArray(), children.ToArray(), node.data); } break; } Helper.DebugAdapter.Instance.fireOnPrintDebug("info : " + string.Format("Decrypted message with {0} id from {1}", node.GetAttribute("id"), author)); return rtnNode; } } return node; } /// <summary> /// decrypt an incomming message /// </summary> /// <param name="from"></param> /// <param name="ciphertext"></param> /// <param name="type"></param> /// <param name="id"></param> /// <param name="t"></param> /// <param name="retry_from"></param> /// <param name="skip_unpad"></param> public object decryptMessage(string from, byte[] ciphertext, string type, string id, string t, string retry_from = null, bool skip_unpad = false){ string version = "2"; #region pkmsg routine if (type == "pkmsg") { if (v2Jids.Contains(ExtractNumber(from))) version = "2"; try { PreKeyWhisperMessage preKeyWhisperMessage = new PreKeyWhisperMessage(ciphertext); SessionCipher sessionCipher = getSessionCipher(ExtractNumber(from)); byte[] plaintext = sessionCipher.decrypt(preKeyWhisperMessage); String text = WhatsApp.SYSEncoding.GetString(plaintext); if (version == "2" && !skip_unpad) return unpadV2Plaintext(text); } catch (Exception e){ // ErrorAxolotl(e.Message); return false; } } #endregion #region WhisperMessage routine if (type == "msg") { if (v2Jids.Contains(ExtractNumber(from))) version = "2"; try { PreKeyWhisperMessage preKeyWhisperMessage = new PreKeyWhisperMessage(ciphertext); SessionCipher sessionCipher = getSessionCipher(ExtractNumber(from)); byte[] plaintext = sessionCipher.decrypt(preKeyWhisperMessage); String text = WhatsApp.SYSEncoding.GetString(plaintext); if (version == "2" && !skip_unpad) return unpadV2Plaintext(text); } catch (Exception e) { } } #endregion #region Group message Cipher routine if (type == "skmsg") { throw new NotImplementedException(); } #endregion return false; } /// <summary> /// Send a request to get cipher keys from an user /// </summary> /// <param name="number">Phone number of the user you want to get the cipher keys</param> /// <param name="replaceKey"></param> public void sendGetCipherKeysFromUser(string number, bool replaceKeyIn = false) { replaceKey = replaceKeyIn; var msgId = TicketManager.GenerateId(); cipherKeys.Add(msgId); ProtocolTreeNode user = new ProtocolTreeNode("user", new[] { new KeyValue("jid", ApiBase.GetJID(number)), }, null, null); ProtocolTreeNode keyNode = new ProtocolTreeNode("key", null, new ProtocolTreeNode[] { user }, null); ProtocolTreeNode Node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", msgId), new KeyValue("xmlns", "encrypt"), new KeyValue("type", "get"), new KeyValue("to", "s.whatsapp.net") }, new ProtocolTreeNode[] { keyNode }, null); this.SendNode(Node); } /// <summary> /// return the stored session cypher for this number /// </summary> public SessionCipher getSessionCipher(string number) { if (sessionCiphers.ContainsKey(number)) { return sessionCiphers[number]; }else{ AxolotlAddress address = new AxolotlAddress(number, 1); sessionCiphers.Add(number, new SessionCipher(this, this, this, this, address)); return sessionCiphers[number]; } } /// <summary> /// Generate the keysets for ourself /// </summary> /// <returns></returns> public bool sendSetPreKeys(bool isnew = false) { uint registrationId = 0; if (!isnew) registrationId = (uint)this.GetLocalRegistrationId(); else registrationId = libaxolotl.util.KeyHelper.generateRegistrationId(true); Random random = new Random(); uint randomid = (uint)libaxolotl.util.KeyHelper.getRandomSequence(5000);//65536 IdentityKeyPair identityKeyPair = libaxolotl.util.KeyHelper.generateIdentityKeyPair(); byte[] privateKey = identityKeyPair.getPrivateKey().serialize(); byte[] publicKey = identityKeyPair.getPublicKey().getPublicKey().serialize(); IList<PreKeyRecord> preKeys = libaxolotl.util.KeyHelper.generatePreKeys((uint)random.Next(), 200); SignedPreKeyRecord signedPreKey = libaxolotl.util.KeyHelper.generateSignedPreKey(identityKeyPair, randomid); PreKeyRecord lastResortKey = libaxolotl.util.KeyHelper.generateLastResortPreKey(); this.StorePreKeys(preKeys); this.StoreLocalData(registrationId, identityKeyPair.getPublicKey().serialize(), identityKeyPair.getPrivateKey().serialize()); this.StoreSignedPreKey(signedPreKey.getId(), signedPreKey); // FOR INTERNAL TESTING ONLY //this.InMemoryTestSetup(identityKeyPair, registrationId); ProtocolTreeNode[] preKeyNodes = new ProtocolTreeNode[200]; for (int i = 0; i < 200; i++) { byte[] prekeyId = adjustId(preKeys[i].getId().ToString()).Skip(1).ToArray(); byte[] prekey = preKeys[i].getKeyPair().getPublicKey().serialize().Skip(1).ToArray(); ProtocolTreeNode NodeId = new ProtocolTreeNode("id", null, null, prekeyId); ProtocolTreeNode NodeValue = new ProtocolTreeNode("value", null, null, prekey); preKeyNodes[i] = new ProtocolTreeNode("key", null, new ProtocolTreeNode[] { NodeId, NodeValue }, null); } ProtocolTreeNode registration = new ProtocolTreeNode("registration", null, null, adjustId(registrationId.ToString())); ProtocolTreeNode type = new ProtocolTreeNode("type", null, null, new byte[] { Curve.DJB_TYPE }); ProtocolTreeNode list = new ProtocolTreeNode("list", null, preKeyNodes, null); ProtocolTreeNode sid = new ProtocolTreeNode("id", null, null, adjustId(signedPreKey.getId().ToString(), true)); ProtocolTreeNode identity = new ProtocolTreeNode("identity", null, null, identityKeyPair.getPublicKey().getPublicKey().serialize().Skip(1).ToArray()); ProtocolTreeNode value = new ProtocolTreeNode("value", null, null, signedPreKey.getKeyPair().getPublicKey().serialize().Skip(1).ToArray()); ProtocolTreeNode signature = new ProtocolTreeNode("signature", null, null, signedPreKey.getSignature()); ProtocolTreeNode secretKey = new ProtocolTreeNode("skey", null, new ProtocolTreeNode[] { sid, value, signature }, null); String id = TicketManager.GenerateId(); Helper.DebugAdapter.Instance.fireOnPrintDebug(string.Format("axolotl id = {0}", id)); ProtocolTreeNode Node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("to", "s.whatsapp.net"), new KeyValue("type", "set"), new KeyValue("xmlns", "encrypt") }, new ProtocolTreeNode[] { identity, registration, type, list, secretKey }, null); this.SendNode(Node); return true; } /// <summary> /// /// </summary> public void resetEncryption() { } /// <summary> /// jid from address /// </summary> /// <param name="from"></param> /// <returns></returns> public string ExtractNumber(string from) { return new StringBuilder(from).Replace("@s.whatsapp.net", "").Replace("@g.us", "").ToString(); } /// <summary> /// add a node to the queue for latter processing /// due to missing cyper keys /// </summary> /// <param name="node"></param> public void addPendingNode(ProtocolTreeNode node) { string number = string.Empty; string from = node.GetAttribute("from"); if (from.IndexOf("s.whatsapp.net", 0) > -1) number = ExtractNumber(node.GetAttribute("from")); else number = ExtractNumber(node.GetAttribute("participant")); if (pending_nodes.ContainsKey(number)) { pending_nodes[number].Add(node); } else { pending_nodes.Add(number, new List<ProtocolTreeNode> { node }); } } /// <summary> /// increment the retry counters base /// </summary> /// <param name="id"></param> /// <param name="counter"></param> public void setRetryCounter(string id, int counter) { if (retryCounters.ContainsKey(id)) { retryCounters[id] = counter; } else { retryCounters.Add(id, counter); } } /// <summary> /// send a retry to reget this node /// </summary> /// <param name="nod"></param> /// <param name="to"></param> /// <param name="id"></param> /// <param name="t"></param> /// <param name="participant"></param> public void sendRetry(ProtocolTreeNode node, string to, string id, string t, string participant = null) { ProtocolTreeNode returnNode = null; #region update retry counters if (!retryCounters.ContainsKey(id)) { retryCounters.Add(id, 1); }else{ if (retryNodes.ContainsKey(id)) { retryNodes[id] = node; }else{ retryNodes.Add(id, node); } } #endregion if (retryCounters[id] > 2) resetEncryption(); retryCounters[id]++; ProtocolTreeNode retryNode = new ProtocolTreeNode("retry", new[] { new KeyValue("v", "1"), new KeyValue("count", retryCounters[id].ToString()), new KeyValue("id", id), new KeyValue("t", t) }, null, null); byte[] regid = adjustId(GetLocalRegistrationId().ToString()); ProtocolTreeNode registrationNode = new ProtocolTreeNode("registration", null, null, regid); // if (participant != null) //isgroups group retry // attrGrp.Add(new KeyValue("participant", participant)); returnNode = new ProtocolTreeNode("receipt", new[] { new KeyValue("id", id), new KeyValue("to", to), new KeyValue("type", "retry"), new KeyValue("t", t) }, new ProtocolTreeNode[] { retryNode, registrationNode }, null); this.SendNode(returnNode); } /// <summary> /// /// </summary> /// <param name="val"></param> /// <returns></returns> public uint deAdjustId(byte[] val) { byte[] newval = null; byte[] bytebase = new byte[] { (byte) 0x00 }; byte[] rv = bytebase.Concat(val).ToArray(); if (val.Length < 4) newval = rv; else newval = val; byte[] reversed = newval.Reverse().ToArray(); return BitConverter.ToUInt32(reversed, 0); } /// <summary> /// /// </summary> /// <param name="id"></param> public byte[] adjustId(String id, bool limitsix = false) { uint idx = uint.Parse(id); byte[] bytes = BitConverter.GetBytes(idx); uint atomSize = BitConverter.ToUInt32(bytes, 0); Array.Reverse(bytes, 0, bytes.Length); string data = bin2Hex(bytes); if (!string.IsNullOrEmpty(data) && limitsix) data = (data.Length <= 6) ? data : data.Substring(data.Length - 6); while (data.Length < 6){ data = "0" + data; } return hex2Bin(data); } /// <summary> /// /// </summary> /// <param name="hex"></param> /// <returns></returns> public byte[] hex2Bin(String hex) { // return (from i in Enumerable.Range(0, hex.Length / 2) // select Convert.ToByte(hex.Substring(i * 2, 2), 16)).ToArray(); int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; } static string bin2Hex(byte[] bin) { return BitConverter.ToString(bin).Replace("-", string.Empty).ToLower(); #region old code /* StringBuilder sb = new StringBuilder(bin.Length *2); foreach (byte b in bin) { sb.Append(b.ToString("x").PadLeft(2, '0')); } return sb.ToString(); */ #endregion } /// <summary> /// /// </summary> /// <param name="strBin"></param> /// <returns></returns> public string bin2HexXX(string strBin) { int decNumber = Convert.ToInt16(strBin, 2); return decNumber.ToString("X"); } /// <summary> /// /// </summary> /// <param name="v2plaintext"></param> /// <returns></returns> public string unpadV2Plaintext(string v2plaintext) { //if(v2plaintext.Length < 128) // return v2plaintext.Substring(2,-1); //else // return v2plaintext.Substring(3,-1); String ret = SubStr(v2plaintext, 2, -1); return FixPadding(ret); } public static String FixPadding(String result) { /* From Chat-API Php Code */ Char lastChar = result[result.Length - 1]; String unpadded = result.TrimEnd(lastChar); /* From Chat-API Php Code */ return unpadded; } //Php SubStr public static string SubStr(String value, int startIndex, int length = 0) { if (length == 0) return value.Substring(startIndex); if (length< 0) length = value.Length - 1 + length; return value.Substring(startIndex, length); } #region raise a delegates error event to the main aplication public event OnErrorAxolotlDelegate OnErrorAxolotl; public void ErrorAxolotl(String ErrorMessage) { if (this.OnErrorAxolotl != null) { this.OnErrorAxolotl(ErrorMessage); } } public delegate void OnErrorAxolotlDelegate(string ErrorMessage); #endregion #region Public Interfaces for AxolotlStore #region session event and delegates ISessionStore public event OnstoreSessionDataDelegate OnstoreSession; public void StoreSession(AxolotlAddress address, SessionRecord record) { if (this.OnstoreSession != null) { this.OnstoreSession(address.getName(), address.getDeviceId(), record.serialize()); } } public event OnloadSessionDelegate OnloadSession; public SessionRecord LoadSession(AxolotlAddress address) { if (this.OnloadSession != null) { byte[] session = this.OnloadSession(address.getName(), address.getDeviceId()); if(session == null) return new SessionRecord(); else return new SessionRecord(session); } return null; } public event OngetSubDeviceSessionsDelegate OngetSubDeviceSessions; public List<UInt32> GetSubDeviceSessions(string recipientId) { if (this.OngetSubDeviceSessions != null) { return this.OngetSubDeviceSessions(recipientId); } return null; } public event OncontainsSessionDelegate OncontainsSession; public bool ContainsSession(AxolotlAddress address) { if (this.OncontainsSession != null) { return this.OncontainsSession(address.getName(), address.getDeviceId()); } return false; } public event OndeleteSessionDelegate OndeleteSession; public void DeleteSession(AxolotlAddress address) { if (this.OndeleteSession != null) { this.OndeleteSession(address.getName(), address.getDeviceId()); } } public event OndeleteAllSessionsDelegate OndeleteAllSessions; public void DeleteAllSessions(string name) { if (this.OndeleteAllSessions != null) { this.OndeleteAllSessions(name); } } //event delegates public delegate void OnstoreSessionDataDelegate(string recipientId, uint deviceId, byte[] sessionRecord); public delegate byte[] OnloadSessionDelegate(string recipientId, uint deviceId); public delegate List<UInt32> OngetSubDeviceSessionsDelegate(string recipientId); public delegate bool OncontainsSessionDelegate(string recipientId, uint deviceId); public delegate void OndeleteAllSessionsDelegate(string recipientId); public delegate void OndeleteSessionDelegate(string recipientId, uint deviceId); #endregion #region PreKeys event and delegates IPreKeyStore // internat store all generatet keys public void StorePreKeys(IList<PreKeyRecord> keys) { foreach (PreKeyRecord key in keys) StorePreKey((uint)key.getId(), key); } public event OnstorePreKeyDelegate OnstorePreKey; public void StorePreKey(uint preKeyId, PreKeyRecord record) { if (this.OnstorePreKey != null) { this.OnstorePreKey(preKeyId, record.serialize()); } } public event OnloadPreKeyDelegate OnloadPreKey; public PreKeyRecord LoadPreKey(uint preKeyId) { if (this.OnloadPreKey != null) { return new PreKeyRecord(this.OnloadPreKey(preKeyId)); } return null; } public event OncontainsPreKeyDelegate OncontainsPreKey; public bool ContainsPreKey(uint preKeyId) { if (this.OncontainsPreKey != null) { return this.OncontainsPreKey(preKeyId); } return false; } public event OnremovePreKeyDelegate OnremovePreKey; public void RemovePreKey(uint preKeyId) { if (this.OnremovePreKey != null) { this.OnremovePreKey(preKeyId); } } public event OnloadPreKeysDelegate OnloadPreKeys; public List<byte[]> LoadPreKeys() { if (this.OnloadPreKeys != null) { return this.OnloadPreKeys(); } return null; } public event OnremoveAllPreKeysDelegate OnremoveAllPreKeys; protected void RemoveAllPreKeys() { if (this.OnremoveAllPreKeys != null) { this.OnremoveAllPreKeys(); } } //event delegates public delegate void OnstorePreKeyDelegate(uint prekeyId, byte[] preKeyRecord); public delegate byte[] OnloadPreKeyDelegate(uint preKeyId); public delegate List<byte[]> OnloadPreKeysDelegate(); public delegate bool OncontainsPreKeyDelegate(uint preKeyId); public delegate void OnremovePreKeyDelegate(uint preKeyId); public delegate void OnremoveAllPreKeysDelegate(); #endregion #region signedPreKey event and delegates ISignedPreKeyStore public event OnstoreSignedPreKeyDelegate OnstoreSignedPreKey; public void StoreSignedPreKey(UInt32 signedPreKeyId, SignedPreKeyRecord record) { if (this.OnstoreSignedPreKey != null){ this.OnstoreSignedPreKey(signedPreKeyId, record.serialize()); } } public event OnloadSignedPreKeyDelegate OnloadSignedPreKey; public SignedPreKeyRecord LoadSignedPreKey(UInt32 signedPreKeyId) { if (this.OnloadSignedPreKey != null){ byte[] bytes = this.OnloadSignedPreKey(signedPreKeyId); if (bytes.Length > 0) { return new SignedPreKeyRecord(bytes); } } return null; } public event OnloadSignedPreKeysDelegate OnloadSignedPreKeys; public List<SignedPreKeyRecord> LoadSignedPreKeys() { if (this.OnloadSignedPreKeys != null){ List<byte[]> inputList = this.OnloadSignedPreKeys(); return inputList.Select(x => new SignedPreKeyRecord(x)).ToList(); } return null; } public event OncontainsSignedPreKeyDelegate OncontainsSignedPreKey; public bool ContainsSignedPreKey(UInt32 signedPreKeyId) { if (this.OncontainsSignedPreKey != null){ return this.OncontainsSignedPreKey(signedPreKeyId); } return false; } public event OnremoveSignedPreKeyDelegate OnremoveSignedPreKey; public void RemoveSignedPreKey(UInt32 signedPreKeyId) { if (this.OnremoveSignedPreKey != null){ this.OnremoveSignedPreKey(signedPreKeyId); } } //event delegates public delegate void OnstoreSignedPreKeyDelegate(UInt32 signedPreKeyId, byte[] signedPreKeyRecord); public delegate byte[] OnloadSignedPreKeyDelegate(UInt32 preKeyId); public delegate List<byte[]> OnloadSignedPreKeysDelegate(); public delegate void OnremoveSignedPreKeyDelegate(UInt32 preKeyId); public delegate bool OncontainsSignedPreKeyDelegate(UInt32 preKeyId); #endregion #region identity event and delegates IIdentityKeyStore public event OngetIdentityKeyPairDelegate OngetIdentityKeyPair; public IdentityKeyPair GetIdentityKeyPair() { if (this.OngetIdentityKeyPair != null){ List<byte[]> pair = this.OngetIdentityKeyPair(); return new IdentityKeyPair(new IdentityKey(new DjbECPublicKey(pair[0])), new DjbECPrivateKey(pair[1])); } return null; } public event OngetLocalRegistrationIdDelegate OngetLocalRegistrationId; public UInt32 GetLocalRegistrationId() { if (this.OngetLocalRegistrationId != null){ return this.OngetLocalRegistrationId(); } return 0; // FIXME: this isn't correct workaround only } /// <summary> /// Determine whether a remote client's identity is trusted. Convention is /// that the TextSecure protocol is 'trust on first use.' This means that /// an identity key is considered 'trusted' if there is no entry for the recipient /// in the local store, or if it matches the saved key for a recipient in the local /// store.Only if it mismatches an entry in the local store is it considered /// 'untrusted.' /// </summary> public event OnisTrustedIdentityDelegate OnisTrustedIdentity; public bool IsTrustedIdentity(string name, IdentityKey identityKey) { if (this.OnisTrustedIdentity != null){ return this.OnisTrustedIdentity(name, identityKey.serialize()); } return false; // FIXME: this isn't correct workaround only } public event OnsaveIdentityDelegate OnsaveIdentity; public bool SaveIdentity(string name, IdentityKey identityKey) { if (this.OnsaveIdentity != null){ return this.OnsaveIdentity(name, identityKey.serialize()); } return false; } public event OnstoreLocalDataDelegate OnstoreLocalData; public void StoreLocalData(uint registrationId, byte[] publickey, byte[] privatekey) { if (this.OnstoreLocalData != null) { this.OnstoreLocalData(registrationId, publickey, privatekey); } } //event delegates public delegate void OnstoreLocalDataDelegate(uint registrationId, byte[] publickey, byte[] privatekey); public delegate List<byte[]> OngetIdentityKeyPairDelegate(); public delegate UInt32 OngetLocalRegistrationIdDelegate(); public delegate bool OnisTrustedIdentityDelegate(string recipientId, byte[] identityKey); public delegate bool OnsaveIdentityDelegate(string recipientId, byte[] identityKey); #endregion #region sender_keys event and delegates public event OnstoreSenderKeyDelegate OnstoreSenderKey; protected void firestoreSenderKey(int senderKeyId, byte[] senderKeyRecord) { if (this.OnstoreSenderKey != null){ this.OnstoreSenderKey( senderKeyId, senderKeyRecord); } } public event OnloadSenderKeyDelegate OnloadSenderKey; protected byte[] fireloadSenderKey(int senderKeyId) { if (this.OnloadSenderKey != null){ return this.OnloadSenderKey(senderKeyId); } return null; } public event OnremoveSenderKeyDelegate OnremoveSenderKey; protected void fireremoveSenderKey(int senderKeyId) { if (this.OnremoveSenderKey != null){ this.OnremoveSenderKey(senderKeyId); } } public event OncontainsSenderKeyDelegate OncontainsSenderKey; protected bool firecontainsSenderKey(int senderKeyId) { if (this.OncontainsSenderKey != null){ return this.OncontainsSenderKey(senderKeyId); } return false; } //event delegates public delegate void OnstoreSenderKeyDelegate(int senderKeyId, byte[] senderKeyRecord); public delegate byte[] OnloadSenderKeyDelegate(int senderKeyId); public delegate void OnremoveSenderKeyDelegate(int senderKeyId); public delegate bool OncontainsSenderKeyDelegate(int senderKeyId); #endregion #endregion #region TESTING IN MEMORY STORE /* private InMemoryPreKeyStore preKeyStore = new InMemoryPreKeyStore(); private InMemorySessionStore sessionStore = new InMemorySessionStore(); private InMemorySignedPreKeyStore signedPreKeyStore = new InMemorySignedPreKeyStore(); private InMemoryIdentityKeyStore identityKeyStore; public List<byte[]> LoadPreKeys() { return null; } public void RemoveAllPreKeys() { } public void StorePreKeys(IList<PreKeyRecord> keys) { } public void StoreLocalData(uint registrationId, byte[] publickey, byte[] privatekey) { } public void InMemoryTestSetup(IdentityKeyPair identityKeyPair, uint registrationId) { this.identityKeyStore = new InMemoryIdentityKeyStore(identityKeyPair, registrationId); } public IdentityKeyPair GetIdentityKeyPair() { return identityKeyStore.GetIdentityKeyPair(); } public uint GetLocalRegistrationId() { return identityKeyStore.GetLocalRegistrationId(); } public bool SaveIdentity(String name, IdentityKey identityKey) { identityKeyStore.SaveIdentity(name, identityKey); return true; } public bool IsTrustedIdentity(String name, IdentityKey identityKey) { return identityKeyStore.IsTrustedIdentity(name, identityKey); } public PreKeyRecord LoadPreKey(uint preKeyId) { return preKeyStore.LoadPreKey(preKeyId); } public void StorePreKey(uint preKeyId, PreKeyRecord record) { preKeyStore.StorePreKey(preKeyId, record); } public bool ContainsPreKey(uint preKeyId) { return preKeyStore.ContainsPreKey(preKeyId); } public void RemovePreKey(uint preKeyId) { preKeyStore.RemovePreKey(preKeyId); } public SessionRecord LoadSession(AxolotlAddress address) { return sessionStore.LoadSession(address); } public List<uint> GetSubDeviceSessions(String name) { return sessionStore.GetSubDeviceSessions(name); } public void StoreSession(AxolotlAddress address, SessionRecord record) { sessionStore.StoreSession(address, record); } public bool ContainsSession(AxolotlAddress address) { return sessionStore.ContainsSession(address); } public void DeleteSession(AxolotlAddress address) { sessionStore.DeleteSession(address); } public void DeleteAllSessions(String name) { sessionStore.DeleteAllSessions(name); } public SignedPreKeyRecord LoadSignedPreKey(uint signedPreKeyId) { return signedPreKeyStore.LoadSignedPreKey(signedPreKeyId); } public List<SignedPreKeyRecord> LoadSignedPreKeys() { return signedPreKeyStore.LoadSignedPreKeys(); } public void StoreSignedPreKey(uint signedPreKeyId, SignedPreKeyRecord record) { signedPreKeyStore.StoreSignedPreKey(signedPreKeyId, record); } public bool ContainsSignedPreKey(uint signedPreKeyId) { return signedPreKeyStore.ContainsSignedPreKey(signedPreKeyId); } public void RemoveSignedPreKey(uint signedPreKeyId) { signedPreKeyStore.RemoveSignedPreKey(signedPreKeyId); } */ #endregion } /// <summary> /// NOT USED YET /// </summary> public class ExtraFunctions { public static byte[] SerializeToBytes<T>(T item) { var formatter = new BinaryFormatter(); using (var stream = new MemoryStream()) { formatter.Serialize(stream, item); stream.Seek(0, SeekOrigin.Begin); return stream.ToArray(); } } public static object DeserializeFromBytes(byte[] bytes) { var formatter = new BinaryFormatter(); using (var stream = new MemoryStream(bytes)) { return formatter.Deserialize(stream); } } public static byte[] GetBigEndianBytes(UInt32 val, bool isLittleEndian) { UInt32 bigEndian = val; if (isLittleEndian) { bigEndian = (val & 0x000000FFU) << 24 | (val & 0x0000FF00U) << 8 | (val & 0x00FF0000U) >> 8 | (val & 0xFF000000U) >> 24; } return BitConverter.GetBytes(bigEndian); } public static byte[] intToByteArray(int value) { byte[] b = new byte[4]; // for (int i = 0; i >> offset) & 0xFF); return b; } public static void writetofile(string pathtofile, string data) { using (StreamWriter writer = new StreamWriter(pathtofile, true)) { writer.WriteLine(data); } } } }
// -------------------------------------------------------------------------- // // File: BufferCache.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: BufferCache class implementation. // //--------------------------------------------------------------------------- using System; using System.Threading; using MS.Internal.Text.TextInterface; namespace MS.Internal.FontCache { /// <summary> /// A static, thread safe array cache used to minimize heap allocations. /// </summary> /// <remarks> /// Cached arrays are not zero initialized, and they may be larger than /// the requested number of elements. /// </remarks> internal static class BufferCache { //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// Attempts to release all allocated memory. Has no effect if the cache /// is locked by another thread. /// </summary> internal static void Reset() { if (Interlocked.Increment(ref _mutex) == 1) { _buffers = null; } Interlocked.Decrement(ref _mutex); } /// <summary> /// Returns a GlyphMetrics[]. /// </summary> /// <param name="length"> /// Minimum number of elements in the array. /// </param> internal static GlyphMetrics[] GetGlyphMetrics(int length) { GlyphMetrics[] glyphMetrics = (GlyphMetrics[])GetBuffer(length, GlyphMetricsIndex); if (glyphMetrics == null) { glyphMetrics = new GlyphMetrics[length]; } return glyphMetrics; } /// <summary> /// Releases a previously allocated GlyphMetrics[], possibly adding it /// to the cache. /// </summary> /// <remarks> /// It is not strictly necessary to call this method after receiving an /// array. The penalty is the performance hit of doing a heap allocation /// on the next request if this method is not called. /// </remarks> internal static void ReleaseGlyphMetrics(GlyphMetrics[] glyphMetrics) { ReleaseBuffer(glyphMetrics, GlyphMetricsIndex); } /// <summary> /// Returns a ushort[]. /// </summary> /// <param name="length"> /// Minimum number of elements in the array. /// </param> internal static ushort[] GetUShorts(int length) { ushort[] ushorts = (ushort[])GetBuffer(length, UShortsIndex); if (ushorts == null) { ushorts = new ushort[length]; } return ushorts; } /// <summary> /// Releases a previously allocated ushort[], possibly adding it /// to the cache. /// </summary> /// <remarks> /// It is not strictly necessary to call this method after receiving an /// array. The penalty is the performance hit of doing a heap allocation /// on the next request if this method is not called. /// </remarks> internal static void ReleaseUShorts(ushort[] ushorts) { ReleaseBuffer(ushorts, UShortsIndex); } /// <summary> /// Returns a uint[]. /// </summary> /// <param name="length"> /// Minimum number of elements in the array. /// </param> internal static uint[] GetUInts(int length) { uint[] uints = (uint[])GetBuffer(length, UIntsIndex); if (uints == null) { uints = new uint[length]; } return uints; } /// <summary> /// Releases a previously allocated uint[], possibly adding it /// to the cache. /// </summary> /// <remarks> /// It is not strictly necessary to call this method after receiving an /// array. The penalty is the performance hit of doing a heap allocation /// on the next request if this method is not called. /// </remarks> internal static void ReleaseUInts(uint[] uints) { ReleaseBuffer(uints, UIntsIndex); } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods /// <summary> /// Searches for an array in the cache. /// </summary> /// <param name="length"> /// Minimum number of elements in the array. /// </param> /// <param name="index"> /// Specifies the type of array. /// </param> /// <returns> /// A matching array if present, otherwise null. /// </returns> private static Array GetBuffer(int length, int index) { Array buffer = null; if (Interlocked.Increment(ref _mutex) == 1) { if (_buffers != null && _buffers[index] != null && length <= _buffers[index].Length) { buffer = _buffers[index]; _buffers[index] = null; } } Interlocked.Decrement(ref _mutex); return buffer; } /// <summary> /// Takes ownership of an array. /// </summary> /// <param name="buffer"> /// The array. May be null. /// </param> /// <param name="index"> /// Specifies the type of array. /// </param> private static void ReleaseBuffer(Array buffer, int index) { if (buffer != null) { if (Interlocked.Increment(ref _mutex) == 1) { if (_buffers == null) { _buffers = new Array[BuffersLength]; } if (_buffers[index] == null || (_buffers[index].Length < buffer.Length && buffer.Length <= MaxBufferLength)) { _buffers[index] = buffer; } } Interlocked.Decrement(ref _mutex); } } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // Max number of elements in any cached array. If a request if made for a larger array // it will always be allocated from the heap. private const int MaxBufferLength = 1024; // Indices in _buffers for each supported type. private const int GlyphMetricsIndex = 0; private const int UIntsIndex = 1; private const int UShortsIndex = 2; private const int BuffersLength = 3; // Guards access to _buffers. static private long _mutex; // Array of cached arrays, one bucker per supported type. // Currently, we cache just one array per type. A more general cache would hold N byte arrays. // However, we don't currently have any scenarios that hold more than one array of the same type // or more than two arrays of different types at the same time, so it is difficult to justify // making the implementation more complex. ComputeTypographyAvailabilities could benefit from // a more general cache (UnicodeRange.GetFullRange could use a cached array), but the savings // in profiled scenarios are small, ~16k for MSNBaml.exe. If we find a more compelling // scenario a change might be worthwhile. static private Array[] _buffers; #endregion Private Fields } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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; using System.Collections.Generic; using System.Collections.Specialized; using System.Runtime.InteropServices; using System.Text; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// A collection of metadata entries that can be exchanged during a call. /// gRPC supports these types of metadata: /// <list type="bullet"> /// <item><term>Request headers</term><description>are sent by the client at the beginning of a remote call before any request messages are sent.</description></item> /// <item><term>Response headers</term><description>are sent by the server at the beginning of a remote call handler before any response messages are sent.</description></item> /// <item><term>Response trailers</term><description>are sent by the server at the end of a remote call along with resulting call status.</description></item> /// </list> /// </summary> public sealed class Metadata : IList<Metadata.Entry> { /// <summary> /// All binary headers should have this suffix. /// </summary> public const string BinaryHeaderSuffix = "-bin"; /// <summary> /// An read-only instance of metadata containing no entries. /// </summary> public static readonly Metadata Empty = new Metadata().Freeze(); readonly List<Entry> entries; bool readOnly; /// <summary> /// Initializes a new instance of <c>Metadata</c>. /// </summary> public Metadata() { this.entries = new List<Entry>(); } /// <summary> /// Makes this object read-only. /// </summary> /// <returns>this object</returns> internal Metadata Freeze() { this.readOnly = true; return this; } // TODO: add support for access by key #region IList members public int IndexOf(Metadata.Entry item) { return entries.IndexOf(item); } public void Insert(int index, Metadata.Entry item) { CheckWriteable(); entries.Insert(index, item); } public void RemoveAt(int index) { CheckWriteable(); entries.RemoveAt(index); } public Metadata.Entry this[int index] { get { return entries[index]; } set { CheckWriteable(); entries[index] = value; } } public void Add(Metadata.Entry item) { CheckWriteable(); entries.Add(item); } public void Add(string key, string value) { Add(new Entry(key, value)); } public void Add(string key, byte[] valueBytes) { Add(new Entry(key, valueBytes)); } public void Clear() { CheckWriteable(); entries.Clear(); } public bool Contains(Metadata.Entry item) { return entries.Contains(item); } public void CopyTo(Metadata.Entry[] array, int arrayIndex) { entries.CopyTo(array, arrayIndex); } public int Count { get { return entries.Count; } } public bool IsReadOnly { get { return readOnly; } } public bool Remove(Metadata.Entry item) { CheckWriteable(); return entries.Remove(item); } public IEnumerator<Metadata.Entry> GetEnumerator() { return entries.GetEnumerator(); } IEnumerator System.Collections.IEnumerable.GetEnumerator() { return entries.GetEnumerator(); } private void CheckWriteable() { Preconditions.CheckState(!readOnly, "Object is read only"); } #endregion /// <summary> /// Metadata entry /// </summary> public struct Entry { private static readonly Encoding Encoding = Encoding.ASCII; readonly string key; readonly string value; readonly byte[] valueBytes; private Entry(string key, string value, byte[] valueBytes) { this.key = key; this.value = value; this.valueBytes = valueBytes; } /// <summary> /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct with a binary value. /// </summary> /// <param name="key">Metadata key, needs to have suffix indicating a binary valued metadata entry.</param> /// <param name="valueBytes">Value bytes.</param> public Entry(string key, byte[] valueBytes) { this.key = NormalizeKey(key); Preconditions.CheckArgument(this.key.EndsWith(BinaryHeaderSuffix), "Key for binary valued metadata entry needs to have suffix indicating binary value."); this.value = null; Preconditions.CheckNotNull(valueBytes, "valueBytes"); this.valueBytes = new byte[valueBytes.Length]; Buffer.BlockCopy(valueBytes, 0, this.valueBytes, 0, valueBytes.Length); // defensive copy to guarantee immutability } /// <summary> /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct holding an ASCII value. /// </summary> /// <param name="key">Metadata key, must not use suffix indicating a binary valued metadata entry.</param> /// <param name="value">Value string. Only ASCII characters are allowed.</param> public Entry(string key, string value) { this.key = NormalizeKey(key); Preconditions.CheckArgument(!this.key.EndsWith(BinaryHeaderSuffix), "Key for ASCII valued metadata entry cannot have suffix indicating binary value."); this.value = Preconditions.CheckNotNull(value, "value"); this.valueBytes = null; } /// <summary> /// Gets the metadata entry key. /// </summary> public string Key { get { return this.key; } } /// <summary> /// Gets the binary value of this metadata entry. /// </summary> public byte[] ValueBytes { get { if (valueBytes == null) { return Encoding.GetBytes(value); } // defensive copy to guarantee immutability var bytes = new byte[valueBytes.Length]; Buffer.BlockCopy(valueBytes, 0, bytes, 0, valueBytes.Length); return bytes; } } /// <summary> /// Gets the string value of this metadata entry. /// </summary> public string Value { get { Preconditions.CheckState(!IsBinary, "Cannot access string value of a binary metadata entry"); return value ?? Encoding.GetString(valueBytes); } } /// <summary> /// Returns <c>true</c> if this entry is a binary-value entry. /// </summary> public bool IsBinary { get { return value == null; } } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="Grpc.Core.Metadata.Entry"/>. /// </summary> public override string ToString() { if (IsBinary) { return string.Format("[Entry: key={0}, valueBytes={1}]", key, valueBytes); } return string.Format("[Entry: key={0}, value={1}]", key, value); } /// <summary> /// Gets the serialized value for this entry. For binary metadata entries, this leaks /// the internal <c>valueBytes</c> byte array and caller must not change contents of it. /// </summary> internal byte[] GetSerializedValueUnsafe() { return valueBytes ?? Encoding.GetBytes(value); } /// <summary> /// Creates a binary value or ascii value metadata entry from data received from the native layer. /// We trust C core to give us well-formed data, so we don't perform any checks or defensive copying. /// </summary> internal static Entry CreateUnsafe(string key, byte[] valueBytes) { if (key.EndsWith(BinaryHeaderSuffix)) { return new Entry(key, null, valueBytes); } return new Entry(key, Encoding.GetString(valueBytes), null); } private static string NormalizeKey(string key) { return Preconditions.CheckNotNull(key, "key").ToLower(); } } } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using Glass.Mapper.Pipelines.DataMapperResolver; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.Configuration.Attributes; using Glass.Mapper.Sc.DataMappers; using NUnit.Framework; using Sitecore.Data.Managers; using Sitecore.Globalization; using Sitecore.SecurityModel; namespace Glass.Mapper.Sc.Integration.DataMappers { public class SitecoreLinkedMapperFixture : AbstractMapperFixture { #region Property - ReadOnly [Test] public void ReadOnly_ReturnsTrue() { //Assign var mapper = new SitecoreLinkedMapper(); //Act var result = mapper.ReadOnly; //Assert Assert.IsTrue(result); } #endregion #region Method - CanHandle [Test] public void CanHandle_IsEnumerableOfMappedClassWithLinkedConfig_ReturnsTrue() { //Assign var config = new SitecoreLinkedConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds"); var mapper = new SitecoreLinkedMapper(); var context = Context.Create(Utilities.CreateStandardResolver()); context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration")); //Act var result = mapper.CanHandle(config, context); //Assert Assert.IsTrue(result); } [Test] public void CanHandle_IsEnumerableOfNotMappedClassWithLinkedConfig_ReturnsTrueOnDemand() { //Assign var config = new SitecoreLinkedConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("StubNotMappeds"); var mapper = new SitecoreLinkedMapper(); var context = Context.Create(Utilities.CreateStandardResolver()); context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration")); //Act var result = mapper.CanHandle(config, context); //Assert Assert.IsTrue(result); } [Test] public void CanHandle_IsListOfMappedClassWithLinkedConfig_ReturnsFalse() { //Assign var config = new SitecoreLinkedConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("StubMappedsList"); var mapper = new SitecoreLinkedMapper(); var context = Context.Create(Utilities.CreateStandardResolver()); context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration")); //Act var result = mapper.CanHandle(config, context); //Assert Assert.IsFalse(result); } [Test] public void CanHandle_IsEnumerableOfMappedClassWithWrongConfig_ReturnsFalse() { //Assign var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds"); var mapper = new SitecoreLinkedMapper(); var context = Context.Create(Utilities.CreateStandardResolver()); context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration")); //Act var result = mapper.CanHandle(config, context); //Assert Assert.IsFalse(result); } [Test] public void CanHandle_IsNonGenericOfMappedClassWithLinkedConfig_ReturnsTrue() { //Assign var config = new SitecoreLinkedConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("StubMapped"); var mapper = new SitecoreLinkedMapper(); var context = Context.Create(Utilities.CreateStandardResolver()); context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration")); //Act var result = mapper.CanHandle(config, context); //Assert Assert.IsFalse(result); } #endregion #region Method - MapToProperty [Test] public void MapToProperty_GetAllReferrers_ReferrersListReturned() { //Assign var language = LanguageManager.GetLanguage("af-ZA"); var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreLinkedMapper/Target"); var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreLinkedMapper/Source", language ); using (new ItemEditing(source, true)) { source[FieldName] = "<a href=\"~/link.aspx?_id=216C0015-8626-4951-9730-85BCA34EC2A3&amp;_z=z\">Source</a>"; } var config = new SitecoreLinkedConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds"); config.Option = SitecoreLinkedOptions.Referrers; var context = Context.Create(Utilities.CreateStandardResolver()); context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration")); var mapper = new SitecoreLinkedMapper(); mapper.Setup(new DataMapperResolverArgs(context, config)); var service = new SitecoreService(Database, context); //Act var result = mapper.MapToProperty(new SitecoreDataMappingContext(null, item, service)) as IEnumerable<StubMapped>; //Assert Assert.AreEqual(1, result.Count()); Assert.AreEqual(source.ID.Guid, result.First().Id); Assert.AreEqual(language, result.First().Language); } [Test] public void MapToProperty_GetAllReferences_ReferrersListReturned() { //Act var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreLinkedMapper/Target"); //ME - when getting templates you have to disable the role manager using (new SecurityDisabler()) { var template = Database.GetItem("/sitecore/templates/Tests/DataMappers/DataMappersSingleField"); var config = new SitecoreLinkedConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds"); config.Option = SitecoreLinkedOptions.References; var context = Context.Create(Utilities.CreateStandardResolver()); context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration")); var mapper = new SitecoreLinkedMapper(); mapper.Setup(new DataMapperResolverArgs(context, config)); var service = new SitecoreService(Database, context); //Act var result = mapper.MapToProperty(new SitecoreDataMappingContext(null, item, service)) as IEnumerable<StubMapped>; //Assert Assert.AreEqual(1, result.Count()); Assert.AreEqual(template.ID.Guid, result.First().Id); } } [Test] public void MapToProperty_GetAll_ReferrersListReturned() { //Assign var item = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreLinkedMapper/Target"); var language = LanguageManager.GetLanguage("af-ZA"); var source = Database.GetItem("/sitecore/content/Tests/DataMappers/SitecoreLinkedMapper/Source", language); using (new ItemEditing(source, true)) { source[FieldName] = "<a href=\"~/link.aspx?_id=216C0015-8626-4951-9730-85BCA34EC2A3&amp;_z=z\">Source</a>"; } //ME - when getting templates you have to disable the role manager using (new SecurityDisabler()) { var template = Database.GetItem("/sitecore/templates/Tests/DataMappers/DataMappersSingleField"); var config = new SitecoreLinkedConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("StubMappeds"); config.Option = SitecoreLinkedOptions.All; var context = Context.Create(Utilities.CreateStandardResolver()); context.Load(new SitecoreAttributeConfigurationLoader("Glass.Mapper.Sc.Integration")); var mapper = new SitecoreLinkedMapper(); mapper.Setup(new DataMapperResolverArgs(context, config)); var service = new SitecoreService(Database, context); //Act var result = mapper.MapToProperty(new SitecoreDataMappingContext(null, item, service)) as IEnumerable<StubMapped>; //Assert Assert.AreEqual(2, result.Count()); Assert.AreEqual(template.ID.Guid, result.First().Id); Assert.AreEqual(source.ID.Guid, result.Skip(1).First().Id); Assert.AreEqual(source.Language, result.Skip(1).First().Language); } } #endregion #region Stubs [SitecoreType] public class StubMapped { [SitecoreId] public virtual Guid Id { get; set; } [SitecoreInfo(SitecoreInfoType.Language)] public virtual Language Language { get; set; } } public class StubNotMapped { } public class StubClass { public IEnumerable<StubMapped> StubMappeds { get; set; } public IEnumerable<StubNotMapped> StubNotMappeds { get; set; } public List<StubMapped> StubMappedsList { get; set; } public StubMapped StubMapped { get; set; } } #endregion } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects.Scene { public unsafe class OpaqueNode : RootNode { public OpaqueNode() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.OpaqueNodeCreateInstance()); } public OpaqueNode(uint pId) : base(pId) { } public OpaqueNode(string pName) : base(pName) { } public OpaqueNode(IntPtr pObjPtr) : base(pObjPtr) { } public OpaqueNode(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public OpaqueNode(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _OpaqueNodeGetColorSrc(IntPtr opaqueNode); private static _OpaqueNodeGetColorSrc _OpaqueNodeGetColorSrcFunc; internal static IntPtr OpaqueNodeGetColorSrc(IntPtr opaqueNode) { if (_OpaqueNodeGetColorSrcFunc == null) { _OpaqueNodeGetColorSrcFunc = (_OpaqueNodeGetColorSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeGetColorSrc"), typeof(_OpaqueNodeGetColorSrc)); } return _OpaqueNodeGetColorSrcFunc(opaqueNode); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _OpaqueNodeSetColorSrc(IntPtr opaqueNode, string src); private static _OpaqueNodeSetColorSrc _OpaqueNodeSetColorSrcFunc; internal static void OpaqueNodeSetColorSrc(IntPtr opaqueNode, string src) { if (_OpaqueNodeSetColorSrcFunc == null) { _OpaqueNodeSetColorSrcFunc = (_OpaqueNodeSetColorSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeSetColorSrc"), typeof(_OpaqueNodeSetColorSrc)); } _OpaqueNodeSetColorSrcFunc(opaqueNode, src); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _OpaqueNodeGetNormalSrc(IntPtr opaqueNode); private static _OpaqueNodeGetNormalSrc _OpaqueNodeGetNormalSrcFunc; internal static IntPtr OpaqueNodeGetNormalSrc(IntPtr opaqueNode) { if (_OpaqueNodeGetNormalSrcFunc == null) { _OpaqueNodeGetNormalSrcFunc = (_OpaqueNodeGetNormalSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeGetNormalSrc"), typeof(_OpaqueNodeGetNormalSrc)); } return _OpaqueNodeGetNormalSrcFunc(opaqueNode); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _OpaqueNodeSetNormalSrc(IntPtr opaqueNode, string src); private static _OpaqueNodeSetNormalSrc _OpaqueNodeSetNormalSrcFunc; internal static void OpaqueNodeSetNormalSrc(IntPtr opaqueNode, string src) { if (_OpaqueNodeSetNormalSrcFunc == null) { _OpaqueNodeSetNormalSrcFunc = (_OpaqueNodeSetNormalSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeSetNormalSrc"), typeof(_OpaqueNodeSetNormalSrc)); } _OpaqueNodeSetNormalSrcFunc(opaqueNode, src); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _OpaqueNodeGetMetallicSrc(IntPtr opaqueNode); private static _OpaqueNodeGetMetallicSrc _OpaqueNodeGetMetallicSrcFunc; internal static IntPtr OpaqueNodeGetMetallicSrc(IntPtr opaqueNode) { if (_OpaqueNodeGetMetallicSrcFunc == null) { _OpaqueNodeGetMetallicSrcFunc = (_OpaqueNodeGetMetallicSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeGetMetallicSrc"), typeof(_OpaqueNodeGetMetallicSrc)); } return _OpaqueNodeGetMetallicSrcFunc(opaqueNode); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _OpaqueNodeSetMetallicSrc(IntPtr opaqueNode, string src); private static _OpaqueNodeSetMetallicSrc _OpaqueNodeSetMetallicSrcFunc; internal static void OpaqueNodeSetMetallicSrc(IntPtr opaqueNode, string src) { if (_OpaqueNodeSetMetallicSrcFunc == null) { _OpaqueNodeSetMetallicSrcFunc = (_OpaqueNodeSetMetallicSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeSetMetallicSrc"), typeof(_OpaqueNodeSetMetallicSrc)); } _OpaqueNodeSetMetallicSrcFunc(opaqueNode, src); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _OpaqueNodeGetRoughnessSrc(IntPtr opaqueNode); private static _OpaqueNodeGetRoughnessSrc _OpaqueNodeGetRoughnessSrcFunc; internal static IntPtr OpaqueNodeGetRoughnessSrc(IntPtr opaqueNode) { if (_OpaqueNodeGetRoughnessSrcFunc == null) { _OpaqueNodeGetRoughnessSrcFunc = (_OpaqueNodeGetRoughnessSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeGetRoughnessSrc"), typeof(_OpaqueNodeGetRoughnessSrc)); } return _OpaqueNodeGetRoughnessSrcFunc(opaqueNode); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _OpaqueNodeSetRoughnessSrc(IntPtr opaqueNode, string src); private static _OpaqueNodeSetRoughnessSrc _OpaqueNodeSetRoughnessSrcFunc; internal static void OpaqueNodeSetRoughnessSrc(IntPtr opaqueNode, string src) { if (_OpaqueNodeSetRoughnessSrcFunc == null) { _OpaqueNodeSetRoughnessSrcFunc = (_OpaqueNodeSetRoughnessSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeSetRoughnessSrc"), typeof(_OpaqueNodeSetRoughnessSrc)); } _OpaqueNodeSetRoughnessSrcFunc(opaqueNode, src); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _OpaqueNodeGetWorldPosOffsetSrc(IntPtr opaqueNode); private static _OpaqueNodeGetWorldPosOffsetSrc _OpaqueNodeGetWorldPosOffsetSrcFunc; internal static IntPtr OpaqueNodeGetWorldPosOffsetSrc(IntPtr opaqueNode) { if (_OpaqueNodeGetWorldPosOffsetSrcFunc == null) { _OpaqueNodeGetWorldPosOffsetSrcFunc = (_OpaqueNodeGetWorldPosOffsetSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeGetWorldPosOffsetSrc"), typeof(_OpaqueNodeGetWorldPosOffsetSrc)); } return _OpaqueNodeGetWorldPosOffsetSrcFunc(opaqueNode); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _OpaqueNodeSetWorldPosOffsetSrc(IntPtr opaqueNode, string src); private static _OpaqueNodeSetWorldPosOffsetSrc _OpaqueNodeSetWorldPosOffsetSrcFunc; internal static void OpaqueNodeSetWorldPosOffsetSrc(IntPtr opaqueNode, string src) { if (_OpaqueNodeSetWorldPosOffsetSrcFunc == null) { _OpaqueNodeSetWorldPosOffsetSrcFunc = (_OpaqueNodeSetWorldPosOffsetSrc)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeSetWorldPosOffsetSrc"), typeof(_OpaqueNodeSetWorldPosOffsetSrc)); } _OpaqueNodeSetWorldPosOffsetSrcFunc(opaqueNode, src); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _OpaqueNodeCreateInstance(); private static _OpaqueNodeCreateInstance _OpaqueNodeCreateInstanceFunc; internal static IntPtr OpaqueNodeCreateInstance() { if (_OpaqueNodeCreateInstanceFunc == null) { _OpaqueNodeCreateInstanceFunc = (_OpaqueNodeCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "OpaqueNodeCreateInstance"), typeof(_OpaqueNodeCreateInstance)); } return _OpaqueNodeCreateInstanceFunc(); } } #endregion #region Properties public string ColorSrc { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.OpaqueNodeGetColorSrc(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.OpaqueNodeSetColorSrc(ObjectPtr->ObjPtr, value); } } public string NormalSrc { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.OpaqueNodeGetNormalSrc(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.OpaqueNodeSetNormalSrc(ObjectPtr->ObjPtr, value); } } public string MetallicSrc { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.OpaqueNodeGetMetallicSrc(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.OpaqueNodeSetMetallicSrc(ObjectPtr->ObjPtr, value); } } public string RoughnessSrc { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.OpaqueNodeGetRoughnessSrc(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.OpaqueNodeSetRoughnessSrc(ObjectPtr->ObjPtr, value); } } public string WorldPosOffsetSrc { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.OpaqueNodeGetWorldPosOffsetSrc(ObjectPtr->ObjPtr)); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.OpaqueNodeSetWorldPosOffsetSrc(ObjectPtr->ObjPtr, value); } } #endregion #region Methods #endregion } }
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace FunWithSqlServer.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), PasswordHash = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), SecurityStamp = table.Column<string>(nullable: true), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles", column: "UserId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using EventFeedback.Web.Api.Areas.HelpPage.ModelDescriptions; using EventFeedback.Web.Api.Areas.HelpPage.Models; namespace EventFeedback.Web.Api.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/datastore/v1/datastore.proto // Original file comments: // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace Google.Cloud.Datastore.V1 { /// <summary> /// Each RPC normalizes the partition IDs of the keys in its input entities, /// and always returns entities with keys with normalized partition IDs. /// This applies to all keys and entities, including those in values, except keys /// with both an empty path and an empty or unset partition ID. Normalization of /// input keys sets the project ID (if not already set) to the project ID from /// the request. /// </summary> public static partial class Datastore { static readonly string __ServiceName = "google.datastore.v1.Datastore"; static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.LookupRequest> __Marshaller_LookupRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.LookupRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.LookupResponse> __Marshaller_LookupResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.LookupResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.RunQueryRequest> __Marshaller_RunQueryRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.RunQueryRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.RunQueryResponse> __Marshaller_RunQueryResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.RunQueryResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.BeginTransactionRequest> __Marshaller_BeginTransactionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.BeginTransactionRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.BeginTransactionResponse> __Marshaller_BeginTransactionResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.BeginTransactionResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.CommitRequest> __Marshaller_CommitRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.CommitRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.CommitResponse> __Marshaller_CommitResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.CommitResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.RollbackRequest> __Marshaller_RollbackRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.RollbackRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.RollbackResponse> __Marshaller_RollbackResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.RollbackResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.AllocateIdsRequest> __Marshaller_AllocateIdsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.AllocateIdsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.AllocateIdsResponse> __Marshaller_AllocateIdsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.AllocateIdsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.ReserveIdsRequest> __Marshaller_ReserveIdsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.ReserveIdsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.ReserveIdsResponse> __Marshaller_ReserveIdsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.ReserveIdsResponse.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.LookupRequest, global::Google.Cloud.Datastore.V1.LookupResponse> __Method_Lookup = new grpc::Method<global::Google.Cloud.Datastore.V1.LookupRequest, global::Google.Cloud.Datastore.V1.LookupResponse>( grpc::MethodType.Unary, __ServiceName, "Lookup", __Marshaller_LookupRequest, __Marshaller_LookupResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.RunQueryRequest, global::Google.Cloud.Datastore.V1.RunQueryResponse> __Method_RunQuery = new grpc::Method<global::Google.Cloud.Datastore.V1.RunQueryRequest, global::Google.Cloud.Datastore.V1.RunQueryResponse>( grpc::MethodType.Unary, __ServiceName, "RunQuery", __Marshaller_RunQueryRequest, __Marshaller_RunQueryResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.BeginTransactionRequest, global::Google.Cloud.Datastore.V1.BeginTransactionResponse> __Method_BeginTransaction = new grpc::Method<global::Google.Cloud.Datastore.V1.BeginTransactionRequest, global::Google.Cloud.Datastore.V1.BeginTransactionResponse>( grpc::MethodType.Unary, __ServiceName, "BeginTransaction", __Marshaller_BeginTransactionRequest, __Marshaller_BeginTransactionResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.CommitRequest, global::Google.Cloud.Datastore.V1.CommitResponse> __Method_Commit = new grpc::Method<global::Google.Cloud.Datastore.V1.CommitRequest, global::Google.Cloud.Datastore.V1.CommitResponse>( grpc::MethodType.Unary, __ServiceName, "Commit", __Marshaller_CommitRequest, __Marshaller_CommitResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.RollbackRequest, global::Google.Cloud.Datastore.V1.RollbackResponse> __Method_Rollback = new grpc::Method<global::Google.Cloud.Datastore.V1.RollbackRequest, global::Google.Cloud.Datastore.V1.RollbackResponse>( grpc::MethodType.Unary, __ServiceName, "Rollback", __Marshaller_RollbackRequest, __Marshaller_RollbackResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.AllocateIdsRequest, global::Google.Cloud.Datastore.V1.AllocateIdsResponse> __Method_AllocateIds = new grpc::Method<global::Google.Cloud.Datastore.V1.AllocateIdsRequest, global::Google.Cloud.Datastore.V1.AllocateIdsResponse>( grpc::MethodType.Unary, __ServiceName, "AllocateIds", __Marshaller_AllocateIdsRequest, __Marshaller_AllocateIdsResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.ReserveIdsRequest, global::Google.Cloud.Datastore.V1.ReserveIdsResponse> __Method_ReserveIds = new grpc::Method<global::Google.Cloud.Datastore.V1.ReserveIdsRequest, global::Google.Cloud.Datastore.V1.ReserveIdsResponse>( grpc::MethodType.Unary, __ServiceName, "ReserveIds", __Marshaller_ReserveIdsRequest, __Marshaller_ReserveIdsResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of Datastore</summary> public abstract partial class DatastoreBase { /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.LookupResponse> Lookup(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.RunQueryResponse> RunQuery(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.BeginTransactionResponse> BeginTransaction(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.CommitResponse> Commit(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.RollbackResponse> Rollback(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.AllocateIdsResponse> AllocateIds(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Prevents the supplied keys' IDs from being auto-allocated by Cloud /// Datastore. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.ReserveIdsResponse> ReserveIds(global::Google.Cloud.Datastore.V1.ReserveIdsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for Datastore</summary> public partial class DatastoreClient : grpc::ClientBase<DatastoreClient> { /// <summary>Creates a new client for Datastore</summary> /// <param name="channel">The channel to use to make remote calls.</param> public DatastoreClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for Datastore that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public DatastoreClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected DatastoreClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected DatastoreClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.LookupResponse Lookup(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Lookup(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.LookupResponse Lookup(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Lookup, null, options, request); } /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.LookupResponse> LookupAsync(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return LookupAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.LookupResponse> LookupAsync(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Lookup, null, options, request); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.RunQueryResponse RunQuery(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RunQuery(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.RunQueryResponse RunQuery(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_RunQuery, null, options, request); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.RunQueryResponse> RunQueryAsync(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RunQueryAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.RunQueryResponse> RunQueryAsync(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_RunQuery, null, options, request); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.BeginTransactionResponse BeginTransaction(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return BeginTransaction(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.BeginTransactionResponse BeginTransaction(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_BeginTransaction, null, options, request); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.BeginTransactionResponse> BeginTransactionAsync(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return BeginTransactionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.BeginTransactionResponse> BeginTransactionAsync(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_BeginTransaction, null, options, request); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.CommitResponse Commit(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Commit(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.CommitResponse Commit(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Commit, null, options, request); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.CommitResponse> CommitAsync(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CommitAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.CommitResponse> CommitAsync(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Commit, null, options, request); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.RollbackResponse Rollback(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Rollback(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.RollbackResponse Rollback(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Rollback, null, options, request); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.RollbackResponse> RollbackAsync(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RollbackAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.RollbackResponse> RollbackAsync(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Rollback, null, options, request); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.AllocateIdsResponse AllocateIds(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AllocateIds(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.AllocateIdsResponse AllocateIds(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AllocateIds, null, options, request); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.AllocateIdsResponse> AllocateIdsAsync(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AllocateIdsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.AllocateIdsResponse> AllocateIdsAsync(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AllocateIds, null, options, request); } /// <summary> /// Prevents the supplied keys' IDs from being auto-allocated by Cloud /// Datastore. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.ReserveIdsResponse ReserveIds(global::Google.Cloud.Datastore.V1.ReserveIdsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ReserveIds(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Prevents the supplied keys' IDs from being auto-allocated by Cloud /// Datastore. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.ReserveIdsResponse ReserveIds(global::Google.Cloud.Datastore.V1.ReserveIdsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ReserveIds, null, options, request); } /// <summary> /// Prevents the supplied keys' IDs from being auto-allocated by Cloud /// Datastore. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.ReserveIdsResponse> ReserveIdsAsync(global::Google.Cloud.Datastore.V1.ReserveIdsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ReserveIdsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Prevents the supplied keys' IDs from being auto-allocated by Cloud /// Datastore. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.ReserveIdsResponse> ReserveIdsAsync(global::Google.Cloud.Datastore.V1.ReserveIdsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ReserveIds, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override DatastoreClient NewInstance(ClientBaseConfiguration configuration) { return new DatastoreClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(DatastoreBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_Lookup, serviceImpl.Lookup) .AddMethod(__Method_RunQuery, serviceImpl.RunQuery) .AddMethod(__Method_BeginTransaction, serviceImpl.BeginTransaction) .AddMethod(__Method_Commit, serviceImpl.Commit) .AddMethod(__Method_Rollback, serviceImpl.Rollback) .AddMethod(__Method_AllocateIds, serviceImpl.AllocateIds) .AddMethod(__Method_ReserveIds, serviceImpl.ReserveIds).Build(); } } } #endregion
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Collections; using System.IO; using System.Net; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Soap; using System.Text; using System.Text.RegularExpressions; using System.Xml; namespace Hotcakes.Shipping.UpsFreight { [Serializable] public sealed class XmlTools { private XmlTools() { } /// ----------------------------------------------------------------------------- /// <summary> /// builds XML access key for UPS requests /// </summary> /// <param name="settings"></param> /// <returns></returns> /// <remarks> /// </remarks> /// ----------------------------------------------------------------------------- public static string BuildAccessKey(UPSFreightSettings settings) { var sXML = string.Empty; var strWriter = new StringWriter(); var xw = new XmlTextWriter(strWriter) { Formatting = Formatting.Indented, Indentation = 3 }; xw.WriteStartDocument(); //-------------------------------------------- // Agreement Request xw.WriteStartElement("AccessRequest"); xw.WriteElementString("AccessLicenseNumber", settings.License); xw.WriteElementString("UserId", settings.UserID); xw.WriteElementString("Password", settings.Password); xw.WriteEndElement(); // End Agreement Request //-------------------------------------------- xw.WriteEndDocument(); xw.Flush(); xw.Close(); sXML = strWriter.GetStringBuilder().ToString(); xw = null; return sXML; } public static string ReadHtmlPage_POST(string sURL, string sPostData) { HttpWebResponse objResponse; HttpWebRequest objRequest; var result = string.Empty; byte[] bytes; // Encode Post Stream try { bytes = Encoding.Default.GetBytes(sPostData); } catch (Exception Ex1) { throw new ArgumentException("Setup Bytes Exception: " + Ex1.Message); } // Create Request try { objRequest = (HttpWebRequest) WebRequest.Create(sURL); objRequest.Method = "POST"; objRequest.ContentLength = bytes.Length; objRequest.ContentType = "application/x-www-form-urlencoded"; } catch (Exception E) { throw new ArgumentException("Error Creating Web Request: " + E.Message); } // Dump Post Data to Request Stream try { var OutStream = objRequest.GetRequestStream(); OutStream.Write(bytes, 0, bytes.Length); OutStream.Close(); } catch (Exception Ex) { throw new ArgumentException("Error Posting Data: " + Ex.Message + " " + Ex.Source + " " + Ex.StackTrace); } finally { } // Read Response try { objResponse = (HttpWebResponse) objRequest.GetResponse(); var sr = new StreamReader(objResponse.GetResponseStream(), Encoding.Default, true); result += sr.ReadToEnd(); sr.Close(); } catch (Exception Exx) { throw new ArgumentException("Stream Reader Error: " + Exx.Message + " " + Exx.Source); } return result; } public static string CleanPhoneNumber(string sNumber) { var input = sNumber.Trim(); input = Regex.Replace(input, @"[^0-9]", string.Empty); return input; } public static string TrimToLength(string input, int maxLength) { if (input == null) { return string.Empty; } if (input.Length < 1) { return input; } if (maxLength < 0) { maxLength = input.Length; } if (input.Length > maxLength) { return input.Substring(0, maxLength); } return input; } #region " Conversion Methods " public static string ConvertCurrencyCodeToString(CurrencyCode c) { var result = "USD"; switch (c) { case CurrencyCode.AustalianDollar: result = "AUD"; break; case CurrencyCode.Baht: result = "THB"; break; case CurrencyCode.BritishPounds: result = "GBP"; break; case CurrencyCode.CanadianDollar: result = "CAD"; break; case CurrencyCode.DenmarkKrone: result = "DKK"; break; case CurrencyCode.Drachma: result = "GRD"; break; case CurrencyCode.Euro: result = "EUR"; break; case CurrencyCode.HongKongDollar: result = "HKD"; break; case CurrencyCode.NewZealandDollar: result = "NZD"; break; case CurrencyCode.NorwayKrone: result = "NOK"; break; case CurrencyCode.Peso: result = "MXN"; break; case CurrencyCode.Ringgit: result = "MYR"; break; case CurrencyCode.SingaporeDollar: result = "SGD"; break; case CurrencyCode.SwedishKrona: result = "SEK"; break; case CurrencyCode.SwissFranc: result = "CHF"; break; case CurrencyCode.TaiwanDollar: result = "TWD"; break; case CurrencyCode.UsDollar: result = "USD"; break; default: result = "USD"; break; } return result; } public static CurrencyCode ConvertStringToCurrencyCode(string s) { var result = CurrencyCode.UsDollar; switch (s.ToUpper()) { case "AUD": result = CurrencyCode.AustalianDollar; break; case "THB": result = CurrencyCode.Baht; break; case "GBP": result = CurrencyCode.BritishPounds; break; case "CAD": result = CurrencyCode.CanadianDollar; break; case "DKK": result = CurrencyCode.DenmarkKrone; break; case "GRD": result = CurrencyCode.Drachma; break; case "EUR": result = CurrencyCode.Euro; break; case "HKD": result = CurrencyCode.HongKongDollar; break; case "NZD": result = CurrencyCode.NewZealandDollar; break; case "NOK": result = CurrencyCode.NorwayKrone; break; case "MXN": result = CurrencyCode.Peso; break; case "MYR": result = CurrencyCode.Ringgit; break; case "SGD": result = CurrencyCode.SingaporeDollar; break; case "SEK": result = CurrencyCode.SwedishKrona; break; case "CHF": result = CurrencyCode.SwissFranc; break; case "TWD": result = CurrencyCode.TaiwanDollar; break; case "USD": result = CurrencyCode.UsDollar; break; default: result = CurrencyCode.UsDollar; break; } return result; } public static UnitsType ConvertStringToUnits(string s) { var result = UnitsType.Imperial; switch (s.ToUpper()) { case "LBS": result = UnitsType.Imperial; break; case "IN": result = UnitsType.Imperial; break; case "KGS": result = UnitsType.Metric; break; case "CM": result = UnitsType.Metric; break; default: result = UnitsType.Imperial; break; } return result; } #endregion #region " Write Entity Methods " public static bool WriteShipperXml(ref XmlTextWriter xw, ref Entity e) { return WriteEntity(ref xw, ref e, EntityType.Shipper); } public static bool WriteShipToXml(ref XmlTextWriter xw, ref Entity e) { return WriteEntity(ref xw, ref e, EntityType.ShipTo); } public static bool WriteShipFromXml(ref XmlTextWriter xw, ref Entity e) { return WriteEntity(ref xw, ref e, EntityType.ShipFrom); } private static bool WriteEntity(ref XmlTextWriter xw, ref Entity e, EntityType et) { var result = true; //-------------------------------------------- // Start Opening Tag switch (et) { case EntityType.ShipFrom: xw.WriteStartElement("ShipFrom"); xw.WriteElementString("CompanyName", TrimToLength(e.CompanyOrContactName, 35)); break; case EntityType.Shipper: xw.WriteStartElement("Shipper"); xw.WriteElementString("Name", TrimToLength(e.CompanyOrContactName, 35)); xw.WriteElementString("ShipperNumber", e.AccountNumber); if (e.TaxIDNumber != string.Empty) { xw.WriteElementString("TaxIdentificationNumber", e.TaxIDNumber); } break; case EntityType.ShipTo: xw.WriteStartElement("ShipTo"); xw.WriteElementString("CompanyName", TrimToLength(e.CompanyOrContactName, 35)); if (e.TaxIDNumber != string.Empty) { xw.WriteElementString("TaxIdentificationNumber", e.TaxIDNumber); } break; } if (e.AttentionName != string.Empty) { xw.WriteElementString("AttentionName", TrimToLength(e.AttentionName, 35)); } if (e.PhoneNumber != string.Empty) { xw.WriteElementString("PhoneNumber", e.PhoneNumber); } if (e.FaxNumber != string.Empty) { xw.WriteElementString("FaxNumber", e.FaxNumber); } //------------------------------------------- // Start Address xw.WriteStartElement("Address"); xw.WriteElementString("AddressLine1", TrimToLength(e.AddressLine1, 35)); if (e.AddressLine2 != string.Empty) { xw.WriteElementString("AddressLine2", TrimToLength(e.AddressLine2, 35)); } if (e.AddressLine3 != string.Empty) { xw.WriteElementString("AddressLine3", TrimToLength(e.AddressLine3, 35)); } xw.WriteElementString("City", e.City); if (e.StateProvinceCode != string.Empty) { xw.WriteElementString("StateProvinceCode", TrimToLength(e.StateProvinceCode, 5)); } if (e.PostalCode != string.Empty) { xw.WriteElementString("PostalCode", TrimToLength(e.PostalCode, 10)); } xw.WriteElementString("CountryCode", TrimToLength(e.CountryCode, 2)); if (et == EntityType.ShipTo) { if (e.ResidentialAddress) { xw.WriteElementString("ResidentialAddress", ""); } } xw.WriteEndElement(); // End Address //------------------------------------------- xw.WriteEndElement(); // End Opening Tag //-------------------------------------------- return result; } #endregion #region " XPath Parsing Methods " public static string XPathToString(ref XmlDocument xdoc, string xpath) { var result = string.Empty; var node = xdoc.SelectSingleNode(xpath); if (node != null) { result = node.InnerText; } return result; } public static decimal XPathToInteger(ref XmlDocument xdoc, string xpath) { var result = 0; var node = xdoc.SelectSingleNode(xpath); if (node != null) { result = int.Parse(node.InnerText); } return result; } public static decimal XPathToDecimal(ref XmlDocument xdoc, string xpath) { decimal result = 0; var node = xdoc.SelectSingleNode(xpath); if (node != null) { result = decimal.Parse(node.InnerText); } return result; } public static CurrencyCode XPathToCurrencyCode(ref XmlDocument xdoc, string xpath) { var result = CurrencyCode.UsDollar; var node = xdoc.SelectSingleNode(xpath); if (node != null) { result = ConvertStringToCurrencyCode(node.InnerText); } return result; } public static UnitsType XPathToUnits(ref XmlDocument xdoc, string xpath) { var result = UnitsType.Imperial; var node = xdoc.SelectSingleNode(xpath); if (node != null) { result = ConvertStringToUnits(node.InnerText); } return result; } #endregion #region "Soap Methods" public static string SOAPSerializer(Object objToSoap) { IFormatter formatter; MemoryStream memStream = null; string strObject = ""; try { memStream = new MemoryStream(); formatter = new SoapFormatter(); formatter.Serialize(memStream, objToSoap); strObject = Encoding.ASCII.GetString(memStream.GetBuffer()); //Check for the null terminator character int index = strObject.IndexOf("\0"); if (index > 0) { strObject = strObject.Substring(0, index); } } catch (Exception exception) { throw exception; } finally { if (memStream != null) memStream.Close(); } return strObject; } public static string BuildSoapRequest(UPSFreightSettings settings, string bodyElement) { StringBuilder xml = new StringBuilder(); xml.Append(@"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" "); xml.Append(@"xmlns:v1=""http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0"" "); xml.Append(@"xmlns:v11=""http://www.ups.com/XMLSchema/XOLTWS/FreightRate/v1.0"" "); xml.Append(@"xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" "); xml.Append(@"xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" "); xml.Append(@"xmlns:v12=""http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0"">"); xml.Append("<soapenv:Header>"); xml.Append("<v1:UPSSecurity>"); xml.Append("<v1:UsernameToken>"); xml.Append("<v1:Username>Tusharupendoventures</v1:Username>"); xml.Append("<v1:Password>pendo@123</v1:Password>"); xml.Append("</v1:UsernameToken>"); xml.Append("<v1:ServiceAccessToken>"); xml.Append("<v1:AccessLicenseNumber>4A24R5</v1:AccessLicenseNumber>"); xml.Append("</v1:ServiceAccessToken>"); xml.Append("</v1:UPSSecurity>"); xml.Append("</soapenv:Header>"); xml.Append("<soapenv:Body>"); xml.Append(bodyElement); xml.Append("</soapenv:Body>"); xml.Append("</soapenv:Envelope>"); return xml.ToString(); } public static string SOAPWebRequest_POST(string apiURL,string soapData) { XmlDocument soapEnvelopeXml = new XmlDocument(); soapEnvelopeXml.LoadXml(soapData); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(apiURL); webRequest.Headers.Add(@"SOAP:Action"); webRequest.ContentType = "text/xml;charset=\"utf-8\""; webRequest.Accept = "text/xml"; webRequest.Method = "POST"; using (Stream stream = webRequest.GetRequestStream()) { soapEnvelopeXml.Save(stream); } // System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12; using (WebResponse response = webRequest.GetResponse()) { using (StreamReader rd = new StreamReader(response.GetResponseStream())) { string soapResult = rd.ReadToEnd(); return soapResult; //return webRequest; } } } public static object ParseSoapResponse(string response) { XmlDocument responseDoc = new XmlDocument(); responseDoc.LoadXml(response); if (responseDoc.GetElementsByTagName("freightRate:FreightRateResponse") != null && responseDoc.GetElementsByTagName("freightRate:FreightRateResponse").Count > 0) { XmlNode node = responseDoc.GetElementsByTagName("freightRate:FreightRateResponse").Item(0); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(FreightRateResponse)); FreightRateResponse freightRateResponse = (FreightRateResponse)serializer.Deserialize(new StringReader(node.OuterXml.ToString())); return freightRateResponse; } else { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Envelope)); Envelope errorResponse = (Envelope)serializer.Deserialize(new StringReader(responseDoc.OuterXml)); return errorResponse; } } #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; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions.Interpreter { internal abstract partial class Instruction { public const int UnknownInstrIndex = int.MaxValue; public virtual int ConsumedStack { get { return 0; } } public virtual int ProducedStack { get { return 0; } } public virtual int ConsumedContinuations { get { return 0; } } public virtual int ProducedContinuations { get { return 0; } } public int StackBalance { get { return ProducedStack - ConsumedStack; } } public int ContinuationsBalance { get { return ProducedContinuations - ConsumedContinuations; } } public abstract int Run(InterpretedFrame frame); public abstract string InstructionName { get; } public override string ToString() { return InstructionName + "()"; } public virtual string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) { return ToString(); } public virtual object GetDebugCookie(LightCompiler compiler) { return null; } // throws NRE when o is null protected static void NullCheck(object o) { if (o == null) { o.GetType(); } } } internal class NullCheckInstruction : Instruction { public static readonly Instruction Instance = new NullCheckInstruction(); private NullCheckInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Unbox"; } } public override int Run(InterpretedFrame frame) { if (frame.Peek() == null) { throw new NullReferenceException(); } return +1; } } internal abstract class NotInstruction : Instruction { public static Instruction _Bool, _Int64, _Int32, _Int16, _UInt64, _UInt32, _UInt16, _Byte, _SByte; private NotInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Not"; } } private class BoolNot : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((bool)value ? ScriptingRuntimeHelpers.False : ScriptingRuntimeHelpers.True); } return +1; } } private class Int64Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((Int64)~(Int64)value); } return +1; } } private class Int32Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((Int32)(~(Int32)value)); } return +1; } } private class Int16Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((Int16)(~(Int16)value)); } return +1; } } private class UInt64Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((UInt64)(~(UInt64)value)); } return +1; } } private class UInt32Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((UInt32)(~(UInt32)value)); } return +1; } } private class UInt16Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((UInt16)(~(UInt16)value)); } return +1; } } private class ByteNot : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((object)(Byte)(~(Byte)value)); } return +1; } } private class SByteNot : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((object)(SByte)(~(SByte)value)); } return +1; } } public static Instruction Create(Type t) { switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(t))) { case TypeCode.Boolean: return _Bool ?? (_Bool = new BoolNot()); case TypeCode.Int64: return _Int64 ?? (_Int64 = new Int64Not()); case TypeCode.Int32: return _Int32 ?? (_Int32 = new Int32Not()); case TypeCode.Int16: return _Int16 ?? (_Int16 = new Int16Not()); case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new UInt64Not()); case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new UInt32Not()); case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new UInt16Not()); case TypeCode.Byte: return _Byte ?? (_Byte = new ByteNot()); case TypeCode.SByte: return _SByte ?? (_SByte = new SByteNot()); default: throw new InvalidOperationException("Not for " + t.ToString()); } } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace Newtonsoft.Json.Linq { public static class __JToken { public static IObservable<Newtonsoft.Json.JsonReader> CreateReader(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.CreateReader()); } public static IObservable<Newtonsoft.Json.Linq.JToken> FromObject(IObservable<System.Object> o) { return Observable.Select(o, (oLambda) => Newtonsoft.Json.Linq.JToken.FromObject(oLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> FromObject(IObservable<System.Object> o, IObservable<Newtonsoft.Json.JsonSerializer> jsonSerializer) { return Observable.Zip(o, jsonSerializer, (oLambda, jsonSerializerLambda) => Newtonsoft.Json.Linq.JToken.FromObject(oLambda, jsonSerializerLambda)); } public static IObservable<T> ToObject<T>(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) where T : class { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.ToObject<T>()); } public static IObservable<System.Object> ToObject(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Type> objectType) { return Observable.Zip(JTokenValue, objectType, (JTokenValueLambda, objectTypeLambda) => JTokenValueLambda.ToObject(objectTypeLambda)); } public static IObservable<T> ToObject<T>(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<Newtonsoft.Json.JsonSerializer> jsonSerializer) { return Observable.Zip(JTokenValue, jsonSerializer, (JTokenValueLambda, jsonSerializerLambda) => JTokenValueLambda.ToObject<T>(jsonSerializerLambda)); } public static IObservable<System.Object> ToObject(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Type> objectType, IObservable<Newtonsoft.Json.JsonSerializer> jsonSerializer) { return Observable.Zip(JTokenValue, objectType, jsonSerializer, (JTokenValueLambda, objectTypeLambda, jsonSerializerLambda) => JTokenValueLambda.ToObject(objectTypeLambda, jsonSerializerLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> ReadFrom(IObservable<Newtonsoft.Json.JsonReader> reader) { return Observable.Select(reader, (readerLambda) => Newtonsoft.Json.Linq.JToken.ReadFrom(readerLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> ReadFrom(IObservable<Newtonsoft.Json.JsonReader> reader, IObservable<Newtonsoft.Json.Linq.JsonLoadSettings> settings) { return Observable.Zip(reader, settings, (readerLambda, settingsLambda) => Newtonsoft.Json.Linq.JToken.ReadFrom(readerLambda, settingsLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> Parse(IObservable<System.String> json) { return Observable.Select(json, (jsonLambda) => Newtonsoft.Json.Linq.JToken.Parse(jsonLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> Parse(IObservable<System.String> json, IObservable<Newtonsoft.Json.Linq.JsonLoadSettings> settings) { return Observable.Zip(json, settings, (jsonLambda, settingsLambda) => Newtonsoft.Json.Linq.JToken.Parse(jsonLambda, settingsLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> Load(IObservable<Newtonsoft.Json.JsonReader> reader, IObservable<Newtonsoft.Json.Linq.JsonLoadSettings> settings) { return Observable.Zip(reader, settings, (readerLambda, settingsLambda) => Newtonsoft.Json.Linq.JToken.Load(readerLambda, settingsLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> Load(IObservable<Newtonsoft.Json.JsonReader> reader) { return Observable.Select(reader, (readerLambda) => Newtonsoft.Json.Linq.JToken.Load(readerLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> SelectToken(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.String> path) { return Observable.Zip(JTokenValue, path, (JTokenValueLambda, pathLambda) => JTokenValueLambda.SelectToken(pathLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> SelectToken(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.String> path, IObservable<System.Boolean> errorWhenNoMatch) { return Observable.Zip(JTokenValue, path, errorWhenNoMatch, (JTokenValueLambda, pathLambda, errorWhenNoMatchLambda) => JTokenValueLambda.SelectToken(pathLambda, errorWhenNoMatchLambda)); } public static IObservable<System.Collections.Generic.IEnumerable<Newtonsoft.Json.Linq.JToken>> SelectTokens(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.String> path) { return Observable.Zip(JTokenValue, path, (JTokenValueLambda, pathLambda) => JTokenValueLambda.SelectTokens(pathLambda)); } public static IObservable<System.Collections.Generic.IEnumerable<Newtonsoft.Json.Linq.JToken>> SelectTokens(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.String> path, IObservable<System.Boolean> errorWhenNoMatch) { return Observable.Zip(JTokenValue, path, errorWhenNoMatch, (JTokenValueLambda, pathLambda, errorWhenNoMatchLambda) => JTokenValueLambda.SelectTokens(pathLambda, errorWhenNoMatchLambda)); } public static IObservable<Newtonsoft.Json.Linq.JToken> DeepClone(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.DeepClone()); } public static IObservable<System.Reactive.Unit> AddAnnotation(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Object> annotation) { return ObservableExt.ZipExecute(JTokenValue, annotation, (JTokenValueLambda, annotationLambda) => JTokenValueLambda.AddAnnotation(annotationLambda)); } public static IObservable<T> Annotation<T>(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) where T : class { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Annotation<T>()); } public static IObservable<System.Object> Annotation(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Type> type) { return Observable.Zip(JTokenValue, type, (JTokenValueLambda, typeLambda) => JTokenValueLambda.Annotation(typeLambda)); } public static IObservable<IEnumerable<T>> Annotations<T>(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) where T : class { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Annotations<T>()); } public static IObservable<System.Collections.Generic.IEnumerable<System.Object>> Annotations(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Type> type) { return Observable.Zip(JTokenValue, type, (JTokenValueLambda, typeLambda) => JTokenValueLambda.Annotations(typeLambda)); } public static IObservable<System.Reactive.Unit> RemoveAnnotations<T>(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) where T : class { return Observable.Do(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.RemoveAnnotations<T>()).ToUnit(); } public static IObservable<System.Reactive.Unit> RemoveAnnotations(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Type> type) { return ObservableExt.ZipExecute(JTokenValue, type, (JTokenValueLambda, typeLambda) => JTokenValueLambda.RemoveAnnotations(typeLambda)); } public static IObservable<System.Boolean> DeepEquals(IObservable<Newtonsoft.Json.Linq.JToken> t1, IObservable<Newtonsoft.Json.Linq.JToken> t2) { return Observable.Zip(t1, t2, (t1Lambda, t2Lambda) => Newtonsoft.Json.Linq.JToken.DeepEquals(t1Lambda, t2Lambda)); } public static IObservable<System.Reactive.Unit> AddAfterSelf(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Object> content) { return ObservableExt.ZipExecute(JTokenValue, content, (JTokenValueLambda, contentLambda) => JTokenValueLambda.AddAfterSelf(contentLambda)); } public static IObservable<System.Reactive.Unit> AddBeforeSelf(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Object> content) { return ObservableExt.ZipExecute(JTokenValue, content, (JTokenValueLambda, contentLambda) => JTokenValueLambda.AddBeforeSelf(contentLambda)); } public static IObservable<System.Collections.Generic.IEnumerable<Newtonsoft.Json.Linq.JToken>> Ancestors(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Ancestors()); } public static IObservable<System.Collections.Generic.IEnumerable<Newtonsoft.Json.Linq.JToken>> AncestorsAndSelf(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.AncestorsAndSelf()); } public static IObservable<System.Collections.Generic.IEnumerable<Newtonsoft.Json.Linq.JToken>> AfterSelf(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.AfterSelf()); } public static IObservable<System.Collections.Generic.IEnumerable<Newtonsoft.Json.Linq.JToken>> BeforeSelf(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.BeforeSelf()); } public static IObservable<T> Value<T>(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Object> key) { return Observable.Zip(JTokenValue, key, (JTokenValueLambda, keyLambda) => JTokenValueLambda.Value<T>(keyLambda)); } public static IObservable<Newtonsoft.Json.Linq.JEnumerable<Newtonsoft.Json.Linq.JToken>> Children(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Children()); } public static IObservable<JEnumerable<T>> Children<T>(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) where T : Newtonsoft.Json.Linq.JToken { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Children<T>()); } public static IObservable<IEnumerable<T>> Values<T>(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) where T : Newtonsoft.Json.Linq.JToken { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Values<T>()); } public static IObservable<System.Reactive.Unit> Remove(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Do(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Remove()).ToUnit(); } public static IObservable<System.Reactive.Unit> Replace(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<Newtonsoft.Json.Linq.JToken> value) { return ObservableExt.ZipExecute(JTokenValue, value, (JTokenValueLambda, valueLambda) => JTokenValueLambda.Replace(valueLambda)); } public static IObservable<System.Reactive.Unit> WriteTo(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<Newtonsoft.Json.JsonWriter> writer, IObservable<Newtonsoft.Json.JsonConverter[]> converters) { return ObservableExt.ZipExecute(JTokenValue, writer, converters, (JTokenValueLambda, writerLambda, convertersLambda) => JTokenValueLambda.WriteTo(writerLambda, convertersLambda)); } public static IObservable<System.String> ToString(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.ToString()); } public static IObservable<System.String> ToString(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<Newtonsoft.Json.Formatting> formatting, IObservable<Newtonsoft.Json.JsonConverter[]> converters) { return Observable.Zip(JTokenValue, formatting, converters, (JTokenValueLambda, formattingLambda, convertersLambda) => JTokenValueLambda.ToString(formattingLambda, convertersLambda)); } public static IObservable<Newtonsoft.Json.Linq.JTokenEqualityComparer> get_EqualityComparer() { return ObservableExt.Factory(() => Newtonsoft.Json.Linq.JToken.EqualityComparer); } public static IObservable<Newtonsoft.Json.Linq.JContainer> get_Parent(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Parent); } public static IObservable<Newtonsoft.Json.Linq.JToken> get_Root(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Root); } public static IObservable<Newtonsoft.Json.Linq.JTokenType> get_Type(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Type); } public static IObservable<System.Boolean> get_HasValues(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.HasValues); } public static IObservable<Newtonsoft.Json.Linq.JToken> get_Next(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Next); } public static IObservable<Newtonsoft.Json.Linq.JToken> get_Previous(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Previous); } public static IObservable<System.String> get_Path(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Path); } public static IObservable<Newtonsoft.Json.Linq.JToken> get_Item(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Object> key) { return Observable.Zip(JTokenValue, key, (JTokenValueLambda, keyLambda) => JTokenValueLambda[keyLambda]); } public static IObservable<Newtonsoft.Json.Linq.JToken> get_First(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.First); } public static IObservable<Newtonsoft.Json.Linq.JToken> get_Last(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue) { return Observable.Select(JTokenValue, (JTokenValueLambda) => JTokenValueLambda.Last); } public static IObservable<System.Reactive.Unit> set_Item(this IObservable<Newtonsoft.Json.Linq.JToken> JTokenValue, IObservable<System.Object> key, IObservable<Newtonsoft.Json.Linq.JToken> value) { return ObservableExt.ZipExecute(JTokenValue, key, value, (JTokenValueLambda, keyLambda, valueLambda) => JTokenValueLambda[keyLambda] = valueLambda); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.PythonTools.Analysis; namespace Microsoft.PythonTools.Interpreter.Default { class CPythonType : IPythonType, ILocatedMember { private readonly string _typeName, _doc; private readonly bool _includeInModule; private readonly BuiltinTypeId _typeId; private readonly CPythonModule _module; private readonly List<IPythonType> _bases; private readonly IPythonType[] _mro; private readonly bool _isBuiltin; private readonly Dictionary<string, IMember> _members = new Dictionary<string, IMember>(); private readonly bool _hasLocation; private readonly int _line, _column; public CPythonType(IMemberContainer parent, ITypeDatabaseReader typeDb, string typeName, Dictionary<string, object> typeTable, BuiltinTypeId typeId) { Debug.Assert(parent is CPythonType || parent is CPythonModule); Debug.Assert(!typeId.IsVirtualId()); _typeName = typeName; _typeId = typeId; _module = GetDeclaringModule(parent); object value; if (typeTable.TryGetValue("is_hidden", out value)) { _includeInModule = !Convert.ToBoolean(value); } else { _includeInModule = true; } if (typeTable.TryGetValue("doc", out value)) { _doc = value as string; } if (typeTable.TryGetValue("builtin", out value)) { _isBuiltin = Convert.ToBoolean(value); } else { _isBuiltin = true; } if (typeTable.TryGetValue("bases", out value)) { var basesList = (List<object>)value; if (basesList != null) { _bases = new List<IPythonType>(); foreach (var baseType in basesList) { typeDb.LookupType(baseType, StoreBase); } } } if (typeTable.TryGetValue("mro", out value)) { var mroList = (List<object>)value; if (mroList != null && mroList.Count >= 1) { _mro = new IPythonType[mroList.Count]; // Many scraped types have invalid MRO entries because they // report their own module/name incorrectly. Since the first // item in the MRO is always self, we set it now. If the MRO // has a resolvable entry it will replace this one. _mro[0] = this; for (int i = 0; i < mroList.Count; ++i) { var capturedI = i; typeDb.LookupType(mroList[i], t => _mro[capturedI] = t); } } } if (typeTable.TryGetValue("members", out value)) { var membersTable = (Dictionary<string, object>)value; if (membersTable != null) { LoadMembers(typeDb, membersTable); } } _hasLocation = PythonTypeDatabase.TryGetLocation(typeTable, ref _line, ref _column); } private CPythonModule GetDeclaringModule(IMemberContainer parent) { return parent as CPythonModule ?? (CPythonModule)((CPythonType)parent).DeclaringModule; } private void StoreBase(IPythonType type) { if (type != null && _bases != null) { _bases.Add(type); } } private void LoadMembers(ITypeDatabaseReader typeDb, Dictionary<string, object> membersTable) { foreach (var memberEntry in membersTable) { var memberName = memberEntry.Key; var memberValue = memberEntry.Value as Dictionary<string, object>; if (memberValue != null) { _members[memberName] = null; typeDb.ReadMember(memberName, memberValue, StoreMember, this); } } } private void StoreMember(string memberName, IMember value) { _members[memberName] = value; } public bool IncludeInModule { get { return _includeInModule; } } #region IPythonType Members public IMember GetMember(IModuleContext context, string name) { IMember res; if (_members.TryGetValue(name, out res)) { return res; } if (_mro != null) { foreach (var mroType in _mro.OfType<CPythonType>()) { if (mroType._members.TryGetValue(name, out res)) { return res; } } } else if (_bases != null) { foreach (var baseType in _bases) { res = baseType.GetMember(context, name); if (res != null) { return res; } } } return null; } public IPythonFunction GetConstructors() { IMember member; if (_members.TryGetValue("__new__", out member) && member is IPythonFunction && ((IPythonFunction)member).Overloads.Count > 0) { return member as IPythonFunction; } else if (TypeId != BuiltinTypeId.Object && _members.TryGetValue("__init__", out member)) { if (member is CPythonMethodDescriptor) { return ((CPythonMethodDescriptor)member).Function; } return member as IPythonFunction; } return null; } public IList<IPythonType> Mro { get { return _mro; } } public string Name { get { if (TypeId != BuiltinTypeId.Unknown) { return _module.TypeDb.GetBuiltinTypeName(TypeId); } return _typeName; } } public string Documentation { get { return _doc ?? ""; } } public BuiltinTypeId TypeId { get { return _typeId; } } public IPythonModule DeclaringModule { get { return _module; } } public bool IsBuiltin { get { return _isBuiltin; } } #endregion #region IMemberContainer Members public IEnumerable<string> GetMemberNames(IModuleContext moduleContext) { var seen = new HashSet<string>(); foreach (var key in _members.Keys) { if (seen.Add(key)) { yield return key; } } if (_mro != null) { foreach (var type in _mro.OfType<CPythonType>()) { foreach (var key in type._members.Keys) { if (seen.Add(key)) { yield return key; } } } } else if (_bases != null) { foreach (var type in _bases) { foreach (var key in type.GetMemberNames(moduleContext)) { if (seen.Add(key)) { yield return key; } } } } } #endregion #region IMember Members public PythonMemberType MemberType { get { return PythonMemberType.Class; } } #endregion public override string ToString() { return String.Format("CPythonType('{0}')", Name); } #region ILocatedMember Members public IEnumerable<LocationInfo> Locations { get { if (_hasLocation) { yield return new LocationInfo(_module, _line, _column); } } } #endregion } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. // 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.Runtime.CompilerServices; namespace System { /// <summary> /// Implementation of the "System.String" class /// </summary> public sealed class String : IEnumerable, IEnumerable<char> { /// <summary> /// Length /// </summary> internal int length; private char start_char; public int Length { get { return length; } } public static string Empty = ""; internal unsafe char* first_char { get { fixed (char* c = &start_char) { return c; } } } [IndexerName("Chars")] public unsafe char this[int index] { get { if (index < 0 || index >= length) throw new IndexOutOfRangeException(); fixed (char* c = &start_char) { return c[index]; } } } [MethodImpl(MethodImplOptions.InternalCall)] public extern String(char c, int count); [MethodImpl(MethodImplOptions.InternalCall)] public extern String(char[] value); [MethodImpl(MethodImplOptions.InternalCall)] public extern String(char[] value, int startIndex, int length); [MethodImpl(MethodImplOptions.InternalCall)] public extern unsafe String(sbyte* value, int startIndex, int length); [MethodImpl(MethodImplOptions.InternalCall)] public extern unsafe String(sbyte* value); //[MethodImpl(MethodImplOptions.InternalCall)] //public unsafe extern String(sbyte* value, int startIndex, int length, Encoding enc); [MethodImpl(MethodImplOptions.InternalCall)] public unsafe extern String(char* value); [MethodImpl(MethodImplOptions.InternalCall)] public unsafe extern String(char* value, int startIndex, int length); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string InternalAllocateString(int length); private static unsafe string CreateString(char c, int count) { string result = InternalAllocateString(count); char* chars = result.first_char; while (count > 0) { *chars = c; count--; chars++; } return result; } private static string CreateString(char[] value) { return CreateString(value, 0, value.Length); } private static unsafe string CreateString(char[] value, int startIndex, int length) { if (length == 0) return Empty; string result = InternalAllocateString(length); char* chars = result.first_char; for (int index = startIndex; index < startIndex + length; index++) { *chars = value[index]; chars++; } return result; } private static unsafe string CreateString(string source, int startIndex, int length) { if (source.Length == 0) return Empty; string result = InternalAllocateString(length); char* chars = result.first_char; for (int index = startIndex; index < startIndex + length; index++) { *chars = source[index]; chars++; } return result; } private static unsafe string CreateString(sbyte* value, int startIndex, int length) { if (length == 0) return Empty; string result = InternalAllocateString(length); char* chars = result.first_char; value += startIndex; for (int index = 0; index < length; index++) { *chars = (char)*value; chars++; value++; } return result; } private static unsafe string CreateString(sbyte* value) { int length = 0; sbyte* at = value; while (*at != 0) { length++; } if (length == 0) return Empty; string result = InternalAllocateString(length); char* chars = result.first_char; for (int index = 0; index < length; index++) { *chars = (char)*value; chars++; value++; } return result; } private static unsafe string CreateString(char* value, int startIndex, int length) { if (length == 0) return InternalAllocateString(0); string result = InternalAllocateString(length); char* chars = result.first_char; value += startIndex; for (int index = 0; index < length; index++) { *chars = *value; chars++; value++; } return result; } private static unsafe string CreateString(char* value) { int length = 0; char* at = value; while (*at != 0) { length++; } if (length == 0) return Empty; string result = InternalAllocateString(length); char* chars = result.first_char; for (int index = 0; index < length; index++) { *chars = *value; chars++; value++; } return result; } public bool Equals(string i) { return Equals(this, i); } public override bool Equals(object o) { if (!(o is string)) return false; string other = (string)o; return other == this; } public static bool operator ==(string a, string b) { return Equals(a, b); } public static bool operator !=(string a, string b) { return !Equals(a, b); } public static unsafe bool Equals(string a, string b) { if (a == null || b == null) return false; if (a.length != b.length) return false; char* pa = a.first_char; char* pb = b.first_char; for (int i = 0; i < a.Length; ++i) if (pa[i] != pb[i]) return false; return true; } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return this; } public unsafe string ToUpper() { string result = InternalAllocateString(length); char* chars = result.first_char; char* self = first_char; for (int i = 0; i < length; i++) { if (self[i] >= 97 && self[i] <= 122) *chars = (char)(self[i] - 32); else *chars = self[i]; chars++; } return result; } public unsafe string ToLower() { string result = InternalAllocateString(length); char* chars = result.first_char; char* self = first_char; for (int i = 0; i < length; i++) { if (self[i] >= 65 && self[i] <= 90) *chars = (char)(self[i] + 32); else *chars = self[i]; chars++; } return result; } // TODO: Seems some compiler bugs prevent the original algorithms from working... public unsafe static string Concat(string a, string b) { string result = InternalAllocateString(a.length + b.length); char* chars = result.first_char; char* aPtr = a.first_char; char* bPtr = b.first_char; for (int i = 0; i < a.length; i++) { *chars = aPtr[i]; chars++; } for (int i = 0; i < b.length; i++) { *chars = bPtr[i]; chars++; } return result; } public unsafe static string Concat(string a, string b, string c) { string result = InternalAllocateString(a.length + b.length + c.length); char* chars = result.first_char; char* aPtr = a.first_char; char* bPtr = b.first_char; char* cPtr = c.first_char; for (int i = 0; i < a.length; i++) { *chars = aPtr[i]; chars++; } for (int i = 0; i < b.length; i++) { *chars = bPtr[i]; chars++; } for (int i = 0; i < c.length; i++) { *chars = cPtr[i]; chars++; } return result; } public unsafe static string Concat(string a, string b, string c, string d) { string result = InternalAllocateString(a.length + b.length + c.length + d.length); char* chars = result.first_char; char* aPtr = a.first_char; char* bPtr = b.first_char; char* cPtr = c.first_char; char* dPtr = d.first_char; for (int i = 0; i < a.length; i++) { *chars = aPtr[i]; chars++; } for (int i = 0; i < b.length; i++) { *chars = bPtr[i]; chars++; } for (int i = 0; i < c.length; i++) { *chars = cPtr[i]; chars++; } for (int i = 0; i < d.length; i++) { *chars = dPtr[i]; chars++; } return result; } public static string Concat(object a) { return a.ToString(); } public static string Concat(object a, object b) { return Concat(a.ToString(), b.ToString()); } public static string Concat(object a, object b, object c) { return Concat(a.ToString(), b.ToString(), c.ToString()); } public static string Concat(object a, object b, object c, object d) { return Concat(a.ToString(), b.ToString(), c.ToString(), d.ToString()); } public static string Concat(params object[] args) { if (args.Length == 0) return Empty; string result = args[0].ToString(); for (int i = 1; i < args.Length; ++i) result = Concat(result, args[i].ToString()); return result; } public static string Concat(string[] objects) { if (objects.Length == 0) return Empty; string result = objects[0].ToString(); for (int i = 1; i < objects.Length; ++i) result = Concat(result, objects[i].ToString()); return result; } public unsafe string Substring(int startIndex) { if (startIndex == 0) return Empty; // FIXME: Following line does not compile correctly if (startIndex < 0 || startIndex > length) throw new ArgumentOutOfRangeException("startIndex"); if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex"); if (startIndex > length) throw new ArgumentOutOfRangeException("startIndex"); int newlen = length - startIndex; string result = InternalAllocateString(newlen); char* chars = result.first_char; for (int index = 0; index < newlen; index++) *chars++ = this[startIndex + index]; return result; } public unsafe string Substring(int startIndex, int length) { if (length < 0) throw new ArgumentOutOfRangeException("length", "< 0"); if (startIndex < 0 || startIndex > this.length) throw new ArgumentOutOfRangeException("startIndex"); string result = InternalAllocateString(length); char* chars = result.first_char; for (int index = 0; index < length; index++) *chars++ = this[startIndex + index]; return result; } public static bool IsNullOrEmpty(string value) { return (value == null) || (value.Length == 0); } public int IndexOf(string value) { if (length == 0) return -1; return IndexOfImpl(value, 0, length); } public int IndexOf(char value) { if (length == 0) return -1; return IndexOfImpl(value, 0, length); } public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, length - startIndex); } public int IndexOf(char value, int startIndex, int count) { if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException("count", "< 0"); if (startIndex > length - count) throw new ArgumentOutOfRangeException("startIndex + count > this.length"); if ((startIndex == 0 && length == 0) || (startIndex == length) || (count == 0)) return -1; return IndexOfImpl(value, startIndex, count); } public int IndexOfAny(char[] anyOf) { if (anyOf == null) throw new ArgumentNullException("anyOf"); if (length == 0) return -1; return IndexOfAnyImpl(anyOf, 0, length); } public int IndexOfAny(char[] anyOf, int startIndex) { if (anyOf == null) throw new ArgumentNullException("anyOf"); if (startIndex < 0 || startIndex > length) throw new ArgumentOutOfRangeException("startIndex"); return IndexOfAnyImpl(anyOf, startIndex, length - startIndex); } public int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException("anyOf"); if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex", "< 0"); if (count < 0) throw new ArgumentOutOfRangeException("count", "< 0"); if (startIndex > length - count) throw new ArgumentOutOfRangeException("startIndex + count > this.length"); return IndexOfAnyImpl(anyOf, startIndex, count); } public int LastIndexOfAny(char[] anyOf) { if (anyOf == null) throw new ArgumentNullException("anyOf"); return InternalLastIndexOfAny(anyOf, length - 1, length); } public int LastIndexOfAny(char[] anyOf, int startIndex) { if (anyOf == null) throw new ArgumentNullException("anyOf"); if (startIndex < 0 || startIndex >= length) throw new ArgumentOutOfRangeException(); if (length == 0) return -1; return IndexOfAnyImpl(anyOf, startIndex, startIndex + 1); } public int LastIndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new ArgumentNullException("anyOf"); if ((startIndex < 0) || (startIndex >= Length)) throw new ArgumentOutOfRangeException("startIndex", "< 0 || > this.Length"); if ((count < 0) || (count > Length)) throw new ArgumentOutOfRangeException("count", "< 0 || > this.Length"); if (startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException("startIndex - count + 1 < 0"); if (length == 0) return -1; return InternalLastIndexOfAny(anyOf, startIndex, count); } public int LastIndexOf(char value) { if (length == 0) return -1; return LastIndexOfImpl(value, length - 1, length); } public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public int LastIndexOf(char value, int startIndex, int count) { if (startIndex == 0 && length == 0) return -1; if ((startIndex < 0) || (startIndex >= Length)) throw new ArgumentOutOfRangeException("startIndex", "< 0 || >= this.Length"); if ((count < 0) || (count > Length)) throw new ArgumentOutOfRangeException("count", "< 0 || > this.Length"); if (startIndex - count + 1 < 0) throw new ArgumentOutOfRangeException("startIndex - count + 1 < 0"); return LastIndexOfImpl(value, startIndex, count); } private int IndexOfImpl(char value, int startIndex, int count) { for (int i = startIndex; i < count; i++) if (this[i] == value) return i; return -1; } private int IndexOfImpl(string value, int startIndex, int count) { for (int i = startIndex; i < count; i++) { bool found = true; for (int n = 0; n < value.length; n++) { if (this[i + n] != value[n]) { found = false; break; } } if (found) return i; } return -1; } private int IndexOfAnyImpl(char[] anyOf, int startIndex, int count) { for (int i = 0; i < count; i++) for (int loop = 0; loop != anyOf.Length; loop++) if (this[startIndex + i] == anyOf[loop]) return startIndex + i; return -1; } private int LastIndexOfImpl(char value, int startIndex, int count) { for (int i = 0; i < count; i++) if (this[startIndex + i] == value) return startIndex + i; return -1; } private int InternalLastIndexOfAny(char[] anyOf, int startIndex, int count) { for (int i = count - 1; i >= 0; i--) for (int loop = 0; loop != anyOf.Length; loop++) if (this[startIndex + i] == anyOf[loop]) return startIndex + i; return -1; } IEnumerator IEnumerable.GetEnumerator() { return new CharEnumerator(this); } IEnumerator<char> IEnumerable<char>.GetEnumerator() { return new CharEnumerator(this); } private const int TrimHead = 0; private const int TrimTail = 1; private const int TrimBoth = 2; /// <summary> /// Removes a set of characters from the end of this string. /// </summary> /// <param name="trimChars">Characters to remove.</param> /// <returns>Trimmed string.</returns> public string TrimEnd(char[] trimChars) { if (null == trimChars || trimChars.Length == 0) { return TrimHelper(TrimTail); } return TrimHelper(trimChars, TrimTail); } public string TrimEnd() { return TrimHelper(TrimTail); } /// <summary> /// Trims the whitespace from both ends of the string. /// Whitespace is defined by Char.IsWhiteSpace. /// </summary> /// <returns>Trimmed string.</returns> public string Trim() { return TrimHelper(TrimBoth); } private string TrimHelper(int trimType) { //end will point to the first non-trimmed character on the right //start will point to the first non-trimmed character on the Left int end = Length - 1; int start = 0; //Trim specified characters. if (trimType != TrimTail) { for (start = 0; start < Length; start++) { if (!char.IsWhiteSpace(this[start])) break; } } if (trimType != TrimHead) { for (end = Length - 1; end >= start; end--) { if (!char.IsWhiteSpace(this[end])) break; } } return CreateTrimmedString(start, end); } private string TrimHelper(char[] trimChars, int trimType) { //end will point to the first non-trimmed character on the right //start will point to the first non-trimmed character on the Left int end = Length - 1; int start = 0; //Trim specified characters. if (trimType != TrimTail) { for (start = 0; start < Length; start++) { int i = 0; char ch = this[start]; for (i = 0; i < trimChars.Length; i++) { if (trimChars[i] == ch) break; } if (i == trimChars.Length) { // the character is not white space break; } } } if (trimType != TrimHead) { for (end = Length - 1; end >= start; end--) { int i = 0; char ch = this[end]; for (i = 0; i < trimChars.Length; i++) { if (trimChars[i] == ch) break; } if (i == trimChars.Length) { // the character is not white space break; } } } return CreateTrimmedString(start, end); } private string CreateTrimmedString(int start, int end) { int len = end - start + 1; if (len == Length) { // Don't allocate a new string as the trimmed string has not changed. return this; } else { if (len == 0) { return string.Empty; } return string.CreateString(this, start, len); } } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Simple.OData.Client.Tests.FluentApi { using Entry = System.Collections.Generic.Dictionary<string, object>; public class BatchTests : TestBase { [Fact] public async Task Success() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); batch += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test1" }, { "UnitPrice", 10m } }, false); batch += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test2" }, { "UnitPrice", 20m } }, false); await batch.ExecuteAsync(); var client = new ODataClient(settings); var product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test1'"); Assert.NotNull(product); product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test2'"); Assert.NotNull(product); } [Fact] public async Task EmptyBatch() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); await batch.ExecuteAsync(); } [Fact] public async Task ReadOnlyBatch() { var settings = CreateDefaultSettings().WithHttpMock(); IDictionary<string, object> product = null; var batch = new ODataBatch(settings); batch += async c => product = await c.FindEntryAsync("Products"); await batch.ExecuteAsync(); Assert.NotNull(product); } [Fact] public async Task NestedBatch() { var settings = CreateDefaultSettings().WithHttpMock(); var batch1 = new ODataBatch(settings); batch1 += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test1" }, { "UnitPrice", 10m } }, false); batch1 += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test2" }, { "UnitPrice", 20m } }, false); var batch2 = new ODataBatch(settings); batch2 += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test3" }, { "UnitPrice", 30m } }, false); batch2 += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test4" }, { "UnitPrice", 40m } }, false); await batch2.ExecuteAsync(); await batch1.ExecuteAsync(); var client = new ODataClient(settings); var product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test1'"); Assert.NotNull(product); product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test2'"); Assert.NotNull(product); product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test3'"); Assert.NotNull(product); product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test4'"); Assert.NotNull(product); } [Fact] public async Task SuccessWithResults() { var settings = CreateDefaultSettings().WithHttpMock(); IDictionary<string, object> product1 = null; IDictionary<string, object> product2 = null; var batch = new ODataBatch(settings); batch += async x => { product1 = await x.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test1" }, { "UnitPrice", 10m }}); }; batch += async x => { product2 = await x.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test2" }, { "UnitPrice", 20m }}); }; await batch.ExecuteAsync(); Assert.NotNull(product1["ProductID"]); Assert.NotNull(product2["ProductID"]); var client = new ODataClient(settings); product1 = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test1'"); Assert.NotNull(product1); product2 = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test2'"); Assert.NotNull(product2); } [Fact] public async Task PartialFailures() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); batch += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test1" }, { "UnitPrice", 10m } }, false); batch += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test2" }, { "UnitPrice", 10m }, { "SupplierID", 0xFFFF } }, false); try { await batch.ExecuteAsync(); } catch (WebRequestException exception) { Assert.NotNull(exception.Response); } } [Fact] public async Task AllFailures() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); batch += c => c.InsertEntryAsync("Products", new Entry() { { "UnitPrice", 10m } }, false); batch += c => c.InsertEntryAsync("Products", new Entry() { { "UnitPrice", 20m } }, false); try { await batch.ExecuteAsync(); } catch (WebRequestException exception) { Assert.NotNull(exception.Response); } } [Fact] public async Task MultipleUpdateEntrySingleBatch() { var settings = CreateDefaultSettings().WithHttpMock(); IDictionary<string, object> product = null; IDictionary<string, object> product1 = null; IDictionary<string, object> product2 = null; var batch = new ODataBatch(settings); batch += async c => product = await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test11" }, { "UnitPrice", 21m } }); await batch.ExecuteAsync(); batch = new ODataBatch(settings); batch += c => c.UpdateEntryAsync("Products", product, new Entry() { { "UnitPrice", 22m } }); batch += async x => product1 = await x.FindEntryAsync("Products?$filter=ProductName eq 'Test11'"); batch += c => c.UpdateEntryAsync("Products", product, new Entry() { { "UnitPrice", 23m } }); batch += async x => product2 = await x.FindEntryAsync("Products?$filter=ProductName eq 'Test11'"); await batch.ExecuteAsync(); Assert.Equal(22m, product1["UnitPrice"]); Assert.Equal(23m, product2["UnitPrice"]); var client = new ODataClient(settings); product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test11'"); Assert.Equal(23m, product["UnitPrice"]); } [Fact] public async Task MultipleUpdatesEntriesSingleBatch() { var settings = CreateDefaultSettings().WithHttpMock(); IDictionary<string, object> product = null; var batch = new ODataBatch(settings); batch += async c => product = await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test11" }, { "UnitPrice", 121m } }); batch += async c => product = await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test12" }, { "UnitPrice", 121m } }); batch += async c => product = await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test13" }, { "UnitPrice", 121m } }); await batch.ExecuteAsync(); batch = new ODataBatch(settings); batch += c => c.For("Products").Filter("UnitPrice eq 121").Set(new Entry() { { "UnitPrice", 122m } }).UpdateEntriesAsync(); await batch.ExecuteAsync(); var client = new ODataClient(settings); product = await client.FindEntryAsync("Products?$filter=UnitPrice eq 121"); Assert.Null(product); var products = await client.FindEntriesAsync("Products?$filter=UnitPrice eq 122"); Assert.Equal(3, products.Count()); } [Fact] public async Task UpdateDeleteSingleBatch() { var settings = CreateDefaultSettings().WithHttpMock(); IDictionary<string, object> product = null; IDictionary<string, object> product1 = null; IDictionary<string, object> product2 = null; var batch = new ODataBatch(settings); batch += async x => product = await x.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test11" }, { "UnitPrice", 21m } }); await batch.ExecuteAsync(); batch = new ODataBatch(settings); batch += c => c.UpdateEntryAsync("Products", product, new Entry() { { "UnitPrice", 22m } }); batch += async c => product1 = await c.FindEntryAsync("Products?$filter=ProductName eq 'Test11'"); batch += c => c.DeleteEntryAsync("Products", product); batch += async c => product2 = await c.FindEntryAsync("Products?$filter=ProductName eq 'Test11'"); await batch.ExecuteAsync(); Assert.Equal(22m, product1["UnitPrice"]); Assert.Null(product2); var client = new ODataClient(settings); product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test11'"); Assert.Null(product); } [Fact] public async Task InsertUpdateDeleteSeparateBatches() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); batch += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test12" }, { "UnitPrice", 21m } }, false); await batch.ExecuteAsync(); var client = new ODataClient(settings); var product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test12'"); Assert.Equal(21m, product["UnitPrice"]); var key = new Entry() { { "ProductID", product["ProductID"] } }; batch = new ODataBatch(settings); batch += c => c.UpdateEntryAsync("Products", key, new Entry() { { "UnitPrice", 22m } }); await batch.ExecuteAsync(); product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test12'"); Assert.Equal(22m, product["UnitPrice"]); batch = new ODataBatch(settings); batch += c => c.DeleteEntryAsync("Products", key); await batch.ExecuteAsync(); product = await client.FindEntryAsync("Products?$filter=ProductName eq 'Test12'"); Assert.Null(product); } [Fact] public async Task InsertSingleEntityWithSingleAssociationSingleBatch() { var settings = CreateDefaultSettings().WithHttpMock(); IDictionary<string, object> category = null; var batch = new ODataBatch(settings); batch += async x => category = await x.InsertEntryAsync("Categories", new Entry() { { "CategoryName", "Test13" } }); batch += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test14" }, { "UnitPrice", 21m }, { "Category", category } }, false); await batch.ExecuteAsync(); var client = new ODataClient(settings); var product = await client .For("Products") .Expand("Category") .Filter("ProductName eq 'Test14'") .FindEntryAsync(); Assert.Equal("Test13", (product["Category"] as IDictionary<string, object>)["CategoryName"]); } [Fact] public async Task InsertSingleEntityWithMultipleAssociationsSingleBatch() { var settings = CreateDefaultSettings().WithHttpMock(); IDictionary<string, object> product1 = null; IDictionary<string, object> product2 = null; var batch = new ODataBatch(settings); batch += async c => product1 = await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test15" }, { "UnitPrice", 21m } }); batch += async c => product2 = await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test16" }, { "UnitPrice", 22m } }); batch += c => c.InsertEntryAsync("Categories", new Entry() { { "CategoryName", "Test17" }, { "Products", new[] { product1, product2 } } }, false); await batch.ExecuteAsync(); var client = new ODataClient(settings); var category = await client .For("Categories") .Expand("Products") .Filter("CategoryName eq 'Test17'") .FindEntryAsync(); Assert.Equal(2, (category["Products"] as IEnumerable<object>).Count()); } [Fact] public async Task DeleteEntryNonExisting() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); batch += c => c.DeleteEntryAsync("Products", new Entry { { "ProductID", 0xFFFF } }); await AssertThrowsAsync<WebRequestException>(async () => await batch.ExecuteAsync()); } [Fact] public async Task DeleteEntriesExisting() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); batch += async c => await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test19" }, { "UnitPrice", 21m } }); await batch.ExecuteAsync(); batch = new ODataBatch(settings); batch += c => c.DeleteEntriesAsync("Products", "Products?$filter=ProductName eq 'Test19'"); await batch.ExecuteAsync(); var client = new ODataClient(settings); var product = await client .For("Products") .Filter("ProductName eq 'Test19'") .FindEntryAsync(); Assert.Null(product); } [Fact] public async Task DeleteEntriesNonExisting() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); batch += c => c.DeleteEntriesAsync("Products", "Products?$filter=ProductName eq 'Test99'"); await batch.ExecuteAsync(); } [Fact] public async Task DeleteEntriesMultiple() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); batch += async c => await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test21" }, { "UnitPrice", 111m } }); batch += async c => await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test22" }, { "UnitPrice", 111m } }); batch += async c => await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test23" }, { "UnitPrice", 111m } }); await batch.ExecuteAsync(); batch = new ODataBatch(settings); batch += c => c.DeleteEntriesAsync("Products", "Products?$filter=UnitPrice eq 111"); await batch.ExecuteAsync(); var client = new ODataClient(settings); var product = await client .For("Products") .Filter("UnitPrice eq 111") .FindEntryAsync(); Assert.Null(product); } [Fact] public async Task DeleteEntriesNonExistingThenInsert() { var settings = CreateDefaultSettings().WithHttpMock(); IDictionary<string, object> product = null; var batch = new ODataBatch(settings); batch += c => c.DeleteEntriesAsync("Products", "Products?$filter=ProductName eq 'Test99'"); batch += async c => product = await c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test15" }, { "UnitPrice", 21m } }); batch += c => c.InsertEntryAsync("Categories", new Entry() { { "CategoryName", "Test17" }, { "Products", new[] { product } } }, false); await batch.ExecuteAsync(); } [Fact] public async Task UpdateWithResultRequired() { var settings = CreateDefaultSettings().WithHttpMock(); IDictionary<string, object> product = null; IDictionary<string, object> product1 = null; var batch = new ODataBatch(settings); batch += async x => product = await x.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test11" }, { "UnitPrice", 21m } }, true); await batch.ExecuteAsync(); batch = new ODataBatch(settings); batch += async c => product1 = await c.UpdateEntryAsync("Products", product, new Entry() { { "UnitPrice", 22m } }, true); await batch.ExecuteAsync(); Assert.Equal(22m, product1["UnitPrice"]); } [Fact] public async Task Function() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); int result = 0; batch += async c => result = await c.Unbound().Function("ParseInt").Set(new Entry() { { "number", "1" } }).ExecuteAsScalarAsync<int>(); await batch.ExecuteAsync(); Assert.Equal(1, result); } [Theory] [InlineData(false)] [InlineData(true)] public async Task LinkEntry(bool useAbsoluteReferenceUris) { var settings = CreateDefaultSettings().WithHttpMock(); settings.UseAbsoluteReferenceUris = useAbsoluteReferenceUris; var client = new ODataClient(settings); var category = await client .For("Categories") .Set(new { CategoryName = "Test4" }) .InsertEntryAsync(); var product = await client .For("Products") .Set(new { ProductName = "Test5" }) .InsertEntryAsync(); var batch = new ODataBatch(settings); batch += async c => await c .For("Products") .Key(product) .LinkEntryAsync("Category", category); await batch.ExecuteAsync(); product = await client .For("Products") .Filter("ProductName eq 'Test5'") .FindEntryAsync(); Assert.NotNull(product["CategoryID"]); Assert.Equal(category["CategoryID"], product["CategoryID"]); } [Fact] public async Task Count() { var settings = CreateDefaultSettings().WithHttpMock(); var batch = new ODataBatch(settings); int count = 0; batch += async c => count = await c .For("Products") .Count() .FindScalarAsync<int>(); await batch.ExecuteAsync(); Assert.Equal(ExpectedCountOfProducts, count); } [Fact] public async Task WithHttpHeaders() { IDictionary<string, string> headers = null; var settings = CreateDefaultSettings().WithHttpMock(); settings.BeforeRequest = r => headers = r.Headers.ToDictionary(x => x.Key, x => x.Value.First()); var batch = new ODataBatch(settings) .WithHeader("batchHeader", "batchHeaderValue"); batch += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test1" }, { "UnitPrice", 10m } }, false); batch += c => c.InsertEntryAsync("Products", new Entry() { { "ProductName", "Test2" }, { "UnitPrice", 20m } }, false); await batch.ExecuteAsync(); Assert.True(headers.TryGetValue("batchHeader", out var value) && value == "batchHeaderValue"); } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Globalization; using System.IO; using System.Net; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Principal; using System.Text; using System.Web; using System.Web.Routing; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using MbUnit.Framework; using Moq; using Ninject; using Ninject.Activation; using Ninject.Parameters; using Ninject.Planning.Bindings; using Subtext.Configuration; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Emoticons; using Subtext.Framework.Providers; using Subtext.Framework.Routing; using Subtext.Framework.Services; using Subtext.Framework.Services.SearchEngine; using Subtext.Framework.Text; using Subtext.Framework.Web; using Subtext.Framework.Web.HttpModules; using Subtext.Infrastructure; namespace UnitTests.Subtext { /// <summary> /// Contains helpful methods for packing and unpacking resources /// </summary> public static class UnitTestHelper { /// <summary> /// Unpacks an embedded resource into the specified directory. The resource name should /// be everything after 'UnitTests.Subtext.Resources.'. /// </summary> /// <remarks>Omit the UnitTests.Subtext.Resources. part of the /// resource name.</remarks> /// <param name="resourceName"></param> /// <param name="outputPath">The path to write the file as.</param> public static void UnpackEmbeddedResource(string resourceName, string outputPath) { Stream stream = UnpackEmbeddedResource(resourceName); using(var reader = new StreamReader(stream)) { using(StreamWriter writer = File.CreateText(outputPath)) { writer.Write(reader.ReadToEnd()); writer.Flush(); } } } /// <summary> /// Unpacks an embedded resource as a string. The resource name should /// be everything after 'UnitTests.Subtext.Resources.'. /// </summary> /// <remarks>Omit the UnitTests.Subtext.Resources. part of the /// resource name.</remarks> /// <param name="resourceName"></param> /// <param name="encoding">The path to write the file as.</param> public static string UnpackEmbeddedResource(string resourceName, Encoding encoding) { Stream stream = UnpackEmbeddedResource(resourceName); using(var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } /// <summary> /// Unpacks an embedded binary resource into the specified directory. The resource name should /// be everything after 'UnitTests.Subtext.Resources.'. /// </summary> /// <remarks>Omit the UnitTests.Subtext.Resources. part of the /// resource name.</remarks> /// <param name="resourceName"></param> /// <param name="fileName">The file to write the resourcce.</param> public static string UnpackEmbeddedBinaryResource(string resourceName, string fileName) { using(Stream stream = UnpackEmbeddedResource(resourceName)) { var buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); string filePath = !Path.IsPathRooted(fileName) ? GetPathInExecutingAssemblyLocation(fileName) : Path.GetFullPath(fileName); using(FileStream outStream = File.Create(filePath)) { outStream.Write(buffer, 0, buffer.Length); } return filePath; } } public static string GetPathInExecutingAssemblyLocation(string fileName) { return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName); } /// <summary> /// Unpacks an embedded resource into a Stream. The resource name should /// be everything after 'UnitTests.Subtext.Resources.'. /// </summary> /// <remarks>Omit the UnitTests.Subtext.Resources. part of the /// resource name.</remarks> /// <param name="resourceName">Name of the resource.</param> public static Stream UnpackEmbeddedResource(string resourceName) { Assembly assembly = Assembly.GetExecutingAssembly(); return assembly.GetManifestResourceStream("UnitTests.Subtext.Resources." + resourceName); } /// <summary> /// Generates a unique string. /// </summary> /// <returns></returns> public static string GenerateUniqueString() { return Guid.NewGuid().ToString().Replace("-", ""); } /// <summary> /// Generates a unique host name. /// </summary> /// <returns></returns> public static string GenerateUniqueHostname() { return GenerateUniqueString() + ".com"; } /// <summary> /// Sets the HTTP context with a valid request for the blog specified /// by the host and application. /// </summary> /// <param name="host">Host.</param> /// <param name="subfolder">Subfolder Name.</param> public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder) { return SetHttpContextWithBlogRequest(host, subfolder, string.Empty); } /// <summary> /// Sets the HTTP context with a valid request for the blog specified /// by the host and subfolder hosted in a virtual directory. /// </summary> /// <param name="host">Host.</param> /// <param name="subfolder">Subfolder Name.</param> /// <param name="applicationPath"></param> public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder, string applicationPath) { return SetHttpContextWithBlogRequest(host, subfolder, applicationPath, "default.aspx"); } public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, int port, string subfolder, string applicationPath) { return SetHttpContextWithBlogRequest(host, port, subfolder, applicationPath, "default.aspx"); } public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder, string applicationPath, string page) { return SetHttpContextWithBlogRequest(host, 80, subfolder, applicationPath, page); } public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, int port, string subfolder, string applicationPath, string page) { return SetHttpContextWithBlogRequest(host, port, subfolder, applicationPath, page, null, "GET"); } public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder, string applicationPath, string page, TextWriter output) { return SetHttpContextWithBlogRequest(host, subfolder, applicationPath, page, output, "GET"); } public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder, string applicationPath, string page, TextWriter output, string httpVerb) { return SetHttpContextWithBlogRequest(host, 80, subfolder, applicationPath, page, output, httpVerb); } public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, int port, string subfolder, string applicationPath, string page, TextWriter output, string httpVerb) { HttpContext.Current = null; applicationPath = HttpHelper.StripSurroundingSlashes(applicationPath); // Subtext.Web subfolder = StripSlashes(subfolder); // MyBlog string appPhysicalDir = @"c:\projects\SubtextSystem\"; if(applicationPath.Length == 0) { applicationPath = "/"; } else { appPhysicalDir += applicationPath + @"\"; // c:\projects\SubtextSystem\Subtext.Web\ applicationPath = "/" + applicationPath; // /Subtext.Web } SetHttpRequestApplicationPath(applicationPath); if(subfolder.Length > 0) { page = subfolder + "/" + page; // MyBlog/default.aspx } string query = string.Empty; var workerRequest = new SimulatedHttpRequest(applicationPath, appPhysicalDir, appPhysicalDir + page, page, query, output, host, port, httpVerb); HttpContext.Current = new HttpContext(workerRequest); BlogRequest.Current = new BlogRequest(host, subfolder, HttpContext.Current.Request.Url, host == "localhost"); return workerRequest; } static void SetHttpRequestApplicationPath(string applicationPath) { //We cheat by using reflection. FieldInfo runtimeField = typeof(HttpRuntime).GetField("_theRuntime", BindingFlags.NonPublic | BindingFlags.Static); Assert.IsNotNull(runtimeField); var currentRuntime = runtimeField.GetValue(null) as HttpRuntime; Assert.IsNotNull(currentRuntime); FieldInfo appDomainAppVPathField = typeof(HttpRuntime).GetField("_appDomainAppVPath", BindingFlags.NonPublic | BindingFlags.Instance); Assert.IsNotNull(appDomainAppVPathField); Type virtualPathType = Type.GetType( "System.Web.VirtualPath, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true); Assert.IsNotNull(virtualPathType); MethodInfo createMethod = virtualPathType.GetMethod("Create", BindingFlags.Static | BindingFlags.Public, null, new[] {typeof(string)}, null); object virtualPath = createMethod.Invoke(null, new object[] {applicationPath}); appDomainAppVPathField.SetValue(currentRuntime, virtualPath); } /// <summary> /// Strips the slashes from the target string. /// </summary> /// <param name="target">Target.</param> /// <returns></returns> public static string StripSlashes(string target) { if(target.Length == 0) { return target; } return target.Replace(@"\", string.Empty).Replace("/", string.Empty); } /// <summary> /// Strips the outer slashes. /// </summary> /// <param name="target">Target.</param> /// <returns></returns> public static string StripOuterSlashes(string target) { if(target.Length == 0) { return target; } char firstChar = target[0]; if(firstChar == '\\' || firstChar == '/') { target = target.Substring(1); } if(target.Length > 0) { char lastChar = target[target.Length - 1]; if(lastChar == '\\' || lastChar == '/') { target = target.Substring(0, target.Length - 1); } } return target; } /// <summary> /// This is useful when two strings appear to be but Assert.AreEqual says they are not. /// </summary> /// <param name="result"></param> /// <param name="expected"></param> public static void AssertStringsEqualCharacterByCharacter(string expected, string result) { if(result != expected) { int unequalPos = 0; for(int i = 0; i < Math.Max(result.Length, expected.Length); i++) { var originalChar = (char)0; var expectedChar = (char)0; if(i < result.Length) { originalChar = result[i]; } if(i < expected.Length) { expectedChar = expected[i]; } if(unequalPos == 0 && originalChar != expectedChar) { unequalPos = i; } string expectedCharText = "" + originalChar; if(char.IsWhiteSpace(originalChar)) { expectedCharText = "{" + (int)originalChar + "}"; } string expectedCharDisplay = "" + expectedChar; if(char.IsWhiteSpace(expectedChar)) { expectedCharDisplay = "{" + (int)expectedChar + "}"; } Console.WriteLine("{0}:\t{1} ({2})\t{3} ({4})", i, expectedCharDisplay, (int)expectedChar, expectedCharText, (int)originalChar); } Assert.AreEqual(expected, result, "Strings are not equal starting at character {0}", unequalPos); } } public static Entry CreateEntryInstanceForSyndication(string author, string title, string body) { return CreateEntryInstanceForSyndication(Config.CurrentBlog, author, title, body); } public static Entry CreateEntryInstanceForSyndication(Blog blog, string author, string title, string body) { return CreateEntryInstanceForSyndication(blog, author, title, body, null, DateTime.Now); } public static Entry CreateEntryInstanceForSyndication(string author, string title, string body, string entryName, DateTime dateCreated) { return CreateEntryInstanceForSyndication(Config.CurrentBlog, author, title, body, entryName, dateCreated); } public static Entry CreateEntryInstanceForSyndication(Blog blog, string author, string title, string body, string entryName, DateTime dateCreated) { var entry = new Entry(PostType.BlogPost); if(entryName != null) { entry.EntryName = entryName; } entry.BlogId = blog.Id; if(dateCreated != NullValue.NullDateTime) { entry.DateCreated = dateCreated; entry.DateModified = entry.DateCreated; entry.DateSyndicated = entry.DateCreated; } entry.Title = title; entry.Author = author; entry.Body = body; entry.DisplayOnHomePage = true; entry.IsAggregated = true; entry.IsActive = true; entry.AllowComments = true; entry.IncludeInMainSyndication = true; return entry; } public static Link CreateLinkInDb(int categoryId, string title, int? entryId, string rel) { var link = new Link { BlogId = Config.CurrentBlog.Id, IsActive = true, CategoryId = categoryId, Title = title, Url = "http://noneofyourbusiness.com/", Relation = rel }; if(entryId != null) { link.PostId = (int)entryId; } link.Id = Links.CreateLink(link); return link; } /// <summary> /// Creates a blog post link category. /// </summary> /// <param name="blogId"></param> /// <param name="title"></param> /// <returns></returns> public static int CreateCategory(int blogId, string title) { var category = new LinkCategory { BlogId = Config.CurrentBlog.Id, Title = title, CategoryType = CategoryType.PostCollection, IsActive = true }; return Links.CreateLinkCategory(category); } /// <summary> /// Creates a blog post link category. /// </summary> /// <param name="blogId">The blog id.</param> /// <param name="title">The title.</param> /// <param name="categoryType">Type of the category.</param> /// <returns></returns> public static int CreateCategory(int blogId, string title, CategoryType categoryType) { var category = new LinkCategory { BlogId = Config.CurrentBlog.Id, Title = title, CategoryType = categoryType, IsActive = true }; return Links.CreateLinkCategory(category); } /// <summary> /// Useful for unit testing that classes implement serialization. This simply takes in a class, /// serializes it into a byte array, deserializes the byte array, and returns the result. /// The unit test should check that all the properties are set correctly. /// </summary> /// <param name="serializableObject">The serializable object.</param> /// <returns></returns> public static T SerializeRoundTrip<T>(T serializableObject) { var stream = new MemoryStream(); var formatter = new BinaryFormatter(); formatter.Serialize(stream, serializableObject); byte[] serialized = stream.ToArray(); stream = new MemoryStream(serialized) {Position = 0}; formatter = new BinaryFormatter(); object o = formatter.Deserialize(stream); return (T)o; } /// <summary> /// Returns a deflated version of the response sent by the web server. If the /// web server did not send a compressed stream then the original stream is returned. /// </summary> /// <param name="encoding">Encoding of the stream. One of 'deflate' or 'gzip' or Empty.</param> /// <param name="inputStream">Input Stream</param> /// <returns>Seekable Stream</returns> public static Stream GetDeflatedResponse(string encoding, Stream inputStream) { //BORROWED FROM RSS BANDIT. const int bufferSize = 4096; // 4K read buffer Stream compressed = null, input = inputStream; bool tryAgainDeflate = true; if(input.CanSeek) { input.Seek(0, SeekOrigin.Begin); } if(encoding == "deflate") { //to solve issue "invalid checksum" exception with dasBlog and "deflate" setting: //input = ResponseToMemory(input); // need them within mem to have a seekable stream compressed = new InflaterInputStream(input); // try deflate with headers } else if(encoding == "gzip") { compressed = new GZipInputStream(input); } retry_decompress: if(compressed != null) { var decompressed = new MemoryStream(); try { int size = bufferSize; var writeData = new byte[bufferSize]; while(true) { size = compressed.Read(writeData, 0, size); if(size > 0) { decompressed.Write(writeData, 0, size); } else { break; } } } catch(GZipException) { if(tryAgainDeflate && (encoding == "deflate")) { input.Seek(0, SeekOrigin.Begin); // reset position compressed = new InflaterInputStream(input, new Inflater(true)); tryAgainDeflate = false; goto retry_decompress; } throw; } //reposition to beginning of decompressed stream then return decompressed.Seek(0, SeekOrigin.Begin); return decompressed; } // allready seeked, just return return input; } public static Blog CreateBlogAndSetupContext() { string hostName = GenerateUniqueString(); Config.CreateBlog("Just A Test Blog", "test", "test", hostName, string.Empty /* subfolder */); Blog blog = Config.GetBlog(hostName, string.Empty); SetHttpContextWithBlogRequest(hostName, string.Empty); BlogRequest.Current.Blog = blog; Assert.IsNotNull(Config.CurrentBlog, "Current Blog is null."); // NOTE- is this OK? return Config.CurrentBlog; } public static BlogAlias CreateBlogAlias(Blog info, string host, string subfolder) { return CreateBlogAlias(info, host, subfolder, true); } public static BlogAlias CreateBlogAlias(Blog info, string host, string subfolder, bool active) { var alias = new BlogAlias {BlogId = info.Id, Host = host, Subfolder = subfolder, IsActive = active}; Config.AddBlogAlias(alias); return alias; } public static MetaTag BuildMetaTag(string content, string name, string httpEquiv, int blogId, int? entryId, DateTime created) { var mt = new MetaTag {Name = name, HttpEquiv = httpEquiv, Content = content, BlogId = blogId}; if(entryId.HasValue) { mt.EntryId = entryId.Value; } mt.DateCreated = created; return mt; } public static ICollection<MetaTag> BuildMetaTagsFor(Blog blog, Entry entry, int numberOfTags) { var tags = new List<MetaTag>(numberOfTags); int? entryId = null; if(entry != null) { entryId = entry.Id; } for(int i = 0; i < numberOfTags; i++) { MetaTag aTag = BuildMetaTag( GenerateUniqueString().Left(50), // if even, make a name attribute, else http-equiv (i % 2 == 0) ? GenerateUniqueString().Left(25) : null, (i % 2 == 1) ? GenerateUniqueString().Left(25) : null, blog.Id, entryId, DateTime.Now); tags.Add(aTag); } return tags; } public static Enclosure BuildEnclosure(string title, string url, string mimetype, int entryId, long size, bool addToFeed, bool showWithPost) { var enc = new Enclosure { EntryId = entryId, Title = title, Url = url, Size = size, MimeType = mimetype, ShowWithPost = showWithPost, AddToFeed = addToFeed }; return enc; } public static void AssertSimpleProperties(object o, params string[] excludedProperties) { var excludes = new StringDictionary(); foreach(string exclude in excludedProperties) { excludes.Add(exclude, ""); } Type t = o.GetType(); PropertyInfo[] props = t.GetProperties(); foreach(PropertyInfo property in props) { if(excludes.ContainsKey(property.Name)) { continue; } if(property.CanRead && property.CanWrite) { object valueToSet; if(property.PropertyType == typeof(int) || property.PropertyType == typeof(short) || property.PropertyType == typeof(decimal) || property.PropertyType == typeof(double) || property.PropertyType == typeof(long)) { valueToSet = 42; } else if(property.PropertyType == typeof(string)) { valueToSet = "This Is a String"; } else if(property.PropertyType == typeof(DateTime)) { valueToSet = DateTime.Now; } else if(property.PropertyType == typeof(Uri)) { valueToSet = new Uri("http://subtextproject.com/"); } else if(property.PropertyType == typeof(IPAddress)) { valueToSet = IPAddress.Parse("127.0.0.1"); } else if(property.PropertyType == typeof(bool)) { valueToSet = true; } else if(property.PropertyType == typeof(PageType)) { valueToSet = PageType.HomePage; } else if(property.PropertyType == typeof(ICollection<Link>)) { valueToSet = new List<Link>(); } else if(property.PropertyType == typeof(ICollection<Image>)) { valueToSet = new List<Image>(); } else { //Don't know what to do. continue; } property.SetValue(o, valueToSet, null); object retrievedValue = property.GetValue(o, null); Assert.AreEqual(valueToSet, retrievedValue, string.Format(CultureInfo.InvariantCulture, "Could not set and get this property '{0}'", property.Name)); } } } public static IPrincipal MockPrincipalWithRoles(params string[] roles) { var principal = new Mock<IPrincipal>(); principal.Setup(p => p.Identity.IsAuthenticated).Returns(true); principal.Setup(p => p.Identity.Name).Returns("Username"); Array.ForEach(roles, role => principal.Setup(p => p.IsInRole(role)).Returns(true)); return principal.Object; } public static void AssertEnclosures(Enclosure expected, Enclosure result) { Assert.AreEqual(expected.Title, result.Title, "Wrong title."); Assert.AreEqual(expected.Url, result.Url, "Wrong Url."); Assert.AreEqual(expected.MimeType, result.MimeType, "Wrong mimetype."); Assert.AreEqual(expected.Size, result.Size, "Wrong size."); Assert.AreEqual(expected.AddToFeed, result.AddToFeed, "Wrong AddToFeed flag."); Assert.AreEqual(expected.ShowWithPost, result.ShowWithPost, "Wrong ShowWithPost flag."); } /// <summary> /// Takes all the necessary steps to create a blog and set up the HTTP Context /// with the blog. /// </summary> /// <returns> /// Returns a reference to a string builder. /// The stringbuilder will end up containing the Response of any simulated /// requests. /// </returns> internal static SimulatedRequestContext SetupBlog() { return SetupBlog(string.Empty); } /// <summary> /// Takes all the necessary steps to create a blog and set up the HTTP Context /// with the blog. /// </summary> /// <returns> /// Returns a reference to a string builder. /// The stringbuilder will end up containing the Response of any simulated /// requests. /// </returns> /// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param> internal static SimulatedRequestContext SetupBlog(string subfolder) { return SetupBlog(subfolder, string.Empty); } /// <summary> /// Takes all the necessary steps to create a blog and set up the HTTP Context /// with the blog. /// </summary> /// <returns> /// Returns a reference to a string builder. /// The stringbuilder will end up containing the Response of any simulated /// requests. /// </returns> /// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param> /// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param> internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath) { return SetupBlog(subfolder, applicationPath, 80); } /// <summary> /// Takes all the necessary steps to create a blog and set up the HTTP Context /// with the blog. /// </summary> /// <returns> /// Returns a reference to a string builder. /// The stringbuilder will end up containing the Response of any simulated /// requests. /// </returns> /// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param> /// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param> /// <param name="port">The port for this blog.</param> internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath, int port) { return SetupBlog(subfolder, applicationPath, port, string.Empty); } /// <summary> /// Takes all the necessary steps to create a blog and set up the HTTP Context /// with the blog. /// </summary> /// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param> /// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param> /// <param name="page">The page to request.</param> /// <returns> /// Returns a reference to a string builder. /// The stringbuilder will end up containing the Response of any simulated /// requests. /// </returns> internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath, string page) { return SetupBlog(subfolder, applicationPath, 80, page); } /// <summary> /// Takes all the necessary steps to create a blog and set up the HTTP Context /// with the blog. /// </summary> /// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param> /// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param> /// <param name="port">The port for this blog.</param> /// <param name="page">The page to request.</param> /// <returns> /// Returns a reference to a string builder. /// The stringbuilder will end up containing the Response of any simulated /// requests. /// </returns> internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath, int port, string page) { return SetupBlog(subfolder, applicationPath, port, page, "username", "password"); } /// <summary> /// Takes all the necessary steps to create a blog and set up the HTTP Context /// with the blog. /// </summary> /// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param> /// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param> /// <param name="port">The port for this blog.</param> /// <param name="page">The page to request.</param> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <returns> /// Returns a reference to a string builder. /// The stringbuilder will end up containing the Response of any simulated /// requests. /// </returns> internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath, int port, string page, string userName, string password) { string host = GenerateUniqueString(); HttpContext.Current = null; //I wish this returned the blog it created. Config.CreateBlog("Unit Test Blog", userName, password, host, subfolder); Blog blog = Config.GetBlog(host, subfolder); var sb = new StringBuilder(); TextWriter output = new StringWriter(sb); SimulatedHttpRequest request = SetHttpContextWithBlogRequest(host, port, subfolder, applicationPath, page, output, "GET"); BlogRequest.Current.Blog = blog; if(Config.CurrentBlog != null) { Config.CurrentBlog.AutoFriendlyUrlEnabled = true; } HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(userName), new[] {"Administrators"}); return new SimulatedRequestContext(request, sb, output, host); } public static int Create(Entry entry) { var requestContext = new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()); Bootstrapper.RequestContext = requestContext; var serviceLocator = new Mock<IServiceLocator>().Object; var searchEngineService = new Mock<IIndexingService>().Object; Bootstrapper.ServiceLocator = serviceLocator; var routes = new RouteCollection(); var subtextRoutes = new SubtextRouteMapper(routes, serviceLocator); Routes.RegisterRoutes(subtextRoutes); var urlHelper = new UrlHelper(requestContext, routes); var subtextContext = new SubtextContext(Config.CurrentBlog, requestContext, urlHelper, ObjectProvider.Instance(), requestContext.HttpContext.User, new SubtextCache(requestContext.HttpContext.Cache), serviceLocator); IEntryPublisher entryPublisher = CreateEntryPublisher(subtextContext, searchEngineService); int id = entryPublisher.Publish(entry); entry.Id = id; return id; } public static IEntryPublisher CreateEntryPublisher(ISubtextContext subtextContext, IIndexingService searchEngineService) { var slugGenerator = new SlugGenerator(FriendlyUrlSettings.Settings, subtextContext.Repository); var transformations = new CompositeTextTransformation { new XhtmlConverter(), new EmoticonsTransformation(subtextContext) }; return new EntryPublisher(subtextContext, transformations, slugGenerator, searchEngineService); } public static Stream ToStream(this string text) { var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(text); writer.Flush(); stream.Position = 0; return stream; } public static IKernel MockKernel(Func<IEnumerable<object>> returnFunc) { var request = new Mock<IRequest>(); var kernel = new Mock<IKernel>(); kernel.Setup( k => k.CreateRequest(It.IsAny<Type>(), It.IsAny<Func<IBindingMetadata, bool>>(), It.IsAny<IEnumerable<IParameter>>(), It.IsAny<bool>())).Returns(request.Object); kernel.Setup(k => k.Resolve(It.IsAny<IRequest>())).Returns(returnFunc); return kernel.Object; } public static UrlHelper SetupUrlHelper(string appPath) { return SetupUrlHelper(appPath, new RouteData()); } public static UrlHelper SetupUrlHelper(string appPath, RouteData routeData) { var routes = new RouteCollection(); var subtextRoutes = new SubtextRouteMapper(routes, new Mock<IServiceLocator>().Object); Routes.RegisterRoutes(subtextRoutes); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request.ApplicationPath).Returns(appPath); httpContext.Setup(c => c.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(s => s); var requestContext = new RequestContext(httpContext.Object, routeData); var helper = new UrlHelper(requestContext, routes); return helper; } /// <summary> /// Updates the specified entry in the data provider. /// </summary> /// <param name="entry">Entry.</param> /// <param name="context"></param> /// <returns></returns> public static void Update(Entry entry, ISubtextContext context) { if(entry == null) { throw new ArgumentNullException("entry"); } ObjectProvider repository = ObjectProvider.Instance(); var transform = new CompositeTextTransformation { new XhtmlConverter(), new EmoticonsTransformation(context), new KeywordExpander(repository) }; //TODO: Maybe use a INinjectParameter to control this. var searchEngineService = new Mock<IIndexingService>().Object; var publisher = new EntryPublisher(context, transform, new SlugGenerator(FriendlyUrlSettings.Settings), searchEngineService); publisher.Publish(entry); } public static Entry GetEntry(int entryId, PostConfig postConfig, bool includeCategories) { bool isActive = ((postConfig & PostConfig.IsActive) == PostConfig.IsActive); return ObjectProvider.Instance().GetEntry(entryId, isActive, includeCategories); } #region ...Assert.AreNotEqual replacements... public static ArgumentNullException AssertThrowsArgumentNullException(this Action action) { return action.AssertThrows<ArgumentNullException>(); } public static TException AssertThrows<TException>(this Action action) where TException : Exception { try { action(); } catch(TException exception) { return exception; } return null; } /// <summary> /// Asserts that the two values are not equal. /// </summary> /// <param name="first">The first.</param> /// <param name="compare">The compare.</param> public static void AssertAreNotEqual(int first, int compare) { AssertAreNotEqual(first, compare, ""); } /// <summary> /// Makes sure we can read app settings /// </summary> public static void AssertAppSettings() { Assert.AreEqual("UnitTestValue", ConfigurationManager.AppSettings["UnitTestKey"], "Cannot read app settings"); } /// <summary> /// Asserts that the two values are not equal. /// </summary> /// <param name="first">The first.</param> /// <param name="compare">The compare.</param> /// <param name="message"></param> public static void AssertAreNotEqual(int first, int compare, string message) { Assert.IsTrue(first != compare, message + "{0} is equal to {1}", first, compare); } /// <summary> /// Asserts that the two values are not equal. /// </summary> /// <param name="first">The first.</param> /// <param name="compare">The compare.</param> public static void AssertAreNotEqual(string first, string compare) { AssertAreNotEqual(first, compare, ""); } /// <summary> /// Asserts that the two values are not equal. /// </summary> /// <param name="first">The first.</param> /// <param name="compare">The compare.</param> /// <param name="message"></param> public static void AssertAreNotEqual(string first, string compare, string message) { Assert.IsTrue(first != compare, message + "{0} is equal to {1}", first, compare); } #endregion } }
///////////////////////////////////////////////////////////////////////////////// // Paint.NET // // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. // // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. // // See license-pdn.txt for full licensing and attribution details. // ///////////////////////////////////////////////////////////////////////////////// using System; using Cairo; namespace Pinta.Core { /// <summary> /// Adapts a Surface class so it can be used as a two dimensional boolean array. /// Elements are stored compactly, such that each pixel stores 32 boolean values. /// However, the usable width is the same as that of the adapted surface. /// (in other words, a surface that is 100 pixels wide can still only store 100 /// booleans per row) /// </summary> public unsafe sealed class BitVector2DSurfaceAdapter : IBitVector2D { private ImageSurface surface; private int src_width; private int src_height; private ColorBgra* src_data_ptr; public BitVector2DSurfaceAdapter (ImageSurface surface) { if (surface == null) throw new ArgumentNullException ("surface"); this.surface = surface; src_width = surface.Width; src_height = surface.Height; src_data_ptr = (ColorBgra*)surface.DataPtr; } #region Public Properties public int Width { get { return src_width; } } public int Height { get { return src_height; } } public bool IsEmpty { get { return (src_width == 0) || (src_height == 0); } } public bool this[Point pt] { get { return this[pt.X, pt.Y]; } set { this[pt.X, pt.Y] = value; } } public bool this[int x, int y] { get { return Get (x, y); } set { Set (x, y, value); } } #endregion #region Public Methods public void Clear (bool newValue) { unsafe { uint val = newValue ? 0xffffffff : 0; for (int y = 0; y < Height; ++y) { ColorBgra* row = surface.GetRowAddressUnchecked (src_data_ptr, src_width, y); int w = (this.Width + 31) / 32; while (w > 0) { row->Bgra = val; ++row; --w; } } } } public bool Get (int x, int y) { if (x < 0 || x >= this.Width) { throw new ArgumentOutOfRangeException ("x"); } if (y < 0 || y >= this.Height) { throw new ArgumentOutOfRangeException ("y"); } return GetUnchecked (x, y); } public unsafe bool GetUnchecked (int x, int y) { int cx = x / 32; int sx = x % 32; uint mask = surface.GetPointAddressUnchecked (src_data_ptr, src_width, cx, y)->Bgra; return 0 != (mask & (1 << sx)); } public void Set (int x, int y, bool newValue) { if (x < 0 || x >= this.Width) { throw new ArgumentOutOfRangeException ("x"); } if (y < 0 || y >= this.Height) { throw new ArgumentOutOfRangeException ("y"); } SetUnchecked (x, y, newValue); } public void Set (Point pt, bool newValue) { Set (pt.X, pt.Y, newValue); } public void Set (Gdk.Rectangle rect, bool newValue) { for (int y = rect.Y; y <= rect.GetBottom (); ++y) { for (int x = rect.X; x <= rect.GetRight (); ++x) { Set (x, y, newValue); } } } public void Set (Scanline scan, bool newValue) { int x = scan.X; while (x < scan.X + scan.Length) { Set (x, scan.Y, newValue); ++x; } } //public void Set(PdnRegion region, bool newValue) //{ // foreach (Rectangle rect in region.GetRegionScansReadOnlyInt()) // { // Set(rect, newValue); // } //} public unsafe void SetUnchecked (int x, int y, bool newValue) { int cx = x / 32; int sx = x % 32; ColorBgra* ptr = surface.GetPointAddressUnchecked (src_data_ptr, src_width, cx, y); uint mask = ptr->Bgra; uint slice = ((uint)1 << sx); uint newMask; if (newValue) { newMask = mask | slice; } else { newMask = mask & ~slice; } ptr->Bgra = newMask; } public void Invert (int x, int y) { Set (x, y, !Get (x, y)); } public void Invert (Point pt) { Invert (pt.X, pt.Y); } public void Invert (Gdk.Rectangle rect) { for (int y = rect.Y; y <= rect.GetBottom (); ++y) { for (int x = rect.X; x <= rect.GetRight (); ++x) { Invert (x, y); } } } public void Invert (Scanline scan) { int x = scan.X; while (x < scan.X + scan.Length) { Invert (x, scan.Y); ++x; } } //public void Invert(PdnRegion region) //{ // foreach (Rectangle rect in region.GetRegionScansReadOnlyInt()) // { // Invert(rect); // } //} public BitVector2DSurfaceAdapter Clone () { ImageSurface clonedSurface = this.surface.Clone (); return new BitVector2DSurfaceAdapter (clonedSurface); } object ICloneable.Clone () { return Clone (); } #endregion } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using System.Collections.Generic; using Xunit; public class AsyncTargetWrapperTests : NLogTestBase { [Fact] public void AsyncTargetWrapperInitTest() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget, 300, AsyncTargetWrapperOverflowAction.Grow); Assert.Equal(AsyncTargetWrapperOverflowAction.Grow, targetWrapper.OverflowAction); Assert.Equal(300, targetWrapper.QueueLimit); Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches); Assert.Equal(100, targetWrapper.BatchSize); } [Fact] public void AsyncTargetWrapperInitTest2() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper() { WrappedTarget = myTarget, }; Assert.Equal(AsyncTargetWrapperOverflowAction.Discard, targetWrapper.OverflowAction); Assert.Equal(10000, targetWrapper.QueueLimit); Assert.Equal(50, targetWrapper.TimeToSleepBetweenBatches); Assert.Equal(100, targetWrapper.BatchSize); } [Fact] public void AsyncTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var targetWrapper = new AsyncTargetWrapper { WrappedTarget = myTarget, }; targetWrapper.Initialize(null); myTarget.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; ManualResetEvent continuationHit = new ManualResetEvent(false); Thread continuationThread = null; AsyncContinuation continuation = ex => { lastException = ex; continuationThread = Thread.CurrentThread; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); // continuation was not hit Assert.True(continuationHit.WaitOne(2000)); Assert.NotSame(continuationThread, Thread.CurrentThread); Assert.Null(lastException); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotSame(continuationThread, Thread.CurrentThread); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); } [Fact] public void AsyncTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new AsyncTargetWrapper(myTarget); targetWrapper.Initialize(null); myTarget.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne()); Assert.Null(lastException); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); } [Fact] public void AsyncTargetWrapperAsyncWithExceptionTest1() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var targetWrapper = new AsyncTargetWrapper(myTarget); targetWrapper.Initialize(null); myTarget.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit.WaitOne()); Assert.NotNull(lastException); Assert.IsType(typeof(InvalidOperationException), lastException); // no flush on exception Assert.Equal(0, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); lastException = null; targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotNull(lastException); Assert.IsType(typeof(InvalidOperationException), lastException); Assert.Equal(0, myTarget.FlushCount); Assert.Equal(2, myTarget.WriteCount); } [Fact] public void AsyncTargetWrapperFlushTest() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var targetWrapper = new AsyncTargetWrapper(myTarget) { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, }; targetWrapper.Initialize(null); myTarget.Initialize(null); List<Exception> exceptions = new List<Exception>(); int eventCount = 5000; for (int i = 0; i < eventCount; ++i) { targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation( ex => { lock (exceptions) { exceptions.Add(ex); } })); } Exception lastException = null; ManualResetEvent mre = new ManualResetEvent(false); string internalLog = RunAndCaptureInternalLog( () => { targetWrapper.Flush( cont => { try { // by this time all continuations should be completed Assert.Equal(eventCount, exceptions.Count); // with just 1 flush of the target Assert.Equal(1, myTarget.FlushCount); // and all writes should be accounted for Assert.Equal(eventCount, myTarget.WriteCount); } catch (Exception ex) { lastException = ex; } finally { mre.Set(); } }); Assert.True(mre.WaitOne()); }, LogLevel.Trace); if (lastException != null) { Assert.True(false, lastException.ToString() + "\r\n" + internalLog); } } [Fact] public void AsyncTargetWrapperCloseTest() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var targetWrapper = new AsyncTargetWrapper(myTarget) { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 1000, }; targetWrapper.Initialize(null); myTarget.Initialize(null); targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); // quickly close the target before the timer elapses targetWrapper.Close(); } [Fact] public void AsyncTargetWrapperExceptionTest() { var targetWrapper = new AsyncTargetWrapper { OverflowAction = AsyncTargetWrapperOverflowAction.Grow, TimeToSleepBetweenBatches = 500, WrappedTarget = new DebugTarget(), }; LogManager.ThrowExceptions = false; targetWrapper.Initialize(null); // null out wrapped target - will cause exception on the timer thread targetWrapper.WrappedTarget = null; string internalLog = RunAndCaptureInternalLog( () => { targetWrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); targetWrapper.Close(); }, LogLevel.Trace); Assert.True(internalLog.Contains("AsyncWrapper: WrappedTarget is NULL"), internalLog); } [Fact] public void FlushingMultipleTimesSimultaneous() { var asyncTarget = new AsyncTargetWrapper { TimeToSleepBetweenBatches = 2000, WrappedTarget = new DebugTarget(), }; asyncTarget.Initialize(null); asyncTarget.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(ex => { })); var firstContinuationCalled = false; var secondContinuationCalled = false; var firstContinuationResetEvent = new ManualResetEvent(false); var secondContinuationResetEvent = new ManualResetEvent(false); asyncTarget.Flush(ex => { firstContinuationCalled = true; firstContinuationResetEvent.Set(); }); asyncTarget.Flush(ex => { secondContinuationCalled = true; secondContinuationResetEvent.Set(); }); firstContinuationResetEvent.WaitOne(); secondContinuationResetEvent.WaitOne(); Assert.True(firstContinuationCalled); Assert.True(secondContinuationCalled); } class MyAsyncTarget : Target { public int FlushCount; public int WriteCount; protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(this.FlushCount <= this.WriteCount); Interlocked.Increment(ref this.WriteCount); ThreadPool.QueueUserWorkItem( s => { if (this.ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { Interlocked.Increment(ref this.FlushCount); ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } protected override void Write(LogEventInfo logEvent) { Assert.True(this.FlushCount <= this.WriteCount); this.WriteCount++; } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; asyncContinuation(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. /// <license> /// This is a port of the SciMark2a Java Benchmark to C# by /// Chris Re (cmr28@cornell.edu) and Werner Vogels (vogels@cs.cornell.edu) /// /// For details on the original authors see http://math.nist.gov/scimark2 /// /// This software is likely to burn your processor, bitflip your memory chips /// anihilate your screen and corrupt all your disks, so you it at your /// own risk. /// </license> using System; using System.Runtime.CompilerServices; namespace SciMark2 { /* Random.java based on Java Numerical Toolkit (JNT) Random.UniformSequence class. We do not use Java's own java.util.Random so that we can compare results with equivalent C and Fortran coces.*/ public class Random { /*------------------------------------------------------------------------------ CLASS VARIABLES ------------------------------------------------------------------------------ */ internal int seed = 0; private int[] _m; private int _i = 4; private int _j = 16; private const int mdig = 32; private const int one = 1; private int _m1; private int _m2; private double _dm1; private bool _haveRange = false; private double _left = 0.0; private double _right = 1.0; private double _width = 1.0; /* ------------------------------------------------------------------------------ CONSTRUCTORS ------------------------------------------------------------------------------ */ /// <summary> /// Initializes a sequence of uniformly distributed quasi random numbers with a /// seed based on the system clock. /// </summary> public Random() { initialize((int)System.DateTime.Now.Ticks); } /// <summary> /// Initializes a sequence of uniformly distributed quasi random numbers on a /// given half-open interval [left,right) with a seed based on the system /// clock. /// </summary> /// <param name="<B>left</B>">(double)<BR> /// The left endpoint of the half-open interval [left,right). /// </param> /// <param name="<B>right</B>">(double)<BR> /// The right endpoint of the half-open interval [left,right). /// </param> public Random(double left, double right) { initialize((int)System.DateTime.Now.Ticks); _left = left; _right = right; _width = right - left; _haveRange = true; } /// <summary> /// Initializes a sequence of uniformly distributed quasi random numbers with a /// given seed. /// </summary> /// <param name="<B>seed</B>">(int)<BR> /// The seed of the random number generator. Two sequences with the same /// seed will be identical. /// </param> public Random(int seed) { initialize(seed); } /// <summary>Initializes a sequence of uniformly distributed quasi random numbers /// with a given seed on a given half-open interval [left,right). /// </summary> /// <param name="<B>seed</B>">(int)<BR> /// The seed of the random number generator. Two sequences with the same /// seed will be identical. /// </param> /// <param name="<B>left</B>">(double)<BR> /// The left endpoint of the half-open interval [left,right). /// </param> /// <param name="<B>right</B>">(double)<BR> /// The right endpoint of the half-open interval [left,right). /// </param> public Random(int seed, double left, double right) { initialize(seed); _left = left; _right = right; _width = right - left; _haveRange = true; } /* ------------------------------------------------------------------------------ PUBLIC METHODS ------------------------------------------------------------------------------ */ /// <summary> /// Returns the next random number in the sequence. /// </summary> public double nextDouble() { int k; k = _m[_i] - _m[_j]; if (k < 0) k += _m1; _m[_j] = k; if (_i == 0) _i = 16; else _i--; if (_j == 0) _j = 16; else _j--; if (_haveRange) return _left + _dm1 * (double)k * _width; else return _dm1 * (double)k; } /// <summary> /// Returns the next N random numbers in the sequence, as /// a vector. /// </summary> public void nextDoubles(double[] x) { int N = x.Length; int remainder = N & 3; if (_haveRange) { for (int count = 0; count < N; count++) { int k = _m[_i] - _m[_j]; if (_i == 0) _i = 16; else _i--; if (k < 0) k += _m1; _m[_j] = k; if (_j == 0) _j = 16; else _j--; x[count] = _left + _dm1 * (double)k * _width; } } else { for (int count = 0; count < remainder; count++) { int k = _m[_i] - _m[_j]; if (_i == 0) _i = 16; else _i--; if (k < 0) k += _m1; _m[_j] = k; if (_j == 0) _j = 16; else _j--; x[count] = _dm1 * (double)k; } for (int count = remainder; count < N; count += 4) { int k = _m[_i] - _m[_j]; if (_i == 0) _i = 16; else _i--; if (k < 0) k += _m1; _m[_j] = k; if (_j == 0) _j = 16; else _j--; x[count] = _dm1 * (double)k; k = _m[_i] - _m[_j]; if (_i == 0) _i = 16; else _i--; if (k < 0) k += _m1; _m[_j] = k; if (_j == 0) _j = 16; else _j--; x[count + 1] = _dm1 * (double)k; k = _m[_i] - _m[_j]; if (_i == 0) _i = 16; else _i--; if (k < 0) k += _m1; _m[_j] = k; if (_j == 0) _j = 16; else _j--; x[count + 2] = _dm1 * (double)k; k = _m[_i] - _m[_j]; if (_i == 0) _i = 16; else _i--; if (k < 0) k += _m1; _m[_j] = k; if (_j == 0) _j = 16; else _j--; x[count + 3] = _dm1 * (double)k; } } } /*---------------------------------------------------------------------------- PRIVATE METHODS ------------------------------------------------------------------------ */ private void initialize(int seed) { // First the initialization of the member variables; _m1 = (one << mdig - 2) + ((one << mdig - 2) - one); _m2 = one << mdig / 2; _dm1 = 1.0 / (double)_m1; int jseed, k0, k1, j0, j1, iloop; this.seed = seed; _m = new int[17]; jseed = System.Math.Min(System.Math.Abs(seed), _m1); if (jseed % 2 == 0) --jseed; k0 = 9069 % _m2; k1 = 9069 / _m2; j0 = jseed % _m2; j1 = jseed / _m2; for (iloop = 0; iloop < 17; ++iloop) { jseed = j0 * k0; j1 = (jseed / _m2 + j0 * k1 + j1 * k0) % (_m2 / 2); j0 = jseed % _m2; _m[iloop] = j0 + _m2 * j1; } _i = 4; _j = 16; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualInt32() { var test = new SimpleBinaryOpTest__CompareEqualInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt32 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int Op2ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static SimpleBinaryOpTest__CompareEqualInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareEqual( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareEqual( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareEqual( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualInt32(); var result = Sse2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((int)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((int)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; namespace Microsoft.AspNetCore.HttpSys.Internal { internal static class PathNormalizer { private const byte ByteSlash = (byte)'/'; private const byte ByteDot = (byte)'.'; // In-place implementation of the algorithm from https://tools.ietf.org/html/rfc3986#section-5.2.4 public static unsafe int RemoveDotSegments(Span<byte> input) { fixed (byte* start = input) { var end = start + input.Length; return RemoveDotSegments(start, end); } } public static unsafe int RemoveDotSegments(byte* start, byte* end) { if (!ContainsDotSegments(start, end)) { return (int)(end - start); } var src = start; var dst = start; while (src < end) { var ch1 = *src; Debug.Assert(ch1 == '/', "Path segment must always start with a '/'"); byte ch2, ch3, ch4; switch (end - src) { case 1: break; case 2: ch2 = *(src + 1); if (ch2 == ByteDot) { // B. if the input buffer begins with a prefix of "/./" or "/.", // where "." is a complete path segment, then replace that // prefix with "/" in the input buffer; otherwise, src += 1; *src = ByteSlash; continue; } break; case 3: ch2 = *(src + 1); ch3 = *(src + 2); if (ch2 == ByteDot && ch3 == ByteDot) { // C. if the input buffer begins with a prefix of "/../" or "/..", // where ".." is a complete path segment, then replace that // prefix with "/" in the input buffer and remove the last // segment and its preceding "/" (if any) from the output // buffer; otherwise, src += 2; *src = ByteSlash; if (dst > start) { do { dst--; } while (dst > start && *dst != ByteSlash); } continue; } else if (ch2 == ByteDot && ch3 == ByteSlash) { // B. if the input buffer begins with a prefix of "/./" or "/.", // where "." is a complete path segment, then replace that // prefix with "/" in the input buffer; otherwise, src += 2; continue; } break; default: ch2 = *(src + 1); ch3 = *(src + 2); ch4 = *(src + 3); if (ch2 == ByteDot && ch3 == ByteDot && ch4 == ByteSlash) { // C. if the input buffer begins with a prefix of "/../" or "/..", // where ".." is a complete path segment, then replace that // prefix with "/" in the input buffer and remove the last // segment and its preceding "/" (if any) from the output // buffer; otherwise, src += 3; if (dst > start) { do { dst--; } while (dst > start && *dst != ByteSlash); } continue; } else if (ch2 == ByteDot && ch3 == ByteSlash) { // B. if the input buffer begins with a prefix of "/./" or "/.", // where "." is a complete path segment, then replace that // prefix with "/" in the input buffer; otherwise, src += 2; continue; } break; } // E. move the first path segment in the input buffer to the end of // the output buffer, including the initial "/" character (if // any) and any subsequent characters up to, but not including, // the next "/" character or the end of the input buffer. do { *dst++ = ch1; ch1 = *++src; } while (src < end && ch1 != ByteSlash); } if (dst == start) { *dst++ = ByteSlash; } return (int)(dst - start); } public static unsafe bool ContainsDotSegments(byte* start, byte* end) { var src = start; var dst = start; while (src < end) { var ch1 = *src; Debug.Assert(ch1 == '/', "Path segment must always start with a '/'"); byte ch2, ch3, ch4; switch (end - src) { case 1: break; case 2: ch2 = *(src + 1); if (ch2 == ByteDot) { return true; } break; case 3: ch2 = *(src + 1); ch3 = *(src + 2); if ((ch2 == ByteDot && ch3 == ByteDot) || (ch2 == ByteDot && ch3 == ByteSlash)) { return true; } break; default: ch2 = *(src + 1); ch3 = *(src + 2); ch4 = *(src + 3); if ((ch2 == ByteDot && ch3 == ByteDot && ch4 == ByteSlash) || (ch2 == ByteDot && ch3 == ByteSlash)) { return true; } break; } do { ch1 = *++src; } while (src < end && ch1 != ByteSlash); } return false; } } }
// // Copyright 2012 Hakan Kjellerstrand // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Google.OrTools.ConstraintSolver; public class SecretSanta2 { /** * * Secret Santa problem II in Google CP Solver. * * From Maple Primes: 'Secret Santa Graph Theory' * http://www.mapleprimes.com/blog/jpmay/secretsantagraphtheory * """ * Every year my extended family does a 'secret santa' gift exchange. * Each person draws another person at random and then gets a gift for * them. At first, none of my siblings were married, and so the draw was * completely random. Then, as people got married, we added the restriction * that spouses should not draw each others names. This restriction meant * that we moved from using slips of paper on a hat to using a simple * computer program to choose names. Then people began to complain when * they would get the same person two years in a row, so the program was * modified to keep some history and avoid giving anyone a name in their * recent history. This year, not everyone was participating, and so after * removing names, and limiting the number of exclusions to four per person, * I had data something like this: * * Name: Spouse, Recent Picks * * Noah: Ava. Ella, Evan, Ryan, John * Ava: Noah, Evan, Mia, John, Ryan * Ryan: Mia, Ella, Ava, Lily, Evan * Mia: Ryan, Ava, Ella, Lily, Evan * Ella: John, Lily, Evan, Mia, Ava * John: Ella, Noah, Lily, Ryan, Ava * Lily: Evan, John, Mia, Ava, Ella * Evan: Lily, Mia, John, Ryan, Noah * """ * * Note: I interpret this as the following three constraints: * 1) One cannot be a Secret Santa of one's spouse * 2) One cannot be a Secret Santa for somebody two years in a row * 3) Optimization: maximize the time since the last time * * This model also handle single persons, something the original * problem don't mention. * * * Also see http://www.hakank.org/or-tools/secret_santa2.py * */ private static void Solve(int single=0) { Solver solver = new Solver("SecretSanta2"); Console.WriteLine("\nSingle: {0}", single); // // The matrix version of earlier rounds. // M means that no earlier Santa has been assigned. // Note: Ryan and Mia has the same recipient for years 3 and 4, // and Ella and John has for year 4. // This seems to be caused by modification of // original data. // int n_no_single = 8; int M = n_no_single + 1; int[][] rounds_no_single = { // N A R M El J L Ev new int[] {0, M, 3, M, 1, 4, M, 2}, // Noah new int[] {M, 0, 4, 2, M, 3, M, 1}, // Ava new int[] {M, 2, 0, M, 1, M, 3, 4}, // Ryan new int[] {M, 1, M, 0, 2, M, 3, 4}, // Mia new int[] {M, 4, M, 3, 0, M, 1, 2}, // Ella new int[] {1, 4, 3, M, M, 0, 2, M}, // John new int[] {M, 3, M, 2, 4, 1, 0, M}, // Lily new int[] {4, M, 3, 1, M, 2, M, 0} // Evan }; // // Rounds with a single person (fake data) // int n_with_single = 9; M = n_with_single + 1; int[][] rounds_single = { // N A R M El J L Ev S new int[] {0, M, 3, M, 1, 4, M, 2, 2}, // Noah new int[] {M, 0, 4, 2, M, 3, M, 1, 1}, // Ava new int[] {M, 2, 0, M, 1, M, 3, 4, 4}, // Ryan new int[] {M, 1, M, 0, 2, M, 3, 4, 3}, // Mia new int[] {M, 4, M, 3, 0, M, 1, 2, M}, // Ella new int[] {1, 4, 3, M, M, 0, 2, M, M}, // John new int[] {M, 3, M, 2, 4, 1, 0, M, M}, // Lily new int[] {4, M, 3, 1, M, 2, M, 0, M}, // Evan new int[] {1, 2, 3, 4, M, 2, M, M, 0} // Single }; int Noah = 0; int Ava = 1; int Ryan = 2; int Mia = 3; int Ella = 4; int John = 5; int Lily = 6; int Evan = 7; int n = n_no_single; int[][] rounds = rounds_no_single; if (single == 1) { n = n_with_single; rounds = rounds_single; } M = n + 1; IEnumerable<int> RANGE = Enumerable.Range(0, n); String[] persons = {"Noah", "Ava", "Ryan", "Mia", "Ella", "John", "Lily", "Evan", "Single"}; int[] spouses = { Ava, // Noah Noah, // Ava Mia, // Rya Ryan, // Mia John, // Ella Ella, // John Evan, // Lily Lily, // Evan -1 // Single has no spouse }; // // Decision variables // IntVar[] santas = solver.MakeIntVarArray(n, 0, n-1, "santas"); IntVar[] santa_distance = solver.MakeIntVarArray(n, 0, M, "santa_distance"); // total of "distance", to maximize IntVar z = santa_distance.Sum().VarWithName("z"); // // Constraints // solver.Add(santas.AllDifferent()); // Can't be one own"s Secret Santa // (i.e. ensure that there are no fix-point in the array.) foreach(int i in RANGE) { solver.Add(santas[i] != i); } // no Santa for a spouses foreach(int i in RANGE) { if (spouses[i] > -1) { solver.Add(santas[i] != spouses[i]); } } // optimize "distance" to earlier rounds: foreach(int i in RANGE) { solver.Add(santa_distance[i] == rounds[i].Element(santas[i])); } // cannot be a Secret Santa for the same person // two years in a row. foreach(int i in RANGE) { foreach(int j in RANGE) { if (rounds[i][j] == 1) { solver.Add(santas[i] != j); } } } // // Objective (minimize the distances) // OptimizeVar obj = z.Maximize(1); // // Search // DecisionBuilder db = solver.MakePhase(santas, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_CENTER_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.WriteLine("\ntotal distances: {0}", z.Value()); Console.Write("santas: "); for(int i = 0; i < n; i++) { Console.Write(santas[i].Value() + " "); } Console.WriteLine(); foreach(int i in RANGE) { Console.WriteLine("{0}\tis a Santa to {1} (distance {2})", persons[i], persons[santas[i].Value()], santa_distance[i].Value()); } } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); Console.WriteLine("WallTime: {0}ms", solver.WallTime()); Console.WriteLine("Failures: {0}", solver.Failures()); Console.WriteLine("Branches: {0} ", solver.Branches()); solver.EndSearch(); } public static void Main(String[] args) { int single = 0; Solve(single); single = 1; Solve(single); } }
// // http://code.google.com/p/servicestack/wiki/TypeSerializer // ServiceStack.Text: .NET C# POCO Type Text Serializer. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2011 Liquidbit Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Globalization; using System.Text.RegularExpressions; using ServiceStack.Text.Support; namespace ServiceStack.Text { public static class StringExtensions { public static T To<T>(this string value) { return TypeSerializer.DeserializeFromString<T>(value); } public static T To<T>(this string value, T defaultValue) { return string.IsNullOrEmpty(value) ? defaultValue : TypeSerializer.DeserializeFromString<T>(value); } public static T ToOrDefaultValue<T>(this string value) { return string.IsNullOrEmpty(value) ? default(T) : TypeSerializer.DeserializeFromString<T>(value); } public static object To(this string value, Type type) { return TypeSerializer.DeserializeFromString(value, type); } /// <summary> /// Converts from base: 0 - 62 /// </summary> /// <param name="source">The source.</param> /// <param name="from">From.</param> /// <param name="to">To.</param> /// <returns></returns> public static string BaseConvert(this string source, int from, int to) { const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var result = ""; var length = source.Length; var number = new int[length]; for (var i = 0; i < length; i++) { number[i] = chars.IndexOf(source[i]); } int newlen; do { var divide = 0; newlen = 0; for (var i = 0; i < length; i++) { divide = divide * from + number[i]; if (divide >= to) { number[newlen++] = divide / to; divide = divide % to; } else if (newlen > 0) { number[newlen++] = 0; } } length = newlen; result = chars[divide] + result; } while (newlen != 0); return result; } public static string EncodeXml(this string value) { return value.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&", "&amp;"); } public static string EncodeJson(this string value) { return string.Concat ("\"", value.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "").Replace("\n", "\\n"), "\"" ); } public static string EncodeJsv(this string value) { return value.ToCsvField(); } public static string UrlEncode(this string text) { if (string.IsNullOrEmpty(text)) return text; var sb = new StringBuilder(); var textLength = text.Length; for (var i = 0; i < textLength; i++) { var c = text.Substring(i, 1); int charCode = text[i]; if ( charCode >= 65 && charCode <= 90 // A-Z || charCode >= 97 && charCode <= 122 // a-z || charCode >= 48 && charCode <= 57 // 0-9 || charCode >= 44 && charCode <= 46 // ,-. ) { sb.Append(c); } else { sb.Append('%' + charCode.ToString("x")); } } return sb.ToString(); } public static string UrlDecode(this string text) { if (string.IsNullOrEmpty(text)) return null; var sb = new StringBuilder(); var textLength = text.Length; for (var i = 0; i < textLength; i++) { var c = text.Substring(i, 1); if (c == "+") { sb.Append(" "); } else if (c == "%") { var hexNo = Convert.ToInt32(text.Substring(i + 1, 2), 16); sb.Append((char)hexNo); i += 2; } else { sb.Append(c); } } return sb.ToString(); } #if !XBOX public static string HexEscape(this string text, params char[] anyCharOf) { if (string.IsNullOrEmpty(text)) return text; if (anyCharOf == null || anyCharOf.Length == 0) return text; var encodeCharMap = new HashSet<char>(anyCharOf); var sb = new StringBuilder(); var textLength = text.Length; for (var i = 0; i < textLength; i++) { var c = text[i]; if (encodeCharMap.Contains(c)) { sb.Append('%' + ((int)c).ToString("x")); } else { sb.Append(c); } } return sb.ToString(); } #endif public static string HexUnescape(this string text, params char[] anyCharOf) { if (string.IsNullOrEmpty(text)) return null; if (anyCharOf == null || anyCharOf.Length == 0) return text; var sb = new StringBuilder(); var textLength = text.Length; for (var i = 0; i < textLength; i++) { var c = text.Substring(i, 1); if (c == "%") { var hexNo = Convert.ToInt32(text.Substring(i + 1, 2), 16); sb.Append((char)hexNo); i += 2; } else { sb.Append(c); } } return sb.ToString(); } public static string UrlFormat(this string url, params string[] urlComponents) { var encodedUrlComponents = new string[urlComponents.Length]; for (var i = 0; i < urlComponents.Length; i++) { var x = urlComponents[i]; encodedUrlComponents[i] = x.UrlEncode(); } return string.Format(url, encodedUrlComponents); } public static string ToRot13(this string value) { var array = value.ToCharArray(); for (var i = 0; i < array.Length; i++) { var number = (int)array[i]; if (number >= 'a' && number <= 'z') number += (number > 'm') ? -13 : 13; else if (number >= 'A' && number <= 'Z') number += (number > 'M') ? -13 : 13; array[i] = (char)number; } return new string(array); } public static string WithTrailingSlash(this string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); if (path[path.Length - 1] != '/') { return path + "/"; } return path; } public static string AppendUrlPaths(this string uri, params string[] uriComponents) { var sb = new StringBuilder(uri.WithTrailingSlash()); var i = 0; foreach (var uriComponent in uriComponents) { if (i++ > 0) sb.Append('/'); sb.Append(uriComponent.UrlEncode()); } return sb.ToString(); } public static string FromUtf8Bytes(this byte[] bytes) { return bytes == null ? null : Encoding.UTF8.GetString(bytes, 0, bytes.Length); } public static byte[] ToUtf8Bytes(this string value) { return Encoding.UTF8.GetBytes(value); } public static byte[] ToUtf8Bytes(this int intVal) { return FastToUtf8Bytes(intVal.ToString()); } public static byte[] ToUtf8Bytes(this long longVal) { return FastToUtf8Bytes(longVal.ToString()); } public static byte[] ToUtf8Bytes(this double doubleVal) { var doubleStr = doubleVal.ToString(CultureInfo.InvariantCulture.NumberFormat); if (doubleStr.IndexOf('E') != -1 || doubleStr.IndexOf('e') != -1) doubleStr = DoubleConverter.ToExactString(doubleVal); return FastToUtf8Bytes(doubleStr); } /// <summary> /// Skip the encoding process for 'safe strings' /// </summary> /// <param name="strVal"></param> /// <returns></returns> private static byte[] FastToUtf8Bytes(string strVal) { var bytes = new byte[strVal.Length]; for (var i = 0; i < strVal.Length; i++) bytes[i] = (byte)strVal[i]; return bytes; } public static string[] SplitOnFirst(this string strVal, char needle) { if (strVal == null) return new string[0]; var pos = strVal.IndexOf(needle); return pos == -1 ? new[] { strVal } : new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) }; } public static string[] SplitOnFirst(this string strVal, string needle) { if (strVal == null) return new string[0]; var pos = strVal.IndexOf(needle); return pos == -1 ? new[] { strVal } : new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) }; } public static string[] SplitOnLast(this string strVal, char needle) { if (strVal == null) return new string[0]; var pos = strVal.LastIndexOf(needle); return pos == -1 ? new[] { strVal } : new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) }; } public static string[] SplitOnLast(this string strVal, string needle) { if (strVal == null) return new string[0]; var pos = strVal.LastIndexOf(needle); return pos == -1 ? new[] { strVal } : new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) }; } public static string WithoutExtension(this string filePath) { if (string.IsNullOrEmpty(filePath)) return null; var extPos = filePath.LastIndexOf('.'); if (extPos == -1) return filePath; var dirPos = filePath.LastIndexOfAny(DirSeps); return extPos > dirPos ? filePath.Substring(0, extPos) : filePath; } private static readonly char DirSep = Path.DirectorySeparatorChar; private static readonly char AltDirSep = Path.DirectorySeparatorChar == '/' ? '\\' : '/'; static readonly char[] DirSeps = new[] { '\\', '/' }; public static string ParentDirectory(this string filePath) { if (string.IsNullOrEmpty(filePath)) return null; var dirSep = filePath.IndexOf(DirSep) != -1 ? DirSep : filePath.IndexOf(AltDirSep) != -1 ? AltDirSep : (char)0; return dirSep == 0 ? null : filePath.TrimEnd(dirSep).SplitOnLast(dirSep)[0]; } public static string ToJsv<T>(this T obj) { return TypeSerializer.SerializeToString<T>(obj); } public static T FromJsv<T>(this string jsv) { return TypeSerializer.DeserializeFromString<T>(jsv); } public static string ToJson<T>(this T obj) { return JsonSerializer.SerializeToString<T>(obj); } public static T FromJson<T>(this string json) { return JsonSerializer.DeserializeFromString<T>(json); } #if !XBOX && !SILVERLIGHT public static string ToXml<T>(this T obj) { return XmlSerializer.SerializeToString<T>(obj); } #endif #if !XBOX && !SILVERLIGHT public static T FromXml<T>(this string json) { return XmlSerializer.DeserializeFromString<T>(json); } #endif public static string FormatWith(this string text, params object[] args) { return string.Format(text, args); } public static string Fmt(this string text, params object[] args) { return string.Format(text, args); } public static bool StartsWithIgnoreCase(this string text, string startsWith) { return text != null && text.StartsWith(startsWith, StringComparison.InvariantCultureIgnoreCase); } public static string ReadAllText(this string filePath) { #if XBOX && !SILVERLIGHT using( var fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read ) ) { return new StreamReader( fileStream ).ReadToEnd( ) ; } #else return File.ReadAllText(filePath); #endif } public static int IndexOfAny(this string text, params string[] needles) { return IndexOfAny(text, 0, needles); } public static int IndexOfAny(this string text, int startIndex, params string[] needles) { if (text == null) return -1; var firstPos = -1; foreach (var needle in needles) { var pos = text.IndexOf(needle); if (firstPos == -1 || pos < firstPos) firstPos = pos; } return firstPos; } public static string ExtractContents(this string fromText, string startAfter, string endAt) { return ExtractContents(fromText, startAfter, startAfter, endAt); } public static string ExtractContents(this string fromText, string uniqueMarker, string startAfter, string endAt) { if (string.IsNullOrEmpty(uniqueMarker)) throw new ArgumentNullException("uniqueMarker"); if (string.IsNullOrEmpty(startAfter)) throw new ArgumentNullException("startAfter"); if (string.IsNullOrEmpty(endAt)) throw new ArgumentNullException("endAt"); if (string.IsNullOrEmpty(fromText)) return null; var markerPos = fromText.IndexOf(uniqueMarker); if (markerPos == -1) return null; var startPos = fromText.IndexOf(startAfter, markerPos); if (startPos == -1) return null; startPos += startAfter.Length; var endPos = fromText.IndexOf(endAt, startPos); if (endPos == -1) endPos = fromText.Length; return fromText.Substring(startPos, endPos - startPos); } #if XBOX && !SILVERLIGHT static readonly Regex StripHtmlRegEx = new Regex(@"<(.|\n)*?>", RegexOptions.Compiled); #else static readonly Regex StripHtmlRegEx = new Regex(@"<(.|\n)*?>"); #endif public static string StripHtml(this string html) { return string.IsNullOrEmpty(html) ? null : StripHtmlRegEx.Replace(html, ""); } #if XBOX && !SILVERLIGHT static readonly Regex StripBracketsRegEx = new Regex(@"\[(.|\n)*?\]", RegexOptions.Compiled); static readonly Regex StripBracesRegEx = new Regex(@"\((.|\n)*?\)", RegexOptions.Compiled); #else static readonly Regex StripBracketsRegEx = new Regex(@"\[(.|\n)*?\]"); static readonly Regex StripBracesRegEx = new Regex(@"\((.|\n)*?\)"); #endif public static string StripMarkdownMarkup(this string markdown) { if (string.IsNullOrEmpty(markdown)) return null; markdown = StripBracketsRegEx.Replace(markdown, ""); markdown = StripBracesRegEx.Replace(markdown, ""); markdown = markdown .Replace("*", "") .Replace("!", "") .Replace("\r", "") .Replace("\n", "") .Replace("#", ""); return markdown; } private const int LowerCaseOffset = 'a' - 'A'; public static string ToCamelCase(this string value) { if (string.IsNullOrEmpty(value)) return value; var firstChar = value[0]; if (firstChar < 'A' || firstChar > 'Z') return value; return (char)(firstChar + LowerCaseOffset) + value.Substring(1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Intrinsics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Test passing and returning HVAs (homogeneous vector aggregates) to/from managed code. // Test various sizes (including ones that exceed the limit for being treated as HVAs), // as well as passing various numbers of them (so that we exceed the available registers), // and mixing the HVA parameters with non-HVA parameters. // This Test case covers all cases for // Methods that take one HVA argument with between 1 and 5 Vector64 or Vector128 elements // - Called normally or by using reflection // Methods that return an HVA with between 1 and 5 Vector64 or Vector128 elements // - Called normally or by using reflection // Remaining Test cases to do: // - Add tests that have one than one HVA argument // - Add types that are *not* HVA types (e.g. too many vectors, or using Vector256). // - Add tests that use a mix of HVA and non-HVA arguments public static class VectorMgdMgd { private const int PASS = 100; private const int FAIL = 0; static Random random = new Random(12345); public static T GetValueFromInt<T>(int value) { if (typeof(T) == typeof(float)) { float floatValue = (float)value; return (T)(object)floatValue; } if (typeof(T) == typeof(double)) { double doubleValue = (double)value; return (T)(object)doubleValue; } if (typeof(T) == typeof(int)) { return (T)(object)value; } if (typeof(T) == typeof(uint)) { uint uintValue = (uint)value; return (T)(object)uintValue; } if (typeof(T) == typeof(long)) { long longValue = (long)value; return (T)(object)longValue; } if (typeof(T) == typeof(ulong)) { ulong longValue = (ulong)value; return (T)(object)longValue; } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)value; } if (typeof(T) == typeof(byte)) { return (T)(object)(byte)value; } if (typeof(T) == typeof(short)) { return (T)(object)(short)value; } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)value; } else { throw new ArgumentException(); } } public static bool CheckValue<T>(T value, T expectedValue) { bool returnVal; if (typeof(T) == typeof(float)) { returnVal = Math.Abs(((float)(object)value) - ((float)(object)expectedValue)) <= Single.Epsilon; } if (typeof(T) == typeof(double)) { returnVal = Math.Abs(((double)(object)value) - ((double)(object)expectedValue)) <= Double.Epsilon; } else { returnVal = value.Equals(expectedValue); } return returnVal; } public unsafe class HVATests<T> where T : struct { // An HVA can contain up to 4 vectors, so we'll test structs with up to 5 of them // (to ensure that even those that are too large are handled consistently). // So we need 5 * the element count in the largest (128-bit) vector with the smallest // element type (byte). static T[] values; static T[] check; private int ElementCount = (Unsafe.SizeOf<Vector128<T>>() / sizeof(byte)) * 5; public bool isPassing = true; public bool isReflection = false; Type[] reflectionParameterTypes; System.Reflection.MethodInfo reflectionMethodInfo; object[] reflectionInvokeArgs; //////////////////////////////////////// public struct HVA64_01 { public Vector64<T> v0; } public struct HVA64_02 { public Vector64<T> v0; public Vector64<T> v1; } public struct HVA64_03 { public Vector64<T> v0; public Vector64<T> v1; public Vector64<T> v2; } public struct HVA64_04 { public Vector64<T> v0; public Vector64<T> v1; public Vector64<T> v2; public Vector64<T> v3; } public struct HVA64_05 { public Vector64<T> v0; public Vector64<T> v1; public Vector64<T> v2; public Vector64<T> v3; public Vector64<T> v4; } private HVA64_01 hva64_01; private HVA64_02 hva64_02; private HVA64_03 hva64_03; private HVA64_04 hva64_04; private HVA64_05 hva64_05; //////////////////////////////////////// public struct HVA128_01 { public Vector128<T> v0; } public struct HVA128_02 { public Vector128<T> v0; public Vector128<T> v1; } public struct HVA128_03 { public Vector128<T> v0; public Vector128<T> v1; public Vector128<T> v2; } public struct HVA128_04 { public Vector128<T> v0; public Vector128<T> v1; public Vector128<T> v2; public Vector128<T> v3; } public struct HVA128_05 { public Vector128<T> v0; public Vector128<T> v1; public Vector128<T> v2; public Vector128<T> v3; public Vector128<T> v4; } private HVA128_01 hva128_01; private HVA128_02 hva128_02; private HVA128_03 hva128_03; private HVA128_04 hva128_04; private HVA128_05 hva128_05; //////////////////////////////////////// public void Init_HVAs() { int i; i = 0; hva64_01.v0 = Unsafe.As<T, Vector64<T>>(ref values[i]); i = 0; hva64_02.v0 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_02.v1 = Unsafe.As<T, Vector64<T>>(ref values[i]); i = 0; hva64_03.v0 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_03.v1 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_03.v2 = Unsafe.As<T, Vector64<T>>(ref values[i]); i = 0; hva64_04.v0 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_04.v1 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_04.v2 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_04.v3 = Unsafe.As<T, Vector64<T>>(ref values[i]); i = 0; hva64_05.v0 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_05.v1 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_05.v2 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_05.v3 = Unsafe.As<T, Vector64<T>>(ref values[i]); i += Vector64<T>.Count; hva64_05.v4 = Unsafe.As<T, Vector64<T>>(ref values[i]); //////////////////////////////////////// i = 0; hva128_01.v0 = Unsafe.As<T, Vector128<T>>(ref values[i]); i = 0; hva128_02.v0 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_02.v1 = Unsafe.As<T, Vector128<T>>(ref values[i]); i = 0; hva128_03.v0 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_03.v1 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_03.v2 = Unsafe.As<T, Vector128<T>>(ref values[i]); i = 0; hva128_04.v0 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_04.v1 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_04.v2 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_04.v3 = Unsafe.As<T, Vector128<T>>(ref values[i]); i = 0; hva128_05.v0 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_05.v1 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_05.v2 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_05.v3 = Unsafe.As<T, Vector128<T>>(ref values[i]); i += Vector128<T>.Count; hva128_05.v4 = Unsafe.As<T, Vector128<T>>(ref values[i]); } public HVATests() { values = new T[ElementCount]; for (int i = 0; i < values.Length; i++) { int data = random.Next(100); values[i] = GetValueFromInt<T>(data); } Init_HVAs(); } // Checks that the values in v correspond to those in the values array starting // with values[index] private void checkValues(string msg, Vector64<T> v, int index) { bool printedMsg = false; // Print at most one message for (int i = 0; i < Vector64<T>.Count; i++) { if (!CheckValue<T>(v.GetElement(i), values[index])) { if (!printedMsg) { Console.WriteLine("{0}: FAILED - Vector64<T> checkValues(index = {1}, i = {2}) {3}", msg, index, i, isReflection ? "(via reflection)" : "" ); printedMsg = true; } // Record failure status in global isPassing isPassing = false; } index++; } } // Checks that the values in v correspond to those in the values array starting // with values[index] private void checkValues(string msg, Vector128<T> v, int index) { bool printedMsg = false; // Print at most one message for (int i = 0; i < Vector128<T>.Count; i++) { if (!CheckValue<T>(v.GetElement(i), values[index])) { if (!printedMsg) { Console.WriteLine("{0}: FAILED - Vector64<T> checkValues(index = {1}, i = {2}) {3}", msg, index, i, isReflection ? "(via reflection)" : "" ); printedMsg = true; } // Record failure status in global isPassing isPassing = false; } index++; } } public void Done_Reflection() { isReflection = false; } //========== Vector64<T> tests //==================== Tests for passing 1 argumnet of HVA64_01 // Test the case where we've passed in a single argument HVA of 1 vector. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA64_01(HVA64_01 arg1) { checkValues("test1Argument_HVA64_01(arg1.vo)", arg1.v0, 0); } public void Init_Reflection_Args_HVA64_01() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA64_01) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA64_01), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva64_01 }; } //==================== Tests for passing 1 argumnet of HVA64_02 // Test the case where we've passed in a single argument HVA of 2 vectors. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA64_02(HVA64_02 arg1) { checkValues("test1Argument_HVA64_02(arg1.v0)", arg1.v0, 0); checkValues("test1Argument_HVA64_02(arg1.v1)", arg1.v1, Vector64<T>.Count); } public void Init_Reflection_Args_HVA64_02() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA64_02) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA64_02), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva64_02 }; } //==================== Tests for passing 1 argumnet of HVA64_03 // Test the case where we've passed in a single argument HVA of 3 vectors. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA64_03(HVA64_03 arg1) { checkValues("test1Argument_HVA64_03(arg1.v0)", arg1.v0, 0); checkValues("test1Argument_HVA64_03(arg1.v1)", arg1.v1, 1 * Vector64<T>.Count); checkValues("test1Argument_HVA64_03(arg1.v2)", arg1.v2, 2 * Vector64<T>.Count); } public void Init_Reflection_Args_HVA64_03() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA64_03) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA64_03), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva64_03 }; } //==================== Tests for passing 1 argumnet of HVA64_04 // Test the case where we've passed in a single argument HVA of 4 vectors. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA64_04(HVA64_04 arg1) { checkValues("test1Argument_HVA64_04(arg1.v0)", arg1.v0, 0); checkValues("test1Argument_HVA64_04(arg1.v1)", arg1.v1, 1 * Vector64<T>.Count); checkValues("test1Argument_HVA64_04(arg1.v2)", arg1.v2, 2 * Vector64<T>.Count); checkValues("test1Argument_HVA64_04(arg1.v3)", arg1.v3, 3 * Vector64<T>.Count); } public void Init_Reflection_Args_HVA64_04() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA64_04) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA64_04), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva64_04 }; } //==================== Tests for passing 1 argumnet of HVA64_05 // Test the case where we've passed in a single argument HVA of 5 vectors. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA64_05(HVA64_05 arg1) { checkValues("test1Argument_HVA64_05(arg1.v0)", arg1.v0, 0); checkValues("test1Argument_HVA64_05(arg1.v1)", arg1.v1, 1 * Vector64<T>.Count); checkValues("test1Argument_HVA64_05(arg1.v2)", arg1.v2, 2 * Vector64<T>.Count); checkValues("test1Argument_HVA64_05(arg1.v3)", arg1.v3, 3 * Vector64<T>.Count); checkValues("test1Argument_HVA64_05(arg1.v4)", arg1.v4, 4 * Vector64<T>.Count); } public void Init_Reflection_Args_HVA64_05() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA64_05) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA64_05), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva64_05 }; } //=============== Tests for return values if HVA64 //==================== Tests for return values of HVA64_01 // Return an HVA of 1 vectors, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA64_01 returnTest_HVA64_01() { return hva64_01; } public void testReturn_HVA64_01() { HVA64_01 result = returnTest_HVA64_01(); checkValues("testReturn_HVA64_01(result.v0)",result.v0, 0); } public void Init_Reflection_Return_HVA64_01() { isReflection = true; reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA64_01), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA64_01() { Init_Reflection_Return_HVA64_01(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA64_01 result = (HVA64_01)objResult; checkValues("testReflectionReturn_HVA64_01(result.v0)",result.v0, 0); Done_Reflection(); } //==================== Tests for return values of HVA64_02 // Return an HVA of 2 vectors, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA64_02 returnTest_HVA64_02() { return hva64_02; } public void testReturn_HVA64_02() { HVA64_02 result = returnTest_HVA64_02(); checkValues("testReturn_HVA64_02(result.v0)",result.v0, 0); checkValues("testReturn_HVA64_02(result.v1)",result.v1, Vector64<T>.Count); } public void Init_Reflection_Return_HVA64_02() { isReflection = true; reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA64_02), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA64_02() { Init_Reflection_Return_HVA64_02(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA64_02 result = (HVA64_02)objResult; checkValues("testReflectionReturn_HVA64_02(result.v0)",result.v0, 0); checkValues("testReflectionReturn_HVA64_02(result.v1)",result.v1, Vector64<T>.Count); Done_Reflection(); } //==================== Tests for return values of HVA64_03 // Return an HVA of 3 vectors, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA64_03 returnTest_HVA64_03() { return hva64_03; } public void testReturn_HVA64_03() { HVA64_03 result = returnTest_HVA64_03(); checkValues("testReturn_HVA64_03(result.v0)",result.v0, 0); checkValues("testReturn_HVA64_03(result.v1)",result.v1, 1 * Vector64<T>.Count); checkValues("testReturn_HVA64_03(result.v2)",result.v2, 2 * Vector64<T>.Count); } public void Init_Reflection_Return_HVA64_03() { isReflection = true; reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA64_03), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA64_03() { Init_Reflection_Return_HVA64_03(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA64_03 result = (HVA64_03)objResult; checkValues("testReflectionReturn_HVA64_03(result.v0)",result.v0, 0); checkValues("testReflectionReturn_HVA64_03(result.v1)",result.v1, 1 * Vector64<T>.Count); checkValues("testReflectionReturn_HVA64_03(result.v2)",result.v2, 2 * Vector64<T>.Count); Done_Reflection(); } //==================== Tests for return values of HVA64_04 // Return an HVA of 4 vectors, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA64_04 returnTest_HVA64_04() { return hva64_04; } public void testReturn_HVA64_04() { HVA64_04 result = returnTest_HVA64_04(); checkValues("testReturn_HVA64_04(result.v0)",result.v0, 0); checkValues("testReturn_HVA64_04(result.v1)",result.v1, 1 * Vector64<T>.Count); checkValues("testReturn_HVA64_04(result.v2)",result.v2, 2 * Vector64<T>.Count); checkValues("testReturn_HVA64_04(result.v3)",result.v3, 3 * Vector64<T>.Count); } public void Init_Reflection_Return_HVA64_04() { isReflection = true; reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA64_04), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA64_04() { Init_Reflection_Return_HVA64_04(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA64_04 result = (HVA64_04)objResult; checkValues("testReflectionReturn_HVA64_04(result.v0)",result.v0, 0); checkValues("testReflectionReturn_HVA64_04(result.v1)",result.v1, 1 * Vector64<T>.Count); checkValues("testReflectionReturn_HVA64_04(result.v2)",result.v2, 2 * Vector64<T>.Count); checkValues("testReflectionReturn_HVA64_04(result.v3)",result.v3, 3 * Vector64<T>.Count); Done_Reflection(); } //==================== Tests for return values of HVA64_05 // Return an HVA of 5 vectors, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA64_05 returnTest_HVA64_05() { return hva64_05; } public void testReturn_HVA64_05() { HVA64_05 result = returnTest_HVA64_05(); checkValues("testReturn_HVA64_05(result.v0)",result.v0, 0); checkValues("testReturn_HVA64_05(result.v1)",result.v1, 1 * Vector64<T>.Count); checkValues("testReturn_HVA64_05(result.v2)",result.v2, 2 * Vector64<T>.Count); checkValues("testReturn_HVA64_05(result.v3)",result.v3, 3 * Vector64<T>.Count); checkValues("testReturn_HVA64_05(result.v4)",result.v4, 4 * Vector64<T>.Count); } public void Init_Reflection_Return_HVA64_05() { isReflection = true; reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA64_05), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA64_05() { Init_Reflection_Return_HVA64_05(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA64_05 result = (HVA64_05)objResult; checkValues("testReflectionReturn_HVA64_05(result.v0)",result.v0, 0); checkValues("testReflectionReturn_HVA64_05(result.v1)",result.v1, 1 * Vector64<T>.Count); checkValues("testReflectionReturn_HVA64_05(result.v2)",result.v2, 2 * Vector64<T>.Count); checkValues("testReflectionReturn_HVA64_05(result.v3)",result.v3, 3 * Vector64<T>.Count); checkValues("testReflectionReturn_HVA64_05(result.v4)",result.v4, 4 * Vector64<T>.Count); Done_Reflection(); } //========== Vector128<T> tests //==================== Tests for passing 1 argumnet of HVA128_01 // Test the case where we've passed in a single argument HVA of 1 vectors. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA128_01(HVA128_01 arg1) { checkValues("test1Argument_HVA128_01(arg1.v0)", arg1.v0, 0); } public void Init_Reflection_Args_HVA128_01() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA128_01) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA128_01), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva128_01 }; } //==================== Tests for passing 1 argumnet of HVA128_02 // Test the case where we've passed in a single argument HVA of 2 vectors. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA128_02(HVA128_02 arg1) { checkValues("test1Argument_HVA128_02(arg1.v0)", arg1.v0, 0); checkValues("test1Argument_HVA128_02(arg1.v1)", arg1.v1, Vector128<T>.Count); } public void Init_Reflection_Args_HVA128_02() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA128_02) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA128_02), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva128_02 }; } //==================== Tests for passing 1 argumnet of HVA128_03 // Test the case where we've passed in a single argument HVA of 2 vectors. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA128_03(HVA128_03 arg1) { checkValues("test1Argument_HVA128_03(arg1.v0)", arg1.v0, 0); checkValues("test1Argument_HVA128_03(arg1.v1)", arg1.v1, 1 * Vector128<T>.Count); checkValues("test1Argument_HVA128_03(arg1.v2)", arg1.v2, 2 * Vector128<T>.Count); } public void Init_Reflection_Args_HVA128_03() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA128_03) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA128_03), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva128_03 }; } //==================== Tests for passing 1 argumnet of HVA128_04 // Test the case where we've passed in a single argument HVA of 2 vectors. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA128_04(HVA128_04 arg1) { checkValues("test1Argument_HVA128_04(arg1.v0)", arg1.v0, 0); checkValues("test1Argument_HVA128_04(arg1.v1)", arg1.v1, 1 * Vector128<T>.Count); checkValues("test1Argument_HVA128_04(arg1.v2)", arg1.v2, 2 * Vector128<T>.Count); checkValues("test1Argument_HVA128_04(arg1.v3)", arg1.v3, 3 * Vector128<T>.Count); } public void Init_Reflection_Args_HVA128_04() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA128_04) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA128_04), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva128_04 }; } //==================== Tests for passing 1 argumnet of HVA128_05 // Test the case where we've passed in a single argument HVA of 2 vectors. [MethodImpl(MethodImplOptions.NoInlining)] public void test1Argument_HVA128_05(HVA128_05 arg1) { checkValues("test1Argument_HVA128_05(arg1.v0)", arg1.v0, 0); checkValues("test1Argument_HVA128_05(arg1.v1)", arg1.v1, 1 * Vector128<T>.Count); checkValues("test1Argument_HVA128_05(arg1.v2)", arg1.v2, 2 * Vector128<T>.Count); checkValues("test1Argument_HVA128_05(arg1.v3)", arg1.v3, 3 * Vector128<T>.Count); checkValues("test1Argument_HVA128_05(arg1.v4)", arg1.v4, 4 * Vector128<T>.Count); } public void Init_Reflection_Args_HVA128_05() { isReflection = true; reflectionParameterTypes = new Type[] { typeof(HVA128_05) }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.test1Argument_HVA128_05), reflectionParameterTypes); reflectionInvokeArgs = new object[] { hva128_05 }; } //==================== Tests for return values of HVA128_01 // Return an HVA of 1 vector, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA128_01 returnTest_HVA128_01() { return hva128_01; } public void testReturn_HVA128_01() { HVA128_01 result = returnTest_HVA128_01(); checkValues("testReturn_HVA128_01(result.v0)",result.v0, 0); } public void Init_Reflection_Return_HVA128_01() { reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA128_01), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA128_01() { Init_Reflection_Return_HVA128_01(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA128_01 result = (HVA128_01)objResult; checkValues("testReflectionReturn_HVA128_01(result.v0)",result.v0, 0); Done_Reflection(); } //==================== Tests for return values of HVA128_02 // Return an HVA of 2 vectors, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA128_02 returnTest_HVA128_02() { return hva128_02; } public void testReturn_HVA128_02() { HVA128_02 result = returnTest_HVA128_02(); checkValues("testReturn_HVA128_02(result.v0)",result.v0, 0); checkValues("testReturn_HVA128_02(result.v1)",result.v1, Vector128<T>.Count); } public void Init_Reflection_Return_HVA128_02() { isReflection = true; reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA128_02), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA128_02() { Init_Reflection_Return_HVA128_02(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA128_02 result = (HVA128_02)objResult; checkValues("testReflectionReturn_HVA128_02(result.v0)",result.v0, 0); checkValues("testReflectionReturn_HVA128_02(result.v1)",result.v1, Vector128<T>.Count); Done_Reflection(); } //==================== Tests for return values of HVA128_03 // Return an HVA of 3 vectors, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA128_03 returnTest_HVA128_03() { return hva128_03; } public void testReturn_HVA128_03() { HVA128_03 result = returnTest_HVA128_03(); checkValues("testReturn_HVA128_03(result.v0)",result.v0, 0); checkValues("testReturn_HVA128_03(result.v1)",result.v1, 1 * Vector128<T>.Count); checkValues("testReturn_HVA128_03(result.v2)",result.v2, 2 * Vector128<T>.Count); } public void Init_Reflection_Return_HVA128_03() { isReflection = true; reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA128_03), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA128_03() { Init_Reflection_Return_HVA128_03(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA128_03 result = (HVA128_03)objResult; checkValues("testReflectionReturn_HVA128_03(result.v0)",result.v0, 0); checkValues("testReflectionReturn_HVA128_03(result.v1)",result.v1, 1 * Vector128<T>.Count); checkValues("testReflectionReturn_HVA128_03(result.v2)",result.v2, 2 * Vector128<T>.Count); Done_Reflection(); } //==================== Tests for return values of HVA128_04 // Return an HVA of 3 vectors, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA128_04 returnTest_HVA128_04() { return hva128_04; } public void testReturn_HVA128_04() { HVA128_04 result = returnTest_HVA128_04(); checkValues("testReturn_HVA128_04(result.v0)",result.v0, 0); checkValues("testReturn_HVA128_04(result.v1)",result.v1, 1 * Vector128<T>.Count); checkValues("testReturn_HVA128_04(result.v2)",result.v2, 2 * Vector128<T>.Count); checkValues("testReturn_HVA128_04(result.v3)",result.v3, 3 * Vector128<T>.Count); } public void Init_Reflection_Return_HVA128_04() { isReflection = true; reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA128_04), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA128_04() { Init_Reflection_Return_HVA128_04(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA128_04 result = (HVA128_04)objResult; checkValues("testReflectionReturn_HVA128_04(result.v0)",result.v0, 0); checkValues("testReflectionReturn_HVA128_04(result.v1)",result.v1, 1 * Vector128<T>.Count); checkValues("testReflectionReturn_HVA128_04(result.v2)",result.v2, 2 * Vector128<T>.Count); checkValues("testReflectionReturn_HVA128_04(result.v3)",result.v3, 3 * Vector128<T>.Count); Done_Reflection(); } //==================== Tests for return values of HVA128_05 // Return an HVA of 3 vectors, with values from the 'values' array. [MethodImpl(MethodImplOptions.NoInlining)] public HVA128_05 returnTest_HVA128_05() { return hva128_05; } public void testReturn_HVA128_05() { HVA128_05 result = returnTest_HVA128_05(); checkValues("testReturn_HVA128_05(result.v0)",result.v0, 0); checkValues("testReturn_HVA128_05(result.v1)",result.v1, 1 * Vector128<T>.Count); checkValues("testReturn_HVA128_05(result.v2)",result.v2, 2 * Vector128<T>.Count); checkValues("testReturn_HVA128_05(result.v3)",result.v3, 3 * Vector128<T>.Count); checkValues("testReturn_HVA128_05(result.v4)",result.v4, 4 * Vector128<T>.Count); } public void Init_Reflection_Return_HVA128_05() { isReflection = true; reflectionParameterTypes = new Type[] { }; reflectionMethodInfo = typeof(HVATests<T>).GetMethod(nameof(HVATests<T>.returnTest_HVA128_05), reflectionParameterTypes); reflectionInvokeArgs = new object[] { }; } public void testReflectionReturn_HVA128_05() { Init_Reflection_Return_HVA128_05(); object objResult = reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); HVA128_05 result = (HVA128_05)objResult; checkValues("testReflectionReturn_HVA128_05(result.v0)",result.v0, 0); checkValues("testReflectionReturn_HVA128_05(result.v1)",result.v1, 1 * Vector128<T>.Count); checkValues("testReflectionReturn_HVA128_05(result.v2)",result.v2, 2 * Vector128<T>.Count); checkValues("testReflectionReturn_HVA128_05(result.v3)",result.v3, 3 * Vector128<T>.Count); checkValues("testReflectionReturn_HVA128_05(result.v4)",result.v4, 4 * Vector128<T>.Count); Done_Reflection(); } ////////////////////////////////////////////////// public void doTests() { ////// Vector64<T> tests // Test HVA Vector64<T> Arguments test1Argument_HVA64_01(hva64_01); Init_Reflection_Args_HVA64_01(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); test1Argument_HVA64_02(hva64_02); Init_Reflection_Args_HVA64_02(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); test1Argument_HVA64_03(hva64_03); Init_Reflection_Args_HVA64_03(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); test1Argument_HVA64_04(hva64_04); Init_Reflection_Args_HVA64_04(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); test1Argument_HVA64_05(hva64_05); Init_Reflection_Args_HVA64_05(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); // Test HVA Vector64<T> Return values testReturn_HVA64_01(); testReflectionReturn_HVA64_01(); testReturn_HVA64_02(); testReflectionReturn_HVA64_02(); testReturn_HVA64_03(); testReflectionReturn_HVA64_03(); testReturn_HVA64_04(); testReflectionReturn_HVA64_04(); testReturn_HVA64_05(); testReflectionReturn_HVA64_05(); ////// Vector128<T> tests // Test HVA Vector128<T> Arguments test1Argument_HVA128_01(hva128_01); Init_Reflection_Args_HVA128_01(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); test1Argument_HVA128_02(hva128_02); Init_Reflection_Args_HVA128_02(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); test1Argument_HVA128_03(hva128_03); Init_Reflection_Args_HVA128_03(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); test1Argument_HVA128_04(hva128_04); Init_Reflection_Args_HVA128_04(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); test1Argument_HVA128_05(hva128_05); Init_Reflection_Args_HVA128_05(); reflectionMethodInfo.Invoke(this, reflectionInvokeArgs); Done_Reflection(); // Test HVA Vector128<T> Return values testReturn_HVA128_01(); testReflectionReturn_HVA128_01(); testReturn_HVA128_02(); testReflectionReturn_HVA128_02(); testReturn_HVA128_03(); testReflectionReturn_HVA128_03(); testReturn_HVA128_04(); testReflectionReturn_HVA128_04(); testReturn_HVA128_05(); testReflectionReturn_HVA128_05(); } } public static int Main(string[] args) { HVATests<byte> byteTests = new HVATests<byte>(); byteTests.doTests(); if (byteTests.isPassing) { Console.WriteLine("Test Passed"); } else { Console.WriteLine("Test FAILED"); } return byteTests.isPassing ? PASS : FAIL; } }
using System; using System.CodeDom.Compiler; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Microsoft.Extensions.Logging; using Orleans.CodeGeneration; namespace Orleans.Runtime { /// <summary> /// A collection of utility functions for dealing with Type information. /// </summary> internal static class TypeUtils { /// <summary> /// The assembly name of the core Orleans assembly. /// </summary> private static readonly AssemblyName OrleansCoreAssembly = typeof(RuntimeVersion).GetTypeInfo().Assembly.GetName(); /// <summary> /// The assembly name of the core Orleans abstractions assembly. /// </summary> private static readonly AssemblyName OrleansAbstractionsAssembly = typeof(IGrain).GetTypeInfo().Assembly.GetName(); private static readonly ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string> ParseableNameCache = new ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string>(); private static readonly ConcurrentDictionary<Tuple<Type, bool>, List<Type>> ReferencedTypes = new ConcurrentDictionary<Tuple<Type, bool>, List<Type>>(); private static readonly CachedReflectionOnlyTypeResolver ReflectionOnlyTypeResolver = new CachedReflectionOnlyTypeResolver(); public static string GetSimpleTypeName(Type t, Predicate<Type> fullName = null) { return GetSimpleTypeName(t.GetTypeInfo(), fullName); } public static string GetSimpleTypeName(TypeInfo typeInfo, Predicate<Type> fullName = null) { if (typeInfo.IsNestedPublic || typeInfo.IsNestedPrivate) { if (typeInfo.DeclaringType.GetTypeInfo().IsGenericType) { return GetTemplatedName( GetUntemplatedTypeName(typeInfo.DeclaringType.Name), typeInfo.DeclaringType, typeInfo.GetGenericArguments(), _ => true) + "." + GetUntemplatedTypeName(typeInfo.Name); } return GetTemplatedName(typeInfo.DeclaringType) + "." + GetUntemplatedTypeName(typeInfo.Name); } var type = typeInfo.AsType(); if (typeInfo.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name); return fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name; } public static string GetUntemplatedTypeName(string typeName) { int i = typeName.IndexOf('`'); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('<'); if (i > 0) { typeName = typeName.Substring(0, i); } return typeName; } public static string GetSimpleTypeName(string typeName) { int i = typeName.IndexOf('`'); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('['); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('<'); if (i > 0) { typeName = typeName.Substring(0, i); } return typeName; } public static bool IsConcreteTemplateType(Type t) { if (t.GetTypeInfo().IsGenericType) return true; return t.IsArray && IsConcreteTemplateType(t.GetElementType()); } public static string GetTemplatedName(Type t, Predicate<Type> fullName = null) { if (fullName == null) fullName = _ => true; // default to full type names var typeInfo = t.GetTypeInfo(); if (typeInfo.IsGenericType) return GetTemplatedName(GetSimpleTypeName(typeInfo, fullName), t, typeInfo.GetGenericArguments(), fullName); if (t.IsArray) { return GetTemplatedName(t.GetElementType(), fullName) + "[" + new string(',', t.GetArrayRank() - 1) + "]"; } return GetSimpleTypeName(typeInfo, fullName); } public static bool IsConstructedGenericType(this TypeInfo typeInfo) { // is there an API that returns this info without converting back to type already? return typeInfo.AsType().IsConstructedGenericType; } internal static IEnumerable<TypeInfo> GetTypeInfos(this Type[] types) { return types.Select(t => t.GetTypeInfo()); } public static string GetTemplatedName(string baseName, Type t, Type[] genericArguments, Predicate<Type> fullName) { var typeInfo = t.GetTypeInfo(); if (!typeInfo.IsGenericType || (t.DeclaringType != null && t.DeclaringType.GetTypeInfo().IsGenericType)) return baseName; string s = baseName; s += "<"; s += GetGenericTypeArgs(genericArguments, fullName); s += ">"; return s; } public static string GetGenericTypeArgs(IEnumerable<Type> args, Predicate<Type> fullName) { string s = string.Empty; bool first = true; foreach (var genericParameter in args) { if (!first) { s += ","; } if (!genericParameter.GetTypeInfo().IsGenericType) { s += GetSimpleTypeName(genericParameter, fullName); } else { s += GetTemplatedName(genericParameter, fullName); } first = false; } return s; } public static string GetParameterizedTemplateName(TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null) { if (fullName == null) fullName = tt => true; return GetParameterizedTemplateName(typeInfo, fullName, applyRecursively); } public static string GetParameterizedTemplateName(TypeInfo typeInfo, Predicate<Type> fullName, bool applyRecursively = false) { if (typeInfo.IsGenericType) { return GetParameterizedTemplateName(GetSimpleTypeName(typeInfo, fullName), typeInfo, applyRecursively, fullName); } var t = typeInfo.AsType(); if (fullName != null && fullName(t) == true) { return t.FullName; } return t.Name; } public static string GetParameterizedTemplateName(string baseName, TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null) { if (fullName == null) fullName = tt => false; if (!typeInfo.IsGenericType) return baseName; string s = baseName; s += "<"; bool first = true; foreach (var genericParameter in typeInfo.GetGenericArguments()) { if (!first) { s += ","; } var genericParameterTypeInfo = genericParameter.GetTypeInfo(); if (applyRecursively && genericParameterTypeInfo.IsGenericType) { s += GetParameterizedTemplateName(genericParameterTypeInfo, applyRecursively); } else { s += genericParameter.FullName == null || !fullName(genericParameter) ? genericParameter.Name : genericParameter.FullName; } first = false; } s += ">"; return s; } public static string GetRawClassName(string baseName, Type t) { var typeInfo = t.GetTypeInfo(); return typeInfo.IsGenericType ? baseName + '`' + typeInfo.GetGenericArguments().Length : baseName; } public static string GetRawClassName(string typeName) { int i = typeName.IndexOf('['); return i <= 0 ? typeName : typeName.Substring(0, i); } public static Type[] GenericTypeArgsFromClassName(string className) { return GenericTypeArgsFromArgsString(GenericTypeArgsString(className)); } public static Type[] GenericTypeArgsFromArgsString(string genericArgs) { if (string.IsNullOrEmpty(genericArgs)) return Type.EmptyTypes; var genericTypeDef = genericArgs.Replace("[]", "##"); // protect array arguments return InnerGenericTypeArgs(genericTypeDef); } private static Type[] InnerGenericTypeArgs(string className) { var typeArgs = new List<Type>(); var innerTypes = GetInnerTypes(className); foreach (var innerType in innerTypes) { if (innerType.StartsWith("[[")) // Resolve and load generic types recursively { InnerGenericTypeArgs(GenericTypeArgsString(innerType)); string genericTypeArg = className.Trim('[', ']'); typeArgs.Add(Type.GetType(genericTypeArg.Replace("##", "[]"))); } else { string nonGenericTypeArg = innerType.Trim('[', ']'); typeArgs.Add(Type.GetType(nonGenericTypeArg.Replace("##", "[]"))); } } return typeArgs.ToArray(); } private static string[] GetInnerTypes(string input) { // Iterate over strings of length 2 positionwise. var charsWithPositions = input.Zip(Enumerable.Range(0, input.Length), (c, i) => new { Ch = c, Pos = i }); var candidatesWithPositions = charsWithPositions.Zip(charsWithPositions.Skip(1), (c1, c2) => new { Str = c1.Ch.ToString() + c2.Ch, Pos = c1.Pos }); var results = new List<string>(); int startPos = -1; int endPos = -1; int endTokensNeeded = 0; string curStartToken = ""; string curEndToken = ""; var tokenPairs = new[] { new { Start = "[[", End = "]]" }, new { Start = "[", End = "]" } }; // Longer tokens need to come before shorter ones foreach (var candidate in candidatesWithPositions) { if (startPos == -1) { foreach (var token in tokenPairs) { if (candidate.Str.StartsWith(token.Start)) { curStartToken = token.Start; curEndToken = token.End; startPos = candidate.Pos; break; } } } if (curStartToken != "" && candidate.Str.StartsWith(curStartToken)) endTokensNeeded++; if (curEndToken != "" && candidate.Str.EndsWith(curEndToken)) { endPos = candidate.Pos; endTokensNeeded--; } if (endTokensNeeded == 0 && startPos != -1) { results.Add(input.Substring(startPos, endPos - startPos + 2)); startPos = -1; curStartToken = ""; } } return results.ToArray(); } public static string GenericTypeArgsString(string className) { int startIndex = className.IndexOf('['); int endIndex = className.LastIndexOf(']'); return className.Substring(startIndex + 1, endIndex - startIndex - 1); } public static bool IsGenericClass(string name) { return name.Contains("`") || name.Contains("["); } public static string GetFullName(TypeInfo typeInfo) { if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo)); return GetFullName(typeInfo.AsType()); } public static string GetFullName(Type t) { if (t == null) throw new ArgumentNullException(nameof(t)); if (t.IsNested && !t.IsGenericParameter) { return t.Namespace + "." + t.DeclaringType.Name + "." + t.Name; } if (t.IsArray) { return GetFullName(t.GetElementType()) + "[" + new string(',', t.GetArrayRank() - 1) + "]"; } return t.FullName ?? (t.IsGenericParameter ? t.Name : t.Namespace + "." + t.Name); } /// <summary> /// Returns all fields of the specified type. /// </summary> /// <param name="type">The type.</param> /// <returns>All fields of the specified type.</returns> public static IEnumerable<FieldInfo> GetAllFields(this Type type) { const BindingFlags AllFields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; var current = type; while ((current != typeof(object)) && (current != null)) { var fields = current.GetFields(AllFields); foreach (var field in fields) { yield return field; } current = current.GetTypeInfo().BaseType; } } /// <summary> /// Returns <see langword="true"/> if <paramref name="field"/> is marked as /// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise. /// </summary> /// <param name="field">The field.</param> /// <returns> /// <see langword="true"/> if <paramref name="field"/> is marked as /// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise. /// </returns> public static bool IsNotSerialized(this FieldInfo field) => (field.Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized; /// <summary> /// decide whether the class is derived from Grain /// </summary> public static bool IsGrainClass(Type type) { var grainType = typeof(Grain); var grainChevronType = typeof(Grain<>); if (type.Assembly.ReflectionOnly) { grainType = ToReflectionOnlyType(grainType); grainChevronType = ToReflectionOnlyType(grainChevronType); } if (grainType == type || grainChevronType == type) return false; if (!grainType.IsAssignableFrom(type)) return false; // exclude generated classes. return !IsGeneratedType(type); } public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints, bool complain) { complaints = null; if (!IsGrainClass(type)) return false; if (!type.GetTypeInfo().IsAbstract) return true; complaints = complain ? new[] { string.Format("Grain type {0} is abstract and cannot be instantiated.", type.FullName) } : null; return false; } public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints) { return IsConcreteGrainClass(type, out complaints, complain: true); } public static bool IsConcreteGrainClass(Type type) { IEnumerable<string> complaints; return IsConcreteGrainClass(type, out complaints, complain: false); } public static bool IsGeneratedType(Type type) { return TypeHasAttribute(type, typeof(GeneratedCodeAttribute)); } /// <summary> /// Returns true if the provided <paramref name="type"/> is in any of the provided /// <paramref name="namespaces"/>, false otherwise. /// </summary> /// <param name="type">The type to check.</param> /// <param name="namespaces"></param> /// <returns> /// true if the provided <paramref name="type"/> is in any of the provided <paramref name="namespaces"/>, false /// otherwise. /// </returns> public static bool IsInNamespace(Type type, List<string> namespaces) { if (type.Namespace == null) { return false; } foreach (var ns in namespaces) { if (ns.Length > type.Namespace.Length) { continue; } // If the candidate namespace is a prefix of the type's namespace, return true. if (type.Namespace.StartsWith(ns, StringComparison.Ordinal) && (type.Namespace.Length == ns.Length || type.Namespace[ns.Length] == '.')) { return true; } } return false; } /// <summary> /// Returns true if <paramref name="type"/> has implementations of all serialization methods, false otherwise. /// </summary> /// <param name="type">The type.</param> /// <returns> /// true if <paramref name="type"/> has implementations of all serialization methods, false otherwise. /// </returns> public static bool HasAllSerializationMethods(Type type) { // Check if the type has any of the serialization methods. var hasCopier = false; var hasSerializer = false; var hasDeserializer = false; foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { hasSerializer |= method.GetCustomAttribute<SerializerMethodAttribute>(false) != null; hasDeserializer |= method.GetCustomAttribute<DeserializerMethodAttribute>(false) != null; hasCopier |= method.GetCustomAttribute<CopierMethodAttribute>(false) != null; } var hasAllSerializationMethods = hasCopier && hasSerializer && hasDeserializer; return hasAllSerializationMethods; } public static bool IsGrainMethodInvokerType(Type type) { var generalType = typeof(IGrainMethodInvoker); if (type.Assembly.ReflectionOnly) { generalType = ToReflectionOnlyType(generalType); } return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(MethodInvokerAttribute)); } private static readonly Lazy<bool> canUseReflectionOnly = new Lazy<bool>(() => { try { ReflectionOnlyTypeResolver.TryResolveType(typeof(TypeUtils).AssemblyQualifiedName, out _); return true; } catch (PlatformNotSupportedException) { return false; } catch (Exception) { // if other exceptions not related to platform ocurr, assume that ReflectionOnly is supported return true; } }); public static bool CanUseReflectionOnly => canUseReflectionOnly.Value; public static Type ResolveReflectionOnlyType(string assemblyQualifiedName) { return ReflectionOnlyTypeResolver.ResolveType(assemblyQualifiedName); } public static Type ToReflectionOnlyType(Type type) { if (CanUseReflectionOnly) { return type.Assembly.ReflectionOnly ? type : ResolveReflectionOnlyType(type.AssemblyQualifiedName); } else { return type; } } public static IEnumerable<Type> GetTypes(Assembly assembly, Predicate<Type> whereFunc, ILogger logger) { return assembly.IsDynamic ? Enumerable.Empty<Type>() : GetDefinedTypes(assembly, logger).Select(t => t.AsType()).Where(type => !type.GetTypeInfo().IsNestedPrivate && whereFunc(type)); } public static IEnumerable<TypeInfo> GetDefinedTypes(Assembly assembly, ILogger logger=null) { try { return assembly.DefinedTypes; } catch (Exception exception) { if (logger != null && logger.IsEnabled(LogLevel.Warning)) { var message = $"Exception loading types from assembly '{assembly.FullName}': {LogFormatter.PrintException(exception)}."; logger.Warn(ErrorCode.Loader_TypeLoadError_5, message, exception); } var typeLoadException = exception as ReflectionTypeLoadException; if (typeLoadException != null) { return typeLoadException.Types?.Where(type => type != null).Select(type => type.GetTypeInfo()) ?? Enumerable.Empty<TypeInfo>(); } return Enumerable.Empty<TypeInfo>(); } } /// <summary> /// Returns a value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method. /// </summary> /// <param name="methodInfo">The method.</param> /// <returns>A value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.</returns> public static bool IsGrainMethod(MethodInfo methodInfo) { if (methodInfo == null) throw new ArgumentNullException("methodInfo", "Cannot inspect null method info"); if (methodInfo.IsStatic || methodInfo.IsSpecialName || methodInfo.DeclaringType == null) { return false; } return methodInfo.DeclaringType.GetTypeInfo().IsInterface && typeof(IAddressable).IsAssignableFrom(methodInfo.DeclaringType); } public static bool TypeHasAttribute(Type type, Type attribType) { if (type.Assembly.ReflectionOnly || attribType.Assembly.ReflectionOnly) { type = ToReflectionOnlyType(type); attribType = ToReflectionOnlyType(attribType); // we can't use Type.GetCustomAttributes here because we could potentially be working with a reflection-only type. return CustomAttributeData.GetCustomAttributes(type).Any( attrib => attribType.IsAssignableFrom(attrib.AttributeType)); } return TypeHasAttribute(type.GetTypeInfo(), attribType); } public static bool TypeHasAttribute(TypeInfo typeInfo, Type attribType) { return typeInfo.GetCustomAttributes(attribType, true).Any(); } /// <summary> /// Returns a sanitized version of <paramref name="type"/>s name which is suitable for use as a class name. /// </summary> /// <param name="type"> /// The grain type. /// </param> /// <returns> /// A sanitized version of <paramref name="type"/>s name which is suitable for use as a class name. /// </returns> public static string GetSuitableClassName(Type type) { return GetClassNameFromInterfaceName(type.GetUnadornedTypeName()); } /// <summary> /// Returns a class-like version of <paramref name="interfaceName"/>. /// </summary> /// <param name="interfaceName"> /// The interface name. /// </param> /// <returns> /// A class-like version of <paramref name="interfaceName"/>. /// </returns> public static string GetClassNameFromInterfaceName(string interfaceName) { string cleanName; if (interfaceName.StartsWith("i", StringComparison.OrdinalIgnoreCase)) { cleanName = interfaceName.Substring(1); } else { cleanName = interfaceName; } return cleanName; } /// <summary> /// Returns the non-generic type name without any special characters. /// </summary> /// <param name="type"> /// The type. /// </param> /// <returns> /// The non-generic type name without any special characters. /// </returns> public static string GetUnadornedTypeName(this Type type) { var index = type.Name.IndexOf('`'); // An ampersand can appear as a suffix to a by-ref type. return (index > 0 ? type.Name.Substring(0, index) : type.Name).TrimEnd('&'); } /// <summary> /// Returns the non-generic method name without any special characters. /// </summary> /// <param name="method"> /// The method. /// </param> /// <returns> /// The non-generic method name without any special characters. /// </returns> public static string GetUnadornedMethodName(this MethodInfo method) { var index = method.Name.IndexOf('`'); return index > 0 ? method.Name.Substring(0, index) : method.Name; } /// <summary>Returns a string representation of <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="options">The type formatting options.</param> /// <param name="getNameFunc">The delegate used to get the unadorned, simple type name of <paramref name="type"/>.</param> /// <returns>A string representation of the <paramref name="type"/>.</returns> public static string GetParseableName(this Type type, TypeFormattingOptions options = null, Func<Type, string> getNameFunc = null) { options = options ?? TypeFormattingOptions.Default; // If a naming function has been specified, skip the cache. if (getNameFunc != null) return BuildParseableName(); return ParseableNameCache.GetOrAdd(Tuple.Create(type, options), _ => BuildParseableName()); string BuildParseableName() { var builder = new StringBuilder(); var typeInfo = type.GetTypeInfo(); GetParseableName( type, builder, new Queue<Type>( typeInfo.IsGenericTypeDefinition ? typeInfo.GetGenericArguments() : typeInfo.GenericTypeArguments), options, getNameFunc ?? (t => t.GetUnadornedTypeName() + options.NameSuffix)); return builder.ToString(); } } /// <summary>Returns a string representation of <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="builder">The <see cref="StringBuilder"/> to append results to.</param> /// <param name="typeArguments">The type arguments of <paramref name="type"/>.</param> /// <param name="options">The type formatting options.</param> private static void GetParseableName( Type type, StringBuilder builder, Queue<Type> typeArguments, TypeFormattingOptions options, Func<Type, string> getNameFunc) { var typeInfo = type.GetTypeInfo(); if (typeInfo.IsArray) { var elementType = typeInfo.GetElementType().GetParseableName(options); if (!string.IsNullOrWhiteSpace(elementType)) { builder.AppendFormat( "{0}[{1}]", elementType, string.Concat(Enumerable.Range(0, type.GetArrayRank() - 1).Select(_ => ','))); } return; } if (typeInfo.IsGenericParameter) { if (options.IncludeGenericTypeParameters) { builder.Append(type.GetUnadornedTypeName()); } return; } if (typeInfo.DeclaringType != null) { // This is not the root type. GetParseableName(typeInfo.DeclaringType, builder, typeArguments, options, t => t.GetUnadornedTypeName()); builder.Append(options.NestedTypeSeparator); } else if (!string.IsNullOrWhiteSpace(type.Namespace) && options.IncludeNamespace) { // This is the root type, so include the namespace. var namespaceName = type.Namespace; if (options.NestedTypeSeparator != '.') { namespaceName = namespaceName.Replace('.', options.NestedTypeSeparator); } if (options.IncludeGlobal) { builder.AppendFormat("global::"); } builder.AppendFormat("{0}{1}", namespaceName, options.NestedTypeSeparator); } if (type.IsConstructedGenericType) { // Get the unadorned name, the generic parameters, and add them together. var unadornedTypeName = getNameFunc(type); builder.Append(EscapeIdentifier(unadornedTypeName)); var generics = Enumerable.Range(0, Math.Min(typeInfo.GetGenericArguments().Count(), typeArguments.Count)) .Select(_ => typeArguments.Dequeue()) .ToList(); if (generics.Count > 0 && options.IncludeTypeParameters) { var genericParameters = string.Join( ",", generics.Select(generic => GetParseableName(generic, options))); builder.AppendFormat("<{0}>", genericParameters); } } else if (typeInfo.IsGenericTypeDefinition) { // Get the unadorned name, the generic parameters, and add them together. var unadornedTypeName = getNameFunc(type); builder.Append(EscapeIdentifier(unadornedTypeName)); var generics = Enumerable.Range(0, Math.Min(type.GetGenericArguments().Count(), typeArguments.Count)) .Select(_ => typeArguments.Dequeue()) .ToList(); if (generics.Count > 0 && options.IncludeTypeParameters) { var genericParameters = string.Join( ",", generics.Select(_ => options.IncludeGenericTypeParameters ? _.ToString() : string.Empty)); builder.AppendFormat("<{0}>", genericParameters); } } else { builder.Append(EscapeIdentifier(getNameFunc(type))); } } /// <summary> /// Returns the namespaces of the specified types. /// </summary> /// <param name="types"> /// The types to include. /// </param> /// <returns> /// The namespaces of the specified types. /// </returns> public static IEnumerable<string> GetNamespaces(params Type[] types) { return types.Select(type => "global::" + type.Namespace).Distinct(); } /// <summary> /// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T"> /// The containing type of the method. /// </typeparam> /// <typeparam name="TResult"> /// The return type of the method. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </returns> public static MethodInfo Method<T, TResult>(Expression<Func<T, TResult>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T"> /// The containing type of the property. /// </typeparam> /// <typeparam name="TResult"> /// The return type of the property. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>. /// </returns> public static PropertyInfo Property<T, TResult>(Expression<Func<T, TResult>> expression) { var property = expression.Body as MemberExpression; if (property != null) { return property.Member as PropertyInfo; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="TResult"> /// The return type of the property. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>. /// </returns> public static PropertyInfo Property<TResult>(Expression<Func<TResult>> expression) { var property = expression.Body as MemberExpression; if (property != null) { return property.Member as PropertyInfo; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T"> /// The containing type of the method. /// </typeparam> /// <typeparam name="TResult"> /// The return type of the method. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>. /// </returns> public static MemberInfo Member<T, TResult>(Expression<Func<T, TResult>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } var property = expression.Body as MemberExpression; if (property != null) { return property.Member; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.</summary> /// <typeparam name="TResult">The return type of the method.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.</returns> public static MemberInfo Member<TResult>(Expression<Func<TResult>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } var property = expression.Body as MemberExpression; if (property != null) { return property.Member; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</summary> /// <typeparam name="T">The containing type of the method.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns> public static MethodInfo Method<T>(Expression<Func<T>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T">The containing type of the method.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns> public static MethodInfo Method<T>(Expression<Action<T>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </summary> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </returns> public static MethodInfo Method(Expression<Action> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</summary> /// <param name="type">The type.</param> /// <returns>The namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</returns> public static string GetNamespaceOrEmpty(this Type type) { if (type == null || string.IsNullOrEmpty(type.Namespace)) { return string.Empty; } return type.Namespace; } /// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param> /// <returns>The types referenced by the provided <paramref name="type"/>.</returns> public static IList<Type> GetTypes(this Type type, bool includeMethods = false) { List<Type> results; var key = Tuple.Create(type, includeMethods); if (!ReferencedTypes.TryGetValue(key, out results)) { results = GetTypes(type, includeMethods, null).ToList(); ReferencedTypes.TryAdd(key, results); } return results; } /// <summary> /// Get a public or non-public constructor that matches the constructor arguments signature /// </summary> /// <param name="type">The type to use.</param> /// <param name="constructorArguments">The constructor argument types to match for the signature.</param> /// <returns>A constructor that matches the signature or <see langword="null"/>.</returns> public static ConstructorInfo GetConstructorThatMatches(Type type, Type[] constructorArguments) { var constructorInfo = type.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, constructorArguments, null); return constructorInfo; } /// <summary> /// Returns a value indicating whether or not the provided assembly is the Orleans assembly or references it. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>A value indicating whether or not the provided assembly is the Orleans assembly or references it.</returns> internal static bool IsOrleansOrReferencesOrleans(Assembly assembly) { // We want to be loosely coupled to the assembly version if an assembly depends on an older Orleans, // but we want a strong assembly match for the Orleans binary itself // (so we don't load 2 different versions of Orleans by mistake) var references = assembly.GetReferencedAssemblies(); return DoReferencesContain(references, OrleansCoreAssembly) || DoReferencesContain(references, OrleansAbstractionsAssembly) || string.Equals(assembly.GetName().FullName, OrleansCoreAssembly.FullName, StringComparison.Ordinal); } /// <summary> /// Returns a value indicating whether or not the specified references contain the provided assembly name. /// </summary> /// <param name="references">The references.</param> /// <param name="assemblyName">The assembly name.</param> /// <returns>A value indicating whether or not the specified references contain the provided assembly name.</returns> private static bool DoReferencesContain(IReadOnlyCollection<AssemblyName> references, AssemblyName assemblyName) { if (references.Count == 0) { return false; } return references.Any(asm => string.Equals(asm.Name, assemblyName.Name, StringComparison.Ordinal)); } /// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param> /// <param name="exclude">Types to exclude</param> /// <returns>The types referenced by the provided <paramref name="type"/>.</returns> private static IEnumerable<Type> GetTypes( this Type type, bool includeMethods, HashSet<Type> exclude) { exclude = exclude ?? new HashSet<Type>(); if (!exclude.Add(type)) { yield break; } yield return type; if (type.IsArray) { foreach (var elementType in type.GetElementType().GetTypes(false, exclude: exclude)) { yield return elementType; } } if (type.IsConstructedGenericType) { foreach (var genericTypeArgument in type.GetGenericArguments().SelectMany(_ => GetTypes(_, false, exclude: exclude))) { yield return genericTypeArgument; } } if (!includeMethods) { yield break; } foreach (var method in type.GetMethods()) { foreach (var referencedType in GetTypes(method.ReturnType, false, exclude: exclude)) { yield return referencedType; } foreach (var parameter in method.GetParameters()) { foreach (var referencedType in GetTypes(parameter.ParameterType, false, exclude: exclude)) { yield return referencedType; } } } } private static string EscapeIdentifier(string identifier) { if (IsCSharpKeyword(identifier)) return "@" + identifier; return identifier; } internal static bool IsCSharpKeyword(string identifier) { switch (identifier) { case "abstract": case "add": case "alias": case "as": case "ascending": case "async": case "await": case "base": case "bool": case "break": case "byte": case "case": case "catch": case "char": case "checked": case "class": case "const": case "continue": case "decimal": case "default": case "delegate": case "descending": case "do": case "double": case "dynamic": case "else": case "enum": case "event": case "explicit": case "extern": case "false": case "finally": case "fixed": case "float": case "for": case "foreach": case "from": case "get": case "global": case "goto": case "group": case "if": case "implicit": case "in": case "int": case "interface": case "internal": case "into": case "is": case "join": case "let": case "lock": case "long": case "nameof": case "namespace": case "new": case "null": case "object": case "operator": case "orderby": case "out": case "override": case "params": case "partial": case "private": case "protected": case "public": case "readonly": case "ref": case "remove": case "return": case "sbyte": case "sealed": case "select": case "set": case "short": case "sizeof": case "stackalloc": case "static": case "string": case "struct": case "switch": case "this": case "throw": case "true": case "try": case "typeof": case "uint": case "ulong": case "unchecked": case "unsafe": case "ushort": case "using": case "value": case "var": case "virtual": case "void": case "volatile": case "when": case "where": case "while": case "yield": return true; default: return false; } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; public sealed class CompoundValueHandle : AbstractValueHandle { public struct Fragment { // // State // public AbstractValueHandle Component; public int Offset; // // Contructor Methods // public Fragment( AbstractValueHandle component , int offset ) { this.Component = component; this.Offset = offset; } // // Helper Methods // internal bool IsEquivalent( ref Fragment other ) { if(this.Offset == other.Offset) { if(this.Component.IsEquivalent( other.Component )) { return true; } } return false; } internal bool Read( Emulation.Hosting.BinaryBlob bb , int offset , int count , out bool fChanged ) { if(this.Component == null) { fChanged = false; return false; } int start = Math.Max( offset , this.Offset ); int end = Math.Min( offset + count, this.Offset + this.Component.Size ); if(start >= end) { // // Non-overlapping regions. // fChanged = false; return true; } var bbSub = this.Component.Read( start - this.Offset, end - start, out fChanged ); if(bbSub != null) { bb.Insert( bbSub, start - offset ); return true; } return false; } internal bool Write( Emulation.Hosting.BinaryBlob bb , int offset , int count ) { if(this.Component == null) { return false; } int start = Math.Max( offset , this.Offset ); int end = Math.Min( offset + count, this.Offset + this.Component.Size ); if(start >= end) { // // Non-overlapping regions. // return true; } var bbSub = bb.Extract( start - offset, end - start ); return this.Component.Write( bbSub, start - this.Offset, end - start ); } } // // State // public readonly Fragment[] Fragments; // // Contructor Methods // public CompoundValueHandle( TS.TypeRepresentation type , bool fAsHoldingVariable , params Fragment[] fragments ) : base( type, null, null, fAsHoldingVariable ) { this.Fragments = fragments; } // // Helper Methods // public override bool IsEquivalent( AbstractValueHandle abstractValueHandle ) { var other = abstractValueHandle as CompoundValueHandle; if(other != null) { if(this.Fragments.Length == other.Fragments.Length) { for(int i = 0; i < this.Fragments.Length; i++) { if(this.Fragments[i].IsEquivalent( ref other.Fragments[i] ) == false) { return false; } } return true; } } return false; } public override Emulation.Hosting.BinaryBlob Read( int offset , int count , out bool fChanged ) { var bb = new Emulation.Hosting.BinaryBlob( count ); fChanged = false; foreach(var fragment in this.Fragments) { bool fChangedFragment; if(fragment.Read( bb, offset, count, out fChangedFragment ) == false) { return null; } fChanged |= fChangedFragment; } return bb; } public override bool Write( Emulation.Hosting.BinaryBlob bb , int offset , int count ) { foreach(var fragment in this.Fragments) { if(fragment.Write( bb, offset, count ) == false) { return false; } } return true; } public override AbstractValueHandle AccessField( TS.InstanceFieldRepresentation fd , TS.CustomAttributeRepresentation caMemoryMappedPeripheral , TS.CustomAttributeRepresentation caMemoryMappedRegister ) { int offset = fd.Offset; int size = (int)fd.FieldType.SizeOfHoldingVariable; foreach(var fragment in this.Fragments) { if(fragment.Offset == offset) { var subLoc = fragment.Component; if(subLoc != null && subLoc.Size == size) { return subLoc; } } } return base.AccessField( fd, caMemoryMappedPeripheral, caMemoryMappedRegister ); } // // Access Methods // public override bool CanUpdate { get { foreach(var fragment in this.Fragments) { if(fragment.Component == null) { return false; } if(fragment.Component.CanUpdate == false) { return false; } } return true; } } public override bool HasAddress { get { return false; } } public override uint Address { get { return 0; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.StorSimple; using Microsoft.WindowsAzure.Management.StorSimple.Models; namespace Microsoft.WindowsAzure.Management.StorSimple { /// <summary> /// All Operations related to Device Details /// </summary> internal partial class DeviceDetailsOperations : IServiceOperations<StorSimpleManagementClient>, IDeviceDetailsOperations { /// <summary> /// Initializes a new instance of the DeviceDetailsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DeviceDetailsOperations(StorSimpleManagementClient client) { this._client = client; } private StorSimpleManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.StorSimple.StorSimpleManagementClient. /// </summary> public StorSimpleManagementClient Client { get { return this._client; } } /// <summary> /// Begin task for updating device details as specified by /// deviceDetails. The task can then be tracked for completion using /// returned task information /// </summary> /// <param name='deviceDetails'> /// Required. Updated DeviceDetails. Contains the corresponding DeviceId /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// This is the Task Response for all Async Calls /// </returns> public async Task<GuidTaskResponse> BeginUpdateDeviceDetailsAsync(DeviceDetailsRequest deviceDetails, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceDetails == null) { throw new ArgumentNullException("deviceDetails"); } if (deviceDetails.Chap != null) { if (deviceDetails.Chap.InitiatorSecret == null) { throw new ArgumentNullException("deviceDetails.Chap.InitiatorSecret"); } if (deviceDetails.Chap.InitiatorUser == null) { throw new ArgumentNullException("deviceDetails.Chap.InitiatorUser"); } if (deviceDetails.Chap.TargetSecret == null) { throw new ArgumentNullException("deviceDetails.Chap.TargetSecret"); } if (deviceDetails.Chap.TargetUser == null) { throw new ArgumentNullException("deviceDetails.Chap.TargetUser"); } } if (deviceDetails.DeviceProperties != null) { if (deviceDetails.DeviceProperties.ActivationTime == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.ActivationTime"); } if (deviceDetails.DeviceProperties.Culture == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.Culture"); } if (deviceDetails.DeviceProperties.Description == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.Description"); } if (deviceDetails.DeviceProperties.DeviceId == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.DeviceId"); } if (deviceDetails.DeviceProperties.DeviceSoftwareVersion == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.DeviceSoftwareVersion"); } if (deviceDetails.DeviceProperties.FriendlyName == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.FriendlyName"); } if (deviceDetails.DeviceProperties.Location == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.Location"); } if (deviceDetails.DeviceProperties.ModelDescription == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.ModelDescription"); } if (deviceDetails.DeviceProperties.SerialNumber == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.SerialNumber"); } if (deviceDetails.DeviceProperties.TargetIQN == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.TargetIQN"); } if (deviceDetails.DeviceProperties.TimeZone == null) { throw new ArgumentNullException("deviceDetails.DeviceProperties.TimeZone"); } } if (deviceDetails.DnsServer != null) { if (deviceDetails.DnsServer.PrimaryIPv4 == null) { throw new ArgumentNullException("deviceDetails.DnsServer.PrimaryIPv4"); } if (deviceDetails.DnsServer.PrimaryIPv6 == null) { throw new ArgumentNullException("deviceDetails.DnsServer.PrimaryIPv6"); } } if (deviceDetails.Name == null) { throw new ArgumentNullException("deviceDetails.Name"); } if (deviceDetails.NetInterfaceList != null) { foreach (NetInterface netInterfaceListParameterItem in deviceDetails.NetInterfaceList) { if (netInterfaceListParameterItem.NicIPv4Settings != null) { if (netInterfaceListParameterItem.NicIPv4Settings.IPv4Address == null) { throw new ArgumentNullException("deviceDetails.NetInterfaceList.NicIPv4Settings.IPv4Address"); } if (netInterfaceListParameterItem.NicIPv4Settings.IPv4Netmask == null) { throw new ArgumentNullException("deviceDetails.NetInterfaceList.NicIPv4Settings.IPv4Netmask"); } } if (netInterfaceListParameterItem.NicIPv6Settings != null) { if (netInterfaceListParameterItem.NicIPv6Settings.IPv6Prefix == null) { throw new ArgumentNullException("deviceDetails.NetInterfaceList.NicIPv6Settings.IPv6Prefix"); } } } } if (deviceDetails.TimeServer != null) { if (deviceDetails.TimeServer.Primary == null) { throw new ArgumentNullException("deviceDetails.TimeServer.Primary"); } if (deviceDetails.TimeServer.TimeZone == null) { throw new ArgumentNullException("deviceDetails.TimeServer.TimeZone"); } } if (deviceDetails.WebProxy != null) { if (deviceDetails.WebProxy.ConnectionURI == null) { throw new ArgumentNullException("deviceDetails.WebProxy.ConnectionURI"); } if (deviceDetails.WebProxy.Username == null) { throw new ArgumentNullException("deviceDetails.WebProxy.Username"); } } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceDetails", deviceDetails); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "BeginUpdateDeviceDetailsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; if (deviceDetails.DeviceProperties != null && deviceDetails.DeviceProperties.DeviceId != null) { url = url + Uri.EscapeDataString(deviceDetails.DeviceProperties.DeviceId); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.3.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement deviceDetailsV3Element = new XElement(XName.Get("DeviceDetails_V3", "http://windowscloudbackup.com/CiS/V2013_03")); requestDoc.Add(deviceDetailsV3Element); if (deviceDetails.InstanceId != null) { XElement instanceIdElement = new XElement(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); instanceIdElement.Value = deviceDetails.InstanceId; deviceDetailsV3Element.Add(instanceIdElement); } XElement nameElement = new XElement(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); nameElement.Value = deviceDetails.Name; deviceDetailsV3Element.Add(nameElement); XElement operationInProgressElement = new XElement(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); operationInProgressElement.Value = deviceDetails.OperationInProgress.ToString(); deviceDetailsV3Element.Add(operationInProgressElement); if (deviceDetails.AlertNotification != null) { XElement alertNotificationElement = new XElement(XName.Get("AlertNotification", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(alertNotificationElement); if (deviceDetails.AlertNotification.AlertNotifcationCulture != null) { XElement alertNotifcationCultureElement = new XElement(XName.Get("AlertNotifcationCulture", "http://windowscloudbackup.com/CiS/V2013_03")); alertNotifcationCultureElement.Value = deviceDetails.AlertNotification.AlertNotifcationCulture; alertNotificationElement.Add(alertNotifcationCultureElement); } XElement alertNotifcationEnabledElement = new XElement(XName.Get("AlertNotifcationEnabled", "http://windowscloudbackup.com/CiS/V2013_03")); alertNotifcationEnabledElement.Value = deviceDetails.AlertNotification.AlertNotifcationEnabled.ToString().ToLower(); alertNotificationElement.Add(alertNotifcationEnabledElement); if (deviceDetails.AlertNotification.AlertNotificationEmailList != null) { XElement alertNotificationEmailListSequenceElement = new XElement(XName.Get("AlertNotificationEmailList", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (string alertNotificationEmailListItem in deviceDetails.AlertNotification.AlertNotificationEmailList) { XElement alertNotificationEmailListItemElement = new XElement(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")); alertNotificationEmailListItemElement.Value = alertNotificationEmailListItem; alertNotificationEmailListSequenceElement.Add(alertNotificationEmailListItemElement); } alertNotificationElement.Add(alertNotificationEmailListSequenceElement); } XElement alertNotificationEnabledForAdminCoAdminsElement = new XElement(XName.Get("AlertNotificationEnabledForAdminCoAdmins", "http://windowscloudbackup.com/CiS/V2013_03")); alertNotificationEnabledForAdminCoAdminsElement.Value = deviceDetails.AlertNotification.AlertNotificationEnabledForAdminCoAdmins.ToString().ToLower(); alertNotificationElement.Add(alertNotificationEnabledForAdminCoAdminsElement); } if (deviceDetails.Chap != null) { XElement chapElement = new XElement(XName.Get("Chap", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(chapElement); XElement initiatorSecretElement = new XElement(XName.Get("InitiatorSecret", "http://windowscloudbackup.com/CiS/V2013_03")); initiatorSecretElement.Value = deviceDetails.Chap.InitiatorSecret; chapElement.Add(initiatorSecretElement); XElement initiatorUserElement = new XElement(XName.Get("InitiatorUser", "http://windowscloudbackup.com/CiS/V2013_03")); initiatorUserElement.Value = deviceDetails.Chap.InitiatorUser; chapElement.Add(initiatorUserElement); XElement targetSecretElement = new XElement(XName.Get("TargetSecret", "http://windowscloudbackup.com/CiS/V2013_03")); targetSecretElement.Value = deviceDetails.Chap.TargetSecret; chapElement.Add(targetSecretElement); XElement targetUserElement = new XElement(XName.Get("TargetUser", "http://windowscloudbackup.com/CiS/V2013_03")); targetUserElement.Value = deviceDetails.Chap.TargetUser; chapElement.Add(targetUserElement); } if (deviceDetails.DeviceProperties != null) { XElement devicePropertiesElement = new XElement(XName.Get("DeviceProperties", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(devicePropertiesElement); XElement aCRCountElement = new XElement(XName.Get("ACRCount", "http://windowscloudbackup.com/CiS/V2013_03")); aCRCountElement.Value = deviceDetails.DeviceProperties.ACRCount.ToString(); devicePropertiesElement.Add(aCRCountElement); XElement activationTimeElement = new XElement(XName.Get("ActivationTime", "http://windowscloudbackup.com/CiS/V2013_03")); activationTimeElement.Value = deviceDetails.DeviceProperties.ActivationTime; devicePropertiesElement.Add(activationTimeElement); XElement activeControllerElement = new XElement(XName.Get("ActiveController", "http://windowscloudbackup.com/CiS/V2013_03")); activeControllerElement.Value = deviceDetails.DeviceProperties.ActiveController.ToString(); devicePropertiesElement.Add(activeControllerElement); XElement availableStorageInBytesElement = new XElement(XName.Get("AvailableStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03")); availableStorageInBytesElement.Value = deviceDetails.DeviceProperties.AvailableStorageInBytes.ToString(); devicePropertiesElement.Add(availableStorageInBytesElement); XElement cloudCredCountElement = new XElement(XName.Get("CloudCredCount", "http://windowscloudbackup.com/CiS/V2013_03")); cloudCredCountElement.Value = deviceDetails.DeviceProperties.CloudCredCount.ToString(); devicePropertiesElement.Add(cloudCredCountElement); XElement cultureElement = new XElement(XName.Get("Culture", "http://windowscloudbackup.com/CiS/V2013_03")); cultureElement.Value = deviceDetails.DeviceProperties.Culture; devicePropertiesElement.Add(cultureElement); XElement currentControllerElement = new XElement(XName.Get("CurrentController", "http://windowscloudbackup.com/CiS/V2013_03")); currentControllerElement.Value = deviceDetails.DeviceProperties.CurrentController.ToString(); devicePropertiesElement.Add(currentControllerElement); XElement dataContainerCountElement = new XElement(XName.Get("DataContainerCount", "http://windowscloudbackup.com/CiS/V2013_03")); dataContainerCountElement.Value = deviceDetails.DeviceProperties.DataContainerCount.ToString(); devicePropertiesElement.Add(dataContainerCountElement); XElement descriptionElement = new XElement(XName.Get("Description", "http://windowscloudbackup.com/CiS/V2013_03")); descriptionElement.Value = deviceDetails.DeviceProperties.Description; devicePropertiesElement.Add(descriptionElement); XElement deviceIdElement = new XElement(XName.Get("DeviceId", "http://windowscloudbackup.com/CiS/V2013_03")); deviceIdElement.Value = deviceDetails.DeviceProperties.DeviceId; devicePropertiesElement.Add(deviceIdElement); XElement deviceSoftwareVersionElement = new XElement(XName.Get("DeviceSoftwareVersion", "http://windowscloudbackup.com/CiS/V2013_03")); deviceSoftwareVersionElement.Value = deviceDetails.DeviceProperties.DeviceSoftwareVersion; devicePropertiesElement.Add(deviceSoftwareVersionElement); XElement friendlyNameElement = new XElement(XName.Get("FriendlyName", "http://windowscloudbackup.com/CiS/V2013_03")); friendlyNameElement.Value = deviceDetails.DeviceProperties.FriendlyName; devicePropertiesElement.Add(friendlyNameElement); XElement isConfigUpdatedElement = new XElement(XName.Get("IsConfigUpdated", "http://windowscloudbackup.com/CiS/V2013_03")); isConfigUpdatedElement.Value = deviceDetails.DeviceProperties.IsConfigUpdated.ToString().ToLower(); devicePropertiesElement.Add(isConfigUpdatedElement); XElement isVirtualApplianceInterimEntryElement = new XElement(XName.Get("IsVirtualApplianceInterimEntry", "http://windowscloudbackup.com/CiS/V2013_03")); isVirtualApplianceInterimEntryElement.Value = deviceDetails.DeviceProperties.IsVirtualApplianceInterimEntry.ToString().ToLower(); devicePropertiesElement.Add(isVirtualApplianceInterimEntryElement); XElement locationElement = new XElement(XName.Get("Location", "http://windowscloudbackup.com/CiS/V2013_03")); locationElement.Value = deviceDetails.DeviceProperties.Location; devicePropertiesElement.Add(locationElement); XElement modelDescriptionElement = new XElement(XName.Get("ModelDescription", "http://windowscloudbackup.com/CiS/V2013_03")); modelDescriptionElement.Value = deviceDetails.DeviceProperties.ModelDescription; devicePropertiesElement.Add(modelDescriptionElement); XElement nNicCardsElement = new XElement(XName.Get("NNicCards", "http://windowscloudbackup.com/CiS/V2013_03")); nNicCardsElement.Value = deviceDetails.DeviceProperties.NNicCards.ToString(); devicePropertiesElement.Add(nNicCardsElement); XElement provisionedStorageInBytesElement = new XElement(XName.Get("ProvisionedStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03")); provisionedStorageInBytesElement.Value = deviceDetails.DeviceProperties.ProvisionedStorageInBytes.ToString(); devicePropertiesElement.Add(provisionedStorageInBytesElement); XElement serialNumberElement = new XElement(XName.Get("SerialNumber", "http://windowscloudbackup.com/CiS/V2013_03")); serialNumberElement.Value = deviceDetails.DeviceProperties.SerialNumber; devicePropertiesElement.Add(serialNumberElement); XElement statusElement = new XElement(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03")); statusElement.Value = deviceDetails.DeviceProperties.Status.ToString(); devicePropertiesElement.Add(statusElement); XElement targetIQNElement = new XElement(XName.Get("TargetIQN", "http://windowscloudbackup.com/CiS/V2013_03")); targetIQNElement.Value = deviceDetails.DeviceProperties.TargetIQN; devicePropertiesElement.Add(targetIQNElement); XElement timeZoneElement = new XElement(XName.Get("TimeZone", "http://windowscloudbackup.com/CiS/V2013_03")); timeZoneElement.Value = deviceDetails.DeviceProperties.TimeZone; devicePropertiesElement.Add(timeZoneElement); XElement totalStorageInBytesElement = new XElement(XName.Get("TotalStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03")); totalStorageInBytesElement.Value = deviceDetails.DeviceProperties.TotalStorageInBytes.ToString(); devicePropertiesElement.Add(totalStorageInBytesElement); XElement typeElement = new XElement(XName.Get("Type", "http://windowscloudbackup.com/CiS/V2013_03")); typeElement.Value = deviceDetails.DeviceProperties.Type.ToString(); devicePropertiesElement.Add(typeElement); XElement usingStorageInBytesElement = new XElement(XName.Get("UsingStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03")); usingStorageInBytesElement.Value = deviceDetails.DeviceProperties.UsingStorageInBytes.ToString(); devicePropertiesElement.Add(usingStorageInBytesElement); XElement volumeCountElement = new XElement(XName.Get("VolumeCount", "http://windowscloudbackup.com/CiS/V2013_03")); volumeCountElement.Value = deviceDetails.DeviceProperties.VolumeCount.ToString(); devicePropertiesElement.Add(volumeCountElement); } if (deviceDetails.DnsServer != null) { XElement dnsServerElement = new XElement(XName.Get("DnsServer", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(dnsServerElement); XElement primaryIPv4Element = new XElement(XName.Get("PrimaryIPv4", "http://windowscloudbackup.com/CiS/V2013_03")); primaryIPv4Element.Value = deviceDetails.DnsServer.PrimaryIPv4; dnsServerElement.Add(primaryIPv4Element); XElement primaryIPv6Element = new XElement(XName.Get("PrimaryIPv6", "http://windowscloudbackup.com/CiS/V2013_03")); primaryIPv6Element.Value = deviceDetails.DnsServer.PrimaryIPv6; dnsServerElement.Add(primaryIPv6Element); if (deviceDetails.DnsServer.SecondaryIPv4 != null) { XElement secondaryIPv4SequenceElement = new XElement(XName.Get("SecondaryIPv4", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (string secondaryIPv4Item in deviceDetails.DnsServer.SecondaryIPv4) { XElement secondaryIPv4ItemElement = new XElement(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")); secondaryIPv4ItemElement.Value = secondaryIPv4Item; secondaryIPv4SequenceElement.Add(secondaryIPv4ItemElement); } dnsServerElement.Add(secondaryIPv4SequenceElement); } if (deviceDetails.DnsServer.SecondaryIPv6 != null) { XElement secondaryIPv6SequenceElement = new XElement(XName.Get("SecondaryIPv6", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (string secondaryIPv6Item in deviceDetails.DnsServer.SecondaryIPv6) { XElement secondaryIPv6ItemElement = new XElement(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")); secondaryIPv6ItemElement.Value = secondaryIPv6Item; secondaryIPv6SequenceElement.Add(secondaryIPv6ItemElement); } dnsServerElement.Add(secondaryIPv6SequenceElement); } } if (deviceDetails.NetInterfaceList != null) { XElement netInterfaceListSequenceElement = new XElement(XName.Get("NetInterfaceList", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (NetInterface netInterfaceListItem in deviceDetails.NetInterfaceList) { XElement netInterfaceElement = new XElement(XName.Get("NetInterface", "http://windowscloudbackup.com/CiS/V2013_03")); netInterfaceListSequenceElement.Add(netInterfaceElement); XElement interfaceIdElement = new XElement(XName.Get("InterfaceId", "http://windowscloudbackup.com/CiS/V2013_03")); interfaceIdElement.Value = netInterfaceListItem.InterfaceId.ToString(); netInterfaceElement.Add(interfaceIdElement); XElement isCloudEnabledElement = new XElement(XName.Get("IsCloudEnabled", "http://windowscloudbackup.com/CiS/V2013_03")); isCloudEnabledElement.Value = netInterfaceListItem.IsCloudEnabled.ToString().ToLower(); netInterfaceElement.Add(isCloudEnabledElement); XElement isDefaultElement = new XElement(XName.Get("IsDefault", "http://windowscloudbackup.com/CiS/V2013_03")); isDefaultElement.Value = netInterfaceListItem.IsDefault.ToString().ToLower(); netInterfaceElement.Add(isDefaultElement); XElement isEnabledElement = new XElement(XName.Get("IsEnabled", "http://windowscloudbackup.com/CiS/V2013_03")); isEnabledElement.Value = netInterfaceListItem.IsEnabled.ToString().ToLower(); netInterfaceElement.Add(isEnabledElement); XElement isIScsiEnabledElement = new XElement(XName.Get("IsIScsiEnabled", "http://windowscloudbackup.com/CiS/V2013_03")); isIScsiEnabledElement.Value = netInterfaceListItem.IsIScsiEnabled.ToString().ToLower(); netInterfaceElement.Add(isIScsiEnabledElement); XElement mediaConnectStateElement = new XElement(XName.Get("MediaConnectState", "http://windowscloudbackup.com/CiS/V2013_03")); mediaConnectStateElement.Value = netInterfaceListItem.MediaConnectState.ToString(); netInterfaceElement.Add(mediaConnectStateElement); XElement modeElement = new XElement(XName.Get("Mode", "http://windowscloudbackup.com/CiS/V2013_03")); modeElement.Value = netInterfaceListItem.Mode.ToString(); netInterfaceElement.Add(modeElement); if (netInterfaceListItem.NicIPv4Settings != null) { XElement nicIPv4SettingsElement = new XElement(XName.Get("NicIPv4Settings", "http://windowscloudbackup.com/CiS/V2013_03")); netInterfaceElement.Add(nicIPv4SettingsElement); if (netInterfaceListItem.NicIPv4Settings.Controller0IPv4Address != null) { XElement controller0IPv4AddressElement = new XElement(XName.Get("Controller0IPv4Address", "http://windowscloudbackup.com/CiS/V2013_03")); controller0IPv4AddressElement.Value = netInterfaceListItem.NicIPv4Settings.Controller0IPv4Address; nicIPv4SettingsElement.Add(controller0IPv4AddressElement); } if (netInterfaceListItem.NicIPv4Settings.Controller1IPv4Address != null) { XElement controller1IPv4AddressElement = new XElement(XName.Get("Controller1IPv4Address", "http://windowscloudbackup.com/CiS/V2013_03")); controller1IPv4AddressElement.Value = netInterfaceListItem.NicIPv4Settings.Controller1IPv4Address; nicIPv4SettingsElement.Add(controller1IPv4AddressElement); } XElement iPv4AddressElement = new XElement(XName.Get("IPv4Address", "http://windowscloudbackup.com/CiS/V2013_03")); iPv4AddressElement.Value = netInterfaceListItem.NicIPv4Settings.IPv4Address; nicIPv4SettingsElement.Add(iPv4AddressElement); if (netInterfaceListItem.NicIPv4Settings.IPv4Gateway != null) { XElement iPv4GatewayElement = new XElement(XName.Get("IPv4Gateway", "http://windowscloudbackup.com/CiS/V2013_03")); iPv4GatewayElement.Value = netInterfaceListItem.NicIPv4Settings.IPv4Gateway; nicIPv4SettingsElement.Add(iPv4GatewayElement); } XElement iPv4NetmaskElement = new XElement(XName.Get("IPv4Netmask", "http://windowscloudbackup.com/CiS/V2013_03")); iPv4NetmaskElement.Value = netInterfaceListItem.NicIPv4Settings.IPv4Netmask; nicIPv4SettingsElement.Add(iPv4NetmaskElement); } if (netInterfaceListItem.NicIPv6Settings != null) { XElement nicIPv6SettingsElement = new XElement(XName.Get("NicIPv6Settings", "http://windowscloudbackup.com/CiS/V2013_03")); netInterfaceElement.Add(nicIPv6SettingsElement); if (netInterfaceListItem.NicIPv6Settings.Controller0IPv6Address != null) { XElement controller0IPv6AddressElement = new XElement(XName.Get("Controller0IPv6Address", "http://windowscloudbackup.com/CiS/V2013_03")); controller0IPv6AddressElement.Value = netInterfaceListItem.NicIPv6Settings.Controller0IPv6Address; nicIPv6SettingsElement.Add(controller0IPv6AddressElement); } if (netInterfaceListItem.NicIPv6Settings.Controller1IPv6Address != null) { XElement controller1IPv6AddressElement = new XElement(XName.Get("Controller1IPv6Address", "http://windowscloudbackup.com/CiS/V2013_03")); controller1IPv6AddressElement.Value = netInterfaceListItem.NicIPv6Settings.Controller1IPv6Address; nicIPv6SettingsElement.Add(controller1IPv6AddressElement); } if (netInterfaceListItem.NicIPv6Settings.IPv6Address != null) { XElement iPv6AddressElement = new XElement(XName.Get("IPv6Address", "http://windowscloudbackup.com/CiS/V2013_03")); iPv6AddressElement.Value = netInterfaceListItem.NicIPv6Settings.IPv6Address; nicIPv6SettingsElement.Add(iPv6AddressElement); } if (netInterfaceListItem.NicIPv6Settings.IPv6Gateway != null) { XElement iPv6GatewayElement = new XElement(XName.Get("IPv6Gateway", "http://windowscloudbackup.com/CiS/V2013_03")); iPv6GatewayElement.Value = netInterfaceListItem.NicIPv6Settings.IPv6Gateway; nicIPv6SettingsElement.Add(iPv6GatewayElement); } XElement iPv6PrefixElement = new XElement(XName.Get("IPv6Prefix", "http://windowscloudbackup.com/CiS/V2013_03")); iPv6PrefixElement.Value = netInterfaceListItem.NicIPv6Settings.IPv6Prefix; nicIPv6SettingsElement.Add(iPv6PrefixElement); } XElement speedElement = new XElement(XName.Get("Speed", "http://windowscloudbackup.com/CiS/V2013_03")); speedElement.Value = netInterfaceListItem.Speed.ToString(); netInterfaceElement.Add(speedElement); } deviceDetailsV3Element.Add(netInterfaceListSequenceElement); } if (deviceDetails.Snapshot != null) { XElement snapshotElement = new XElement(XName.Get("Snapshot", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(snapshotElement); XElement isSnapshotSecretSetElement = new XElement(XName.Get("IsSnapshotSecretSet", "http://windowscloudbackup.com/CiS/V2013_03")); isSnapshotSecretSetElement.Value = deviceDetails.Snapshot.IsSnapshotSecretSet.ToString().ToLower(); snapshotElement.Add(isSnapshotSecretSetElement); if (deviceDetails.Snapshot.SnapshotSecret != null) { XElement snapshotSecretElement = new XElement(XName.Get("SnapshotSecret", "http://windowscloudbackup.com/CiS/V2013_03")); snapshotSecretElement.Value = deviceDetails.Snapshot.SnapshotSecret; snapshotElement.Add(snapshotSecretElement); } } if (deviceDetails.TimeServer != null) { XElement timeServerElement = new XElement(XName.Get("TimeServer", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(timeServerElement); XElement primaryElement = new XElement(XName.Get("Primary", "http://windowscloudbackup.com/CiS/V2013_03")); primaryElement.Value = deviceDetails.TimeServer.Primary; timeServerElement.Add(primaryElement); if (deviceDetails.TimeServer.Secondary != null) { XElement secondarySequenceElement = new XElement(XName.Get("Secondary", "http://windowscloudbackup.com/CiS/V2013_03")); foreach (string secondaryItem in deviceDetails.TimeServer.Secondary) { XElement secondaryItemElement = new XElement(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")); secondaryItemElement.Value = secondaryItem; secondarySequenceElement.Add(secondaryItemElement); } timeServerElement.Add(secondarySequenceElement); } XElement timeZoneElement2 = new XElement(XName.Get("TimeZone", "http://windowscloudbackup.com/CiS/V2013_03")); timeZoneElement2.Value = deviceDetails.TimeServer.TimeZone; timeServerElement.Add(timeZoneElement2); } if (deviceDetails.WebProxy != null) { XElement webProxyElement = new XElement(XName.Get("WebProxy", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(webProxyElement); XElement authenticationElement = new XElement(XName.Get("Authentication", "http://windowscloudbackup.com/CiS/V2013_03")); authenticationElement.Value = deviceDetails.WebProxy.Authentication.ToString(); webProxyElement.Add(authenticationElement); XElement connectionURIElement = new XElement(XName.Get("ConnectionURI", "http://windowscloudbackup.com/CiS/V2013_03")); connectionURIElement.Value = deviceDetails.WebProxy.ConnectionURI; webProxyElement.Add(connectionURIElement); XElement usernameElement = new XElement(XName.Get("Username", "http://windowscloudbackup.com/CiS/V2013_03")); usernameElement.Value = deviceDetails.WebProxy.Username; webProxyElement.Add(usernameElement); } if (deviceDetails.SecretEncryptionCertThumbprint != null) { XElement secretEncryptionCertThumbprintElement = new XElement(XName.Get("SecretEncryptionCertThumbprint", "http://windowscloudbackup.com/CiS/V2013_03")); secretEncryptionCertThumbprintElement.Value = deviceDetails.SecretEncryptionCertThumbprint; deviceDetailsV3Element.Add(secretEncryptionCertThumbprintElement); } if (deviceDetails.RemoteMgmtSettingsInfo != null) { XElement remoteMgmtSettingsInfoElement = new XElement(XName.Get("RemoteMgmtSettingsInfo", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(remoteMgmtSettingsInfoElement); XElement remoteManagementModeElement = new XElement(XName.Get("RemoteManagementMode", "http://windowscloudbackup.com/CiS/V2013_03")); remoteManagementModeElement.Value = deviceDetails.RemoteMgmtSettingsInfo.RemoteManagementMode.ToString(); remoteMgmtSettingsInfoElement.Add(remoteManagementModeElement); } if (deviceDetails.RemoteMinishellSecretInfo != null) { XElement remoteMinishellSecretInfoElement = new XElement(XName.Get("RemoteMinishellSecretInfo", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(remoteMinishellSecretInfoElement); XElement isMinishellSecretSetElement = new XElement(XName.Get("IsMinishellSecretSet", "http://windowscloudbackup.com/CiS/V2013_03")); isMinishellSecretSetElement.Value = deviceDetails.RemoteMinishellSecretInfo.IsMinishellSecretSet.ToString().ToLower(); remoteMinishellSecretInfoElement.Add(isMinishellSecretSetElement); if (deviceDetails.RemoteMinishellSecretInfo.MinishellSecret != null) { XElement minishellSecretElement = new XElement(XName.Get("MinishellSecret", "http://windowscloudbackup.com/CiS/V2013_03")); minishellSecretElement.Value = deviceDetails.RemoteMinishellSecretInfo.MinishellSecret; remoteMinishellSecretInfoElement.Add(minishellSecretElement); } } XElement typeElement2 = new XElement(XName.Get("Type", "http://windowscloudbackup.com/CiS/V2013_03")); typeElement2.Value = deviceDetails.Type.ToString(); deviceDetailsV3Element.Add(typeElement2); if (deviceDetails.VirtualApplianceProperties != null) { XElement virtualAppliancePropertiesElement = new XElement(XName.Get("VirtualApplianceProperties", "http://windowscloudbackup.com/CiS/V2013_03")); deviceDetailsV3Element.Add(virtualAppliancePropertiesElement); if (deviceDetails.VirtualApplianceProperties.DnsName != null) { XElement dnsNameElement = new XElement(XName.Get("DnsName", "http://windowscloudbackup.com/CiS/V2013_03")); dnsNameElement.Value = deviceDetails.VirtualApplianceProperties.DnsName; virtualAppliancePropertiesElement.Add(dnsNameElement); } if (deviceDetails.VirtualApplianceProperties.EncodedChannelIntegrityKey != null) { XElement encodedChannelIntegrityKeyElement = new XElement(XName.Get("EncodedChannelIntegrityKey", "http://windowscloudbackup.com/CiS/V2013_03")); encodedChannelIntegrityKeyElement.Value = deviceDetails.VirtualApplianceProperties.EncodedChannelIntegrityKey; virtualAppliancePropertiesElement.Add(encodedChannelIntegrityKeyElement); } if (deviceDetails.VirtualApplianceProperties.EncodedServiceEncryptionKey != null) { XElement encodedServiceEncryptionKeyElement = new XElement(XName.Get("EncodedServiceEncryptionKey", "http://windowscloudbackup.com/CiS/V2013_03")); encodedServiceEncryptionKeyElement.Value = deviceDetails.VirtualApplianceProperties.EncodedServiceEncryptionKey; virtualAppliancePropertiesElement.Add(encodedServiceEncryptionKeyElement); } if (deviceDetails.VirtualApplianceProperties.InternalIpAddress != null) { XElement internalIpAddressElement = new XElement(XName.Get("InternalIpAddress", "http://windowscloudbackup.com/CiS/V2013_03")); internalIpAddressElement.Value = deviceDetails.VirtualApplianceProperties.InternalIpAddress; virtualAppliancePropertiesElement.Add(internalIpAddressElement); } XElement isServiceEncryptionKeySetElement = new XElement(XName.Get("IsServiceEncryptionKeySet", "http://windowscloudbackup.com/CiS/V2013_03")); isServiceEncryptionKeySetElement.Value = deviceDetails.VirtualApplianceProperties.IsServiceEncryptionKeySet.ToString().ToLower(); virtualAppliancePropertiesElement.Add(isServiceEncryptionKeySetElement); if (deviceDetails.VirtualApplianceProperties.PublicIpAddress != null) { XElement publicIpAddressElement = new XElement(XName.Get("PublicIpAddress", "http://windowscloudbackup.com/CiS/V2013_03")); publicIpAddressElement.Value = deviceDetails.VirtualApplianceProperties.PublicIpAddress; virtualAppliancePropertiesElement.Add(publicIpAddressElement); } if (deviceDetails.VirtualApplianceProperties.Region != null) { XElement regionElement = new XElement(XName.Get("Region", "http://windowscloudbackup.com/CiS/V2013_03")); regionElement.Value = deviceDetails.VirtualApplianceProperties.Region; virtualAppliancePropertiesElement.Add(regionElement); } if (deviceDetails.VirtualApplianceProperties.SubnetName != null) { XElement subnetNameElement = new XElement(XName.Get("SubnetName", "http://windowscloudbackup.com/CiS/V2013_03")); subnetNameElement.Value = deviceDetails.VirtualApplianceProperties.SubnetName; virtualAppliancePropertiesElement.Add(subnetNameElement); } if (deviceDetails.VirtualApplianceProperties.VirtualNetworkName != null) { XElement virtualNetworkNameElement = new XElement(XName.Get("VirtualNetworkName", "http://windowscloudbackup.com/CiS/V2013_03")); virtualNetworkNameElement.Value = deviceDetails.VirtualApplianceProperties.VirtualNetworkName; virtualAppliancePropertiesElement.Add(virtualNetworkNameElement); } } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GuidTaskResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GuidTaskResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement guidElement = responseDoc.Element(XName.Get("guid", "http://schemas.microsoft.com/2003/10/Serialization/")); if (guidElement != null) { string guidInstance = guidElement.Value; result.TaskId = guidInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='deviceId'> /// Required. The device id for which the call will be made. /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for device details. /// </returns> public async Task<DeviceDetailsResponse> GetAsync(string deviceId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceId == null) { throw new ArgumentNullException("deviceId"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; url = url + Uri.EscapeDataString(deviceId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.3.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DeviceDetailsResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DeviceDetailsResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement deviceDetailsElement = responseDoc.Element(XName.Get("DeviceDetails", "http://windowscloudbackup.com/CiS/V2013_03")); if (deviceDetailsElement != null) { DeviceDetails deviceDetailsInstance = new DeviceDetails(); result.DeviceDetails = deviceDetailsInstance; XElement instanceIdElement = deviceDetailsElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement != null) { string instanceIdInstance = instanceIdElement.Value; deviceDetailsInstance.InstanceId = instanceIdInstance; } XElement nameElement = deviceDetailsElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement != null) { string nameInstance = nameElement.Value; deviceDetailsInstance.Name = nameInstance; } XElement operationInProgressElement = deviceDetailsElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement != null) { OperationInProgress operationInProgressInstance = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement.Value, true)); deviceDetailsInstance.OperationInProgress = operationInProgressInstance; } XElement alertNotificationElement = deviceDetailsElement.Element(XName.Get("AlertNotification", "http://windowscloudbackup.com/CiS/V2013_03")); if (alertNotificationElement != null) { AlertNotificationSettings alertNotificationInstance = new AlertNotificationSettings(); deviceDetailsInstance.AlertNotification = alertNotificationInstance; XElement alertNotifcationCultureElement = alertNotificationElement.Element(XName.Get("AlertNotifcationCulture", "http://windowscloudbackup.com/CiS/V2013_03")); if (alertNotifcationCultureElement != null) { string alertNotifcationCultureInstance = alertNotifcationCultureElement.Value; alertNotificationInstance.AlertNotifcationCulture = alertNotifcationCultureInstance; } XElement alertNotifcationEnabledElement = alertNotificationElement.Element(XName.Get("AlertNotifcationEnabled", "http://windowscloudbackup.com/CiS/V2013_03")); if (alertNotifcationEnabledElement != null) { bool alertNotifcationEnabledInstance = bool.Parse(alertNotifcationEnabledElement.Value); alertNotificationInstance.AlertNotifcationEnabled = alertNotifcationEnabledInstance; } XElement alertNotificationEmailListSequenceElement = alertNotificationElement.Element(XName.Get("AlertNotificationEmailList", "http://windowscloudbackup.com/CiS/V2013_03")); if (alertNotificationEmailListSequenceElement != null) { foreach (XElement alertNotificationEmailListElement in alertNotificationEmailListSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { alertNotificationInstance.AlertNotificationEmailList.Add(alertNotificationEmailListElement.Value); } } XElement alertNotificationEnabledForAdminCoAdminsElement = alertNotificationElement.Element(XName.Get("AlertNotificationEnabledForAdminCoAdmins", "http://windowscloudbackup.com/CiS/V2013_03")); if (alertNotificationEnabledForAdminCoAdminsElement != null) { bool alertNotificationEnabledForAdminCoAdminsInstance = bool.Parse(alertNotificationEnabledForAdminCoAdminsElement.Value); alertNotificationInstance.AlertNotificationEnabledForAdminCoAdmins = alertNotificationEnabledForAdminCoAdminsInstance; } } XElement chapElement = deviceDetailsElement.Element(XName.Get("Chap", "http://windowscloudbackup.com/CiS/V2013_03")); if (chapElement != null) { ChapSettings chapInstance = new ChapSettings(); deviceDetailsInstance.Chap = chapInstance; XElement initiatorSecretElement = chapElement.Element(XName.Get("InitiatorSecret", "http://windowscloudbackup.com/CiS/V2013_03")); if (initiatorSecretElement != null) { string initiatorSecretInstance = initiatorSecretElement.Value; chapInstance.InitiatorSecret = initiatorSecretInstance; } XElement initiatorUserElement = chapElement.Element(XName.Get("InitiatorUser", "http://windowscloudbackup.com/CiS/V2013_03")); if (initiatorUserElement != null) { string initiatorUserInstance = initiatorUserElement.Value; chapInstance.InitiatorUser = initiatorUserInstance; } XElement targetSecretElement = chapElement.Element(XName.Get("TargetSecret", "http://windowscloudbackup.com/CiS/V2013_03")); if (targetSecretElement != null) { string targetSecretInstance = targetSecretElement.Value; chapInstance.TargetSecret = targetSecretInstance; } XElement targetUserElement = chapElement.Element(XName.Get("TargetUser", "http://windowscloudbackup.com/CiS/V2013_03")); if (targetUserElement != null) { string targetUserInstance = targetUserElement.Value; chapInstance.TargetUser = targetUserInstance; } } XElement devicePropertiesElement = deviceDetailsElement.Element(XName.Get("DeviceProperties", "http://windowscloudbackup.com/CiS/V2013_03")); if (devicePropertiesElement != null) { DeviceInfo devicePropertiesInstance = new DeviceInfo(); deviceDetailsInstance.DeviceProperties = devicePropertiesInstance; XElement aCRCountElement = devicePropertiesElement.Element(XName.Get("ACRCount", "http://windowscloudbackup.com/CiS/V2013_03")); if (aCRCountElement != null) { int aCRCountInstance = int.Parse(aCRCountElement.Value, CultureInfo.InvariantCulture); devicePropertiesInstance.ACRCount = aCRCountInstance; } XElement activationTimeElement = devicePropertiesElement.Element(XName.Get("ActivationTime", "http://windowscloudbackup.com/CiS/V2013_03")); if (activationTimeElement != null) { string activationTimeInstance = activationTimeElement.Value; devicePropertiesInstance.ActivationTime = activationTimeInstance; } XElement activeControllerElement = devicePropertiesElement.Element(XName.Get("ActiveController", "http://windowscloudbackup.com/CiS/V2013_03")); if (activeControllerElement != null) { ControllerId activeControllerInstance = ((ControllerId)Enum.Parse(typeof(ControllerId), activeControllerElement.Value, true)); devicePropertiesInstance.ActiveController = activeControllerInstance; } XElement availableStorageInBytesElement = devicePropertiesElement.Element(XName.Get("AvailableStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03")); if (availableStorageInBytesElement != null) { long availableStorageInBytesInstance = long.Parse(availableStorageInBytesElement.Value, CultureInfo.InvariantCulture); devicePropertiesInstance.AvailableStorageInBytes = availableStorageInBytesInstance; } XElement cloudCredCountElement = devicePropertiesElement.Element(XName.Get("CloudCredCount", "http://windowscloudbackup.com/CiS/V2013_03")); if (cloudCredCountElement != null) { int cloudCredCountInstance = int.Parse(cloudCredCountElement.Value, CultureInfo.InvariantCulture); devicePropertiesInstance.CloudCredCount = cloudCredCountInstance; } XElement cultureElement = devicePropertiesElement.Element(XName.Get("Culture", "http://windowscloudbackup.com/CiS/V2013_03")); if (cultureElement != null) { string cultureInstance = cultureElement.Value; devicePropertiesInstance.Culture = cultureInstance; } XElement currentControllerElement = devicePropertiesElement.Element(XName.Get("CurrentController", "http://windowscloudbackup.com/CiS/V2013_03")); if (currentControllerElement != null) { ControllerId currentControllerInstance = ((ControllerId)Enum.Parse(typeof(ControllerId), currentControllerElement.Value, true)); devicePropertiesInstance.CurrentController = currentControllerInstance; } XElement dataContainerCountElement = devicePropertiesElement.Element(XName.Get("DataContainerCount", "http://windowscloudbackup.com/CiS/V2013_03")); if (dataContainerCountElement != null) { int dataContainerCountInstance = int.Parse(dataContainerCountElement.Value, CultureInfo.InvariantCulture); devicePropertiesInstance.DataContainerCount = dataContainerCountInstance; } XElement descriptionElement = devicePropertiesElement.Element(XName.Get("Description", "http://windowscloudbackup.com/CiS/V2013_03")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; devicePropertiesInstance.Description = descriptionInstance; } XElement deviceIdElement = devicePropertiesElement.Element(XName.Get("DeviceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (deviceIdElement != null) { string deviceIdInstance = deviceIdElement.Value; devicePropertiesInstance.DeviceId = deviceIdInstance; } XElement deviceSoftwareVersionElement = devicePropertiesElement.Element(XName.Get("DeviceSoftwareVersion", "http://windowscloudbackup.com/CiS/V2013_03")); if (deviceSoftwareVersionElement != null) { string deviceSoftwareVersionInstance = deviceSoftwareVersionElement.Value; devicePropertiesInstance.DeviceSoftwareVersion = deviceSoftwareVersionInstance; } XElement friendlyNameElement = devicePropertiesElement.Element(XName.Get("FriendlyName", "http://windowscloudbackup.com/CiS/V2013_03")); if (friendlyNameElement != null) { string friendlyNameInstance = friendlyNameElement.Value; devicePropertiesInstance.FriendlyName = friendlyNameInstance; } XElement isConfigUpdatedElement = devicePropertiesElement.Element(XName.Get("IsConfigUpdated", "http://windowscloudbackup.com/CiS/V2013_03")); if (isConfigUpdatedElement != null) { bool isConfigUpdatedInstance = bool.Parse(isConfigUpdatedElement.Value); devicePropertiesInstance.IsConfigUpdated = isConfigUpdatedInstance; } XElement isVirtualApplianceInterimEntryElement = devicePropertiesElement.Element(XName.Get("IsVirtualApplianceInterimEntry", "http://windowscloudbackup.com/CiS/V2013_03")); if (isVirtualApplianceInterimEntryElement != null) { bool isVirtualApplianceInterimEntryInstance = bool.Parse(isVirtualApplianceInterimEntryElement.Value); devicePropertiesInstance.IsVirtualApplianceInterimEntry = isVirtualApplianceInterimEntryInstance; } XElement locationElement = devicePropertiesElement.Element(XName.Get("Location", "http://windowscloudbackup.com/CiS/V2013_03")); if (locationElement != null) { string locationInstance = locationElement.Value; devicePropertiesInstance.Location = locationInstance; } XElement modelDescriptionElement = devicePropertiesElement.Element(XName.Get("ModelDescription", "http://windowscloudbackup.com/CiS/V2013_03")); if (modelDescriptionElement != null) { string modelDescriptionInstance = modelDescriptionElement.Value; devicePropertiesInstance.ModelDescription = modelDescriptionInstance; } XElement nNicCardsElement = devicePropertiesElement.Element(XName.Get("NNicCards", "http://windowscloudbackup.com/CiS/V2013_03")); if (nNicCardsElement != null) { int nNicCardsInstance = int.Parse(nNicCardsElement.Value, CultureInfo.InvariantCulture); devicePropertiesInstance.NNicCards = nNicCardsInstance; } XElement provisionedStorageInBytesElement = devicePropertiesElement.Element(XName.Get("ProvisionedStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03")); if (provisionedStorageInBytesElement != null) { long provisionedStorageInBytesInstance = long.Parse(provisionedStorageInBytesElement.Value, CultureInfo.InvariantCulture); devicePropertiesInstance.ProvisionedStorageInBytes = provisionedStorageInBytesInstance; } XElement serialNumberElement = devicePropertiesElement.Element(XName.Get("SerialNumber", "http://windowscloudbackup.com/CiS/V2013_03")); if (serialNumberElement != null) { string serialNumberInstance = serialNumberElement.Value; devicePropertiesInstance.SerialNumber = serialNumberInstance; } XElement statusElement = devicePropertiesElement.Element(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03")); if (statusElement != null) { DeviceStatus statusInstance = ((DeviceStatus)Enum.Parse(typeof(DeviceStatus), statusElement.Value, true)); devicePropertiesInstance.Status = statusInstance; } XElement targetIQNElement = devicePropertiesElement.Element(XName.Get("TargetIQN", "http://windowscloudbackup.com/CiS/V2013_03")); if (targetIQNElement != null) { string targetIQNInstance = targetIQNElement.Value; devicePropertiesInstance.TargetIQN = targetIQNInstance; } XElement timeZoneElement = devicePropertiesElement.Element(XName.Get("TimeZone", "http://windowscloudbackup.com/CiS/V2013_03")); if (timeZoneElement != null) { string timeZoneInstance = timeZoneElement.Value; devicePropertiesInstance.TimeZone = timeZoneInstance; } XElement totalStorageInBytesElement = devicePropertiesElement.Element(XName.Get("TotalStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03")); if (totalStorageInBytesElement != null) { long totalStorageInBytesInstance = long.Parse(totalStorageInBytesElement.Value, CultureInfo.InvariantCulture); devicePropertiesInstance.TotalStorageInBytes = totalStorageInBytesInstance; } XElement typeElement = devicePropertiesElement.Element(XName.Get("Type", "http://windowscloudbackup.com/CiS/V2013_03")); if (typeElement != null) { DeviceType typeInstance = ((DeviceType)Enum.Parse(typeof(DeviceType), typeElement.Value, true)); devicePropertiesInstance.Type = typeInstance; } XElement usingStorageInBytesElement = devicePropertiesElement.Element(XName.Get("UsingStorageInBytes", "http://windowscloudbackup.com/CiS/V2013_03")); if (usingStorageInBytesElement != null) { long usingStorageInBytesInstance = long.Parse(usingStorageInBytesElement.Value, CultureInfo.InvariantCulture); devicePropertiesInstance.UsingStorageInBytes = usingStorageInBytesInstance; } XElement volumeCountElement = devicePropertiesElement.Element(XName.Get("VolumeCount", "http://windowscloudbackup.com/CiS/V2013_03")); if (volumeCountElement != null) { int volumeCountInstance = int.Parse(volumeCountElement.Value, CultureInfo.InvariantCulture); devicePropertiesInstance.VolumeCount = volumeCountInstance; } } XElement dnsServerElement = deviceDetailsElement.Element(XName.Get("DnsServer", "http://windowscloudbackup.com/CiS/V2013_03")); if (dnsServerElement != null) { DnsServerSettings dnsServerInstance = new DnsServerSettings(); deviceDetailsInstance.DnsServer = dnsServerInstance; XElement primaryIPv4Element = dnsServerElement.Element(XName.Get("PrimaryIPv4", "http://windowscloudbackup.com/CiS/V2013_03")); if (primaryIPv4Element != null) { string primaryIPv4Instance = primaryIPv4Element.Value; dnsServerInstance.PrimaryIPv4 = primaryIPv4Instance; } XElement primaryIPv6Element = dnsServerElement.Element(XName.Get("PrimaryIPv6", "http://windowscloudbackup.com/CiS/V2013_03")); if (primaryIPv6Element != null) { string primaryIPv6Instance = primaryIPv6Element.Value; dnsServerInstance.PrimaryIPv6 = primaryIPv6Instance; } XElement secondaryIPv4SequenceElement = dnsServerElement.Element(XName.Get("SecondaryIPv4", "http://windowscloudbackup.com/CiS/V2013_03")); if (secondaryIPv4SequenceElement != null) { foreach (XElement secondaryIPv4Element in secondaryIPv4SequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { dnsServerInstance.SecondaryIPv4.Add(secondaryIPv4Element.Value); } } XElement secondaryIPv6SequenceElement = dnsServerElement.Element(XName.Get("SecondaryIPv6", "http://windowscloudbackup.com/CiS/V2013_03")); if (secondaryIPv6SequenceElement != null) { foreach (XElement secondaryIPv6Element in secondaryIPv6SequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { dnsServerInstance.SecondaryIPv6.Add(secondaryIPv6Element.Value); } } } XElement netInterfaceListSequenceElement = deviceDetailsElement.Element(XName.Get("NetInterfaceList", "http://windowscloudbackup.com/CiS/V2013_03")); if (netInterfaceListSequenceElement != null) { foreach (XElement netInterfaceListElement in netInterfaceListSequenceElement.Elements(XName.Get("NetInterface", "http://windowscloudbackup.com/CiS/V2013_03"))) { NetInterface netInterfaceInstance = new NetInterface(); deviceDetailsInstance.NetInterfaceList.Add(netInterfaceInstance); XElement interfaceIdElement = netInterfaceListElement.Element(XName.Get("InterfaceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (interfaceIdElement != null) { NetInterfaceId interfaceIdInstance = ((NetInterfaceId)Enum.Parse(typeof(NetInterfaceId), interfaceIdElement.Value, true)); netInterfaceInstance.InterfaceId = interfaceIdInstance; } XElement isCloudEnabledElement = netInterfaceListElement.Element(XName.Get("IsCloudEnabled", "http://windowscloudbackup.com/CiS/V2013_03")); if (isCloudEnabledElement != null) { bool isCloudEnabledInstance = bool.Parse(isCloudEnabledElement.Value); netInterfaceInstance.IsCloudEnabled = isCloudEnabledInstance; } XElement isDefaultElement = netInterfaceListElement.Element(XName.Get("IsDefault", "http://windowscloudbackup.com/CiS/V2013_03")); if (isDefaultElement != null) { bool isDefaultInstance = bool.Parse(isDefaultElement.Value); netInterfaceInstance.IsDefault = isDefaultInstance; } XElement isEnabledElement = netInterfaceListElement.Element(XName.Get("IsEnabled", "http://windowscloudbackup.com/CiS/V2013_03")); if (isEnabledElement != null) { bool isEnabledInstance = bool.Parse(isEnabledElement.Value); netInterfaceInstance.IsEnabled = isEnabledInstance; } XElement isIScsiEnabledElement = netInterfaceListElement.Element(XName.Get("IsIScsiEnabled", "http://windowscloudbackup.com/CiS/V2013_03")); if (isIScsiEnabledElement != null) { bool isIScsiEnabledInstance = bool.Parse(isIScsiEnabledElement.Value); netInterfaceInstance.IsIScsiEnabled = isIScsiEnabledInstance; } XElement mediaConnectStateElement = netInterfaceListElement.Element(XName.Get("MediaConnectState", "http://windowscloudbackup.com/CiS/V2013_03")); if (mediaConnectStateElement != null) { int mediaConnectStateInstance = int.Parse(mediaConnectStateElement.Value, CultureInfo.InvariantCulture); netInterfaceInstance.MediaConnectState = mediaConnectStateInstance; } XElement modeElement = netInterfaceListElement.Element(XName.Get("Mode", "http://windowscloudbackup.com/CiS/V2013_03")); if (modeElement != null) { NetworkMode modeInstance = ((NetworkMode)Enum.Parse(typeof(NetworkMode), modeElement.Value, true)); netInterfaceInstance.Mode = modeInstance; } XElement nicIPv4SettingsElement = netInterfaceListElement.Element(XName.Get("NicIPv4Settings", "http://windowscloudbackup.com/CiS/V2013_03")); if (nicIPv4SettingsElement != null) { NicIPv4 nicIPv4SettingsInstance = new NicIPv4(); netInterfaceInstance.NicIPv4Settings = nicIPv4SettingsInstance; XElement controller0IPv4AddressElement = nicIPv4SettingsElement.Element(XName.Get("Controller0IPv4Address", "http://windowscloudbackup.com/CiS/V2013_03")); if (controller0IPv4AddressElement != null) { string controller0IPv4AddressInstance = controller0IPv4AddressElement.Value; nicIPv4SettingsInstance.Controller0IPv4Address = controller0IPv4AddressInstance; } XElement controller1IPv4AddressElement = nicIPv4SettingsElement.Element(XName.Get("Controller1IPv4Address", "http://windowscloudbackup.com/CiS/V2013_03")); if (controller1IPv4AddressElement != null) { string controller1IPv4AddressInstance = controller1IPv4AddressElement.Value; nicIPv4SettingsInstance.Controller1IPv4Address = controller1IPv4AddressInstance; } XElement iPv4AddressElement = nicIPv4SettingsElement.Element(XName.Get("IPv4Address", "http://windowscloudbackup.com/CiS/V2013_03")); if (iPv4AddressElement != null) { string iPv4AddressInstance = iPv4AddressElement.Value; nicIPv4SettingsInstance.IPv4Address = iPv4AddressInstance; } XElement iPv4GatewayElement = nicIPv4SettingsElement.Element(XName.Get("IPv4Gateway", "http://windowscloudbackup.com/CiS/V2013_03")); if (iPv4GatewayElement != null) { string iPv4GatewayInstance = iPv4GatewayElement.Value; nicIPv4SettingsInstance.IPv4Gateway = iPv4GatewayInstance; } XElement iPv4NetmaskElement = nicIPv4SettingsElement.Element(XName.Get("IPv4Netmask", "http://windowscloudbackup.com/CiS/V2013_03")); if (iPv4NetmaskElement != null) { string iPv4NetmaskInstance = iPv4NetmaskElement.Value; nicIPv4SettingsInstance.IPv4Netmask = iPv4NetmaskInstance; } } XElement nicIPv6SettingsElement = netInterfaceListElement.Element(XName.Get("NicIPv6Settings", "http://windowscloudbackup.com/CiS/V2013_03")); if (nicIPv6SettingsElement != null) { NicIPv6 nicIPv6SettingsInstance = new NicIPv6(); netInterfaceInstance.NicIPv6Settings = nicIPv6SettingsInstance; XElement controller0IPv6AddressElement = nicIPv6SettingsElement.Element(XName.Get("Controller0IPv6Address", "http://windowscloudbackup.com/CiS/V2013_03")); if (controller0IPv6AddressElement != null) { string controller0IPv6AddressInstance = controller0IPv6AddressElement.Value; nicIPv6SettingsInstance.Controller0IPv6Address = controller0IPv6AddressInstance; } XElement controller1IPv6AddressElement = nicIPv6SettingsElement.Element(XName.Get("Controller1IPv6Address", "http://windowscloudbackup.com/CiS/V2013_03")); if (controller1IPv6AddressElement != null) { string controller1IPv6AddressInstance = controller1IPv6AddressElement.Value; nicIPv6SettingsInstance.Controller1IPv6Address = controller1IPv6AddressInstance; } XElement iPv6AddressElement = nicIPv6SettingsElement.Element(XName.Get("IPv6Address", "http://windowscloudbackup.com/CiS/V2013_03")); if (iPv6AddressElement != null) { string iPv6AddressInstance = iPv6AddressElement.Value; nicIPv6SettingsInstance.IPv6Address = iPv6AddressInstance; } XElement iPv6GatewayElement = nicIPv6SettingsElement.Element(XName.Get("IPv6Gateway", "http://windowscloudbackup.com/CiS/V2013_03")); if (iPv6GatewayElement != null) { string iPv6GatewayInstance = iPv6GatewayElement.Value; nicIPv6SettingsInstance.IPv6Gateway = iPv6GatewayInstance; } XElement iPv6PrefixElement = nicIPv6SettingsElement.Element(XName.Get("IPv6Prefix", "http://windowscloudbackup.com/CiS/V2013_03")); if (iPv6PrefixElement != null) { string iPv6PrefixInstance = iPv6PrefixElement.Value; nicIPv6SettingsInstance.IPv6Prefix = iPv6PrefixInstance; } } XElement speedElement = netInterfaceListElement.Element(XName.Get("Speed", "http://windowscloudbackup.com/CiS/V2013_03")); if (speedElement != null) { long speedInstance = long.Parse(speedElement.Value, CultureInfo.InvariantCulture); netInterfaceInstance.Speed = speedInstance; } } } XElement snapshotElement = deviceDetailsElement.Element(XName.Get("Snapshot", "http://windowscloudbackup.com/CiS/V2013_03")); if (snapshotElement != null) { SnapshotSettings snapshotInstance = new SnapshotSettings(); deviceDetailsInstance.Snapshot = snapshotInstance; XElement isSnapshotSecretSetElement = snapshotElement.Element(XName.Get("IsSnapshotSecretSet", "http://windowscloudbackup.com/CiS/V2013_03")); if (isSnapshotSecretSetElement != null) { bool isSnapshotSecretSetInstance = bool.Parse(isSnapshotSecretSetElement.Value); snapshotInstance.IsSnapshotSecretSet = isSnapshotSecretSetInstance; } XElement snapshotSecretElement = snapshotElement.Element(XName.Get("SnapshotSecret", "http://windowscloudbackup.com/CiS/V2013_03")); if (snapshotSecretElement != null) { string snapshotSecretInstance = snapshotSecretElement.Value; snapshotInstance.SnapshotSecret = snapshotSecretInstance; } } XElement timeServerElement = deviceDetailsElement.Element(XName.Get("TimeServer", "http://windowscloudbackup.com/CiS/V2013_03")); if (timeServerElement != null) { TimeSettings timeServerInstance = new TimeSettings(); deviceDetailsInstance.TimeServer = timeServerInstance; XElement primaryElement = timeServerElement.Element(XName.Get("Primary", "http://windowscloudbackup.com/CiS/V2013_03")); if (primaryElement != null) { string primaryInstance = primaryElement.Value; timeServerInstance.Primary = primaryInstance; } XElement secondarySequenceElement = timeServerElement.Element(XName.Get("Secondary", "http://windowscloudbackup.com/CiS/V2013_03")); if (secondarySequenceElement != null) { foreach (XElement secondaryElement in secondarySequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { timeServerInstance.Secondary.Add(secondaryElement.Value); } } XElement timeZoneElement2 = timeServerElement.Element(XName.Get("TimeZone", "http://windowscloudbackup.com/CiS/V2013_03")); if (timeZoneElement2 != null) { string timeZoneInstance2 = timeZoneElement2.Value; timeServerInstance.TimeZone = timeZoneInstance2; } } XElement webProxyElement = deviceDetailsElement.Element(XName.Get("WebProxy", "http://windowscloudbackup.com/CiS/V2013_03")); if (webProxyElement != null) { WebProxySettings webProxyInstance = new WebProxySettings(); deviceDetailsInstance.WebProxy = webProxyInstance; XElement authenticationElement = webProxyElement.Element(XName.Get("Authentication", "http://windowscloudbackup.com/CiS/V2013_03")); if (authenticationElement != null) { AuthenticationType authenticationInstance = ((AuthenticationType)Enum.Parse(typeof(AuthenticationType), authenticationElement.Value, true)); webProxyInstance.Authentication = authenticationInstance; } XElement connectionURIElement = webProxyElement.Element(XName.Get("ConnectionURI", "http://windowscloudbackup.com/CiS/V2013_03")); if (connectionURIElement != null) { string connectionURIInstance = connectionURIElement.Value; webProxyInstance.ConnectionURI = connectionURIInstance; } XElement usernameElement = webProxyElement.Element(XName.Get("Username", "http://windowscloudbackup.com/CiS/V2013_03")); if (usernameElement != null) { string usernameInstance = usernameElement.Value; webProxyInstance.Username = usernameInstance; } } XElement secretEncryptionCertThumbprintElement = deviceDetailsElement.Element(XName.Get("SecretEncryptionCertThumbprint", "http://windowscloudbackup.com/CiS/V2013_03")); if (secretEncryptionCertThumbprintElement != null) { string secretEncryptionCertThumbprintInstance = secretEncryptionCertThumbprintElement.Value; deviceDetailsInstance.SecretEncryptionCertThumbprint = secretEncryptionCertThumbprintInstance; } XElement remoteMgmtSettingsInfoElement = deviceDetailsElement.Element(XName.Get("RemoteMgmtSettingsInfo", "http://windowscloudbackup.com/CiS/V2013_03")); if (remoteMgmtSettingsInfoElement != null) { RemoteManagementSettings remoteMgmtSettingsInfoInstance = new RemoteManagementSettings(); deviceDetailsInstance.RemoteMgmtSettingsInfo = remoteMgmtSettingsInfoInstance; XElement remoteManagementModeElement = remoteMgmtSettingsInfoElement.Element(XName.Get("RemoteManagementMode", "http://windowscloudbackup.com/CiS/V2013_03")); if (remoteManagementModeElement != null) { RemoteManagementModeConfiguration remoteManagementModeInstance = ((RemoteManagementModeConfiguration)Enum.Parse(typeof(RemoteManagementModeConfiguration), remoteManagementModeElement.Value, true)); remoteMgmtSettingsInfoInstance.RemoteManagementMode = remoteManagementModeInstance; } } XElement remoteMinishellSecretInfoElement = deviceDetailsElement.Element(XName.Get("RemoteMinishellSecretInfo", "http://windowscloudbackup.com/CiS/V2013_03")); if (remoteMinishellSecretInfoElement != null) { RemoteMinishellSettings remoteMinishellSecretInfoInstance = new RemoteMinishellSettings(); deviceDetailsInstance.RemoteMinishellSecretInfo = remoteMinishellSecretInfoInstance; XElement isMinishellSecretSetElement = remoteMinishellSecretInfoElement.Element(XName.Get("IsMinishellSecretSet", "http://windowscloudbackup.com/CiS/V2013_03")); if (isMinishellSecretSetElement != null) { bool isMinishellSecretSetInstance = bool.Parse(isMinishellSecretSetElement.Value); remoteMinishellSecretInfoInstance.IsMinishellSecretSet = isMinishellSecretSetInstance; } XElement minishellSecretElement = remoteMinishellSecretInfoElement.Element(XName.Get("MinishellSecret", "http://windowscloudbackup.com/CiS/V2013_03")); if (minishellSecretElement != null) { string minishellSecretInstance = minishellSecretElement.Value; remoteMinishellSecretInfoInstance.MinishellSecret = minishellSecretInstance; } } XElement typeElement2 = deviceDetailsElement.Element(XName.Get("Type", "http://windowscloudbackup.com/CiS/V2013_03")); if (typeElement2 != null) { DeviceType typeInstance2 = ((DeviceType)Enum.Parse(typeof(DeviceType), typeElement2.Value, true)); deviceDetailsInstance.Type = typeInstance2; } XElement virtualAppliancePropertiesElement = deviceDetailsElement.Element(XName.Get("VirtualApplianceProperties", "http://windowscloudbackup.com/CiS/V2013_03")); if (virtualAppliancePropertiesElement != null) { VirtualApplianceInfo virtualAppliancePropertiesInstance = new VirtualApplianceInfo(); deviceDetailsInstance.VirtualApplianceProperties = virtualAppliancePropertiesInstance; XElement dnsNameElement = virtualAppliancePropertiesElement.Element(XName.Get("DnsName", "http://windowscloudbackup.com/CiS/V2013_03")); if (dnsNameElement != null) { string dnsNameInstance = dnsNameElement.Value; virtualAppliancePropertiesInstance.DnsName = dnsNameInstance; } XElement encodedChannelIntegrityKeyElement = virtualAppliancePropertiesElement.Element(XName.Get("EncodedChannelIntegrityKey", "http://windowscloudbackup.com/CiS/V2013_03")); if (encodedChannelIntegrityKeyElement != null) { string encodedChannelIntegrityKeyInstance = encodedChannelIntegrityKeyElement.Value; virtualAppliancePropertiesInstance.EncodedChannelIntegrityKey = encodedChannelIntegrityKeyInstance; } XElement encodedServiceEncryptionKeyElement = virtualAppliancePropertiesElement.Element(XName.Get("EncodedServiceEncryptionKey", "http://windowscloudbackup.com/CiS/V2013_03")); if (encodedServiceEncryptionKeyElement != null) { string encodedServiceEncryptionKeyInstance = encodedServiceEncryptionKeyElement.Value; virtualAppliancePropertiesInstance.EncodedServiceEncryptionKey = encodedServiceEncryptionKeyInstance; } XElement internalIpAddressElement = virtualAppliancePropertiesElement.Element(XName.Get("InternalIpAddress", "http://windowscloudbackup.com/CiS/V2013_03")); if (internalIpAddressElement != null) { string internalIpAddressInstance = internalIpAddressElement.Value; virtualAppliancePropertiesInstance.InternalIpAddress = internalIpAddressInstance; } XElement isServiceEncryptionKeySetElement = virtualAppliancePropertiesElement.Element(XName.Get("IsServiceEncryptionKeySet", "http://windowscloudbackup.com/CiS/V2013_03")); if (isServiceEncryptionKeySetElement != null) { bool isServiceEncryptionKeySetInstance = bool.Parse(isServiceEncryptionKeySetElement.Value); virtualAppliancePropertiesInstance.IsServiceEncryptionKeySet = isServiceEncryptionKeySetInstance; } XElement publicIpAddressElement = virtualAppliancePropertiesElement.Element(XName.Get("PublicIpAddress", "http://windowscloudbackup.com/CiS/V2013_03")); if (publicIpAddressElement != null) { string publicIpAddressInstance = publicIpAddressElement.Value; virtualAppliancePropertiesInstance.PublicIpAddress = publicIpAddressInstance; } XElement regionElement = virtualAppliancePropertiesElement.Element(XName.Get("Region", "http://windowscloudbackup.com/CiS/V2013_03")); if (regionElement != null) { string regionInstance = regionElement.Value; virtualAppliancePropertiesInstance.Region = regionInstance; } XElement subnetNameElement = virtualAppliancePropertiesElement.Element(XName.Get("SubnetName", "http://windowscloudbackup.com/CiS/V2013_03")); if (subnetNameElement != null) { string subnetNameInstance = subnetNameElement.Value; virtualAppliancePropertiesInstance.SubnetName = subnetNameInstance; } XElement virtualNetworkNameElement = virtualAppliancePropertiesElement.Element(XName.Get("VirtualNetworkName", "http://windowscloudbackup.com/CiS/V2013_03")); if (virtualNetworkNameElement != null) { string virtualNetworkNameInstance = virtualNetworkNameElement.Value; virtualAppliancePropertiesInstance.VirtualNetworkName = virtualNetworkNameInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update device details as specified by deviceDetails /// </summary> /// <param name='deviceDetails'> /// Required. Updated DeviceDetails. Contains the corresponding DeviceId /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Info about the async task /// </returns> public async Task<TaskStatusInfo> UpdateDeviceDetailsAsync(DeviceDetailsRequest deviceDetails, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { StorSimpleManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceDetails", deviceDetails); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UpdateDeviceDetailsAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); GuidTaskResponse response = await client.DeviceDetails.BeginUpdateDeviceDetailsAsync(deviceDetails, customRequestHeaders, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); TaskStatusInfo result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 5; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); delayInSeconds = 5; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } } }
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Microsoft.Kinect.Face { // // Microsoft.Kinect.Face.FaceFrameReader // public sealed partial class FaceFrameReader : RootSystem.IDisposable, Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal FaceFrameReader(RootSystem.IntPtr pNative) { _pNative = pNative; Microsoft_Kinect_Face_FaceFrameReader_AddRefObject(ref _pNative); } ~FaceFrameReader() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_FaceFrameReader_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_FaceFrameReader_AddRefObject(ref RootSystem.IntPtr pNative); private void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } __EventCleanup(); Helper.NativeObjectCache.RemoveObject<FaceFrameReader>(_pNative); if (disposing) { Microsoft_Kinect_Face_FaceFrameReader_Dispose(_pNative); } Microsoft_Kinect_Face_FaceFrameReader_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern bool Microsoft_Kinect_Face_FaceFrameReader_get_IsPaused(RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_FaceFrameReader_put_IsPaused(RootSystem.IntPtr pNative, bool isPaused); public bool IsPaused { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("FaceFrameReader"); } return Microsoft_Kinect_Face_FaceFrameReader_get_IsPaused(_pNative); } set { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("FaceFrameReader"); } Microsoft_Kinect_Face_FaceFrameReader_put_IsPaused(_pNative, value); Helper.ExceptionHelper.CheckLastError(); } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceFrameReader_get_FaceFrameSource(RootSystem.IntPtr pNative); public Microsoft.Kinect.Face.FaceFrameSource FaceFrameSource { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("FaceFrameReader"); } RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceFrameReader_get_FaceFrameSource(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceFrameSource>(objectPointer, n => new Microsoft.Kinect.Face.FaceFrameSource(n)); } } // Events private static RootSystem.Runtime.InteropServices.GCHandle _Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.Face.FaceFrameArrivedEventArgs>>> Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Microsoft.Kinect.Face.FaceFrameArrivedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate))] private static void Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Microsoft.Kinect.Face.FaceFrameArrivedEventArgs>> callbackList = null; Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<FaceFrameReader>(pNative); var args = new Microsoft.Kinect.Face.FaceFrameArrivedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_FaceFrameReader_add_FrameArrived(RootSystem.IntPtr pNative, _Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Microsoft.Kinect.Face.FaceFrameArrivedEventArgs> FrameArrived { add { Helper.EventPump.EnsureInitialized(); Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate(Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_Handler); _Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Microsoft_Kinect_Face_FaceFrameReader_add_FrameArrived(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Microsoft_Kinect_Face_FaceFrameReader_add_FrameArrived(_pNative, Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_Handler, true); _Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_Handle.Free(); } } } } private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle; [RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)] private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative); private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>(); [AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))] private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative) { List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null; Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList); lock(callbackList) { var objThis = Helper.NativeObjectCache.GetObject<FaceFrameReader>(pNative); var args = new Windows.Data.PropertyChangedEventArgs(result); foreach(var func in callbackList) { Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } }); } } } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_FaceFrameReader_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe); public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged { add { Helper.EventPump.EnsureInitialized(); Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Add(value); if(callbackList.Count == 1) { var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del); Microsoft_Kinect_Face_FaceFrameReader_add_PropertyChanged(_pNative, del, false); } } } remove { if (_pNative == RootSystem.IntPtr.Zero) { return; } Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { callbackList.Remove(value); if(callbackList.Count == 0) { Microsoft_Kinect_Face_FaceFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } // Public Methods [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Microsoft_Kinect_Face_FaceFrameReader_AcquireLatestFrame(RootSystem.IntPtr pNative); public Microsoft.Kinect.Face.FaceFrame AcquireLatestFrame() { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("FaceFrameReader"); } RootSystem.IntPtr objectPointer = Microsoft_Kinect_Face_FaceFrameReader_AcquireLatestFrame(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Microsoft.Kinect.Face.FaceFrame>(objectPointer, n => new Microsoft.Kinect.Face.FaceFrame(n)); } [RootSystem.Runtime.InteropServices.DllImport("KinectFaceUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Microsoft_Kinect_Face_FaceFrameReader_Dispose(RootSystem.IntPtr pNative); public void Dispose() { if (_pNative == RootSystem.IntPtr.Zero) { return; } Dispose(true); RootSystem.GC.SuppressFinalize(this); } private void __EventCleanup() { { Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Microsoft_Kinect_Face_FaceFrameReader_add_FrameArrived(_pNative, Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_Handler, true); } _Microsoft_Kinect_Face_FaceFrameArrivedEventArgs_Delegate_Handle.Free(); } } } { Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative); var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative]; lock (callbackList) { if (callbackList.Count > 0) { callbackList.Clear(); if (_pNative != RootSystem.IntPtr.Zero) { Microsoft_Kinect_Face_FaceFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true); } _Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free(); } } } } } }
/* * CP10007.cs - Cyrillic (Mac) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "mac-10007.ucm". namespace I18N.Other { using System; using I18N.Common; public class CP10007 : ByteEncoding { public CP10007() : base(10007, ToChars, "Cyrillic (Mac)", "windows-10007", "windows-10007", "windows-10007", false, false, false, false, 1251) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u007F', '\u0410', '\u0411', '\u0412', '\u0413', '\u0414', '\u0415', '\u0416', '\u0417', '\u0418', '\u0419', '\u041A', '\u041B', '\u041C', '\u041D', '\u041E', '\u041F', '\u0420', '\u0421', '\u0422', '\u0423', '\u0424', '\u0425', '\u0426', '\u0427', '\u0428', '\u0429', '\u042A', '\u042B', '\u042C', '\u042D', '\u042E', '\u042F', '\u2020', '\u00B0', '\u00A2', '\u00A3', '\u00A7', '\u2022', '\u00B6', '\u0406', '\u00AE', '\u00A9', '\u2122', '\u0402', '\u0452', '\u2260', '\u0403', '\u0453', '\u221E', '\u00B1', '\u2264', '\u2265', '\u0456', '\u00B5', '\u2202', '\u0408', '\u0404', '\u0454', '\u0407', '\u0457', '\u0409', '\u0459', '\u040A', '\u045A', '\u0458', '\u0405', '\u00AC', '\u221A', '\u0192', '\u2248', '\u2206', '\u00AB', '\u00BB', '\u2026', '\u00A0', '\u040B', '\u045B', '\u040C', '\u045C', '\u0455', '\u2013', '\u2014', '\u201C', '\u201D', '\u2018', '\u2019', '\u00F7', '\u201E', '\u040E', '\u045E', '\u040F', '\u045F', '\u2116', '\u0401', '\u0451', '\u044F', '\u0430', '\u0431', '\u0432', '\u0433', '\u0434', '\u0435', '\u0436', '\u0437', '\u0438', '\u0439', '\u043A', '\u043B', '\u043C', '\u043D', '\u043E', '\u043F', '\u0440', '\u0441', '\u0442', '\u0443', '\u0444', '\u0445', '\u0446', '\u0447', '\u0448', '\u0449', '\u044A', '\u044B', '\u044C', '\u044D', '\u044E', '\u00A4', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 128) switch(ch) { case 0x00A2: case 0x00A3: case 0x00A9: case 0x00B1: case 0x00B5: break; case 0x00A0: ch = 0xCA; break; case 0x00A4: ch = 0xFF; break; case 0x00A7: ch = 0xA4; break; case 0x00AB: ch = 0xC7; break; case 0x00AC: ch = 0xC2; break; case 0x00AE: ch = 0xA8; break; case 0x00B0: ch = 0xA1; break; case 0x00B6: ch = 0xA6; break; case 0x00BB: ch = 0xC8; break; case 0x00F7: ch = 0xD6; break; case 0x0192: ch = 0xC4; break; case 0x0401: ch = 0xDD; break; case 0x0402: ch = 0xAB; break; case 0x0403: ch = 0xAE; break; case 0x0404: ch = 0xB8; break; case 0x0405: ch = 0xC1; break; case 0x0406: ch = 0xA7; break; case 0x0407: ch = 0xBA; break; case 0x0408: ch = 0xB7; break; case 0x0409: ch = 0xBC; break; case 0x040A: ch = 0xBE; break; case 0x040B: ch = 0xCB; break; case 0x040C: ch = 0xCD; break; case 0x040E: ch = 0xD8; break; case 0x040F: ch = 0xDA; break; case 0x0410: case 0x0411: case 0x0412: case 0x0413: case 0x0414: case 0x0415: case 0x0416: case 0x0417: case 0x0418: case 0x0419: case 0x041A: case 0x041B: case 0x041C: case 0x041D: case 0x041E: case 0x041F: case 0x0420: case 0x0421: case 0x0422: case 0x0423: case 0x0424: case 0x0425: case 0x0426: case 0x0427: case 0x0428: case 0x0429: case 0x042A: case 0x042B: case 0x042C: case 0x042D: case 0x042E: case 0x042F: ch -= 0x0390; break; case 0x0430: case 0x0431: case 0x0432: case 0x0433: case 0x0434: case 0x0435: case 0x0436: case 0x0437: case 0x0438: case 0x0439: case 0x043A: case 0x043B: case 0x043C: case 0x043D: case 0x043E: case 0x043F: case 0x0440: case 0x0441: case 0x0442: case 0x0443: case 0x0444: case 0x0445: case 0x0446: case 0x0447: case 0x0448: case 0x0449: case 0x044A: case 0x044B: case 0x044C: case 0x044D: case 0x044E: ch -= 0x0350; break; case 0x044F: ch = 0xDF; break; case 0x0451: ch = 0xDE; break; case 0x0452: ch = 0xAC; break; case 0x0453: ch = 0xAF; break; case 0x0454: ch = 0xB9; break; case 0x0455: ch = 0xCF; break; case 0x0456: ch = 0xB4; break; case 0x0457: ch = 0xBB; break; case 0x0458: ch = 0xC0; break; case 0x0459: ch = 0xBD; break; case 0x045A: ch = 0xBF; break; case 0x045B: ch = 0xCC; break; case 0x045C: ch = 0xCE; break; case 0x045E: ch = 0xD9; break; case 0x045F: ch = 0xDB; break; case 0x2013: ch = 0xD0; break; case 0x2014: ch = 0xD1; break; case 0x2018: ch = 0xD4; break; case 0x2019: ch = 0xD5; break; case 0x201C: ch = 0xD2; break; case 0x201D: ch = 0xD3; break; case 0x201E: ch = 0xD7; break; case 0x2020: ch = 0xA0; break; case 0x2022: ch = 0xA5; break; case 0x2026: ch = 0xC9; break; case 0x2116: ch = 0xDC; break; case 0x2122: ch = 0xAA; break; case 0x2202: ch = 0xB6; break; case 0x2206: ch = 0xC6; break; case 0x221A: ch = 0xC3; break; case 0x221E: ch = 0xB0; break; case 0x2248: ch = 0xC5; break; case 0x2260: ch = 0xAD; break; case 0x2264: ch = 0xB2; break; case 0x2265: ch = 0xB3; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 128) switch(ch) { case 0x00A2: case 0x00A3: case 0x00A9: case 0x00B1: case 0x00B5: break; case 0x00A0: ch = 0xCA; break; case 0x00A4: ch = 0xFF; break; case 0x00A7: ch = 0xA4; break; case 0x00AB: ch = 0xC7; break; case 0x00AC: ch = 0xC2; break; case 0x00AE: ch = 0xA8; break; case 0x00B0: ch = 0xA1; break; case 0x00B6: ch = 0xA6; break; case 0x00BB: ch = 0xC8; break; case 0x00F7: ch = 0xD6; break; case 0x0192: ch = 0xC4; break; case 0x0401: ch = 0xDD; break; case 0x0402: ch = 0xAB; break; case 0x0403: ch = 0xAE; break; case 0x0404: ch = 0xB8; break; case 0x0405: ch = 0xC1; break; case 0x0406: ch = 0xA7; break; case 0x0407: ch = 0xBA; break; case 0x0408: ch = 0xB7; break; case 0x0409: ch = 0xBC; break; case 0x040A: ch = 0xBE; break; case 0x040B: ch = 0xCB; break; case 0x040C: ch = 0xCD; break; case 0x040E: ch = 0xD8; break; case 0x040F: ch = 0xDA; break; case 0x0410: case 0x0411: case 0x0412: case 0x0413: case 0x0414: case 0x0415: case 0x0416: case 0x0417: case 0x0418: case 0x0419: case 0x041A: case 0x041B: case 0x041C: case 0x041D: case 0x041E: case 0x041F: case 0x0420: case 0x0421: case 0x0422: case 0x0423: case 0x0424: case 0x0425: case 0x0426: case 0x0427: case 0x0428: case 0x0429: case 0x042A: case 0x042B: case 0x042C: case 0x042D: case 0x042E: case 0x042F: ch -= 0x0390; break; case 0x0430: case 0x0431: case 0x0432: case 0x0433: case 0x0434: case 0x0435: case 0x0436: case 0x0437: case 0x0438: case 0x0439: case 0x043A: case 0x043B: case 0x043C: case 0x043D: case 0x043E: case 0x043F: case 0x0440: case 0x0441: case 0x0442: case 0x0443: case 0x0444: case 0x0445: case 0x0446: case 0x0447: case 0x0448: case 0x0449: case 0x044A: case 0x044B: case 0x044C: case 0x044D: case 0x044E: ch -= 0x0350; break; case 0x044F: ch = 0xDF; break; case 0x0451: ch = 0xDE; break; case 0x0452: ch = 0xAC; break; case 0x0453: ch = 0xAF; break; case 0x0454: ch = 0xB9; break; case 0x0455: ch = 0xCF; break; case 0x0456: ch = 0xB4; break; case 0x0457: ch = 0xBB; break; case 0x0458: ch = 0xC0; break; case 0x0459: ch = 0xBD; break; case 0x045A: ch = 0xBF; break; case 0x045B: ch = 0xCC; break; case 0x045C: ch = 0xCE; break; case 0x045E: ch = 0xD9; break; case 0x045F: ch = 0xDB; break; case 0x2013: ch = 0xD0; break; case 0x2014: ch = 0xD1; break; case 0x2018: ch = 0xD4; break; case 0x2019: ch = 0xD5; break; case 0x201C: ch = 0xD2; break; case 0x201D: ch = 0xD3; break; case 0x201E: ch = 0xD7; break; case 0x2020: ch = 0xA0; break; case 0x2022: ch = 0xA5; break; case 0x2026: ch = 0xC9; break; case 0x2116: ch = 0xDC; break; case 0x2122: ch = 0xAA; break; case 0x2202: ch = 0xB6; break; case 0x2206: ch = 0xC6; break; case 0x221A: ch = 0xC3; break; case 0x221E: ch = 0xB0; break; case 0x2248: ch = 0xC5; break; case 0x2260: ch = 0xAD; break; case 0x2264: ch = 0xB2; break; case 0x2265: ch = 0xB3; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP10007 public class ENCwindows_10007 : CP10007 { public ENCwindows_10007() : base() {} }; // class ENCwindows_10007 }; // namespace I18N.Other
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; // ERROR: Not supported in C#: OptionDeclaration using Microsoft.VisualBasic.PowerPacks; namespace _4PosBackOffice.NET { internal partial class frmPriceList : System.Windows.Forms.Form { private ADODB.Recordset withEventsField_adoPrimaryRS; public ADODB.Recordset adoPrimaryRS { get { return withEventsField_adoPrimaryRS; } set { if (withEventsField_adoPrimaryRS != null) { withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete; withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord; } withEventsField_adoPrimaryRS = value; if (withEventsField_adoPrimaryRS != null) { withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete; withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord; } } } bool mbChangedByCode; int mvBookMark; bool mbEditFlag; bool mbAddNewFlag; bool mbDataChanged; List<TextBox> txtFields = new List<TextBox>(); List<CheckBox> chkFields = new List<CheckBox>(); int gID; private void loadLanguage() { //frmPriceList = No Code [Edit Price List] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmPriceList.Caption = rsLang("LanguageLayoutLnk_Description"): frmPriceList.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074; //Undo|Checked if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1188; //Allocate|Checked if (modRecordSet.rsLang.RecordCount){cmdAllocate.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdAllocate.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1085; //Print|Checked if (modRecordSet.rsLang.RecordCount){cmdPrint.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdPrint.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdClose.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdClose.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010; //General|Checked if (modRecordSet.rsLang.RecordCount){_lbl_5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1192; //Price List Name|Checked if (modRecordSet.rsLang.RecordCount){_lblLabels_38.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_38.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1193; //COD Channel Name|Checked if (modRecordSet.rsLang.RecordCount){_lblLabels_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1194; //Delivery Channel Name|Checked if (modRecordSet.rsLang.RecordCount){chkChannel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;chkChannel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2463; //Disabled|Checked if (modRecordSet.rsLang.RecordCount){_chkFields_12.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_chkFields_12.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmPriceList.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } private void buildDataControls() { ADODB.Recordset rs = default(ADODB.Recordset); rs = modRecordSet.getRS(ref "SELECT * FROM Channel ORDER BY ChannelID"); cmbCOD.Items.Clear(); cmbDelivery.Items.Clear(); int x = 0; while (!(rs.EOF)) { x = cmbCOD.Items.Add(new LBI(rs.Fields("Channel_Name").Value, rs.Fields("ChannelID").Value)); if (adoPrimaryRS.Fields("Pricelist_CODChannelID").Value == rs.Fields("ChannelID").Value) { cmbCOD.SelectedIndex = x; } cmbDelivery.Items.Add(new LBI(rs.Fields("Channel_Name").Value, rs.Fields("ChannelID").Value)); if (adoPrimaryRS.Fields("Pricelist_DeliveryChannelID").Value == rs.Fields("ChannelID").Value) { cmbDelivery.SelectedIndex = x; } rs.moveNext(); } // doDataControl Me.cmbChannel, "SELECT ChannelID, Channel_Name FROM Channel ORDER BY ChannelID", "Customer_ChannelID", "ChannelID", "Channel_Name" } private void doDataControl(ref System.Windows.Forms.Control dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField) { //Dim rs As ADODB.Recordset //rs = getRS(sql) //UPGRADE_WARNING: Couldn't resolve default property of object dataControl.DataSource. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //dataControl.DataSource = rs //UPGRADE_ISSUE: Control method dataControl.DataSource was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' //dataControl.DataSource = adoPrimaryRS //UPGRADE_ISSUE: Control method dataControl.DataField was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' //dataControl.DataField = DataField //UPGRADE_WARNING: Couldn't resolve default property of object dataControl.boundColumn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //dataControl.boundColumn = boundColumn //UPGRADE_WARNING: Couldn't resolve default property of object dataControl.listField. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"' //dataControl.listField = listField } public void loadItem(ref int id) { System.Windows.Forms.TextBox oText = null; System.Windows.Forms.CheckBox oCheck = null; // ERROR: Not supported in C#: OnErrorStatement if (id) { adoPrimaryRS = modRecordSet.getRS(ref "select * from Pricelist WHERE PricelistID = " + id); } else { adoPrimaryRS = modRecordSet.getRS(ref "select * from Pricelist"); adoPrimaryRS.AddNew(); this.Text = this.Text + " [New record]"; mbAddNewFlag = true; } setup(); foreach (TextBox oText_loopVariable in txtFields) { oText = oText_loopVariable; oText.DataBindings.Add(adoPrimaryRS); oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize; } // For Each oText In Me.txtInteger // Set oText.DataBindings.Add(adoPrimaryRS) // txtInteger_LostFocus oText.Index // Next // For Each oText In Me.txtFloat // Set oText.DataBindings.Add(adoPrimaryRS) // If oText.Text = "" Then oText.Text = "0" // oText.Text = oText.Text * 100 // txtFloat_LostFocus oText.Index // Next // For Each oText In Me.txtFloatNegative // Set oText.DataBindings.Add(adoPrimaryRS) // If oText.Text = "" Then oText.Text = "0" // oText.Text = oText.Text * 100 // txtFloatNegative_LostFocus oText.Index // Next //Bind the check boxes to the data provider foreach (CheckBox oCheck_loopVariable in chkFields) { oCheck = oCheck_loopVariable; oCheck.DataBindings.Add(adoPrimaryRS); } buildDataControls(); mbDataChanged = false; if (this.cmbDelivery.SelectedIndex == -1) { chkChannel.CheckState = System.Windows.Forms.CheckState.Unchecked; cmbDelivery.Enabled = false; } else { chkChannel.CheckState = System.Windows.Forms.CheckState.Checked; cmbDelivery.Enabled = true; } loadLanguage(); ShowDialog(); } private void setup() { } //UPGRADE_WARNING: Event chkChannel.CheckStateChanged may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' private void chkChannel_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs) { cmbDelivery.Enabled = (chkChannel.CheckState); } private void cmdAllocate_Click(System.Object eventSender, System.EventArgs eventArgs) { if (update_Renamed()) { My.MyProject.Forms.frmPricelistItem.loadItem(ref adoPrimaryRS.Fields("PricelistID").Value); } } private void cmdPrint_Click(System.Object eventSender, System.EventArgs eventArgs) { ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Recordset rsCompany = default(ADODB.Recordset); string sql = null; CrystalDecisions.CrystalReports.Engine.ReportDocument Report = default(CrystalDecisions.CrystalReports.Engine.ReportDocument); update_Renamed(); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; rsCompany = modRecordSet.getRS(ref "SELECT * FROM Company"); if (this.chkChannel.CheckState) { Report.Load("cryPriceList.rpt"); sql = "SELECT Pricelist.Pricelist_Name, StockItem.StockItem_Name, Max(codCase.CatalogueChannelLnk_Price) AS codCase, Max(codCase.CatalogueChannelLnk_Quantity) AS codQuantity, codSingle.CatalogueChannelLnk_Price AS codSingle, Max(deliveryCase.CatalogueChannelLnk_Quantity) AS delQuantity, Max(deliveryCase.CatalogueChannelLnk_Price) AS delCase, deliverySingle.CatalogueChannelLnk_Price AS delSingle"; sql = sql + " FROM ShrinkItem INNER JOIN"; sql = sql + " (CatalogueChannelLnk AS deliverySingle INNER JOIN (CatalogueChannelLnk AS deliveryCase INNER JOIN ((CatalogueChannelLnk AS codCase INNER JOIN (StockItem INNER JOIN (PricelistStockItemLnk INNER JOIN Pricelist ON PricelistStockItemLnk.PricelistStockitemLnk_PricelistID = Pricelist.PricelistID) ON StockItem.StockItemID = PricelistStockItemLnk.PricelistStockitemLnk_StockitemID) ON (codCase.CatalogueChannelLnk_ChannelID = Pricelist.Pricelist_CODChannelID) AND (codCase.CatalogueChannelLnk_StockItemID = StockItem.StockItemID)) INNER JOIN CatalogueChannelLnk AS codSingle ON (StockItem.StockItemID = codSingle.CatalogueChannelLnk_StockItemID) AND (Pricelist.Pricelist_CODChannelID = codSingle.CatalogueChannelLnk_ChannelID)) ON (deliveryCase.CatalogueChannelLnk_StockItemID = StockItem.StockItemID) AND (deliveryCase.CatalogueChannelLnk_ChannelID = Pricelist.Pricelist_DeliveryChannelID)) ON (deliverySingle.CatalogueChannelLnk_ChannelID = Pricelist.Pricelist_DeliveryChannelID)"; sql = sql + " AND (deliverySingle.CatalogueChannelLnk_StockItemID = StockItem.StockItemID)) ON (ShrinkItem.ShrinkItem_Quantity = codCase.CatalogueChannelLnk_Quantity) AND (ShrinkItem.ShrinkItem_Quantity = deliveryCase.CatalogueChannelLnk_Quantity) AND (ShrinkItem.ShrinkItem_ShrinkID = StockItem.StockItem_ShrinkID)"; sql = sql + " Where (((codSingle.CatalogueChannelLnk_Quantity) = 1) And ((Pricelist.Pricelist_Disabled) = 0) And ((deliverySingle.CatalogueChannelLnk_Quantity) = 1))"; sql = sql + " GROUP BY Pricelist.Pricelist_Name, StockItem.StockItem_Name, codSingle.CatalogueChannelLnk_Price, deliverySingle.CatalogueChannelLnk_Price"; sql = sql + " ORDER BY Pricelist.Pricelist_Name, StockItem.StockItem_Name;"; } else { Report.Load("cryPriceListSingle.rpt"); sql = "SELECT Pricelist.Pricelist_Name, StockItem.StockItem_Name, Max(codCase.CatalogueChannelLnk_Price) AS codCase, Max(codCase.CatalogueChannelLnk_Quantity) AS codQuantity, codSingle.CatalogueChannelLnk_Price AS codSingle, StockItem.StockItemID "; sql = sql + "FROM ((CatalogueChannelLnk AS codCase INNER JOIN (StockItem INNER JOIN (PricelistStockItemLnk INNER JOIN Pricelist ON PricelistStockItemLnk.PricelistStockitemLnk_PricelistID = Pricelist.PricelistID) ON StockItem.StockItemID = PricelistStockItemLnk.PricelistStockitemLnk_StockitemID) ON (codCase.CatalogueChannelLnk_StockItemID = StockItem.StockItemID) AND (codCase.CatalogueChannelLnk_ChannelID = Pricelist.Pricelist_CODChannelID)) INNER JOIN CatalogueChannelLnk AS codSingle ON (Pricelist.Pricelist_CODChannelID = codSingle.CatalogueChannelLnk_ChannelID) AND (StockItem.StockItemID = codSingle.CatalogueChannelLnk_StockItemID)) INNER JOIN ShrinkItem ON (ShrinkItem.ShrinkItem_Quantity = codCase.CatalogueChannelLnk_Quantity) AND (StockItem.StockItem_ShrinkID = ShrinkItem.ShrinkItem_ShrinkID) "; sql = sql + "Where (((codSingle.CatalogueChannelLnk_Quantity) = 1) And ((Pricelist.Pricelist_Disabled) = 0)) GROUP BY Pricelist.Pricelist_Name, StockItem.StockItem_Name, codSingle.CatalogueChannelLnk_Price, StockItem.StockItemID ORDER BY Pricelist.Pricelist_Name, StockItem.StockItem_Name;"; } rs = modRecordSet.getRS(ref sql); if (rs.BOF | rs.EOF) { Interaction.MsgBox("No Price allocated!", MsgBoxStyle.Exclamation, "PRICE LIST"); return; } if (this.chkChannel.CheckState) { Report.SetParameterValue("Text3", cmbCOD.Text); Report.SetParameterValue("Text4", cmbDelivery.Text); } else { Report.SetParameterValue("Text3", cmbCOD.Text); } Report.Database.Tables(1).SetDataSource(rs); Report.Database.Tables(2).SetDataSource(rsCompany); Report.SetParameterValue("txtCompanyName", rsCompany.Fields("Company_Name")); My.MyProject.Forms.frmReportShow.Text = "Price List"; My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report; My.MyProject.Forms.frmReportShow.mReport = Report; My.MyProject.Forms.frmReportShow.sMode = "0"; My.MyProject.Forms.frmReportShow.CRViewer1.Refresh(); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; My.MyProject.Forms.frmReportShow.ShowDialog(); } //UPGRADE_WARNING: Event frmPriceList.Resize may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"' private void frmPriceList_Resize(System.Object eventSender, System.EventArgs eventArgs) { Button cmdLast = new Button(); Button cmdNext = new Button(); Label lblStatus = new Label(); // ERROR: Not supported in C#: OnErrorStatement lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500; cmdNext.Left = lblStatus.Width + 700; cmdLast.Left = cmdNext.Left + 340; } private void frmPriceList_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (mbEditFlag | mbAddNewFlag) goto EventExitSub; switch (KeyAscii) { case System.Windows.Forms.Keys.Escape: KeyAscii = 0; adoPrimaryRS.Move(0); cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); cmdClose_Click(cmdClose, new System.EventArgs()); break; } EventExitSub: eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void frmPriceList_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs) { //UPGRADE_WARNING: Screen property Screen.MousePointer has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6BA9B8D2-2A32-4B6E-8D36-44949974A5B4"' System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; } private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset) { //This will display the current record position for this recordset } private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset) { //This is where you put validation code //This event gets called when the following actions occur bool bCancel = false; switch (adReason) { case ADODB.EventReasonEnum.adRsnAddNew: break; case ADODB.EventReasonEnum.adRsnClose: break; case ADODB.EventReasonEnum.adRsnDelete: break; case ADODB.EventReasonEnum.adRsnFirstChange: break; case ADODB.EventReasonEnum.adRsnMove: break; case ADODB.EventReasonEnum.adRsnRequery: break; case ADODB.EventReasonEnum.adRsnResynch: break; case ADODB.EventReasonEnum.adRsnUndoAddNew: break; case ADODB.EventReasonEnum.adRsnUndoDelete: break; case ADODB.EventReasonEnum.adRsnUndoUpdate: break; case ADODB.EventReasonEnum.adRsnUpdate: break; } if (bCancel) adStatus = ADODB.EventStatusEnum.adStatusCancel; } private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs) { // ERROR: Not supported in C#: OnErrorStatement if (mbAddNewFlag) { this.Close(); } else { mbEditFlag = false; mbAddNewFlag = false; adoPrimaryRS.CancelUpdate(); if (mvBookMark > 0) { adoPrimaryRS.Bookmark = mvBookMark; } else { adoPrimaryRS.MoveFirst(); } mbDataChanged = false; } } //UPGRADE_NOTE: update was upgraded to update_Renamed. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="A9E4979A-37FA-4718-9994-97DD76ED70A7"' private bool update_Renamed() { bool functionReturnValue = false; // ERROR: Not supported in C#: OnErrorStatement functionReturnValue = true; adoPrimaryRS.Fields("Pricelist_CODChannelID").Value = Convert.ToInt32(cmbCOD.SelectedIndex); if (chkChannel.CheckState) { adoPrimaryRS.Fields("Pricelist_DeliveryChannelID").Value = Convert.ToInt32(cmbDelivery.SelectedIndex); } else { adoPrimaryRS.Fields("Pricelist_DeliveryChannelID").Value = 0; } adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll); if (mbAddNewFlag) { adoPrimaryRS.MoveLast(); //move to the new record } mbEditFlag = false; mbAddNewFlag = false; mbDataChanged = false; return functionReturnValue; UpdateErr: Interaction.MsgBox(Err().Description); functionReturnValue = false; return functionReturnValue; } private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs) { cmdClose.Focus(); System.Windows.Forms.Application.DoEvents(); if (update_Renamed()) { this.Close(); } } //Handles txtFields.Enter private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs) { TextBox txtBox = new TextBox(); txtBox = (TextBox)eventSender; int Index = GetIndex.GetIndexer(ref txtBox, ref txtFields); modUtilities.MyGotFocus(ref txtFields[Index]); } private void txtInteger_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtInteger(Index) } private void txtInteger_KeyPress(ref short Index, ref short KeyAscii) { // KeyPress KeyAscii } private void txtInteger_MyLostFocus(ref short Index) { // LostFocus txtInteger(Index), 0 } private void txtFloat_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtFloat(Index) } private void txtFloat_KeyPress(ref short Index, ref short KeyAscii) { // KeyPress KeyAscii } private void txtFloat_MyLostFocus(ref short Index) { // MyGotFocusNumeric txtFloat(Index), 2 } private void txtFloatNegative_MyGotFocus(ref short Index) { // MyGotFocusNumeric txtFloatNegative(Index) } private void txtFloatNegative_KeyPress(ref short Index, ref short KeyAscii) { // KeyPressNegative txtFloatNegative(Index), KeyAscii } private void txtFloatNegative_MyLostFocus(ref short Index) { // LostFocus txtFloatNegative(Index), 2 } private void frmPriceList_Load(object sender, System.EventArgs e) { txtFields.AddRange(new TextBox[] { _txtFields_0 }); _txtFields_0.Enter += txtFields_Enter; chkFields.AddRange(new CheckBox[] { _chkFields_12 }); } } }
using System; using System.Threading; using System.IO; using System.Runtime.InteropServices; using Microsoft.XLANGs.BaseTypes; using Microsoft.BizTalk.TransportProxy.Interop; using Microsoft.BizTalk.Message.Interop; /// <summary> /// Summary description for Class1 /// </summary> namespace inSyca.foundation.integration.biztalk.adapter.common { /// <summary> /// This class encapsulates the typical behavior we want in a Transmit Adapter running asynchronously. /// In summary our policy is: /// (1) on a resubmit failure Move to the next transport /// (2) on a move to next transport failure move to the suspend queue /// Otherwise: /// TODO: we should use SetErrorInfo on the transportProxy to log the error appropriately /// </summary> public sealed class TransmitResponseBatch : Batch { public delegate void AllWorkDoneDelegate(); private AllWorkDoneDelegate allWorkDoneDelegate; public TransmitResponseBatch(IBTTransportProxy transportProxy, AllWorkDoneDelegate allWorkDoneDelegate) : base(transportProxy, true) { this.allWorkDoneDelegate = allWorkDoneDelegate; } public override sealed void SubmitResponseMessage(IBaseMessage solicitDocSent, IBaseMessage responseDocToSubmit) { IBaseMessagePart bodyPart = responseDocToSubmit.BodyPart; if (bodyPart == null) throw new InvalidOperationException("The message does not contain body part"); Stream stream = bodyPart.GetOriginalDataStream(); if (stream == null || stream.CanSeek == false) throw new InvalidOperationException("Message body stream is null or it is not seekable"); base.SubmitResponseMessage(solicitDocSent, responseDocToSubmit, solicitDocSent); } // This method is typically used during process shutdown public void Resubmit(IBaseMessage[] msgs, DateTime timeStamp) { foreach (IBaseMessage message in msgs) base.Resubmit(message, timeStamp); } public void Resubmit(IBaseMessage msg, bool preserveRetryCount, object userData) { SystemMessageContext context = new SystemMessageContext(msg.Context); if (preserveRetryCount) { UpdateProperty[] updates = new UpdateProperty[1]; updates[0] = new UpdateProperty(); updates[0].Name = retryCountProp.Name.Name; updates[0].NameSpace = retryCountProp.Name.Namespace; updates[0].Value = context.RetryCount++; context.UpdateProperties(updates); // If preserveRetryCount is true, ignore RetryInterval // Request the redelivery immediately!! base.Resubmit(msg, DateTime.Now, userData); } else { // This is retry in case of error/failure (i.e. normal retry) if (context.RetryCount > 0) { DateTime retryAt = DateTime.Now.AddMinutes(context.RetryInterval); base.Resubmit(msg, retryAt, userData); } else { base.MoveToNextTransport(msg, userData); } } } protected override void StartBatchComplete(int hrBatchComplete) { this.batchFailed = (this.HRStatus < 0); } protected override void StartProcessFailures() { if (this.batchFailed) { // Retry should happen outside the transaction scope this.batch = new TransmitResponseBatch(this.TransportProxy, this.allWorkDoneDelegate); this.allWorkDoneDelegate = null; } } protected override void EndProcessFailures() { if (this.batch != null) { if (!this.batch.IsEmpty) { this.batch.Done(null); } else { // If suspend or delete fails, then there is nothing adapter can do! this.batch.Dispose(); } } } protected override void EndBatchComplete() { if (this.allWorkDoneDelegate != null) this.allWorkDoneDelegate(); } // This is for submit-response protected override void SubmitSuccess(IBaseMessage message, Int32 hrStatus, object userData) { if (this.batchFailed) { // Previous submit operation might have moved the stream position // Seek the stream position back to zero before submitting again! IBaseMessage solicit = userData as IBaseMessage; if (solicit == null) throw new InvalidOperationException("Response message does not have corresponding request message"); IBaseMessagePart responseBodyPart = message.BodyPart; if (responseBodyPart != null) { Stream stream = responseBodyPart.GetOriginalDataStream(); stream.Position = 0; } this.batch.SubmitResponseMessage(solicit, message); } } protected override void SubmitFailure(IBaseMessage message, Int32 hrStatus, object userData) { // If response cannot be submitted, then Resubmit the original message? // this.batch.Resubmit(message, false, null); this.batch.MoveToSuspendQ(message); } protected override void DeleteSuccess(IBaseMessage message, Int32 hrStatus, object userData) { if (this.batchFailed) { this.batch.DeleteMessage(message); } } // No action required when delete fails! protected override void ResubmitSuccess(IBaseMessage message, Int32 hrStatus, object userData) { if (this.batchFailed) { SystemMessageContext context = new SystemMessageContext(message.Context); DateTime dt = DateTime.Now.AddMinutes(context.RetryInterval); this.batch.Resubmit(message, dt); } } protected override void ResubmitFailure(IBaseMessage message, Int32 hrStatus, object userData) { this.batch.MoveToNextTransport(message); } protected override void MoveToNextTransportSuccess(IBaseMessage message, Int32 hrStatus, object userData) { if (this.batchFailed) { this.batch.MoveToNextTransport(message); } } protected override void MoveToNextTransportFailure(IBaseMessage message, Int32 hrStatus, object userData) { this.batch.MoveToSuspendQ(message); } protected override void MoveToSuspendQSuccess(IBaseMessage message, Int32 hrStatus, object userData) { if (this.batchFailed) { this.batch.MoveToSuspendQ(message); } } // Nothing can be done if suspend fails private TransmitResponseBatch batch; private bool batchFailed = false; private static BTS.RetryCount retryCountProp = new BTS.RetryCount(); } }
// This file is auto generatored. Don't modify it. /* * The MIT License (MIT) * * Copyright (c) 2015 Wu Yuntao * * 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; namespace SecurePrimitive { public partial struct SPInt32 { #region SPInt32 <-> SPSByte public static explicit operator SPInt32(SPSByte value) { return new SPInt32((int)value.Value); } public static explicit operator SPSByte(SPInt32 value) { return new SPSByte((sbyte)value.Value); } #endregion #region SPInt32 <-> sbyte public static explicit operator SPInt32(sbyte value) { return new SPInt32((int)value); } public static explicit operator sbyte(SPInt32 value) { return (sbyte)value.Value; } #endregion #region SPInt32 <-> SPByte public static explicit operator SPInt32(SPByte value) { return new SPInt32((int)value.Value); } public static explicit operator SPByte(SPInt32 value) { return new SPByte((byte)value.Value); } #endregion #region SPInt32 <-> byte public static explicit operator SPInt32(byte value) { return new SPInt32((int)value); } public static explicit operator byte(SPInt32 value) { return (byte)value.Value; } #endregion #region SPInt32 <-> SPInt16 public static explicit operator SPInt32(SPInt16 value) { return new SPInt32((int)value.Value); } public static explicit operator SPInt16(SPInt32 value) { return new SPInt16((short)value.Value); } #endregion #region SPInt32 <-> short public static explicit operator SPInt32(short value) { return new SPInt32((int)value); } public static explicit operator short(SPInt32 value) { return (short)value.Value; } #endregion #region SPInt32 <-> SPUInt16 public static explicit operator SPInt32(SPUInt16 value) { return new SPInt32((int)value.Value); } public static explicit operator SPUInt16(SPInt32 value) { return new SPUInt16((ushort)value.Value); } #endregion #region SPInt32 <-> ushort public static explicit operator SPInt32(ushort value) { return new SPInt32((int)value); } public static explicit operator ushort(SPInt32 value) { return (ushort)value.Value; } #endregion #region SPInt32 <-> int public static implicit operator SPInt32(int value) { return new SPInt32(value); } public static implicit operator int(SPInt32 value) { return value.Value; } #endregion #region SPInt32 <-> SPUInt32 public static explicit operator SPInt32(SPUInt32 value) { return new SPInt32((int)value.Value); } public static explicit operator SPUInt32(SPInt32 value) { return new SPUInt32((uint)value.Value); } #endregion #region SPInt32 <-> uint public static explicit operator SPInt32(uint value) { return new SPInt32((int)value); } public static explicit operator uint(SPInt32 value) { return (uint)value.Value; } #endregion #region SPInt32 <-> SPInt64 public static explicit operator SPInt32(SPInt64 value) { return new SPInt32((int)value.Value); } public static explicit operator SPInt64(SPInt32 value) { return new SPInt64((long)value.Value); } #endregion #region SPInt32 <-> long public static explicit operator SPInt32(long value) { return new SPInt32((int)value); } public static explicit operator long(SPInt32 value) { return (long)value.Value; } #endregion #region SPInt32 <-> SPUInt64 public static explicit operator SPInt32(SPUInt64 value) { return new SPInt32((int)value.Value); } public static explicit operator SPUInt64(SPInt32 value) { return new SPUInt64((ulong)value.Value); } #endregion #region SPInt32 <-> ulong public static explicit operator SPInt32(ulong value) { return new SPInt32((int)value); } public static explicit operator ulong(SPInt32 value) { return (ulong)value.Value; } #endregion } }
#region License /* * Cookie.cs * * This code is derived from System.Net.Cookie.cs of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2004,2009 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2014 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Lawrence Pit <loz@cable.a2000.nl> * - Gonzalo Paniagua Javier <gonzalo@ximian.com> * - Daniel Nauck <dna@mono-project.de> * - Sebastien Pouliot <sebastien@ximian.com> */ #endregion using System; using System.Globalization; using System.Text; namespace WebSocketSharp.Net { /// <summary> /// Provides a set of methods and properties used to manage an HTTP Cookie. /// </summary> /// <remarks> /// <para> /// The Cookie class supports the following cookie formats: /// <see href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">Netscape specification</see>, /// <see href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</see>, and /// <see href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</see> /// </para> /// <para> /// The Cookie class cannot be inherited. /// </para> /// </remarks> [Serializable] public sealed class Cookie { #region Private Static Fields private static char [] _reservedCharsForName = { ' ', '=', ';', ',', '\n', '\r', '\t' }; private static char [] _reservedCharsForValue = { ';', ',' }; #endregion #region Private Fields private string _comment; private Uri _commentUri; private bool _discard; private string _domain; private DateTime _expires; private bool _httpOnly; private string _name; private string _path; private string _port; private int [] _ports; private bool _secure; private DateTime _timestamp; private string _value; private int _version; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class. /// </summary> public Cookie () { _comment = String.Empty; _domain = String.Empty; _expires = DateTime.MinValue; _name = String.Empty; _path = String.Empty; _port = String.Empty; _ports = new int [0]; _timestamp = DateTime.Now; _value = String.Empty; _version = 0; } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with the specified /// <paramref name="name"/> and <paramref name="value"/>. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the Name of the cookie. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the Value of the cookie. /// </param> /// <exception cref="CookieException"> /// <para> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="name"/> contains an invalid character. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> is <see langword="null"/>. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> contains a string not enclosed in double quotes /// that contains an invalid character. /// </para> /// </exception> public Cookie (string name, string value) : this () { Name = name; Value = value; } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with the specified /// <paramref name="name"/>, <paramref name="value"/>, and <paramref name="path"/>. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the Name of the cookie. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the Value of the cookie. /// </param> /// <param name="path"> /// A <see cref="string"/> that represents the value of the Path attribute of the cookie. /// </param> /// <exception cref="CookieException"> /// <para> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="name"/> contains an invalid character. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> is <see langword="null"/>. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> contains a string not enclosed in double quotes /// that contains an invalid character. /// </para> /// </exception> public Cookie (string name, string value, string path) : this (name, value) { Path = path; } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with the specified /// <paramref name="name"/>, <paramref name="value"/>, <paramref name="path"/>, and /// <paramref name="domain"/>. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the Name of the cookie. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the Value of the cookie. /// </param> /// <param name="path"> /// A <see cref="string"/> that represents the value of the Path attribute of the cookie. /// </param> /// <param name="domain"> /// A <see cref="string"/> that represents the value of the Domain attribute of the cookie. /// </param> /// <exception cref="CookieException"> /// <para> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="name"/> contains an invalid character. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> is <see langword="null"/>. /// </para> /// <para> /// - or - /// </para> /// <para> /// <paramref name="value"/> contains a string not enclosed in double quotes /// that contains an invalid character. /// </para> /// </exception> public Cookie (string name, string value, string path, string domain) : this (name, value, path) { Domain = domain; } #endregion #region Internal Properties internal bool ExactDomain { get; set; } internal int MaxAge { get { if (_expires == DateTime.MinValue) return 0; var expires = _expires.Kind != DateTimeKind.Local ? _expires.ToLocalTime () : _expires; var span = expires - DateTime.Now; return span > TimeSpan.Zero ? (int) span.TotalSeconds : 0; } } internal int [] Ports { get { return _ports; } } #endregion #region Public Properties /// <summary> /// Gets or sets the value of the Comment attribute of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the comment to document intended use of the cookie. /// </value> public string Comment { get { return _comment; } set { _comment = value ?? String.Empty; } } /// <summary> /// Gets or sets the value of the CommentURL attribute of the cookie. /// </summary> /// <value> /// A <see cref="Uri"/> that represents the URI that provides the comment to document intended /// use of the cookie. /// </value> public Uri CommentUri { get { return _commentUri; } set { _commentUri = value; } } /// <summary> /// Gets or sets a value indicating whether the client discards the cookie unconditionally /// when the client terminates. /// </summary> /// <value> /// <c>true</c> if the client discards the cookie unconditionally when the client terminates; /// otherwise, <c>false</c>. The default value is <c>false</c>. /// </value> public bool Discard { get { return _discard; } set { _discard = value; } } /// <summary> /// Gets or sets the value of the Domain attribute of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the URI for which the cookie is valid. /// </value> public string Domain { get { return _domain; } set { if (value.IsNullOrEmpty ()) { _domain = String.Empty; ExactDomain = true; } else { _domain = value; ExactDomain = value [0] != '.'; } } } /// <summary> /// Gets or sets a value indicating whether the cookie has expired. /// </summary> /// <value> /// <c>true</c> if the cookie has expired; otherwise, <c>false</c>. /// The default value is <c>false</c>. /// </value> public bool Expired { get { return _expires != DateTime.MinValue && _expires <= DateTime.Now; } set { _expires = value ? DateTime.Now : DateTime.MinValue; } } /// <summary> /// Gets or sets the value of the Expires attribute of the cookie. /// </summary> /// <value> /// A <see cref="DateTime"/> that represents the date and time at which the cookie expires. /// The default value is <see cref="DateTime.MinValue"/>. /// </value> public DateTime Expires { get { return _expires; } set { _expires = value; } } /// <summary> /// Gets or sets a value indicating whether non-HTTP APIs can access the cookie. /// </summary> /// <value> /// <c>true</c> if non-HTTP APIs cannot access the cookie; otherwise, <c>false</c>. /// The default value is <c>false</c>. /// </value> public bool HttpOnly { get { return _httpOnly; } set { _httpOnly = value; } } /// <summary> /// Gets or sets the Name of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the Name of the cookie. /// </value> /// <exception cref="CookieException"> /// <para> /// The value specified for a set operation is <see langword="null"/> or empty. /// </para> /// <para> /// - or - /// </para> /// <para> /// The value specified for a set operation contains an invalid character. /// </para> /// </exception> public string Name { get { return _name; } set { string msg; if (!canSetName (value, out msg)) throw new CookieException (msg); _name = value; } } /// <summary> /// Gets or sets the value of the Path attribute of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the subset of URI on the origin server /// to which the cookie applies. /// </value> public string Path { get { return _path; } set { _path = value ?? String.Empty; } } /// <summary> /// Gets or sets the value of the Port attribute of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the list of TCP ports to which the cookie applies. /// </value> /// <exception cref="CookieException"> /// The value specified for a set operation isn't enclosed in double quotes or /// couldn't be parsed. /// </exception> public string Port { get { return _port; } set { if (value.IsNullOrEmpty ()) { _port = String.Empty; _ports = new int [0]; return; } if (!value.IsEnclosedIn ('"')) throw new CookieException ( "The value of Port attribute must be enclosed in double quotes."); string error; if (!tryCreatePorts (value, out _ports, out error)) throw new CookieException ( String.Format ( "The value specified for a Port attribute contains an invalid value: {0}", error)); _port = value; } } /// <summary> /// Gets or sets a value indicating whether the security level of the cookie is secure. /// </summary> /// <remarks> /// When this property is <c>true</c>, the cookie may be included in the HTTP request /// only if the request is transmitted over the HTTPS. /// </remarks> /// <value> /// <c>true</c> if the security level of the cookie is secure; otherwise, <c>false</c>. /// The default value is <c>false</c>. /// </value> public bool Secure { get { return _secure; } set { _secure = value; } } /// <summary> /// Gets the time when the cookie was issued. /// </summary> /// <value> /// A <see cref="DateTime"/> that represents the time when the cookie was issued. /// </value> public DateTime TimeStamp { get { return _timestamp; } } /// <summary> /// Gets or sets the Value of the cookie. /// </summary> /// <value> /// A <see cref="string"/> that represents the Value of the cookie. /// </value> /// <exception cref="CookieException"> /// <para> /// The value specified for a set operation is <see langword="null"/>. /// </para> /// <para> /// - or - /// </para> /// <para> /// The value specified for a set operation contains a string not enclosed in double quotes /// that contains an invalid character. /// </para> /// </exception> public string Value { get { return _value; } set { string msg; if (!canSetValue (value, out msg)) throw new CookieException (msg); _value = value.Length > 0 ? value : "\"\""; } } /// <summary> /// Gets or sets the value of the Version attribute of the cookie. /// </summary> /// <value> /// An <see cref="int"/> that represents the version of the HTTP state management /// to which the cookie conforms. /// </value> /// <exception cref="ArgumentOutOfRangeException"> /// The value specified for a set operation isn't 0 or 1. /// </exception> public int Version { get { return _version; } set { if (value < 0 || value > 1) throw new ArgumentOutOfRangeException ("value", "Must be 0 or 1."); _version = value; } } #endregion #region Private Methods private static bool canSetName (string name, out string message) { if (name.IsNullOrEmpty ()) { message = "Name must not be null or empty."; return false; } if (name [0] == '$' || name.Contains (_reservedCharsForName)) { message = "The value specified for a Name contains an invalid character."; return false; } message = String.Empty; return true; } private static bool canSetValue (string value, out string message) { if (value == null) { message = "Value must not be null."; return false; } if (value.Contains (_reservedCharsForValue) && !value.IsEnclosedIn ('"')) { message = "The value specified for a Value contains an invalid character."; return false; } message = String.Empty; return true; } private static int hash (int i, int j, int k, int l, int m) { return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25) ^ (m << 20 | m >> 12); } private string toResponseStringVersion0 () { var result = new StringBuilder (64); result.AppendFormat ("{0}={1}", _name, _value); if (_expires != DateTime.MinValue) result.AppendFormat ( "; Expires={0}", _expires.ToUniversalTime ().ToString ( "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", CultureInfo.CreateSpecificCulture ("en-US"))); if (!_path.IsNullOrEmpty ()) result.AppendFormat ("; Path={0}", _path); if (!_domain.IsNullOrEmpty ()) result.AppendFormat ("; Domain={0}", _domain); if (_secure) result.Append ("; Secure"); if (_httpOnly) result.Append ("; HttpOnly"); return result.ToString (); } private string toResponseStringVersion1 () { var result = new StringBuilder (64); result.AppendFormat ("{0}={1}; Version={2}", _name, _value, _version); if (_expires != DateTime.MinValue) result.AppendFormat ("; Max-Age={0}", MaxAge); if (!_path.IsNullOrEmpty ()) result.AppendFormat ("; Path={0}", _path); if (!_domain.IsNullOrEmpty ()) result.AppendFormat ("; Domain={0}", _domain); if (!_port.IsNullOrEmpty ()) { if (_port == "\"\"") result.Append ("; Port"); else result.AppendFormat ("; Port={0}", _port); } if (!_comment.IsNullOrEmpty ()) result.AppendFormat ("; Comment={0}", _comment.UrlEncode ()); if (_commentUri != null) result.AppendFormat ("; CommentURL={0}", _commentUri.OriginalString.Quote ()); if (_discard) result.Append ("; Discard"); if (_secure) result.Append ("; Secure"); return result.ToString (); } private static bool tryCreatePorts (string value, out int [] result, out string parseError) { var ports = value.Trim ('"').Split (','); var tmp = new int [ports.Length]; for (int i = 0; i < ports.Length; i++) { tmp [i] = int.MinValue; var port = ports [i].Trim (); if (port.Length == 0) continue; if (!int.TryParse (port, out tmp [i])) { result = new int [0]; parseError = port; return false; } } result = tmp; parseError = String.Empty; return true; } #endregion #region Internal Methods // From client to server internal string ToRequestString (Uri uri) { if (_name.Length == 0) return String.Empty; if (_version == 0) return String.Format ("{0}={1}", _name, _value); var result = new StringBuilder (64); result.AppendFormat ("$Version={0}; {1}={2}", _version, _name, _value); if (!_path.IsNullOrEmpty ()) result.AppendFormat ("; $Path={0}", _path); else if (uri != null) result.AppendFormat ("; $Path={0}", uri.GetAbsolutePath ()); else result.Append ("; $Path=/"); bool appendDomain = uri == null || uri.Host != _domain; if (appendDomain && !_domain.IsNullOrEmpty ()) result.AppendFormat ("; $Domain={0}", _domain); if (!_port.IsNullOrEmpty ()) { if (_port == "\"\"") result.Append ("; $Port"); else result.AppendFormat ("; $Port={0}", _port); } return result.ToString (); } // From server to client internal string ToResponseString () { return _name.Length > 0 ? (_version == 0 ? toResponseStringVersion0 () : toResponseStringVersion1 ()) : String.Empty; } #endregion #region Public Methods /// <summary> /// Determines whether the specified <see cref="Object"/> is equal to the current /// <see cref="Cookie"/>. /// </summary> /// <param name="comparand"> /// An <see cref="Object"/> to compare with the current <see cref="Cookie"/>. /// </param> /// <returns> /// <c>true</c> if <paramref name="comparand"/> is equal to the current <see cref="Cookie"/>; /// otherwise, <c>false</c>. /// </returns> public override bool Equals (Object comparand) { var cookie = comparand as Cookie; return cookie != null && _name.Equals (cookie.Name, StringComparison.InvariantCultureIgnoreCase) && _value.Equals (cookie.Value, StringComparison.InvariantCulture) && _path.Equals (cookie.Path, StringComparison.InvariantCulture) && _domain.Equals (cookie.Domain, StringComparison.InvariantCultureIgnoreCase) && _version == cookie.Version; } /// <summary> /// Serves as a hash function for a <see cref="Cookie"/> object. /// </summary> /// <returns> /// An <see cref="int"/> that represents the hash code for the current <see cref="Cookie"/>. /// </returns> public override int GetHashCode () { return hash ( StringComparer.InvariantCultureIgnoreCase.GetHashCode (_name), _value.GetHashCode (), _path.GetHashCode (), StringComparer.InvariantCultureIgnoreCase.GetHashCode (_domain), _version); } /// <summary> /// Returns a <see cref="string"/> that represents the current <see cref="Cookie"/>. /// </summary> /// <remarks> /// This method returns a <see cref="string"/> to use to send an HTTP Cookie to /// an origin server. /// </remarks> /// <returns> /// A <see cref="string"/> that represents the current <see cref="Cookie"/>. /// </returns> public override string ToString () { // i.e., only used for clients // See para 4.2.2 of RFC 2109 and para 3.3.4 of RFC 2965 // See also bug #316017 return ToRequestString (null); } #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; using System.Text; using System.Collections; using System.IO; using System.Globalization; using System.Diagnostics; using System.Reflection; #if XMLSERIALIZERGENERATOR namespace Microsoft.XmlSerializer.Generator #else namespace System.Xml.Serialization #endif { ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> #if XMLSERIALIZERGENERATOR internal class CodeIdentifier #else public class CodeIdentifier #endif { internal const int MaxIdentifierLength = 511; [Obsolete("This class should never get constructed as it contains only static methods.")] public CodeIdentifier() { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string MakePascal(string identifier) { identifier = MakeValid(identifier); if (identifier.Length <= 2) return CultureInfo.InvariantCulture.TextInfo.ToUpper(identifier); else if (char.IsLower(identifier[0])) return char.ToUpperInvariant(identifier[0]) + identifier.Substring(1); else return identifier; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string MakeCamel(string identifier) { identifier = MakeValid(identifier); if (identifier.Length <= 2) return CultureInfo.InvariantCulture.TextInfo.ToLower(identifier); else if (char.IsUpper(identifier[0])) return char.ToLower(identifier[0]) + identifier.Substring(1); else return identifier; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string MakeValid(string identifier) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < identifier.Length && builder.Length < MaxIdentifierLength; i++) { char c = identifier[i]; if (IsValid(c)) { if (builder.Length == 0 && !IsValidStart(c)) { builder.Append("Item"); } builder.Append(c); } } if (builder.Length == 0) return "Item"; return builder.ToString(); } internal static string MakeValidInternal(string identifier) { if (identifier.Length > 30) { return "Item"; } return MakeValid(identifier); } private static bool IsValidStart(char c) { // the given char is already a valid name character #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (!IsValid(c)) throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Invalid identifier character " + ((Int16)c).ToString(CultureInfo.InvariantCulture)), "c"); #endif // First char cannot be a number if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber) return false; return true; } private static bool IsValid(char c) { UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c); // each char must be Lu, Ll, Lt, Lm, Lo, Nd, Mn, Mc, Pc // switch (uc) { case UnicodeCategory.UppercaseLetter: // Lu case UnicodeCategory.LowercaseLetter: // Ll case UnicodeCategory.TitlecaseLetter: // Lt case UnicodeCategory.ModifierLetter: // Lm case UnicodeCategory.OtherLetter: // Lo case UnicodeCategory.DecimalDigitNumber: // Nd case UnicodeCategory.NonSpacingMark: // Mn case UnicodeCategory.SpacingCombiningMark: // Mc case UnicodeCategory.ConnectorPunctuation: // Pc break; case UnicodeCategory.LetterNumber: case UnicodeCategory.OtherNumber: case UnicodeCategory.EnclosingMark: case UnicodeCategory.SpaceSeparator: case UnicodeCategory.LineSeparator: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.Control: case UnicodeCategory.Format: case UnicodeCategory.Surrogate: case UnicodeCategory.PrivateUse: case UnicodeCategory.DashPunctuation: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.ClosePunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.FinalQuotePunctuation: case UnicodeCategory.OtherPunctuation: case UnicodeCategory.MathSymbol: case UnicodeCategory.CurrencySymbol: case UnicodeCategory.ModifierSymbol: case UnicodeCategory.OtherSymbol: case UnicodeCategory.OtherNotAssigned: return false; default: #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Unhandled category " + uc), "c"); #else return false; #endif } return true; } internal static void CheckValidIdentifier(string ident) { if (!CSharpHelpers.IsValidLanguageIndependentIdentifier(ident)) throw new ArgumentException(SR.Format(SR.XmlInvalidIdentifier, ident), nameof(ident)); } internal static string GetCSharpName(string name) { return EscapeKeywords(name.Replace('+', '.')); } private static int GetCSharpName(Type t, Type[] parameters, int index, StringBuilder sb) { if (t.DeclaringType != null && t.DeclaringType != t) { index = GetCSharpName(t.DeclaringType, parameters, index, sb); sb.Append("."); } string name = t.Name; int nameEnd = name.IndexOf('`'); if (nameEnd < 0) { nameEnd = name.IndexOf('!'); } if (nameEnd > 0) { EscapeKeywords(name.Substring(0, nameEnd), sb); sb.Append("<"); int arguments = Int32.Parse(name.Substring(nameEnd + 1), CultureInfo.InvariantCulture) + index; for (; index < arguments; index++) { sb.Append(GetCSharpName(parameters[index])); if (index < arguments - 1) { sb.Append(","); } } sb.Append(">"); } else { EscapeKeywords(name, sb); } return index; } internal static string GetCSharpName(Type t) { int rank = 0; while (t.IsArray) { t = t.GetElementType(); rank++; } StringBuilder sb = new StringBuilder(); sb.Append("global::"); string ns = t.Namespace; if (ns != null && ns.Length > 0) { string[] parts = ns.Split(new char[] { '.' }); for (int i = 0; i < parts.Length; i++) { EscapeKeywords(parts[i], sb); sb.Append("."); } } Type[] arguments = t.IsGenericType || t.ContainsGenericParameters ? t.GetGenericArguments() : Array.Empty<Type>(); GetCSharpName(t, arguments, 0, sb); for (int i = 0; i < rank; i++) { sb.Append("[]"); } return sb.ToString(); } /* internal static string GetTypeName(string name, CodeDomProvider codeProvider) { return codeProvider.GetTypeOutput(new CodeTypeReference(name)); } */ private static void EscapeKeywords(string identifier, StringBuilder sb) { if (identifier == null || identifier.Length == 0) return; int arrayCount = 0; while (identifier.EndsWith("[]", StringComparison.Ordinal)) { arrayCount++; identifier = identifier.Substring(0, identifier.Length - 2); } if (identifier.Length > 0) { CheckValidIdentifier(identifier); identifier = CSharpHelpers.CreateEscapedIdentifier(identifier); sb.Append(identifier); } for (int i = 0; i < arrayCount; i++) { sb.Append("[]"); } } private static string EscapeKeywords(string identifier) { if (identifier == null || identifier.Length == 0) return identifier; string originalIdentifier = identifier; string[] names = identifier.Split(new char[] { '.', ',', '<', '>' }); StringBuilder sb = new StringBuilder(); int separator = -1; for (int i = 0; i < names.Length; i++) { if (separator >= 0) { sb.Append(originalIdentifier.Substring(separator, 1)); } separator++; separator += names[i].Length; string escapedName = names[i].Trim(); EscapeKeywords(escapedName, sb); } if (sb.Length != originalIdentifier.Length) return sb.ToString(); return originalIdentifier; } } }
// Copyright 2011 Microsoft 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. namespace Microsoft.Data.Spatial { using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Spatial; /// <summary> /// WellKnownText Writer /// </summary> internal sealed class WellKnownTextSqlWriter : DrawBoth { /// <summary> /// restricts the writer to allow only two dimensions. /// </summary> private bool allowOnlyTwoDimensions; /// <summary> /// The underlying writer /// </summary> private TextWriter writer; /// <summary> /// Stack of spatial types currently been built /// </summary> private Stack<SpatialType> parentStack; /// <summary> /// Detects if a CoordinateSystem (SRID) has been written already. /// </summary> private bool coordinateSystemWritten; /// <summary> /// Figure has been written to the current spatial type /// </summary> private bool figureWritten; /// <summary> /// A shape has been written in the current nesting level /// </summary> private bool shapeWritten; /// <summary> /// Wells the known text SQL format. -- 2D writer /// </summary> /// <param name="writer">The writer.</param> public WellKnownTextSqlWriter(TextWriter writer) : this(writer, false) { } /// <summary> /// Initializes a new instance of the <see cref="WellKnownTextSqlWriter"/> class. /// </summary> /// <param name="writer">The writer.</param> /// <param name="allowOnlyTwoDimensions">if set to <c>true</c> allows only two dimensions.</param> public WellKnownTextSqlWriter(TextWriter writer, bool allowOnlyTwoDimensions) { this.allowOnlyTwoDimensions = allowOnlyTwoDimensions; this.writer = writer; this.parentStack = new Stack<SpatialType>(); Reset(); } #region DrawBoth /// <summary> /// Draw a point in the specified coordinate /// </summary> /// <param name="position">Next position</param> /// <returns> /// The position to be passed down the pipeline /// </returns> protected override GeographyPosition OnLineTo(GeographyPosition position) { this.AddLineTo(position.Longitude, position.Latitude, position.Z, position.M); return position; } /// <summary> /// Draw a point in the specified coordinate /// </summary> /// <param name="position">Next position</param> /// <returns> /// The position to be passed down the pipeline /// </returns> protected override GeometryPosition OnLineTo(GeometryPosition position) { this.AddLineTo(position.X, position.Y, position.Z, position.M); return position; } /// <summary> /// Begin drawing a spatial object /// </summary> /// <param name="type">The spatial type of the object</param> /// <returns> /// The type to be passed down the pipeline /// </returns> protected override SpatialType OnBeginGeography(SpatialType type) { BeginGeo(type); return type; } /// <summary> /// Begin drawing a spatial object /// </summary> /// <param name="type">The spatial type of the object</param> /// <returns> /// The type to be passed down the pipeline /// </returns> protected override SpatialType OnBeginGeometry(SpatialType type) { BeginGeo(type); return type; } /// <summary> /// Begin drawing a figure /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected override GeographyPosition OnBeginFigure(GeographyPosition position) { WriteFigureScope(position.Longitude, position.Latitude, position.Z, position.M); return position; } /// <summary> /// Begin drawing a figure /// </summary> /// <param name="position">Next position</param> /// <returns>The position to be passed down the pipeline</returns> protected override GeometryPosition OnBeginFigure(GeometryPosition position) { WriteFigureScope(position.X, position.Y, position.Z, position.M); return position; } /// <summary> /// Ends the current figure /// </summary> protected override void OnEndFigure() { EndFigure(); } /// <summary> /// Ends the current spatial object /// </summary> protected override void OnEndGeography() { EndGeo(); } /// <summary> /// Ends the current spatial object /// </summary> protected override void OnEndGeometry() { EndGeo(); } /// <summary> /// Set the coordinate system /// </summary> /// <param name="coordinateSystem">The CoordinateSystem</param> /// <returns> /// the coordinate system to be passed down the pipeline /// </returns> protected override CoordinateSystem OnSetCoordinateSystem(CoordinateSystem coordinateSystem) { WriteCoordinateSystem(coordinateSystem); return coordinateSystem; } /// <summary> /// Setup the pipeline for reuse /// </summary> protected override void OnReset() { Reset(); } #endregion /// <summary> /// Write the coordinate system /// </summary> /// <param name="coordinateSystem">The CoordinateSystem</param> private void WriteCoordinateSystem(CoordinateSystem coordinateSystem) { if (!this.coordinateSystemWritten) { // SRID can only be set once in WKT, but can be set once per BeginGeo in collection types this.writer.Write(WellKnownTextConstants.WktSrid); this.writer.Write(WellKnownTextConstants.WktEquals); this.writer.Write(coordinateSystem.Id); this.writer.Write(WellKnownTextConstants.WktSemiColon); this.coordinateSystemWritten = true; } } /// <summary> /// Setup the pipeline for reuse /// </summary> private void Reset() { this.figureWritten = default(bool); this.parentStack.Clear(); this.shapeWritten = default(bool); this.coordinateSystemWritten = default(bool); // we are unable to reset the text writer, we will just // noop and start writing fresh ////this.writer. } /// <summary> /// Start to write a new Geography/Geometry /// </summary> /// <param name="type">The SpatialType to write</param> private void BeginGeo(SpatialType type) { SpatialType parentType = this.parentStack.Count == 0 ? SpatialType.Unknown : this.parentStack.Peek(); if (parentType == SpatialType.MultiPoint || parentType == SpatialType.MultiLineString || parentType == SpatialType.MultiPolygon || parentType == SpatialType.Collection) { // container, first element should write out (, subsequent ones write out "," this.writer.Write(this.shapeWritten ? WellKnownTextConstants.WktDelimiterWithWhiteSpace : WellKnownTextConstants.WktOpenParen); } // Write tagged text // Only write if toplevel, or the parent is a collection type if (parentType == SpatialType.Unknown || parentType == SpatialType.Collection) { this.WriteTaggedText(type); } this.figureWritten = false; this.parentStack.Push(type); } /// <summary> /// Adds the control point. /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="z">The z.</param> /// <param name="m">The m.</param> private void AddLineTo(double x, double y, double? z, double? m) { this.writer.Write(WellKnownTextConstants.WktDelimiterWithWhiteSpace); this.WritePoint(x, y, z, m); } /// <summary> /// Ends the figure. /// </summary> private void EndFigure() { this.writer.Write(WellKnownTextConstants.WktCloseParen); } /// <summary> /// write tagged text for type /// </summary> /// <param name="type">the spatial type</param> private void WriteTaggedText(SpatialType type) { switch (type) { case SpatialType.Point: this.writer.Write(WellKnownTextConstants.WktPoint); break; case SpatialType.LineString: this.writer.Write(WellKnownTextConstants.WktLineString); break; case SpatialType.Polygon: this.writer.Write(WellKnownTextConstants.WktPolygon); break; case SpatialType.Collection: this.shapeWritten = false; this.writer.Write(WellKnownTextConstants.WktCollection); break; case SpatialType.MultiPoint: this.shapeWritten = false; this.writer.Write(WellKnownTextConstants.WktMultiPoint); break; case SpatialType.MultiLineString: this.shapeWritten = false; this.writer.Write(WellKnownTextConstants.WktMultiLineString); break; case SpatialType.MultiPolygon: this.shapeWritten = false; this.writer.Write(WellKnownTextConstants.WktMultiPolygon); break; case SpatialType.FullGlobe: this.writer.Write(WellKnownTextConstants.WktFullGlobe); break; } if (type != SpatialType.FullGlobe) { this.writer.Write(WellKnownTextConstants.WktWhitespace); } } /// <summary> /// Start to write a figure /// </summary> /// <param name="coordinate1">The coordinate1.</param> /// <param name="coordinate2">The coordinate2.</param> /// <param name="coordinate3">The coordinate3.</param> /// <param name="coordinate4">The coordinate4.</param> private void WriteFigureScope(double coordinate1, double coordinate2, double? coordinate3, double? coordinate4) { Debug.Assert(this.parentStack.Count > 0, "Should have called BeginGeo"); if (this.figureWritten) { this.writer.Write(WellKnownTextConstants.WktDelimiterWithWhiteSpace); } else { // first figure if (this.parentStack.Peek() == SpatialType.Polygon) { // Polygon has additional set of paren to separate out rings this.writer.Write(WellKnownTextConstants.WktOpenParen); } } // figure scope this.writer.Write(WellKnownTextConstants.WktOpenParen); this.figureWritten = true; this.WritePoint(coordinate1, coordinate2, coordinate3, coordinate4); } /// <summary> /// End the current Geography/Geometry /// </summary> private void EndGeo() { switch (this.parentStack.Pop()) { case SpatialType.Point: case SpatialType.LineString: if (!figureWritten) { this.writer.Write(WellKnownTextConstants.WktEmpty); } break; case SpatialType.Polygon: this.writer.Write(figureWritten ? WellKnownTextConstants.WktCloseParen : WellKnownTextConstants.WktEmpty); break; case SpatialType.Collection: case SpatialType.MultiPoint: case SpatialType.MultiLineString: case SpatialType.MultiPolygon: this.writer.Write(this.shapeWritten ? WellKnownTextConstants.WktCloseParen : WellKnownTextConstants.WktEmpty); break; case SpatialType.FullGlobe: this.writer.Write(WellKnownTextConstants.WktCloseParen); break; } this.shapeWritten = true; this.writer.Flush(); } /// <summary> /// Write out a point /// </summary> /// <param name="x">The x coordinate</param> /// <param name="y">The y coordinate</param> /// <param name="z">The z coordinate</param> /// <param name="m">The m coordinate</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704", Justification = "x, y, z, m are meaningful")] private void WritePoint(double x, double y, double? z, double? m) { this.writer.WriteRoundtrippable(x); this.writer.Write(WellKnownTextConstants.WktWhitespace); this.writer.WriteRoundtrippable(y); if (!this.allowOnlyTwoDimensions && z.HasValue) { this.writer.Write(WellKnownTextConstants.WktWhitespace); this.writer.WriteRoundtrippable(z.Value); if (!this.allowOnlyTwoDimensions && m.HasValue) { this.writer.Write(WellKnownTextConstants.WktWhitespace); this.writer.WriteRoundtrippable(m.Value); } } else { if (!this.allowOnlyTwoDimensions && m.HasValue) { this.writer.Write(WellKnownTextConstants.WktWhitespace); this.writer.Write(WellKnownTextConstants.WktNull); this.writer.Write(WellKnownTextConstants.WktWhitespace); this.writer.Write(m.Value); } } } } }
// 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.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LoadBalancerNetworkInterfacesOperations operations. /// </summary> internal partial class LoadBalancerNetworkInterfacesOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancerNetworkInterfacesOperations { /// <summary> /// Initializes a new instance of the LoadBalancerNetworkInterfacesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LoadBalancerNetworkInterfacesOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Gets associated load balancer network interfaces. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='loadBalancerName'> /// The name of the load balancer. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (loadBalancerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-08-01"; // 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("loadBalancerName", loadBalancerName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/networkInterfaces").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets associated load balancer network interfaces. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<NetworkInterface>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<NetworkInterface>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<NetworkInterface>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/******************************************************************************* INTEL CORPORATION PROPRIETARY INFORMATION This software is supplied under the terms of a license agreement or nondisclosure agreement with Intel Corporation and may not be copied or disclosed except in accordance with the terms of that agreement Copyright(c) 2012 Intel Corporation. All Rights Reserved. *******************************************************************************/ using System; using System.Runtime.InteropServices; public struct PXCMRectU32 { public UInt32 x, y, w, h; }; public struct PXCMPoint3DF32 { public float x, y, z; }; public struct PXCMPointF32 { public float x, y; }; public class PXCMFaceAnalysis { public class Detection { [Flags] public enum ViewAngle : int { VIEW_ANGLE_0 = 0x00000001, VIEW_ANGLE_45 = 0x00000002, VIEW_ANGLE_FRONTAL = 0x00000004, VIEW_ANGLE_135 = 0x00000008, VIEW_ANGLE_180 = 0x00000010, VIEW_ROLL_30 = 0x00000020, VIEW_ROLL_30N = 0x00000040, VIEW_ROLL_60 = 0x00000080, VIEW_ROLL_60N = 0x00000100, VIEW_ANGLE_HALF_MULTI = VIEW_ANGLE_FRONTAL | VIEW_ANGLE_45 | VIEW_ANGLE_135, VIEW_ANGLE_MULTI = VIEW_ANGLE_HALF_MULTI | VIEW_ANGLE_0 | VIEW_ANGLE_180, VIEW_ANGLE_FRONTALROLL = VIEW_ANGLE_FRONTAL | VIEW_ROLL_30| VIEW_ROLL_30N | VIEW_ROLL_60 | VIEW_ROLL_60N, VIEW_ANGLE_OMNI = -1, }; public struct Data { public PXCMRectU32 rectangle; public Int32 fid; public UInt32 confidence; public ViewAngle viewAngle; private Int32 reserved1, reserved2, reserved3, reserved4; }; }; public class Landmark { [Flags] public enum Label: int { LABEL_LEFT_EYE_OUTER_CORNER = 0x0001000, LABEL_LEFT_EYE_INNER_CORNER = 0x0002000, LABEL_RIGHT_EYE_OUTER_CORNER = 0x0004000, LABEL_RIGHT_EYE_INNER_CORNER = 0x0008000, LABEL_MOUTH_LEFT_CORNER = 0x0010000, LABEL_MOUTH_RIGHT_CORNER = 0x0020000, LABEL_NOSE_TIP = 0x0040000, LABEL_6POINTS = 0x003F006, LABEL_7POINTS = 0x007F007, LABEL_SIZE_MASK = 0x0000FFF, }; public struct PoseData { public Int32 fid; public float yaw; public float roll; public float pitch; private Int32 reserved1, reserved2, reserved3, reserved4; }; public struct LandmarkData { public PXCMPoint3DF32 position; public Int32 fid; public Label label; public UInt32 lidx; private Int32 rsv1, rsv2, rsv3, rsv4, rsv5, rsv6; }; }; }; public class PXCMGesture { public struct Gesture { [Flags] public enum Label: int { LABEL_ANY=0, LABEL_MASK_SET = unchecked((int)0xffff0000), LABEL_MASK_DETAILS = 0x0000ffff, LABEL_SET_HAND = 0x00010000, /* Common hand gestures */ LABEL_SET_NAVIGATION = 0x00020000, /* Navigation gestures */ LABEL_SET_POSE = 0x00040000, /* Common hand poses */ LABEL_SET_CUSTOMIZED = 0x00080000, /* predefined nativation gestures */ LABEL_NAV_SWIPE_LEFT = LABEL_SET_NAVIGATION+1, LABEL_NAV_SWIPE_RIGHT, LABEL_NAV_SWIPE_UP, LABEL_NAV_SWIPE_DOWN, /* predefined common hand gestures */ LABEL_HAND_WAVE = LABEL_SET_HAND+1, LABEL_HAND_CIRCLE, /* predefined common hand poses */ LABEL_POSE_THUMB_UP = LABEL_SET_POSE+1, LABEL_POSE_THUMB_DOWN, LABEL_POSE_PEACE, LABEL_POSE_BIG5, }; public UInt64 timeStamp; public Int32 user; public GeoNode.Label body; public Label label; public UInt32 confidence; public Boolean active; private UInt32 r1, r2, r3, r4, r5, r6, r7, r8, r9; }; [StructLayout(LayoutKind.Explicit,Size=128)] public struct GeoNode { [Flags] public enum Label: int { LABEL_ANY=0, LABEL_MASK_BODY =unchecked((int)0xffffff00), LABEL_MASK_DETAILS =0x000000ff, /* full body labels */ LABEL_BODY_ELBOW_PRIMARY = 0x00004000, LABEL_BODY_ELBOW_LEFT = 0x00004000, LABEL_BODY_ELBOW_SECONDARY = 0x00008000, LABEL_BODY_ELBOW_RIGHT = 0x00008000, LABEL_BODY_HAND_PRIMARY = 0x00040000, LABEL_BODY_HAND_LEFT = 0x00040000, LABEL_BODY_HAND_SECONDARY = 0x00080000, LABEL_BODY_HAND_RIGHT = 0x00080000, /* detailed labels: Hand */ LABEL_FINGER_THUMB = 1, LABEL_FINGER_INDEX, LABEL_FINGER_MIDDLE, LABEL_FINGER_RING, LABEL_FINGER_PINKY, LABEL_HAND_FINGERTIP, LABEL_HAND_UPPER, LABEL_HAND_MIDDLE, LABEL_HAND_LOWER, }; public enum Side : int { LABEL_SIDE_ANY=0, LABEL_LEFT, LABEL_RIGHT, }; public enum Openness : int { LABEL_OPENNESS_ANY=0, LABEL_CLOSE, LABEL_OPEN, }; [FieldOffset(0)] public UInt64 timeStamp; [FieldOffset(8)] public Int32 user; [FieldOffset(12)] public Label body; [FieldOffset(16)] public Side side; [FieldOffset(20)] public UInt32 confidence; [FieldOffset(24)] public PXCMPoint3DF32 positionWorld; [FieldOffset(36)] public PXCMPoint3DF32 positionImage; [FieldOffset(64)] public float radiusWorld; [FieldOffset(68)] public float radiusImage; [FieldOffset(64)] public PXCMPoint3DF32 massCenterWorld; [FieldOffset(76)] public PXCMPoint3DF32 massCenterImage; [FieldOffset(88)] public PXCMPoint3DF32 normal; [FieldOffset(100)] public UInt32 openness; [FieldOffset(104)] public Openness opennessState; }; public struct Blob { [Flags] public enum Label: int { LABEL_ANY=0, LABEL_SCENE=1, }; public UInt64 timeStamp; public Label name; public UInt32 labelBackground; public UInt32 labelLeftHand; public UInt32 labelRightHand; private UInt32 r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19, r20, r21, r22, r23, r24, r25, r26; }; }; public class PXCMCapture { public class Device { public enum CameraModel: int { CAMERA_MODEL_DS325 = 0x00100245, }; public enum Property: int { /* Single value properties */ PROPERTY_COLOR_EXPOSURE = 1, PROPERTY_COLOR_BRIGHTNESS = 2, PROPERTY_COLOR_CONTRAST = 3, PROPERTY_COLOR_SATURATION = 4, PROPERTY_COLOR_HUE = 5, PROPERTY_COLOR_GAMMA = 6, PROPERTY_COLOR_WHITE_BALANCE = 7, PROPERTY_COLOR_SHARPNESS = 8, PROPERTY_COLOR_BACK_LIGHT_COMPENSATION = 9, PROPERTY_COLOR_GAIN = 10, PROPERTY_AUDIO_MIX_LEVEL = 100, PROPERTY_DEPTH_SATURATION_VALUE = 200, PROPERTY_DEPTH_LOW_CONFIDENCE_VALUE = 201, PROPERTY_DEPTH_CONFIDENCE_THRESHOLD = 202, PROPERTY_DEPTH_SMOOTHING = 203, PROPERTY_DEPTH_UNIT = 204, PROPERTY_CAMERA_MODEL = 300, /* Two value properties */ PROPERTY_COLOR_FIELD_OF_VIEW = 1000, PROPERTY_COLOR_SENSOR_RANGE = 1002, PROPERTY_COLOR_FOCAL_LENGTH = 1006, PROPERTY_COLOR_PRINCIPAL_POINT = 1008, PROPERTY_DEPTH_FIELD_OF_VIEW = 2000, PROPERTY_DEPTH_SENSOR_RANGE = 2002, PROPERTY_DEPTH_FOCAL_LENGTH = 2006, PROPERTY_DEPTH_PRINCIPAL_POINT = 2008, /* Three value properties */ PROPERTY_ACCELEROMETER_READING = 3000, /* Customized properties */ PROPERTY_CUSTOMIZED=0x04000000, }; }; }; public class PXCMVoiceRecognition { public struct Recognition { public struct NBest { public Int32 label; public Int32 confidence; }; public UInt64 timeStamp; public NBest[] nBest; public Int32 grammar; public UInt32 duration; public String dictation; public Int32 label { get { return nBest[0].label; } set { nBest[0].label=value; } } public Int32 confidence { get { return nBest[0].confidence; } set { nBest[0].confidence=value; } } }; public struct ProfileInfo { public enum Language { LANGUAGE_US_ENGLISH=((int)('e')+((int)('n')<<8)+((int)('U')<<16)+((int)('S')<<24)), LANGUAGE_GB_ENGLISH=((int)('e')+((int)('n')<<8)+((int)('G')<<16)+((int)('B')<<24)), LANGUAGE_DE_GERMAN=((int)('d')+((int)('e')<<8)+((int)('D')<<16)+((int)('E')<<24)), LANGUAGE_US_SPANISH=((int)('e')+((int)('s')<<8)+((int)('U')<<16)+((int)('S')<<24)), LANGUAGE_FR_FRENCH=((int)('f')+((int)('r')<<8)+((int)('F')<<16)+((int)('R')<<24)), LANGUAGE_IT_ITALIAN=((int)('i')+((int)('t')<<8)+((int)('I')<<16)+((int)('T')<<24)), LANGUAGE_JP_JAPANESE=((int)('j')+((int)('a')<<8)+((int)('J')<<16)+((int)('P')<<24)), LANGUAGE_CN_CHINESE=((int)('z')+((int)('h')<<8)+((int)('C')<<16)+((int)('N')<<24)), LANGUAGE_BR_PORTUGUESE=((int)('p')+((int)('t')<<8)+((int)('B')<<16)+((int)('R')<<24)), }; }; };
/* ** $Id: lundump.c,v 2.7.1.4 2008/04/04 19:51:41 roberto Exp $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace SharpLua { using TValue = Lua.lua_TValue; using lua_Number = System.Double; using lu_byte = System.Byte; using StkId = Lua.lua_TValue; using Instruction = System.UInt32; using ZIO = Lua.Zio; public partial class Lua { /* for header of binary files -- this is Lua 5.1 */ public const int LUAC_VERSION = 0x51; /* for header of binary files -- this is the official format */ public const int LUAC_FORMAT = 0; /* size of header of binary files */ public const int LUAC_HEADERSIZE = 12; public class LoadState{ public LuaState L; public ZIO Z; public Mbuffer b; public CharPtr name; }; //#ifdef LUAC_TRUST_BINARIES //#define IF(c,s) //#define error(S,s) //#else //#define IF(c,s) if (c) error(S,s) public static void IF(int c, string s) { } public static void IF(bool c, string s) { } static void error(LoadState S, CharPtr why) { luaO_pushfstring(S.L,"%s: %s in precompiled chunk",S.name,why); luaD_throw(S.L,LUA_ERRSYNTAX); } //#endif public static object LoadMem(LoadState S, Type t) { int size = Marshal.SizeOf(t); CharPtr str = new char[size]; LoadBlock(S, str, size); byte[] bytes = new byte[str.chars.Length]; for (int i = 0; i < str.chars.Length; i++) bytes[i] = (byte)str.chars[i]; GCHandle pinnedPacket = GCHandle.Alloc(bytes, GCHandleType.Pinned); object b = Marshal.PtrToStructure(pinnedPacket.AddrOfPinnedObject(), t); pinnedPacket.Free(); return b; } public static object LoadMem(LoadState S, Type t, int n) { #if SILVERLIGHT List<object> array = new List<object>(); for (int i = 0; i < n; i++) array.Add(LoadMem(S, t)); return array.ToArray(); #else ArrayList array = new ArrayList(); for (int i=0; i<n; i++) array.Add(LoadMem(S, t)); return array.ToArray(t); #endif } public static lu_byte LoadByte(LoadState S) {return (lu_byte)LoadChar(S);} public static object LoadVar(LoadState S, Type t) { return LoadMem(S, t); } public static object LoadVector(LoadState S, Type t, int n) {return LoadMem(S, t, n);} private static void LoadBlock(LoadState S, CharPtr b, int size) { uint r=luaZ_read(S.Z, b, (uint)size); IF (r!=0, "unexpected end"); } private static int LoadChar(LoadState S) { return (char)LoadVar(S, typeof(char)); } private static int LoadInt(LoadState S) { int x = (int)LoadVar(S, typeof(int)); IF (x<0, "bad integer"); return x; } private static lua_Number LoadNumber(LoadState S) { return (lua_Number)LoadVar(S, typeof(lua_Number)); } private static TString LoadString(LoadState S) { uint size = (uint)LoadVar(S, typeof(uint)); if (size==0) return null; else { CharPtr s=luaZ_openspace(S.L,S.b,size); LoadBlock(S, s, (int)size); return luaS_newlstr(S.L,s,size-1); /* remove trailing '\0' */ } } private static void LoadCode(LoadState S, Proto f) { int n=LoadInt(S); f.code = luaM_newvector<Instruction>(S.L, n); f.sizecode=n; f.code = (Instruction[])LoadVector(S, typeof(Instruction), n); } private static void LoadConstants(LoadState S, Proto f) { int i,n; n=LoadInt(S); f.k = luaM_newvector<TValue>(S.L, n); f.sizek=n; for (i=0; i<n; i++) setnilvalue(f.k[i]); for (i=0; i<n; i++) { TValue o=f.k[i]; int t=LoadChar(S); switch (t) { case LUA_TNIL: setnilvalue(o); break; case LUA_TBOOLEAN: setbvalue(o, LoadChar(S)); break; case LUA_TNUMBER: setnvalue(o, LoadNumber(S)); break; case LUA_TSTRING: setsvalue2n(S.L, o, LoadString(S)); break; default: error(S,"bad constant"); break; } } n=LoadInt(S); f.p=luaM_newvector<Proto>(S.L,n); f.sizep=n; for (i=0; i<n; i++) f.p[i]=null; for (i=0; i<n; i++) f.p[i]=LoadFunction(S,f.source); } private static void LoadDebug(LoadState S, Proto f) { int i,n; n=LoadInt(S); f.lineinfo=luaM_newvector<int>(S.L,n); f.sizelineinfo=n; f.lineinfo = (int[])LoadVector(S, typeof(int), n); n=LoadInt(S); f.locvars=luaM_newvector<LocVar>(S.L,n); f.sizelocvars=n; for (i=0; i<n; i++) f.locvars[i].varname=null; for (i=0; i<n; i++) { f.locvars[i].varname=LoadString(S); f.locvars[i].startpc=LoadInt(S); f.locvars[i].endpc=LoadInt(S); } n=LoadInt(S); f.upvalues=luaM_newvector<TString>(S.L, n); f.sizeupvalues=n; for (i=0; i<n; i++) f.upvalues[i]=null; for (i=0; i<n; i++) f.upvalues[i]=LoadString(S); } private static Proto LoadFunction(LoadState S, TString p) { Proto f; if (++S.L.nCcalls > LUAI_MAXCCALLS) error(S,"code too deep"); f=luaF_newproto(S.L); setptvalue2s(S.L,S.L.top,f); incr_top(S.L); f.source=LoadString(S); if (f.source==null) f.source=p; f.linedefined=LoadInt(S); f.lastlinedefined=LoadInt(S); f.nups=LoadByte(S); f.numparams=LoadByte(S); f.is_vararg=LoadByte(S); f.maxstacksize=LoadByte(S); LoadCode(S,f); LoadConstants(S,f); LoadDebug(S,f); IF (luaG_checkcode(f)==0 ? 1 : 0, "bad code"); StkId.dec(ref S.L.top); S.L.nCcalls--; return f; } private static void LoadHeader(LoadState S) { CharPtr h = new char[LUAC_HEADERSIZE]; CharPtr s = new char[LUAC_HEADERSIZE]; luaU_header(h); LoadBlock(S, s, LUAC_HEADERSIZE); IF (memcmp(h, s, LUAC_HEADERSIZE)!=0, "bad header"); } /* ** load precompiled chunk */ public static Proto luaU_undump (LuaState L, ZIO Z, Mbuffer buff, CharPtr name) { LoadState S = new LoadState(); if (name[0] == '@' || name[0] == '=') S.name = name+1; else if (name[0]==LUA_SIGNATURE[0]) S.name="binary string"; else S.name=name; S.L=L; S.Z=Z; S.b=buff; LoadHeader(S); return LoadFunction(S,luaS_newliteral(L,"=?")); } /* * make header */ public static void luaU_header(CharPtr h) { h = new CharPtr(h); int x=1; memcpy(h, LUA_SIGNATURE, LUA_SIGNATURE.Length); h = h.add(LUA_SIGNATURE.Length); h[0] = (char)LUAC_VERSION; h.inc(); h[0] = (char)LUAC_FORMAT; h.inc(); //*h++=(char)*(char*)&x; /* endianness */ h[0] = (char)x; /* endianness */ h.inc(); h[0] = (char)sizeof(int); h.inc(); h[0] = (char)sizeof(uint); h.inc(); h[0] = (char)sizeof(Instruction); h.inc(); h[0] = (char)sizeof(lua_Number); h.inc(); //(h++)[0] = ((lua_Number)0.5 == 0) ? 0 : 1; /* is lua_Number integral? */ h[0] = (char)0; // always 0 on this build } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.SqlClient; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Transactions; using NUnit.Framework; using PeanutButter.FluentMigrator; using PeanutButter.TempDb; using PeanutButter.TempDb.LocalDb; using PeanutButter.TestUtils.Entity.Attributes; namespace PeanutButter.TestUtils.Entity { public class TestFixtureWithTempDb<TDbContext> where TDbContext : DbContext { private Func<string, IDBMigrationsRunner> _createMigrationsRunner; #pragma warning disable S2743 private bool _databaseShouldHaveAspNetTables = true; // ReSharper disable once StaticMemberInGenericType private static readonly List<string> AspNetTables = new List<string>(); #pragma warning restore S2743 private readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1); private readonly List<Action<TDbContext>> _toRunBeforeProvidingContext = new List<Action<TDbContext>>(); private readonly List<Task> _disposeTasks = new List<Task>(); private bool _runBeforeFirstGettingContext = true; protected TestFixtureWithTempDb() { EnableTestIsolationInTransactions(); _createMigrationsRunner = connectionString => { throw new Exception("Please run the Configure protected method before attempting any actual tests."); }; } protected void Configure( bool databaseShouldHaveAspNetTables, Func<string, IDBMigrationsRunner> migrationsRunnerFactory ) { _databaseShouldHaveAspNetTables = databaseShouldHaveAspNetTables; _createMigrationsRunner = migrationsRunnerFactory; } protected void DisableDatabaseRegeneration() { if (_databaseLifetime == TempDatabaseLifetimes.Fixture) return; _lock.Wait(); _databaseLifetime = TempDatabaseLifetimes.Fixture; } // ReSharper disable once UnusedMember.Global protected void EnableDatabaseRegeneration() { if (_databaseLifetime == TempDatabaseLifetimes.Test) return; ReleaseTempDb(); _lock.Release(); } // ReSharper disable once VirtualMemberNeverOverridden.Global protected virtual void RunBeforeFirstGettingContext(Action<TDbContext> action) { lock (_toRunBeforeProvidingContext) { _toRunBeforeProvidingContext.Add(action); } } private void IsolateIfNecessary() { if (!_testIsolationEnabled || !_testIsolationRequired) return; _testIsolationRequired = false; _transactionScope = CreateTransactionScopeCapableOfSurvivingAsyncAwait(); } private static TransactionScope CreateTransactionScopeCapableOfSurvivingAsyncAwait() { return new TransactionScope( TransactionScopeOption.Required, TimeSpan.FromMinutes(9), TransactionScopeAsyncFlowOption.Enabled); } // ReSharper disable once VirtualMemberNeverOverridden.Global protected virtual TDbContext GetContext(bool logSql = false) { var connection = _tempDb.OpenConnection(); lock (_tempDb) { var context = (TDbContext) Activator.CreateInstance(typeof(TDbContext), connection); if (logSql) context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); RunFirstTimeActionsOn(context); IsolateIfNecessary(); return context; } } // ReSharper disable once MemberCanBePrivate.Global protected void RunFirstTimeActionsOn(TDbContext context) { if (_runBeforeFirstGettingContext) { _runBeforeFirstGettingContext = false; lock (_toRunBeforeProvidingContext) { _toRunBeforeProvidingContext.ForEach(action => action(context)); } } } static TestFixtureWithTempDb() { AspNetTables.Add(@" CREATE TABLE [AspNetRoles]( [Id] [nvarchar](128) NOT NULL, [Name] [nvarchar](256) NOT NULL )"); AspNetTables.Add(@" CREATE Table [AspNetUserClaims]( [Id] [int] IDENTITY(1,1) NOT NULL, [UserId] [nvarchar](128) NOT NULL, [ClaimType] [nvarchar](4000) NULL, [ClaimValue] [nvarchar](4000) NULL )"); AspNetTables.Add(@" CREATE TABLE [AspNetUserLogins]( [LoginProvider] [nvarchar](128) NOT NULL, [ProviderKey] [nvarchar](128) NOT NULL, [UserId] [nvarchar](128) NOT NULL )"); AspNetTables.Add(@" CREATE TABLE [AspNetUserRoles]( [UserId] [nvarchar](128) NOT NULL, [RoleId] [nvarchar](128) NOT NULL )"); AspNetTables.Add(@" CREATE TABLE [AspNetUsers]( [Id] [nvarchar](128) NOT NULL, [Email] [nvarchar](256) NULL, [EmailConfirmed] [bit] NOT NULL, [PasswordHash] [nvarchar](4000) NULL, [SecurityStamp] [nvarchar](4000) NULL, [PhoneNumber] [nvarchar](4000) NULL, [PhoneNumberConfirmed] [bit] NOT NULL, [TwoFactorEnabled] [bit] NOT NULL, [LockoutEndDateUtc] [datetime] NULL, [LockoutEnabled] [bit] NOT NULL, [AccessFailedCount] [int] NOT NULL, [UserName] [nvarchar](256) NOT NULL )"); } private ITempDB _tempDbActual; private TempDatabaseLifetimes _databaseLifetime; private bool _testIsolationEnabled; private bool _testIsolationRequired; private TransactionScope _transactionScope; // ReSharper disable once InconsistentNaming #pragma warning disable S100 // ReSharper disable once InconsistentNaming protected ITempDB _tempDb { #pragma warning restore S100 get { if (_tempDbActual != null) return _tempDbActual; _tempDbActual = CreateNewTempDb(); return _tempDbActual; } } protected ITempDB CreateNewTempDb() { var shared = FindSharedTempDb(); if (shared != null) return shared; var created = new TempDBLocalDb(); if (_databaseShouldHaveAspNetTables) CreateAspNetTablesOn(created.ConnectionString); var migrator = _createMigrationsRunner(created.ConnectionString); migrator.MigrateToLatest(); RegisterSharedDb(created); return created; } private ITempDB FindSharedTempDb() { var sharedDbName = GetSharedDbNameForThisFixture(); if (sharedDbName == null) return null; ValidateCanShareTempDb(); return SharedDatabaseLocator.Find(sharedDbName); } private void ValidateCanShareTempDb() { var myType = GetType(); var requiredAttrib = myType.Assembly .GetCustomAttributes(true) .OfType<AllowSharedTempDbInstancesAttribute>() .FirstOrDefault(); if (requiredAttrib == null) throw new SharedTempDbFeatureRequiresAssemblyAttributeException(myType); } private void RegisterSharedDb(ITempDB db) { var sharedDbName = GetSharedDbNameForThisFixture(); if (sharedDbName == null) return; SharedDatabaseLocator.Register(sharedDbName, db); } private string GetSharedDbNameForThisFixture() { return GetType() .GetCustomAttributes(true) .OfType<UseSharedTempDbAttribute>() .FirstOrDefault() ?.Name; } private void CreateAspNetTablesOn(string connectionString) { using (var connection = new SqlConnection(connectionString)) { connection.Open(); AspNetTables.ForEach(sql => { using (var cmd = connection.CreateCommand()) { cmd.CommandText = sql; cmd.ExecuteNonQuery(); } }); } } [SetUp] public void TestFixtureWithTempDbBaseSetup() { _runBeforeFirstGettingContext = true; _testIsolationRequired = true; if (_databaseLifetime == TempDatabaseLifetimes.Test) { _lock.Wait(); _tempDbActual = null; } } [TearDown] public void TestFixtureWithTempDbBaseTeardown() { if (_testIsolationEnabled) { RollBackIsolationTransaction(); _testIsolationRequired = true; } if (_databaseLifetime == TempDatabaseLifetimes.Test) { DisposeCurrentTempDb(); _runBeforeFirstGettingContext = true; _lock.Release(); } } [OneTimeTearDown] public void TestFixtureWithTempDbBaseOneTimeTearDown() { DisposeCurrentTempDb(); Task.WaitAll(_disposeTasks.ToArray()); if (_databaseLifetime == TempDatabaseLifetimes.Fixture) _lock.Release(); } private void DisposeCurrentTempDb() { if (GetSharedDbNameForThisFixture() != null) { _tempDbActual = null; return; // never destroy a shared db } var tempDb = _tempDbActual; _tempDbActual = null; _disposeTasks.Add(Task.Run(() => { tempDb?.Dispose(); })); } private enum TempDatabaseLifetimes { Test, Fixture } private void ReleaseTempDb() { _tempDbActual?.Dispose(); _tempDbActual = null; } protected void EnableTestIsolationInTransactions() { _testIsolationEnabled = true; DisableDatabaseRegeneration(); } protected void DisableTestIsolationInTransactions() { _testIsolationEnabled = false; CommitIsolationTransaction(); } protected void CommitIsolationTransaction() { _transactionScope?.Complete(); _transactionScope = null; } protected void RollBackIsolationTransaction() { _transactionScope?.Dispose(); _transactionScope = 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.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Text { internal ref partial struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span<char> _chars; private int _pos; public ValueStringBuilder(Span<char> initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity); _chars = _arrayToReturnToPool; _pos = 0; } public int Length { get => _pos; set { Debug.Assert(value >= 0); Debug.Assert(value <= _chars.Length); _pos = value; } } public int Capacity => _chars.Length; public void EnsureCapacity(int capacity) { if (capacity > _chars.Length) Grow(capacity - _pos); } /// <summary> /// Get a pinnable reference to the builder. /// Does not ensure there is a null char after <see cref="Length"/> /// This overload is pattern matched in the C# 7.3+ compiler so you can omit /// the explicit method call, and write eg "fixed (char* c = builder)" /// </summary> public ref char GetPinnableReference() { return ref MemoryMarshal.GetReference(_chars); } /// <summary> /// Get a pinnable reference to the builder. /// </summary> /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param> public ref char GetPinnableReference(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return ref MemoryMarshal.GetReference(_chars); } public ref char this[int index] { get { Debug.Assert(index < _pos); return ref _chars[index]; } } public override string ToString() { var s = _chars.Slice(0, _pos).ToString(); Dispose(); return s; } /// <summary>Returns the underlying storage of the builder.</summary> public Span<char> RawChars => _chars; /// <summary> /// Returns a span around the contents of the builder. /// </summary> /// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param> public ReadOnlySpan<char> AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan<char> AsSpan() => _chars.Slice(0, _pos); public ReadOnlySpan<char> AsSpan(int start) => _chars.Slice(start, _pos - start); public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length); public bool TryCopyTo(Span<char> destination, out int charsWritten) { if (_chars.Slice(0, _pos).TryCopyTo(destination)) { charsWritten = _pos; Dispose(); return true; } else { charsWritten = 0; Dispose(); return false; } } public void Insert(int index, char value, int count) { if (_pos > _chars.Length - count) { Grow(count); } int remaining = _pos - index; _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count)); _chars.Slice(index, count).Fill(value); _pos += count; } public void Insert(int index, string s) { int count = s.Length; if (_pos > (_chars.Length - count)) { Grow(count); } int remaining = _pos - index; _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count)); s.AsSpan().CopyTo(_chars.Slice(index)); _pos += count; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; if ((uint)pos < (uint)_chars.Length) { _chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string s) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc. { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.AsSpan().CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span<char> dst = _chars.Slice(_pos, count); for (int i = 0; i < dst.Length; i++) { dst[i] = c; } _pos += count; } public unsafe void Append(char* value, int length) { int pos = _pos; if (pos > _chars.Length - length) { Grow(length); } Span<char> dst = _chars.Slice(_pos, length); for (int i = 0; i < dst.Length; i++) { dst[i] = *value++; } _pos += length; } public void Append(ReadOnlySpan<char> value) { int pos = _pos; if (pos > _chars.Length - value.Length) { Grow(value.Length); } value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<char> AppendSpan(int length) { int origPos = _pos; if (origPos > _chars.Length - length) { Grow(length); } _pos = origPos + length; return _chars.Slice(origPos, length); } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowAndAppend(char c) { Grow(1); Append(c); } /// <summary> /// Resize the internal buffer either by doubling current buffer size or /// by adding <paramref name="additionalCapacityBeyondPos"/> to /// <see cref="_pos"/> whichever is greater. /// </summary> /// <param name="additionalCapacityBeyondPos"> /// Number of chars requested beyond current position. /// </param> [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalCapacityBeyondPos) { Debug.Assert(additionalCapacityBeyondPos > 0); Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed."); char[] poolArray = ArrayPool<char>.Shared.Rent(Math.Max(_pos + additionalCapacityBeyondPos, _chars.Length * 2)); _chars.CopyTo(poolArray); char[] toReturn = _arrayToReturnToPool; _chars = _arrayToReturnToPool = poolArray; if (toReturn != null) { ArrayPool<char>.Shared.Return(toReturn); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { char[] toReturn = _arrayToReturnToPool; this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again if (toReturn != null) { ArrayPool<char>.Shared.Return(toReturn); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace BaselineTypeDiscovery.Testing { internal static class TypeExtensions { private static readonly IList<Type> _integerTypes = new List<Type> { typeof(byte), typeof(short), typeof(int), typeof(long), typeof(sbyte), typeof(ushort), typeof(uint), typeof(ulong), typeof(byte?), typeof(short?), typeof(int?), typeof(long?), typeof(sbyte?), typeof(ushort?), typeof(uint?), typeof(ulong?) }; /// <summary> /// Does a hard cast of the object to T. *Will* throw InvalidCastException /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target"></param> /// <returns></returns> public static T As<T>(this object target) { return (T) target; } public static bool IsNullableOfT(this Type theType) { if (theType == null) return false; return theType.GetTypeInfo().IsGenericType && theType.GetGenericTypeDefinition() == typeof(Nullable<>); } public static bool IsNullableOf(this Type theType, Type otherType) { return theType.IsNullableOfT() && theType.GetGenericArguments()[0] == otherType; } public static bool IsTypeOrNullableOf<T>(this Type theType) { var otherType = typeof(T); return theType == otherType || (theType.IsNullableOfT() && theType.GetGenericArguments()[0] == otherType); } public static bool CanBeCastTo<T>(this Type type) { if (type == null) return false; var destinationType = typeof(T); return CanBeCastTo(type, destinationType); } public static bool CanBeCastTo(this Type type, Type destinationType) { if (type == null) return false; if (type == destinationType) return true; return destinationType.IsAssignableFrom(type); } public static bool IsInNamespace(this Type type, string nameSpace) { if (type == null) return false; return type.Namespace.StartsWith(nameSpace); } public static bool IsOpenGeneric(this Type type) { if (type == null) return false; var typeInfo = type.GetTypeInfo(); return typeInfo.IsGenericTypeDefinition || typeInfo.ContainsGenericParameters; } public static bool IsGenericEnumerable(this Type type) { if (type == null) return false; var genericArgs = type.GetGenericArguments(); return genericArgs.Length == 1 && typeof(IEnumerable<>).MakeGenericType(genericArgs).IsAssignableFrom(type); } public static bool IsConcreteTypeOf<T>(this Type pluggedType) { if (pluggedType == null) return false; return pluggedType.IsConcrete() && typeof(T).IsAssignableFrom(pluggedType); } public static bool ImplementsInterfaceTemplate(this Type pluggedType, Type templateType) { if (!pluggedType.IsConcrete()) return false; foreach (var interfaceType in pluggedType.GetInterfaces()) { if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == templateType) { return true; } } return false; } public static bool IsConcreteWithDefaultCtor(this Type type) { return type.IsConcrete() && type.GetConstructor(new Type[0]) != null; } public static Type FindInterfaceThatCloses(this Type type, Type openType) { if (type == typeof(object)) return null; var typeInfo = type.GetTypeInfo(); if (typeInfo.IsInterface && typeInfo.IsGenericType && type.GetGenericTypeDefinition() == openType) return type; foreach (var interfaceType in type.GetInterfaces()) { var interfaceTypeInfo = interfaceType.GetTypeInfo(); if (interfaceTypeInfo.IsGenericType && interfaceType.GetGenericTypeDefinition() == openType) { return interfaceType; } } if (!type.IsConcrete()) return null; return typeInfo.BaseType == typeof(object) ? null : typeInfo.BaseType.FindInterfaceThatCloses(openType); } public static Type FindParameterTypeTo(this Type type, Type openType) { var interfaceType = type.FindInterfaceThatCloses(openType); return interfaceType?.GetGenericArguments().FirstOrDefault(); } public static bool IsNullable(this Type type) { var typeInfo = type.GetTypeInfo(); return typeInfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } public static bool Closes(this Type type, Type openType) { if (type == null) return false; var typeInfo = type.GetTypeInfo(); if (typeInfo.IsGenericType && type.GetGenericTypeDefinition() == openType) return true; foreach (var @interface in type.GetInterfaces()) { if (@interface.Closes(openType)) return true; } var baseType = typeInfo.BaseType; if (baseType == null) return false; var baseTypeInfo = baseType.GetTypeInfo(); var closes = baseTypeInfo.IsGenericType && baseType.GetGenericTypeDefinition() == openType; if (closes) return true; return typeInfo.BaseType?.Closes(openType) ?? false; } public static Type GetInnerTypeFromNullable(this Type nullableType) { return nullableType.GetGenericArguments()[0]; } public static bool IsString(this Type type) { return type == typeof(string); } public static bool IsPrimitive(this Type type) { var typeInfo = type.GetTypeInfo(); return typeInfo.IsPrimitive && !IsString(type) && type != typeof(IntPtr); } public static bool IsSimple(this Type type) { var typeInfo = type.GetTypeInfo(); return typeInfo.IsPrimitive || IsString(type) || typeInfo.IsEnum; } public static bool IsConcrete(this Type type) { if (type == null) return false; var typeInfo = type.GetTypeInfo(); return !typeInfo.IsAbstract && !typeInfo.IsInterface; } public static bool IsNotConcrete(this Type type) { return !type.IsConcrete(); } /// <summary> /// Returns true if the type is a DateTime or nullable DateTime /// </summary> /// <param name="typeToCheck"></param> /// <returns></returns> public static bool IsDateTime(this Type typeToCheck) { return typeToCheck == typeof(DateTime) || typeToCheck == typeof(DateTime?); } public static bool IsBoolean(this Type typeToCheck) { return typeToCheck == typeof(bool) || typeToCheck == typeof(bool?); } /// <summary> /// Displays type names using CSharp syntax style. Supports funky generic types. /// </summary> /// <param name="type">Type to be pretty printed</param> /// <returns></returns> public static string PrettyPrint(this Type type) { return type.PrettyPrint(t => t.Name); } /// <summary> /// Displays type names using CSharp syntax style. Supports funky generic types. /// </summary> /// <param name="type">Type to be pretty printed</param> /// <param name="selector"> /// Function determining the name of the type to be displayed. Useful if you want a fully qualified /// name. /// </param> /// <returns></returns> public static string PrettyPrint(this Type type, Func<Type, string> selector) { var typeName = selector(type) ?? string.Empty; var typeInfo = type.GetTypeInfo(); if (!typeInfo.IsGenericType) { return typeName; } var genericParamSelector = typeInfo.IsGenericTypeDefinition ? t => t.Name : selector; var genericTypeList = string.Join(",", type.GetGenericArguments().Select(genericParamSelector).ToArray()); var tickLocation = typeName.IndexOf('`'); if (tickLocation >= 0) { typeName = typeName.Substring(0, tickLocation); } return $"{typeName}<{genericTypeList}>"; } /// <summary> /// Returns a boolean value indicating whether or not the type is: /// int, long, decimal, short, float, or double /// </summary> /// <param name="type"></param> /// <returns>Bool indicating whether the type is numeric</returns> public static bool IsNumeric(this Type type) { return type.IsFloatingPoint() || type.IsIntegerBased(); } /// <summary> /// Returns a boolean value indicating whether or not the type is: /// int, long or short /// </summary> /// <param name="type"></param> /// <returns>Bool indicating whether the type is integer based</returns> public static bool IsIntegerBased(this Type type) { return _integerTypes.Contains(type); } /// <summary> /// Returns a boolean value indicating whether or not the type is: /// decimal, float or double /// </summary> /// <param name="type"></param> /// <returns>Bool indicating whether the type is floating point</returns> public static bool IsFloatingPoint(this Type type) { return type == typeof(decimal) || type == typeof(float) || type == typeof(double); } public static T CloseAndBuildAs<T>(this Type openType, params Type[] parameterTypes) { var closedType = openType.MakeGenericType(parameterTypes); return (T) Activator.CreateInstance(closedType); } public static T CloseAndBuildAs<T>(this Type openType, object ctorArgument, params Type[] parameterTypes) { var closedType = openType.MakeGenericType(parameterTypes); return (T) Activator.CreateInstance(closedType, ctorArgument); } public static T CloseAndBuildAs<T>(this Type openType, object ctorArgument1, object ctorArgument2, params Type[] parameterTypes) { var closedType = openType.MakeGenericType(parameterTypes); return (T) Activator.CreateInstance(closedType, ctorArgument1, ctorArgument2); } public static bool PropertyMatches(this PropertyInfo prop1, PropertyInfo prop2) { return prop1.DeclaringType == prop2.DeclaringType && prop1.Name == prop2.Name; } public static T Create<T>(this Type type) { return (T) type.Create(); } public static object Create(this Type type) { return Activator.CreateInstance(type); } public static Type DeriveElementType(this Type type) { return type.GetElementType() ?? type.GetGenericArguments().FirstOrDefault(); } public static Type IsAnEnumerationOf(this Type type) { if (!type.Closes(typeof(IEnumerable<>))) { throw new Exception("Duh, its gotta be enumerable"); } if (type.IsArray) { return type.GetElementType(); } if (type.GetTypeInfo().IsGenericType) { return type.GetGenericArguments()[0]; } throw new Exception($"I don't know how to figure out what this is a collection of. Can you tell me? {type}"); } public static void ForAttribute<T>(this Type type, Action<T> action) where T : Attribute { var atts = type.GetTypeInfo().GetCustomAttributes(typeof(T)); foreach (T att in atts) { action(att); } } public static void ForAttribute<T>(this Type type, Action<T> action, Action elseDo) where T : Attribute { var atts = type.GetTypeInfo().GetCustomAttributes(typeof(T)).ToArray(); foreach (T att in atts) { action(att); } if (!atts.Any()) { elseDo(); } } public static bool HasAttribute<T>(this Type type) where T : Attribute { return type.GetTypeInfo().GetCustomAttributes<T>().Any(); } public static T GetAttribute<T>(this Type type) where T : Attribute { return type.GetTypeInfo().GetCustomAttributes<T>().FirstOrDefault(); } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif [ExecuteInEditMode] [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] public class BoxVolume : MonoBehaviour { public Material volumetricMaterial = null; public Vector3 boxSize = Vector3.one * 5f; public float visibility = 3.0f; public Color volumeColor = new Color(1.0f, 1.0f, 1.0f, 1.0f); public Texture2D texture = null; public float textureScale = 1f; public Vector3 textureMovement = new Vector3(0f, -0.1f, 0f); private Mesh meshInstance = null; private Material materialInstance = null; private Transform thisTransform = null; private Vector3 previousBoxSize = Vector3.one; private float previousVisibility = 1.0f; private Color previousVolumeColor = new Color(1.0f, 1.0f, 1.0f, 1.0f); private Vector3 forcedLocalScale = Vector3.one; private Texture2D previousTexture = null; private float previousTextureScale = 10f; private Vector3 previousTextureMovement = new Vector3(0f, 0.1f, 0f); private Vector3[] unitVerts = new Vector3[8]; #if UNITY_EDITOR private bool setSceneCameraDepthMode = false; [MenuItem("GameObject/Create Other/Volumetric Objects/Box Volume")] static public void CreateSphereVolume() { GameObject newObject = new GameObject("Box Volume"); if (SceneView.currentDrawingSceneView) SceneView.currentDrawingSceneView.MoveToView(newObject.transform); BoxVolume boxVolume = (BoxVolume)newObject.AddComponent<BoxVolume>(); boxVolume.enabled = false; boxVolume.enabled = true; } #endif void Awake() { if (volumetricMaterial == null) { this.enabled = false; return; } } void OnEnable() { SetupUnitVerts(); thisTransform = transform; if (meshInstance != null) { #if UNITY_EDITOR DestroyImmediate(meshInstance); #else Destroy(meshInstance); #endif } meshInstance = CreateCube(); MeshFilter mf = GetComponent<MeshFilter>(); mf.sharedMesh = meshInstance; if (materialInstance != null) { #if UNITY_EDITOR DestroyImmediate(materialInstance); #else Destroy(materialInstance); #endif } MeshRenderer mr = GetComponent<MeshRenderer>(); mr.sharedMaterial = (Material)Instantiate(volumetricMaterial); materialInstance = mr.sharedMaterial; if (Camera.current) { Camera.current.depthTextureMode |= DepthTextureMode.Depth; } if (Camera.main) { Camera.main.depthTextureMode |= DepthTextureMode.Depth; } #if UNITY_EDITOR setSceneCameraDepthMode = true; #endif UpdateVolume(); } void LateUpdate() { #if UNITY_EDITOR if (setSceneCameraDepthMode) { SetSceneCameraDepthMode(); } #endif if (boxSize != previousBoxSize || visibility != previousVisibility || volumeColor != previousVolumeColor || thisTransform.localScale != forcedLocalScale || texture != previousTexture || textureScale != previousTextureScale || textureMovement != previousTextureMovement) { previousBoxSize = boxSize; previousVisibility = visibility; previousVolumeColor = volumeColor; thisTransform.localScale = forcedLocalScale; previousTexture = texture; previousTextureScale = textureScale; previousTextureMovement = textureMovement; UpdateVolume(); } } #if UNITY_EDITOR void SetSceneCameraDepthMode() { Camera[] sceneCameras = SceneView.GetAllSceneCameras(); for (int i = 0; i < sceneCameras.Length; i++) { sceneCameras[i].depthTextureMode |= DepthTextureMode.Depth; } } #endif public void UpdateVolume() { Vector3 halfBoxSize = boxSize * 0.5f; if (meshInstance) { ScaleMesh(meshInstance, boxSize); // Set bounding volume so modified vertices don't get culled Bounds bounds = new Bounds(); bounds.SetMinMax(-halfBoxSize, halfBoxSize); meshInstance.bounds = bounds; } if (materialInstance) { materialInstance.SetVector("_BoxMin", new Vector4(-halfBoxSize.x, -halfBoxSize.y, -halfBoxSize.z, 0f)); materialInstance.SetVector("_BoxMax", new Vector4(halfBoxSize.x, halfBoxSize.y, halfBoxSize.z, 0f)); materialInstance.SetVector("_TextureData", new Vector4(-textureMovement.x, -textureMovement.y, -textureMovement.z, (1f / textureScale))); materialInstance.SetFloat("_Visibility", visibility); materialInstance.SetColor("_Color", volumeColor); materialInstance.SetTexture("_MainTex", texture); } } public void SetupUnitVerts() { // Vert order // -x -y -z // +x -y -z // +x +y -z // +x -y +z // +x +y +z // -x +y -z // -x +y +z // -x -y +z float s = 0.5f; unitVerts[0].x = -s; unitVerts[0].y = -s; unitVerts[0].z = -s; unitVerts[1].x = +s; unitVerts[1].y = -s; unitVerts[1].z = -s; unitVerts[2].x = +s; unitVerts[2].y = +s; unitVerts[2].z = -s; unitVerts[3].x = +s; unitVerts[3].y = -s; unitVerts[3].z = +s; unitVerts[4].x = +s; unitVerts[4].y = +s; unitVerts[4].z = +s; unitVerts[5].x = -s; unitVerts[5].y = +s; unitVerts[5].z = -s; unitVerts[6].x = -s; unitVerts[6].y = +s; unitVerts[6].z = +s; unitVerts[7].x = -s; unitVerts[7].y = -s; unitVerts[7].z = +s; } public Mesh CreateCube() { Mesh mesh = new Mesh(); Vector3[] verts = new Vector3[unitVerts.Length]; unitVerts.CopyTo(verts, 0); mesh.vertices = verts; int[] indices = new int[36]; int i = 0; indices[i] = 0; i++; indices[i] = 2; i++; indices[i] = 1; i++; indices[i] = 0; i++; indices[i] = 5; i++; indices[i] = 2; i++; indices[i] = 3; i++; indices[i] = 6; i++; indices[i] = 7; i++; indices[i] = 3; i++; indices[i] = 4; i++; indices[i] = 6; i++; indices[i] = 1; i++; indices[i] = 4; i++; indices[i] = 3; i++; indices[i] = 1; i++; indices[i] = 2; i++; indices[i] = 4; i++; indices[i] = 7; i++; indices[i] = 5; i++; indices[i] = 0; i++; indices[i] = 7; i++; indices[i] = 6; i++; indices[i] = 5; i++; indices[i] = 7; i++; indices[i] = 1; i++; indices[i] = 3; i++; indices[i] = 7; i++; indices[i] = 0; i++; indices[i] = 1; i++; indices[i] = 5; i++; indices[i] = 4; i++; indices[i] = 2; i++; indices[i] = 5; i++; indices[i] = 6; i++; indices[i] = 4; i++; mesh.triangles = indices; mesh.RecalculateBounds(); return mesh; } public void ScaleMesh(Mesh mesh, Vector3 scaleFactor) { Vector3[] scaledVertices = new Vector3[mesh.vertexCount]; for (int i = 0; i < mesh.vertexCount; i++) { scaledVertices[i] = ScaleVector(unitVerts[i], scaleFactor); } mesh.vertices = scaledVertices; } Vector3 ScaleVector(Vector3 vector, Vector3 scale) { return new Vector3(vector.x * scale.x, vector.y * scale.y, vector.z * scale.z); } public Mesh CopyMesh(Mesh original) { Mesh mesh = new Mesh(); // Copy Verts Vector3[] verts = new Vector3[original.vertices.Length]; original.vertices.CopyTo(verts, 0); mesh.vertices = verts; // Copy UV Vector2[] uv = new Vector2[original.uv.Length]; original.uv.CopyTo(uv, 0); mesh.uv = uv; // Copy UV1 Vector2[] uv1 = new Vector2[original.uv1.Length]; original.uv1.CopyTo(uv1, 0); mesh.uv1 = uv1; // Copy UV2 Vector2[] uv2 = new Vector2[original.uv2.Length]; original.uv2.CopyTo(uv2, 0); mesh.uv2 = uv2; // Copy Normals Vector3[] norms = new Vector3[original.normals.Length]; original.normals.CopyTo(norms, 0); mesh.normals = norms; // Copy Tangents Vector4[] tans = new Vector4[original.tangents.Length]; original.tangents.CopyTo(tans, 0); mesh.tangents = tans; // Copy Colors Color[] cols = new Color[original.colors.Length]; original.colors.CopyTo(cols, 0); mesh.colors = cols; // Triangles (sub meshes) mesh.subMeshCount = original.subMeshCount; for (int i = 0; i < original.subMeshCount; i++) { int[] subTris = original.GetTriangles(i); int[] triangles = new int[subTris.Length]; subTris.CopyTo(triangles, 0); mesh.SetTriangles(subTris, i); } mesh.RecalculateBounds(); return mesh; } }
// 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; using System.Runtime; using Internal.Runtime.Augments; using Microsoft.Win32.SafeHandles; namespace System.Threading { public abstract partial class WaitHandle { internal static unsafe int WaitForSingleObject(IntPtr handle, int millisecondsTimeout) { return WaitForMultipleObjects(&handle, 1, false, millisecondsTimeout); } private static unsafe int WaitForMultipleObjects(IntPtr[] handles, int numHandles, bool waitAll, int millisecondsTimeout) { fixed (IntPtr* pHandles = handles) { return WaitForMultipleObjects(pHandles, numHandles, waitAll, millisecondsTimeout); } } private static unsafe int WaitForMultipleObjects(IntPtr* pHandles, int numHandles, bool waitAll, int millisecondsTimeout) { Debug.Assert(millisecondsTimeout >= -1); // // In the CLR, we use CoWaitForMultipleHandles to pump messages while waiting in an STA. In that case, we cannot use WAIT_ALL. // That's because the wait would only be satisfied if a message arrives while the handles are signalled. // if (waitAll) { if (numHandles == 1) waitAll = false; else if (RuntimeThread.GetCurrentApartmentType() == RuntimeThread.ApartmentType.STA) throw new NotSupportedException(SR.NotSupported_WaitAllSTAThread); } RuntimeThread currentThread = RuntimeThread.CurrentThread; currentThread.SetWaitSleepJoinState(); int result; if (RuntimeThread.ReentrantWaitsEnabled) { Debug.Assert(!waitAll); result = RuntimeImports.RhCompatibleReentrantWaitAny(false, millisecondsTimeout, numHandles, pHandles); } else { result = (int)Interop.mincore.WaitForMultipleObjectsEx((uint)numHandles, (IntPtr)pHandles, waitAll, (uint)millisecondsTimeout, false); } currentThread.ClearWaitSleepJoinState(); if (result == WaitHandle.WaitFailed) { int errorCode = Interop.mincore.GetLastError(); if (waitAll && errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) { // Check for duplicate handles. This is a brute force O(n^2) search, which is intended since the typical // array length is short enough that this would actually be faster than using a hash set. Also, the worst // case is not so bad considering that the array length is limited by // <see cref="WaitHandle.MaxWaitHandles"/>. for (int i = 1; i < numHandles; ++i) { IntPtr handle = pHandles[i]; for (int j = 0; j < i; ++j) { if (pHandles[j] == handle) { throw new DuplicateWaitObjectException("waitHandles[" + i + ']'); } } } } ThrowWaitFailedException(errorCode); } return result; } private static bool WaitOneCore(IntPtr handle, int millisecondsTimeout) { Debug.Assert(millisecondsTimeout >= -1); int ret = WaitForSingleObject(handle, millisecondsTimeout); if (ret == WaitAbandoned) { ThrowAbandonedMutexException(); } return ret != WaitTimeout; } /*======================================================================== ** Waits for signal from all the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when all the object have been pulsed ** or timeout milliseonds have elapsed. ========================================================================*/ private static int WaitMultiple( RuntimeThread currentThread, SafeWaitHandle[] safeWaitHandles, int count, int millisecondsTimeout, bool waitAll) { Debug.Assert(currentThread == RuntimeThread.CurrentThread); Debug.Assert(safeWaitHandles != null); Debug.Assert(safeWaitHandles.Length >= count); IntPtr[] handles = currentThread.GetWaitedHandleArray(count); for (int i = 0; i < count; i++) { handles[i] = safeWaitHandles[i].DangerousGetHandle(); } return WaitForMultipleObjects(handles, count, waitAll, millisecondsTimeout); } private static int WaitAnyCore( RuntimeThread currentThread, SafeWaitHandle[] safeWaitHandles, WaitHandle[] waitHandles, int millisecondsTimeout) { Debug.Assert(currentThread == RuntimeThread.CurrentThread); Debug.Assert(safeWaitHandles != null); Debug.Assert(safeWaitHandles.Length >= waitHandles.Length); Debug.Assert(waitHandles != null); Debug.Assert(waitHandles.Length > 0); Debug.Assert(waitHandles.Length <= MaxWaitHandles); Debug.Assert(millisecondsTimeout >= -1); int ret = WaitMultiple(currentThread, safeWaitHandles, waitHandles.Length, millisecondsTimeout, false /* waitany*/ ); if ((WaitAbandoned <= ret) && (WaitAbandoned + waitHandles.Length > ret)) { int mutexIndex = ret - WaitAbandoned; if (0 <= mutexIndex && mutexIndex < waitHandles.Length) { ThrowAbandonedMutexException(mutexIndex, waitHandles[mutexIndex]); } else { ThrowAbandonedMutexException(); } } return ret; } private static bool WaitAllCore( RuntimeThread currentThread, SafeWaitHandle[] safeWaitHandles, WaitHandle[] waitHandles, int millisecondsTimeout) { Debug.Assert(currentThread == RuntimeThread.CurrentThread); Debug.Assert(safeWaitHandles != null); Debug.Assert(safeWaitHandles.Length >= waitHandles.Length); Debug.Assert(millisecondsTimeout >= -1); int ret = WaitMultiple(currentThread, safeWaitHandles, waitHandles.Length, millisecondsTimeout, true /* waitall*/ ); if ((WaitAbandoned <= ret) && (WaitAbandoned + waitHandles.Length > ret)) { //In the case of WaitAll the OS will only provide the // information that mutex was abandoned. // It won't tell us which one. So we can't set the Index or provide access to the Mutex ThrowAbandonedMutexException(); } return ret != WaitTimeout; } private static bool SignalAndWaitCore(IntPtr handleToSignal, IntPtr handleToWaitOn, int millisecondsTimeout) { Debug.Assert(millisecondsTimeout >= -1); int ret = (int)Interop.mincore.SignalObjectAndWait(handleToSignal, handleToWaitOn, (uint)millisecondsTimeout, false); if (ret == WaitAbandoned) { ThrowAbandonedMutexException(); } if (ret == WaitFailed) { ThrowWaitFailedException(Interop.mincore.GetLastError()); } return ret != WaitTimeout; } private static void ThrowAbandonedMutexException() { throw new AbandonedMutexException(); } private static void ThrowAbandonedMutexException(int location, WaitHandle handle) { throw new AbandonedMutexException(location, handle); } internal static void ThrowSignalOrUnsignalException() { int errorCode = Interop.mincore.GetLastError(); switch (errorCode) { case Interop.Errors.ERROR_INVALID_HANDLE: ThrowInvalidHandleException(); break; case Interop.Errors.ERROR_TOO_MANY_POSTS: throw new SemaphoreFullException(); case Interop.Errors.ERROR_NOT_OWNER: throw new ApplicationException(SR.Arg_SynchronizationLockException); default: var ex = new Exception(); ex.SetErrorCode(errorCode); throw ex; } } private static void ThrowWaitFailedException(int errorCode) { switch (errorCode) { case Interop.Errors.ERROR_INVALID_HANDLE: ThrowInvalidHandleException(); break; case Interop.Errors.ERROR_INVALID_PARAMETER: throw new ArgumentException(); case Interop.Errors.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(); case Interop.Errors.ERROR_NOT_ENOUGH_MEMORY: throw new OutOfMemoryException(); case Interop.Errors.ERROR_TOO_MANY_POSTS: // Only applicable to <see cref="WaitHandle.SignalAndWait(WaitHandle, WaitHandle)"/>. Note however, that // if the semahpore already has the maximum signal count, the Windows SignalObjectAndWait function does not // return an error, but this code is kept for historical reasons and to convey the intent, since ideally, // that should be an error. throw new InvalidOperationException(SR.Threading_SemaphoreFullException); case Interop.Errors.ERROR_NOT_OWNER: // Only applicable to <see cref="WaitHandle.SignalAndWait(WaitHandle, WaitHandle)"/> when signaling a mutex // that is locked by a different thread. Note that if the mutex is already unlocked, the Windows // SignalObjectAndWait function does not return an error. throw new ApplicationException(SR.Arg_SynchronizationLockException); case Interop.Errors.ERROR_MUTANT_LIMIT_EXCEEDED: throw new OverflowException(SR.Overflow_MutexReacquireCount); default: Exception ex = new Exception(); ex.SetErrorCode(errorCode); throw ex; } } internal static Exception ExceptionFromCreationError(int errorCode, string path) { switch (errorCode) { case Interop.Errors.ERROR_PATH_NOT_FOUND: return new IOException(SR.Format(SR.IO_PathNotFound_Path, path)); case Interop.Errors.ERROR_ACCESS_DENIED: return new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, path)); case Interop.Errors.ERROR_ALREADY_EXISTS: return new IOException(SR.Format(SR.IO_AlreadyExists_Name, path)); case Interop.Errors.ERROR_FILENAME_EXCED_RANGE: return new PathTooLongException(); default: return new IOException(SR.Arg_IOException, errorCode); } } } }
// // Mono.System.Xml.Schema.XmlSchemaSimpleType.cs // // Author: // Dwivedi, Ajay kumar Adwiv@Yahoo.com // Atsushi Enomoto ginga@kit.hi-ho.ne.jp // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.System.Xml.Serialization; using Mono.System.Xml; using Mono.Xml.Schema; namespace Mono.System.Xml.Schema { /// <summary> /// Summary description for XmlSchemaSimpleType. /// </summary> public class XmlSchemaSimpleType : XmlSchemaType { const string xmlname = "simpleType"; private static XmlSchemaSimpleType schemaLocationType; private XmlSchemaSimpleTypeContent content; //compilation vars internal bool islocal = true; // Assuming local means we have to specify islocal=false only in XmlSchema private bool recursed; private XmlSchemaDerivationMethod variety; #if NET_2_0 // predefined simple types internal static readonly XmlSchemaSimpleType XsAnySimpleType; internal static readonly XmlSchemaSimpleType XsString; internal static readonly XmlSchemaSimpleType XsBoolean; internal static readonly XmlSchemaSimpleType XsDecimal; internal static readonly XmlSchemaSimpleType XsFloat; internal static readonly XmlSchemaSimpleType XsDouble; internal static readonly XmlSchemaSimpleType XsDuration; internal static readonly XmlSchemaSimpleType XsDateTime; internal static readonly XmlSchemaSimpleType XsTime; internal static readonly XmlSchemaSimpleType XsDate; internal static readonly XmlSchemaSimpleType XsGYearMonth; internal static readonly XmlSchemaSimpleType XsGYear; internal static readonly XmlSchemaSimpleType XsGMonthDay; internal static readonly XmlSchemaSimpleType XsGDay; internal static readonly XmlSchemaSimpleType XsGMonth; internal static readonly XmlSchemaSimpleType XsHexBinary; internal static readonly XmlSchemaSimpleType XsBase64Binary; internal static readonly XmlSchemaSimpleType XsAnyUri; internal static readonly XmlSchemaSimpleType XsQName; internal static readonly XmlSchemaSimpleType XsNotation; internal static readonly XmlSchemaSimpleType XsNormalizedString; internal static readonly XmlSchemaSimpleType XsToken; internal static readonly XmlSchemaSimpleType XsLanguage; internal static readonly XmlSchemaSimpleType XsNMToken; internal static readonly XmlSchemaSimpleType XsNMTokens; internal static readonly XmlSchemaSimpleType XsName; internal static readonly XmlSchemaSimpleType XsNCName; internal static readonly XmlSchemaSimpleType XsID; internal static readonly XmlSchemaSimpleType XsIDRef; internal static readonly XmlSchemaSimpleType XsIDRefs; internal static readonly XmlSchemaSimpleType XsEntity; internal static readonly XmlSchemaSimpleType XsEntities; internal static readonly XmlSchemaSimpleType XsInteger; internal static readonly XmlSchemaSimpleType XsNonPositiveInteger; internal static readonly XmlSchemaSimpleType XsNegativeInteger; internal static readonly XmlSchemaSimpleType XsLong; internal static readonly XmlSchemaSimpleType XsInt; internal static readonly XmlSchemaSimpleType XsShort; internal static readonly XmlSchemaSimpleType XsByte; internal static readonly XmlSchemaSimpleType XsNonNegativeInteger; internal static readonly XmlSchemaSimpleType XsUnsignedLong; internal static readonly XmlSchemaSimpleType XsUnsignedInt; internal static readonly XmlSchemaSimpleType XsUnsignedShort; internal static readonly XmlSchemaSimpleType XsUnsignedByte; internal static readonly XmlSchemaSimpleType XsPositiveInteger; // xdt:* internal static readonly XmlSchemaSimpleType XdtUntypedAtomic; internal static readonly XmlSchemaSimpleType XdtAnyAtomicType; internal static readonly XmlSchemaSimpleType XdtYearMonthDuration; internal static readonly XmlSchemaSimpleType XdtDayTimeDuration; #endif static XmlSchemaSimpleType () { // This is not used in the meantime. XmlSchemaSimpleType st = new XmlSchemaSimpleType (); XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList (); list.ItemTypeName = new XmlQualifiedName ("anyURI", XmlSchema.Namespace); st.Content = list; st.BaseXmlSchemaTypeInternal = null; st.variety = XmlSchemaDerivationMethod.List; schemaLocationType = st; #if NET_2_0 // Built-In schema types XsAnySimpleType = BuildSchemaType ("anySimpleType", null); XsString = BuildSchemaType ("string", "anySimpleType"); XsBoolean = BuildSchemaType ("boolean", "anySimpleType"); XsDecimal = BuildSchemaType ("decimal", "anySimpleType"); XsFloat = BuildSchemaType ("float", "anySimpleType"); XsDouble = BuildSchemaType ("double", "anySimpleType"); XsDuration = BuildSchemaType ("duration", "anySimpleType"); XsDateTime = BuildSchemaType ("dateTime", "anySimpleType"); XsTime = BuildSchemaType ("time", "anySimpleType"); XsDate = BuildSchemaType ("date", "anySimpleType"); XsGYearMonth = BuildSchemaType ("gYearMonth", "anySimpleType"); XsGYear = BuildSchemaType ("gYear", "anySimpleType"); XsGMonthDay = BuildSchemaType ("gMonthDay", "anySimpleType"); XsGDay = BuildSchemaType ("gDay", "anySimpleType"); XsGMonth = BuildSchemaType ("gMonth", "anySimpleType"); XsHexBinary = BuildSchemaType ("hexBinary", "anySimpleType"); XsBase64Binary = BuildSchemaType ("base64Binary", "anySimpleType"); XsAnyUri = BuildSchemaType ("anyURI", "anySimpleType"); XsQName = BuildSchemaType ("QName", "anySimpleType"); XsNotation = BuildSchemaType ("NOTATION", "anySimpleType"); // derived types XsNormalizedString = BuildSchemaType ("normalizedString", "string"); XsToken = BuildSchemaType ("token", "normalizedString"); XsLanguage = BuildSchemaType ("language", "token"); XsNMToken = BuildSchemaType ("NMTOKEN", "token"); XsName = BuildSchemaType ("Name", "token"); XsNCName = BuildSchemaType ("NCName", "Name"); XsID = BuildSchemaType ("ID", "NCName"); XsIDRef = BuildSchemaType ("IDREF", "NCName"); XsEntity = BuildSchemaType ("ENTITY", "NCName"); XsInteger = BuildSchemaType ("integer", "decimal"); XsNonPositiveInteger = BuildSchemaType ("nonPositiveInteger", "integer"); XsNegativeInteger = BuildSchemaType ("negativeInteger", "nonPositiveInteger"); XsLong = BuildSchemaType ("long", "integer"); XsInt = BuildSchemaType ("int", "long"); XsShort = BuildSchemaType ("short", "int"); XsByte = BuildSchemaType ("byte", "short"); XsNonNegativeInteger = BuildSchemaType ("nonNegativeInteger", "integer"); XsUnsignedLong = BuildSchemaType ("unsignedLong", "nonNegativeInteger"); XsUnsignedInt = BuildSchemaType ("unsignedInt", "unsignedLong"); XsUnsignedShort = BuildSchemaType ("unsignedShort", "unsignedInt"); XsUnsignedByte = BuildSchemaType ("unsignedByte", "unsignedShort"); XsPositiveInteger = BuildSchemaType ("positiveInteger", "nonNegativeInteger"); // xdt:* XdtAnyAtomicType = BuildSchemaType ("anyAtomicType", "anySimpleType", true, false); XdtUntypedAtomic = BuildSchemaType ("untypedAtomic", "anyAtomicType", true, true); XdtDayTimeDuration = BuildSchemaType ("dayTimeDuration", "duration", true, false); XdtYearMonthDuration = BuildSchemaType ("yearMonthDuration", "duration", true, false); // NMTOKENS, IDREFS, ENTITIES - lists XsIDRefs = new XmlSchemaSimpleType (); XmlSchemaSimpleTypeList sl = new XmlSchemaSimpleTypeList (); sl.ItemType = XsIDRef; XsIDRefs.Content = sl; XsEntities = new XmlSchemaSimpleType (); sl = new XmlSchemaSimpleTypeList (); sl.ItemType = XsEntity; XsEntities.Content = sl; XsNMTokens = new XmlSchemaSimpleType (); sl = new XmlSchemaSimpleTypeList (); sl.ItemType = XsNMToken; XsNMTokens.Content = sl; #endif } #if NET_2_0 private static XmlSchemaSimpleType BuildSchemaType (string name, string baseName) { return BuildSchemaType (name, baseName, false, false); } private static XmlSchemaSimpleType BuildSchemaType (string name, string baseName, bool xdt, bool baseXdt) { string ns = xdt ? "http://www.w3.org/2003/11/xpath-datatypes" : XmlSchema.Namespace; string ns2 = baseXdt ? "http://www.w3.org/2003/11/xpath-datatypes" : XmlSchema.Namespace; XmlSchemaSimpleType st = new XmlSchemaSimpleType (); st.QNameInternal = new XmlQualifiedName (name, ns); if (baseName != null) st.BaseXmlSchemaTypeInternal = XmlSchemaType. GetBuiltInSimpleType (new XmlQualifiedName (baseName, ns2)); st.DatatypeInternal = XmlSchemaDatatype.FromName (st.QualifiedName); return st; } #endif internal static XsdAnySimpleType AnySimpleType { get { return XsdAnySimpleType.Instance; } } internal static XmlSchemaSimpleType SchemaLocationType { get { return schemaLocationType; } } public XmlSchemaSimpleType () { } [XmlElement("restriction",typeof(XmlSchemaSimpleTypeRestriction))] [XmlElement("list",typeof(XmlSchemaSimpleTypeList))] [XmlElement("union",typeof(XmlSchemaSimpleTypeUnion))] public XmlSchemaSimpleTypeContent Content { get{ return content; } set{ content = value; } } internal XmlSchemaDerivationMethod Variety { get{ return variety; } } internal override void SetParent (XmlSchemaObject parent) { base.SetParent (parent); if (Content != null) Content.SetParent (this); } /// <remarks> /// For a simple Type: /// 1. Content must be present /// 2. id if present, must have be a valid ID /// a) If the simpletype is local /// 1- are from <xs:complexType name="simpleType"> and <xs:complexType name="localSimpleType"> /// 1. name is prohibited /// 2. final is prohibited /// b) If the simpletype is toplevel /// 1- are from <xs:complexType name="simpleType"> and <xs:complexType name="topLevelSimpleType"> /// 1. name is required, type must be NCName /// 2. Content is required /// 3. final can have values : #all | (list | union | restriction) /// 4. If final is set, finalResolved is same as final (but within the values of b.3) /// 5. If final is not set, the finalDefault of the schema (ie. only #all and restriction) /// 6. Base type is: /// 4.1 If restriction is chosen,the base type of restriction or elements /// 4.2 otherwise simple ur-type /// </remarks> internal override int Compile(ValidationEventHandler h, XmlSchema schema) { // If this is already compiled this time, simply skip. if (CompilationId == schema.CompilationId) return 0; errorCount = 0; if(this.islocal) // a { if(this.Name != null) // a.1 error(h,"Name is prohibited in a local simpletype"); else this.QNameInternal = new XmlQualifiedName(this.Name, AncestorSchema.TargetNamespace); if(this.Final != XmlSchemaDerivationMethod.None) //a.2 error(h,"Final is prohibited in a local simpletype"); } else //b { if(this.Name == null) //b.1 error(h,"Name is required in top level simpletype"); else if(!XmlSchemaUtil.CheckNCName(this.Name)) // b.1.2 error(h,"name attribute of a simpleType must be NCName"); else this.QNameInternal = new XmlQualifiedName(this.Name, AncestorSchema.TargetNamespace); //NOTE: Although the FinalResolved can be Empty, it is not a valid value for Final //DEVIATION: If an error occurs, the finaldefault is always consulted. This deviates // from the way MS implementation works. switch(this.Final) //b.3, b.4 { case XmlSchemaDerivationMethod.All: this.finalResolved = XmlSchemaDerivationMethod.All; break; case XmlSchemaDerivationMethod.List: case XmlSchemaDerivationMethod.Union: case XmlSchemaDerivationMethod.Restriction: this.finalResolved = Final; break; default: error(h,"The value of final attribute is not valid for simpleType"); goto case XmlSchemaDerivationMethod.None; // use assignment from finaldefault on schema. case XmlSchemaDerivationMethod.None: // b.5 XmlSchemaDerivationMethod flags = (XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.Union ); switch (schema.FinalDefault) { case XmlSchemaDerivationMethod.All: finalResolved = XmlSchemaDerivationMethod.All; break; case XmlSchemaDerivationMethod.None: finalResolved = XmlSchemaDerivationMethod.Empty; break; default: finalResolved = schema.FinalDefault & flags; break; } break; } } XmlSchemaUtil.CompileID(Id,this,schema.IDCollection,h); if (Content != null) Content.OwnerType = this; if(this.Content == null) //a.3,b.2 error(h,"Content is required in a simpletype"); else if(Content is XmlSchemaSimpleTypeRestriction) { this.resolvedDerivedBy = XmlSchemaDerivationMethod.Restriction; errorCount += ((XmlSchemaSimpleTypeRestriction)Content).Compile(h,schema); } else if(Content is XmlSchemaSimpleTypeList) { this.resolvedDerivedBy = XmlSchemaDerivationMethod.List; errorCount += ((XmlSchemaSimpleTypeList)Content).Compile(h,schema); } else if(Content is XmlSchemaSimpleTypeUnion) { this.resolvedDerivedBy = XmlSchemaDerivationMethod.Union; errorCount += ((XmlSchemaSimpleTypeUnion)Content).Compile(h,schema); } this.CompilationId = schema.CompilationId; return errorCount; } internal void CollectBaseType (ValidationEventHandler h, XmlSchema schema) { if (Content is XmlSchemaSimpleTypeRestriction) { object o = ((XmlSchemaSimpleTypeRestriction) Content).GetActualType (h, schema, false); BaseXmlSchemaTypeInternal = o as XmlSchemaSimpleType; if (BaseXmlSchemaTypeInternal != null) DatatypeInternal = BaseXmlSchemaTypeInternal.Datatype; else DatatypeInternal = o as XmlSchemaDatatype; } // otherwise, actualBaseSchemaType is null else DatatypeInternal = XmlSchemaSimpleType.AnySimpleType; } internal override int Validate(ValidationEventHandler h, XmlSchema schema) { // 3.14.6 Properties Correct. // // 1. Post Compilation Properties // {name}, {target namespace} => QNameInternal. Already Compile()d. // {base type definition} => baseSchemaTypeInternal // {final} => finalResolved. Already Compile()d. // {variety} => resolvedDerivedBy. Already Compile()d. // // 2. Should be checked by "recursed" field. if(IsValidated (schema.ValidationId)) return errorCount; if (recursed) { error (h, "Circular type reference was found."); return errorCount; } recursed = true; CollectBaseType (h, schema); if (content != null) errorCount += content.Validate (h, schema); /* // BaseSchemaType property BaseXmlSchemaTypeInternal = content.ActualBaseSchemaType as XmlSchemaType; if (this.BaseXmlSchemaTypeInternal == null) this.DatatypeInternal = content.ActualBaseSchemaType as XmlSchemaDatatype; */ // Datatype property XmlSchemaSimpleType simple = BaseXmlSchemaType as XmlSchemaSimpleType; if (simple != null) this.DatatypeInternal = simple.Datatype; // else // DatatypeInternal = BaseSchemaType as XmlSchemaDatatype; // 3. XmlSchemaSimpleType baseSType = BaseXmlSchemaType as XmlSchemaSimpleType; if (baseSType != null) { if ((baseSType.FinalResolved & this.resolvedDerivedBy) != 0) error (h, "Specified derivation is prohibited by the base simple type."); } // {variety} if (this.resolvedDerivedBy == XmlSchemaDerivationMethod.Restriction && baseSType != null) this.variety = baseSType.Variety; else this.variety = this.resolvedDerivedBy; // 3.14.6 Derivation Valid (Restriction, Simple) XmlSchemaSimpleTypeRestriction r = Content as XmlSchemaSimpleTypeRestriction; object baseType = BaseXmlSchemaType != null ? (object) BaseXmlSchemaType : Datatype; if (r != null) ValidateDerivationValid (baseType, r.Facets, h, schema); // TODO: describe which validation term this belongs to. XmlSchemaSimpleTypeList l = Content as XmlSchemaSimpleTypeList; if (l != null) { XmlSchemaSimpleType itemSimpleType = l.ValidatedListItemType as XmlSchemaSimpleType; if (itemSimpleType != null && itemSimpleType.Content is XmlSchemaSimpleTypeList) error (h, "List type must not be derived from another list type."); } recursed = false; ValidationId = schema.ValidationId; return errorCount; } // 3.14.6 Derivation Valid (RestrictionSimple) internal void ValidateDerivationValid (object baseType, XmlSchemaObjectCollection facets, ValidationEventHandler h, XmlSchema schema) { // TODO XmlSchemaSimpleType baseSimpleType = baseType as XmlSchemaSimpleType; switch (this.Variety) { // 1. atomic type case XmlSchemaDerivationMethod.Restriction: // 1.1 if (baseSimpleType != null && baseSimpleType.resolvedDerivedBy != XmlSchemaDerivationMethod.Restriction) error (h, "Base schema type is not either atomic type or primitive type."); // 1.2 if (baseSimpleType != null && (baseSimpleType.FinalResolved & XmlSchemaDerivationMethod.Restriction) != 0) error (h, "Derivation by restriction is prohibited by the base simple type."); // TODO: 1.3 facet restriction valid. break; case XmlSchemaDerivationMethod.List: /* XmlSchemaSimpleTypeList thisList = Content as XmlSchemaSimpleTypeList; // 2.1 item list type not allowed if (baseSimpleType != null && baseSimpleType.resolvedDerivedBy == XmlSchemaDerivationMethod.List) error (h, "Base list schema type is not allowed."); XmlSchemaSimpleTypeUnion baseUnion = baseSimpleType.Content as XmlSchemaSimpleTypeUnion; if (baseUnion != null) { bool errorFound = false; foreach (object memberType in baseUnion.ValidatedTypes) { XmlSchemaSimpleType memberST = memberType as XmlSchemaSimpleType; if (memberST != null && memberST.resolvedDerivedBy == XmlSchemaDerivationMethod.List) errorFound = true; } if (errorFound) error (h, "Base union schema type should not contain list types."); } */ // 2.2 facets limited if (facets != null) foreach (XmlSchemaFacet facet in facets) { if (facet is XmlSchemaLengthFacet || facet is XmlSchemaMaxLengthFacet || facet is XmlSchemaMinLengthFacet || facet is XmlSchemaEnumerationFacet || facet is XmlSchemaPatternFacet) continue; else error (h, "Not allowed facet was found on this simple type which derives list type."); } break; case XmlSchemaDerivationMethod.Union: // 3.1 // 3.2 if (facets != null) foreach (XmlSchemaFacet facet in facets) { if (facet is XmlSchemaEnumerationFacet || facet is XmlSchemaPatternFacet) continue; else error (h, "Not allowed facet was found on this simple type which derives list type."); } break; } } // 3.14.6 Type Derivation OK (Simple) internal bool ValidateTypeDerivationOK (object baseType, ValidationEventHandler h, XmlSchema schema, bool raiseError) { // 1 // Note that anyType should also be allowed as anySimpleType. if (this == baseType || baseType == XmlSchemaSimpleType.AnySimpleType || baseType == XmlSchemaComplexType.AnyType) return true; // 2.1 XmlSchemaSimpleType baseSimpleType = baseType as XmlSchemaSimpleType; if (baseSimpleType != null && (baseSimpleType.FinalResolved & resolvedDerivedBy) != 0) { if (raiseError) error (h, "Specified derivation is prohibited by the base type."); return false; } // 2.2.1 if (BaseXmlSchemaType == baseType || Datatype == baseType) return true; // 2.2.2 XmlSchemaSimpleType thisBaseSimpleType = BaseXmlSchemaType as XmlSchemaSimpleType; if (thisBaseSimpleType != null) { if (thisBaseSimpleType.ValidateTypeDerivationOK (baseType, h, schema, false)) return true; } // 2.2.3 switch (Variety) { case XmlSchemaDerivationMethod.Union: case XmlSchemaDerivationMethod.List: if (baseType == XmlSchemaSimpleType.AnySimpleType) return true; break; } // 2.2.4 validly derived from one of the union member type. if (baseSimpleType != null && baseSimpleType.Variety == XmlSchemaDerivationMethod.Union) { foreach (object memberType in ((XmlSchemaSimpleTypeUnion) baseSimpleType.Content).ValidatedTypes) if (this.ValidateTypeDerivationOK (memberType, h, schema, false)) return true; } if (raiseError) error(h, "Invalid simple type derivation was found."); return false; } internal string Normalize (string s, XmlNameTable nt, XmlNamespaceManager nsmgr) { return Content.Normalize (s, nt, nsmgr); } //<simpleType // final = (#all | (list | union | restriction)) // id = ID // name = NCName // {any attributes with non-schema namespace . . .}> // Content: (annotation?, (restriction | list | union)) //</simpleType> internal static XmlSchemaSimpleType Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaSimpleType stype = new XmlSchemaSimpleType(); reader.MoveToElement(); if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h,"Should not happen :1: XmlSchemaGroup.Read, name="+reader.Name,null); reader.Skip(); return null; } stype.LineNumber = reader.LineNumber; stype.LinePosition = reader.LinePosition; stype.SourceUri = reader.BaseURI; while(reader.MoveToNextAttribute()) { if(reader.Name == "final") { Exception innerex; stype.Final = XmlSchemaUtil.ReadDerivationAttribute(reader, out innerex, "final", XmlSchemaUtil.FinalAllowed); if(innerex != null) error(h, "some invalid values not a valid value for final", innerex); } else if(reader.Name == "id") { stype.Id = reader.Value; } else if(reader.Name == "name") { stype.Name = reader.Value; } else if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h,reader.Name + " is not a valid attribute for simpleType",null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader,stype); } } reader.MoveToElement(); if(reader.IsEmptyElement) return stype; // Content: (annotation?, (restriction | list | union)) int level = 1; while(reader.ReadNextElement()) { if(reader.NodeType == XmlNodeType.EndElement) { if(reader.LocalName != xmlname) error(h,"Should not happen :2: XmlSchemaSimpleType.Read, name="+reader.Name,null); break; } if(level <= 1 && reader.LocalName == "annotation") { level = 2; //Only one annotation XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader,h); if(annotation != null) stype.Annotation = annotation; continue; } if(level <= 2) { if(reader.LocalName == "restriction") { level = 3; XmlSchemaSimpleTypeRestriction restriction = XmlSchemaSimpleTypeRestriction.Read(reader,h); if(restriction != null) stype.content = restriction; continue; } if(reader.LocalName == "list") { level = 3; XmlSchemaSimpleTypeList list = XmlSchemaSimpleTypeList.Read(reader,h); if(list != null) stype.content = list; continue; } if(reader.LocalName == "union") { level = 3; XmlSchemaSimpleTypeUnion union = XmlSchemaSimpleTypeUnion.Read(reader,h); if(union != null) stype.content = union; continue; } } reader.RaiseInvalidElementError(); } return stype; } } }
//------------------------------------------------------------------------------ // <copyright file="EventDescriptorCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Diagnostics.CodeAnalysis; /* This class has the HostProtectionAttribute. The purpose of this attribute is to enforce host-specific programming model guidelines, not security behavior. Suppress FxCop message - BUT REVISIT IF ADDING NEW SECURITY ATTRIBUTES. */ [assembly: SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields", Scope="type", Target="System.ComponentModel.EventDescriptorCollection")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.get_IsFixedSize():System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.ICollection.get_SyncRoot():System.Object")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.ICollection.get_IsSynchronized():System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.get_IsReadOnly():System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.Clear():System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IEnumerable.GetEnumerator():System.Collections.IEnumerator")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.ICollection.CopyTo(System.Array,System.Int32):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.ICollection.get_Count():System.Int32")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.Contains(System.Object):System.Boolean")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.Remove(System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.get_Item(System.Int32):System.Object")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.set_Item(System.Int32,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.Add(System.Object):System.Int32")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.IndexOf(System.Object):System.Int32")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.RemoveAt(System.Int32):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.System.Collections.IList.Insert(System.Int32,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.EventDescriptorCollection..ctor(System.ComponentModel.EventDescriptor[],System.Boolean)")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.get_Count():System.Int32")] [assembly: SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope="member", Target="System.ComponentModel.EventDescriptorCollection.GetEnumerator():System.Collections.IEnumerator")] namespace System.ComponentModel { using System.Runtime.InteropServices; using System.Diagnostics; using Microsoft.Win32; using System.Collections; using System.Globalization; /// <devdoc> /// <para> /// Represents a collection of events. /// </para> /// </devdoc> [System.Runtime.InteropServices.ComVisible(true)] [System.Security.Permissions.HostProtection(Synchronization=true)] public class EventDescriptorCollection : ICollection, IList { private EventDescriptor[] events; private string[] namedSort; private IComparer comparer; private bool eventsOwned = true; private bool needSort = false; private int eventCount; private bool readOnly = false; /// <devdoc> /// An empty AttributeCollection that can used instead of creating a new one with no items. /// </devdoc> public static readonly EventDescriptorCollection Empty = new EventDescriptorCollection(null, true); /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.EventDescriptorCollection'/> class. /// </para> /// </devdoc> public EventDescriptorCollection(EventDescriptor[] events) { this.events = events; if (events == null) { this.events = new EventDescriptor[0]; this.eventCount = 0; } else { this.eventCount = this.events.Length; } this.eventsOwned = true; } /// <devdoc> /// Initializes a new instance of an event descriptor collection, and allows you to mark the /// collection as read-only so it cannot be modified. /// </devdoc> public EventDescriptorCollection(EventDescriptor[] events, bool readOnly) : this(events) { this.readOnly = readOnly; } private EventDescriptorCollection(EventDescriptor[] events, int eventCount, string[] namedSort, IComparer comparer) { this.eventsOwned = false; if (namedSort != null) { this.namedSort = (string[])namedSort.Clone(); } this.comparer = comparer; this.events = events; this.eventCount = eventCount; this.needSort = true; } /// <devdoc> /// <para> /// Gets the number /// of event descriptors in the collection. /// </para> /// </devdoc> public int Count { get { return eventCount; } } /// <devdoc> /// <para>Gets the event with the specified index /// number.</para> /// </devdoc> public virtual EventDescriptor this[int index] { get { if (index >= eventCount) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); return events[index]; } } /// <devdoc> /// <para> /// Gets the event with the specified name. /// </para> /// </devdoc> public virtual EventDescriptor this[string name] { get { return Find(name, false); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int Add(EventDescriptor value) { if (readOnly) { throw new NotSupportedException(); } EnsureSize(eventCount + 1); events[eventCount++] = value; return eventCount - 1; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Clear() { if (readOnly) { throw new NotSupportedException(); } eventCount = 0; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Contains(EventDescriptor value) { return IndexOf(value) >= 0; } /// <internalonly/> void ICollection.CopyTo(Array array, int index) { EnsureEventsOwned(); Array.Copy(events, 0, array, index, Count); } private void EnsureEventsOwned() { if (!eventsOwned) { eventsOwned = true; if (events != null) { EventDescriptor[] newEvents = new EventDescriptor[Count]; Array.Copy(events, 0, newEvents, 0, Count); this.events = newEvents; } } if (needSort) { needSort = false; InternalSort(this.namedSort); } } private void EnsureSize(int sizeNeeded) { if (sizeNeeded <= events.Length) { return; } if (events == null || events.Length == 0) { eventCount = 0; events = new EventDescriptor[sizeNeeded]; return; } EnsureEventsOwned(); int newSize = Math.Max(sizeNeeded, events.Length * 2); EventDescriptor[] newEvents = new EventDescriptor[newSize]; Array.Copy(events, 0, newEvents, 0, eventCount); events = newEvents; } /// <devdoc> /// <para> /// Gets the description of the event with the specified /// name /// in the collection. /// </para> /// </devdoc> public virtual EventDescriptor Find(string name, bool ignoreCase) { EventDescriptor p = null; if (ignoreCase) { for(int i = 0; i < Count; i++) { if (String.Equals(events[i].Name, name, StringComparison.OrdinalIgnoreCase)) { p = events[i]; break; } } } else { for(int i = 0; i < Count; i++) { if (String.Equals(events[i].Name, name, StringComparison.Ordinal)) { p = events[i]; break; } } } return p; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int IndexOf(EventDescriptor value) { return Array.IndexOf(events, value, 0, eventCount); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Insert(int index, EventDescriptor value) { if (readOnly) { throw new NotSupportedException(); } EnsureSize(eventCount + 1); if (index < eventCount) { Array.Copy(events, index, events, index + 1, eventCount - index); } events[index] = value; eventCount++; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Remove(EventDescriptor value) { if (readOnly) { throw new NotSupportedException(); } int index = IndexOf(value); if (index != -1) { RemoveAt(index); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void RemoveAt(int index) { if (readOnly) { throw new NotSupportedException(); } if (index < eventCount - 1) { Array.Copy(events, index + 1, events, index, eventCount - index - 1); } events[eventCount - 1] = null; eventCount--; } /// <devdoc> /// <para> /// Gets an enumerator for this <see cref='System.ComponentModel.EventDescriptorCollection'/>. /// </para> /// </devdoc> public IEnumerator GetEnumerator() { // we can only return an enumerator on the events we actually have... if (events.Length == eventCount) { return events.GetEnumerator(); } else { return new ArraySubsetEnumerator(events, eventCount); } } /// <devdoc> /// <para> /// Sorts the members of this EventDescriptorCollection, using the default sort for this collection, /// which is usually alphabetical. /// </para> /// </devdoc> public virtual EventDescriptorCollection Sort() { return new EventDescriptorCollection(this.events, this.eventCount, this.namedSort, this.comparer); } /// <devdoc> /// <para> /// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </para> /// </devdoc> public virtual EventDescriptorCollection Sort(string[] names) { return new EventDescriptorCollection(this.events, this.eventCount, names, this.comparer); } /// <devdoc> /// <para> /// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </para> /// </devdoc> public virtual EventDescriptorCollection Sort(string[] names, IComparer comparer) { return new EventDescriptorCollection(this.events, this.eventCount, names, comparer); } /// <devdoc> /// <para> /// Sorts the members of this EventDescriptorCollection, using the specified IComparer to compare, /// the EventDescriptors contained in the collection. /// </para> /// </devdoc> public virtual EventDescriptorCollection Sort(IComparer comparer) { return new EventDescriptorCollection(this.events, this.eventCount, this.namedSort, comparer); } /// <devdoc> /// <para> /// Sorts the members of this EventDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </para> /// </devdoc> protected void InternalSort(string[] names) { if (events == null || events.Length == 0) { return; } this.InternalSort(this.comparer); if (names != null && names.Length > 0) { ArrayList eventArrayList = new ArrayList(events); int foundCount = 0; int eventCount = events.Length; for (int i = 0; i < names.Length; i++) { for (int j = 0; j < eventCount; j++) { EventDescriptor currentEvent = (EventDescriptor)eventArrayList[j]; // Found a matching event. Here, we add it to our array. We also // mark it as null in our array list so we don't add it twice later. // if (currentEvent != null && currentEvent.Name.Equals(names[i])) { events[foundCount++] = currentEvent; eventArrayList[j] = null; break; } } } // At this point we have filled in the first "foundCount" number of propeties, one for each // name in our name array. If a name didn't match, then it is ignored. Next, we must fill // in the rest of the properties. We now have a sparse array containing the remainder, so // it's easy. // for (int i = 0; i < eventCount; i++) { if (eventArrayList[i] != null) { events[foundCount++] = (EventDescriptor)eventArrayList[i]; } } Debug.Assert(foundCount == eventCount, "We did not completely fill our event array"); } } /// <devdoc> /// <para> /// Sorts the members of this EventDescriptorCollection using the specified IComparer. /// </para> /// </devdoc> protected void InternalSort(IComparer sorter) { if (sorter == null) { TypeDescriptor.SortDescriptorArray(this); } else { Array.Sort(events, sorter); } } /// <internalonly/> int ICollection.Count { get { return Count; } } /// <internalonly/> bool ICollection.IsSynchronized { get { return false; } } /// <internalonly/> object ICollection.SyncRoot { get { return null; } } /// <internalonly/> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <internalonly/> object IList.this[int index] { get { return this[index]; } set { if (readOnly) { throw new NotSupportedException(); } if (index >= eventCount) { throw new IndexOutOfRangeException(); } EnsureEventsOwned(); events[index] = (EventDescriptor)value; } } /// <internalonly/> int IList.Add(object value) { return Add((EventDescriptor)value); } /// <internalonly/> void IList.Clear() { Clear(); } /// <internalonly/> bool IList.Contains(object value) { return Contains((EventDescriptor)value); } /// <internalonly/> int IList.IndexOf(object value) { return IndexOf((EventDescriptor)value); } /// <internalonly/> void IList.Insert(int index, object value) { Insert(index, (EventDescriptor)value); } /// <internalonly/> void IList.Remove(object value) { Remove((EventDescriptor)value); } /// <internalonly/> void IList.RemoveAt(int index) { RemoveAt(index); } /// <internalonly/> bool IList.IsReadOnly { get { return readOnly; } } /// <internalonly/> bool IList.IsFixedSize { get { return readOnly; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class RemoveStrTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; NameValueCollection nvc; // simple string values string[] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count string[] ks; // Keys array // initialize IntStrings intl = new IntlStrings(); // [] NameValueCollection is constructed as expected //----------------------------------------------------------------- nvc = new NameValueCollection(); // [] Remove() on empty collection // cnt = nvc.Count; nvc.Remove(null); if (nvc.Count != cnt) { Assert.False(true, "Error, changed collection after Remove(null)"); } cnt = nvc.Count; nvc.Remove("some_string"); if (nvc.Count != cnt) { Assert.False(true, "Error, changed collection after Remove(some_string)"); } // [] Remove() on collection filled with simple strings // cnt = nvc.Count; int len = values.Length; for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } if (nvc.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length)); } // for (int i = 0; i < len; i++) { cnt = nvc.Count; nvc.Remove(keys[i]); if (nvc.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item", i)); } ks = nvc.AllKeys; if (Array.IndexOf(ks, keys[i]) > -1) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } // // Intl strings // [] Remove() on collection filled with Intl strings // string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } cnt = nvc.Count; for (int i = 0; i < len; i++) { nvc.Add(intlValues[i + len], intlValues[i]); } if (nvc.Count != (cnt + len)) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + len)); } for (int i = 0; i < len; i++) { // cnt = nvc.Count; nvc.Remove(intlValues[i + len]); if (nvc.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item", i)); } ks = nvc.AllKeys; if (Array.IndexOf(ks, intlValues[i + len]) > -1) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } // // [] Case sensitivity // string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } nvc.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings } // for (int i = 0; i < len; i++) { // uppercase key cnt = nvc.Count; nvc.Remove(intlValues[i + len]); if (nvc.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item", i)); } ks = nvc.AllKeys; if (Array.IndexOf(ks, intlValues[i + len]) > -1) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } nvc.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings } // for (int i = 0; i < len; i++) { // lowercase key cnt = nvc.Count; nvc.Remove(intlValuesLower[i + len]); if (nvc.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item using lowercase key", i)); } ks = nvc.AllKeys; if (Array.IndexOf(ks, intlValues[i + len]) > -1) { Assert.False(true, string.Format("Error, removed wrong item using lowercase key", i)); } } // [] Remove() on filled collection - with multiple items with the same key // nvc.Clear(); len = values.Length; string k = "keykey"; string k1 = "hm1"; for (int i = 0; i < len; i++) { nvc.Add(k, "Value" + i); nvc.Add(k1, "iTem" + i); } if (nvc.Count != 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2)); } nvc.Remove(k); if (nvc.Count != 1) { Assert.False(true, "Error, failed to remove item"); } ks = nvc.AllKeys; if (Array.IndexOf(ks, k) > -1) { Assert.False(true, "Error, removed wrong item"); } nvc.Remove(k1); if (nvc.Count != 0) { Assert.False(true, "Error, failed to remove item"); } ks = nvc.AllKeys; if (Array.IndexOf(ks, k1) > -1) { Assert.False(true, "Error, removed wrong item"); } // // [] Remove(null) - when there is an item with null-key // cnt = nvc.Count; nvc.Add(null, "nullValue"); if (nvc.Count != cnt + 1) { Assert.False(true, "Error, failed to add item with null-key"); } if (nvc[null] == null) { Assert.False(true, "Error, didn't add item with null-key"); } cnt = nvc.Count; nvc.Remove(null); if (nvc.Count != cnt - 1) { Assert.False(true, "Error, failed to remove item"); } if (nvc[null] != null) { Assert.False(true, "Error, didn't remove item with null-key"); } // // [] Remove(null) - when no item with null key // nvc.Clear(); for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } cnt = nvc.Count; nvc.Remove(null); if (nvc.Count != cnt) { Assert.False(true, "Error, removed something "); } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IdentityManagement.Model { /// <summary> /// Contains information about the account password policy. /// /// /// <para> /// This data type is used as a response element in the <a>GetAccountPasswordPolicy</a> /// action. /// </para> /// </summary> public partial class PasswordPolicy { private bool? _allowUsersToChangePassword; private bool? _expirePasswords; private bool? _hardExpiry; private int? _maxPasswordAge; private int? _minimumPasswordLength; private int? _passwordReusePrevention; private bool? _requireLowercaseCharacters; private bool? _requireNumbers; private bool? _requireSymbols; private bool? _requireUppercaseCharacters; /// <summary> /// Gets and sets the property AllowUsersToChangePassword. /// <para> /// Specifies whether IAM users are allowed to change their own password. /// </para> /// </summary> public bool AllowUsersToChangePassword { get { return this._allowUsersToChangePassword.GetValueOrDefault(); } set { this._allowUsersToChangePassword = value; } } // Check to see if AllowUsersToChangePassword property is set internal bool IsSetAllowUsersToChangePassword() { return this._allowUsersToChangePassword.HasValue; } /// <summary> /// Gets and sets the property ExpirePasswords. /// <para> /// Indicates whether passwords in the account expire. Returns true if MaxPasswordAge /// is contains a value greater than 0. Returns false if MaxPasswordAge is 0 or not present. /// </para> /// </summary> public bool ExpirePasswords { get { return this._expirePasswords.GetValueOrDefault(); } set { this._expirePasswords = value; } } // Check to see if ExpirePasswords property is set internal bool IsSetExpirePasswords() { return this._expirePasswords.HasValue; } /// <summary> /// Gets and sets the property HardExpiry. /// <para> /// Specifies whether IAM users are prevented from setting a new password after their /// password has expired. /// </para> /// </summary> public bool HardExpiry { get { return this._hardExpiry.GetValueOrDefault(); } set { this._hardExpiry = value; } } // Check to see if HardExpiry property is set internal bool IsSetHardExpiry() { return this._hardExpiry.HasValue; } /// <summary> /// Gets and sets the property MaxPasswordAge. /// <para> /// The number of days that an IAM user password is valid. /// </para> /// </summary> public int MaxPasswordAge { get { return this._maxPasswordAge.GetValueOrDefault(); } set { this._maxPasswordAge = value; } } // Check to see if MaxPasswordAge property is set internal bool IsSetMaxPasswordAge() { return this._maxPasswordAge.HasValue; } /// <summary> /// Gets and sets the property MinimumPasswordLength. /// <para> /// Minimum length to require for IAM user passwords. /// </para> /// </summary> public int MinimumPasswordLength { get { return this._minimumPasswordLength.GetValueOrDefault(); } set { this._minimumPasswordLength = value; } } // Check to see if MinimumPasswordLength property is set internal bool IsSetMinimumPasswordLength() { return this._minimumPasswordLength.HasValue; } /// <summary> /// Gets and sets the property PasswordReusePrevention. /// <para> /// Specifies the number of previous passwords that IAM users are prevented from reusing. /// </para> /// </summary> public int PasswordReusePrevention { get { return this._passwordReusePrevention.GetValueOrDefault(); } set { this._passwordReusePrevention = value; } } // Check to see if PasswordReusePrevention property is set internal bool IsSetPasswordReusePrevention() { return this._passwordReusePrevention.HasValue; } /// <summary> /// Gets and sets the property RequireLowercaseCharacters. /// <para> /// Specifies whether to require lowercase characters for IAM user passwords. /// </para> /// </summary> public bool RequireLowercaseCharacters { get { return this._requireLowercaseCharacters.GetValueOrDefault(); } set { this._requireLowercaseCharacters = value; } } // Check to see if RequireLowercaseCharacters property is set internal bool IsSetRequireLowercaseCharacters() { return this._requireLowercaseCharacters.HasValue; } /// <summary> /// Gets and sets the property RequireNumbers. /// <para> /// Specifies whether to require numbers for IAM user passwords. /// </para> /// </summary> public bool RequireNumbers { get { return this._requireNumbers.GetValueOrDefault(); } set { this._requireNumbers = value; } } // Check to see if RequireNumbers property is set internal bool IsSetRequireNumbers() { return this._requireNumbers.HasValue; } /// <summary> /// Gets and sets the property RequireSymbols. /// <para> /// Specifies whether to require symbols for IAM user passwords. /// </para> /// </summary> public bool RequireSymbols { get { return this._requireSymbols.GetValueOrDefault(); } set { this._requireSymbols = value; } } // Check to see if RequireSymbols property is set internal bool IsSetRequireSymbols() { return this._requireSymbols.HasValue; } /// <summary> /// Gets and sets the property RequireUppercaseCharacters. /// <para> /// Specifies whether to require uppercase characters for IAM user passwords. /// </para> /// </summary> public bool RequireUppercaseCharacters { get { return this._requireUppercaseCharacters.GetValueOrDefault(); } set { this._requireUppercaseCharacters = value; } } // Check to see if RequireUppercaseCharacters property is set internal bool IsSetRequireUppercaseCharacters() { return this._requireUppercaseCharacters.HasValue; } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.Project { /// <summary> /// This class handles opening, saving of file items in the hierarchy. /// </summary> [CLSCompliant(false)] public class FileDocumentManager : DocumentManager { #region ctors public FileDocumentManager(FileNode node) : base(node) { } #endregion #region overriden methods /// <summary> /// Open a file using the standard editor /// </summary> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the file</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public override int Open(ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { bool newFile = false; bool openWith = false; return this.Open(newFile, openWith, ref logicalView, docDataExisting, out windowFrame, windowFrameAction); } /// <summary> /// Open a file with a specific editor /// </summary> /// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param> /// <param name="editorType">Unique identifier of the editor type</param> /// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the file</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public override int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { windowFrame = null; bool newFile = false; bool openWith = false; return this.Open(newFile, openWith, editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out windowFrame, windowFrameAction); } #endregion #region public methods /// <summary> /// Open a file in a document window with a std editor /// </summary> /// <param name="newFile">Open the file as a new file</param> /// <param name="openWith">Use a dialog box to determine which editor to use</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public int Open(bool newFile, bool openWith, WindowFrameShowAction windowFrameAction) { Guid logicalView = Guid.Empty; IVsWindowFrame windowFrame = null; return this.Open(newFile, openWith, logicalView, out windowFrame, windowFrameAction); } /// <summary> /// Open a file in a document window with a std editor /// </summary> /// <param name="newFile">Open the file as a new file</param> /// <param name="openWith">Use a dialog box to determine which editor to use</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="frame">A reference to the window frame that is mapped to the file</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public int Open(bool newFile, bool openWith, Guid logicalView, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { frame = null; IVsRunningDocumentTable rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; Debug.Assert(rdt != null, " Could not get running document table from the services exposed by this project"); if(rdt == null) { return VSConstants.E_FAIL; } // First we see if someone else has opened the requested view of the file. _VSRDTFLAGS flags = _VSRDTFLAGS.RDT_NoLock; uint itemid; IntPtr docData = IntPtr.Zero; IVsHierarchy ivsHierarchy; uint docCookie; string path = this.GetFullPathForDocument(); int returnValue = VSConstants.S_OK; try { ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)flags, path, out ivsHierarchy, out itemid, out docData, out docCookie)); ErrorHandler.ThrowOnFailure(this.Open(newFile, openWith, ref logicalView, docData, out frame, windowFrameAction)); } catch(COMException e) { Trace.WriteLine("Exception :" + e.Message); returnValue = e.ErrorCode; } finally { if(docData != IntPtr.Zero) { Marshal.Release(docData); } } return returnValue; } #endregion #region virtual methods /// <summary> /// Open a file in a document window /// </summary> /// <param name="newFile">Open the file as a new file</param> /// <param name="openWith">Use a dialog box to determine which editor to use</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the file</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int Open(bool newFile, bool openWith, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { windowFrame = null; Guid editorType = Guid.Empty; return this.Open(newFile, openWith, 0, ref editorType, null, ref logicalView, docDataExisting, out windowFrame, windowFrameAction); } #endregion #region helper methods private int Open(bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { windowFrame = null; if(this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed) { return VSConstants.E_FAIL; } Debug.Assert(this.Node != null, "No node has been initialized for the document manager"); Debug.Assert(this.Node.ProjectMgr != null, "No project manager has been initialized for the document manager"); Debug.Assert(this.Node is FileNode, "Node is not FileNode object"); int returnValue = VSConstants.S_OK; string caption = this.GetOwnerCaption(); string fullPath = this.GetFullPathForDocument(); // Make sure that the file is on disk before we open the editor and display message if not found if(!((FileNode)this.Node).IsFileOnDisk(true)) { // Inform clients that we have an invalid item (wrong icon) this.Node.OnInvalidateItems(this.Node.Parent); // Bail since we are not able to open the item // Do not return an error code otherwise an internal error message is shown. The scenario for this operation // normally is already a reaction to a dialog box telling that the item has been removed. return VSConstants.S_FALSE; } IVsUIShellOpenDocument uiShellOpenDocument = this.Node.ProjectMgr.Site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IOleServiceProvider serviceProvider = this.Node.ProjectMgr.Site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; try { this.Node.ProjectMgr.OnOpenItem(fullPath); int result = VSConstants.E_FAIL; if(openWith) { result = uiShellOpenDocument.OpenStandardEditor((uint)__VSOSEFLAGS.OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, this.Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } else { __VSOSEFLAGS openFlags = 0; if(newFile) { openFlags |= __VSOSEFLAGS.OSE_OpenAsNewFile; } //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid // of the node being opened, otherwise the debugger doesn't work. if(editorType != Guid.Empty) { result = uiShellOpenDocument.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, this.Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } else { openFlags |= __VSOSEFLAGS.OSE_ChooseBestStdEditor; result = uiShellOpenDocument.OpenStandardEditor((uint)openFlags, fullPath, ref logicalView, caption, this.Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } } if(result != VSConstants.S_OK && result != VSConstants.S_FALSE && result != VSConstants.OLE_E_PROMPTSAVECANCELLED) { ErrorHandler.ThrowOnFailure(result); } if(windowFrame != null) { object var; if(newFile) { ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var)); IVsPersistDocData persistDocData = (IVsPersistDocData)var; ErrorHandler.ThrowOnFailure(persistDocData.SetUntitledDocPath(fullPath)); } var = null; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var)); this.Node.DocCookie = (uint)(int)var; if(windowFrameAction == WindowFrameShowAction.Show) { ErrorHandler.ThrowOnFailure(windowFrame.Show()); } else if(windowFrameAction == WindowFrameShowAction.ShowNoActivate) { ErrorHandler.ThrowOnFailure(windowFrame.ShowNoActivate()); } else if(windowFrameAction == WindowFrameShowAction.Hide) { ErrorHandler.ThrowOnFailure(windowFrame.Hide()); } } } catch(COMException e) { Trace.WriteLine("Exception e:" + e.Message); returnValue = e.ErrorCode; CloseWindowFrame(ref windowFrame); } return returnValue; } #endregion } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; namespace PclUnit.Constraints.Pieces { public delegate void TestDelegate(); #region ThrowsConstraint /// <summary> /// ThrowsConstraint is used to test the exception thrown by /// a delegate by applying a constraint to it. /// </summary> public class ThrowsConstraint : PrefixConstraint { private Exception caughtException; /// <summary> /// Initializes a new instance of the <see cref="T:ThrowsConstraint"/> class, /// using a constraint to be applied to the exception. /// </summary> /// <param name="baseConstraint">A constraint to apply to the caught exception.</param> public ThrowsConstraint(Constraint baseConstraint) : base(baseConstraint) { } /// <summary> /// Get the actual exception thrown - used by Assert.Throws. /// </summary> public Exception ActualException { get { return caughtException; } } #region Constraint Overrides /// <summary> /// Executes the code of the delegate and captures any exception. /// If a non-null base constraint was provided, it applies that /// constraint to the exception. /// </summary> /// <param name="actual">A delegate representing the code to be tested</param> /// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns> public override bool Matches(object actual) { TestDelegate code = actual as TestDelegate; if (code == null) throw new ArgumentException( string.Format("The actual value must be a TestDelegate but was {0}",actual.GetType().Name), "actual"); this.caughtException = null; try { code(); } catch (Exception ex) { this.caughtException = ex; } if (this.caughtException == null) return false; return baseConstraint == null || baseConstraint.Matches(caughtException); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Converts an ActualValueDelegate to a TestDelegate /// before calling the primary overload. /// </summary> /// <param name="del"></param> /// <returns></returns> public override bool Matches(ActualValueDelegate del) { TestDelegate testDelegate = new TestDelegate(delegate { del(); }); return Matches((object)testDelegate); } #endif /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo(MessageWriter writer) { if (baseConstraint == null) writer.WritePredicate("an exception"); else baseConstraint.WriteDescriptionTo(writer); } /// <summary> /// Write the actual value for a failing constraint test to a /// MessageWriter. The default implementation simply writes /// the raw value of actual, leaving it to the writer to /// perform any formatting. /// </summary> /// <param name="writer">The writer on which the actual value is displayed</param> public override void WriteActualValueTo(MessageWriter writer) { if (caughtException == null) writer.Write("no exception thrown"); else if (baseConstraint != null) baseConstraint.WriteActualValueTo(writer); else writer.WriteActualValue(caughtException); } #endregion /// <summary> /// Returns the string representation of this constraint /// </summary> protected override string GetStringRepresentation() { if (baseConstraint == null) return "<throws>"; return base.GetStringRepresentation(); } } #endregion #region ThrowsNothingConstraint /// <summary> /// ThrowsNothingConstraint tests that a delegate does not /// throw an exception. /// </summary> public class ThrowsNothingConstraint : Constraint { private Exception caughtException; /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True if no exception is thrown, otherwise false</returns> public override bool Matches(object actual) { TestDelegate code = actual as TestDelegate; if (code == null) throw new ArgumentException("The actual value must be a TestDelegate", "actual"); this.caughtException = null; try { code(); } catch (Exception ex) { this.caughtException = ex; } return this.caughtException == null; } #if CLR_2_0 || CLR_4_0 /// <summary> /// Converts an ActualValueDelegate to a TestDelegate /// before calling the primary overload. /// </summary> /// <param name="del"></param> /// <returns></returns> public override bool Matches(ActualValueDelegate del) { TestDelegate testDelegate = new TestDelegate(delegate { del(); }); return Matches((object)testDelegate); } #endif /// <summary> /// Write the constraint description to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> public override void WriteDescriptionTo(MessageWriter writer) { writer.Write(string.Format("No Exception to be thrown")); } /// <summary> /// Write the actual value for a failing constraint test to a /// MessageWriter. The default implementation simply writes /// the raw value of actual, leaving it to the writer to /// perform any formatting. /// </summary> /// <param name="writer">The writer on which the actual value is displayed</param> public override void WriteActualValueTo(MessageWriter writer) { writer.WriteLine(" ({0})", caughtException.Message); writer.Write(caughtException.StackTrace); } } #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; using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Collections.Concurrent; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.CustomAttributes; using Internal.LowLevelLinq; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; using CharSet = System.Runtime.InteropServices.CharSet; using LayoutKind = System.Runtime.InteropServices.LayoutKind; using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute; namespace System.Reflection.Runtime.TypeInfos { // // TypeInfos that represent type definitions (i.e. Foo or Foo<>, but not Foo<int> or arrays/pointers/byrefs.) // // internal abstract partial class RuntimeNamedTypeInfo : RuntimeTypeDefinitionTypeInfo, IEquatable<RuntimeNamedTypeInfo> { protected RuntimeNamedTypeInfo(RuntimeTypeHandle typeHandle) { _typeHandle = typeHandle; } public sealed override bool ContainsGenericParameters { get { return IsGenericTypeDefinition; } } public bool Equals(RuntimeNamedTypeInfo other) { // RuntimeTypeInfo.Equals(object) is the one that encapsulates our unification strategy so defer to him. object otherAsObject = other; return base.Equals(otherAsObject); } /// <summary> /// Override this function to read the Guid attribute from a type's metadata. If the attribute /// is not present, or isn't parseable, return null. Should be overriden by metadata specific logic /// </summary> protected abstract Guid? ComputeGuidFromCustomAttributes(); public sealed override Guid GUID { get { Guid? guidFromAttributes = ComputeGuidFromCustomAttributes(); if (guidFromAttributes.HasValue) return guidFromAttributes.Value; // // If we got here, there was no [Guid] attribute. // // Ideally, we'd now compute the same GUID the desktop returns - however, that algorithm is complex and has questionable dependencies // (in particular, the GUID changes if the language compilers ever change the way it emits metadata tokens into certain unordered lists. // We don't even retain that order across the Project N toolchain.) // // For now, this is a compromise that satisfies our app-compat goals. We ensure that each unique Type receives a different GUID (at least one app // uses the GUID as a dictionary key to look up types.) It will not be the same GUID on multiple runs of the app but so far, there's // no evidence that's needed. // return s_namedTypeToGuidTable.GetOrAdd(this).Item1; } } public sealed override string FullName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_FullName(this); #endif Debug.Assert(!IsConstructedGenericType); Debug.Assert(!IsGenericParameter); Debug.Assert(!HasElementType); string name = Name; Type declaringType = this.DeclaringType; if (declaringType != null) { string declaringTypeFullName = declaringType.FullName; return declaringTypeFullName + "+" + name; } string ns = Namespace; if (ns == null) return name; return ns + "." + name; } } protected abstract void GetPackSizeAndSize(out int packSize, out int size); public sealed override StructLayoutAttribute StructLayoutAttribute { get { const int DefaultPackingSize = 8; // Note: CoreClr checks HasElementType and IsGenericParameter in addition to IsInterface but those properties cannot be true here as this // RuntimeTypeInfo subclass is solely for TypeDef types.) if (IsInterface) return null; TypeAttributes attributes = Attributes; LayoutKind layoutKind; switch (attributes & TypeAttributes.LayoutMask) { case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break; case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break; case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; default: layoutKind = LayoutKind.Auto; break; } CharSet charSet; switch (attributes & TypeAttributes.StringFormatMask) { case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break; case TypeAttributes.AutoClass: charSet = CharSet.Auto; break; case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; default: charSet = CharSet.None; break; } int pack; int size; GetPackSizeAndSize(out pack, out size); // Metadata parameter checking should not have allowed 0 for packing size. // The runtime later converts a packing size of 0 to 8 so do the same here // because it's more useful from a user perspective. if (pack == 0) pack = DefaultPackingSize; return new StructLayoutAttribute(layoutKind) { CharSet = charSet, Pack = pack, Size = size, }; } } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // baseclass and interfaces based on its constraints. // internal sealed override RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { return this; } } internal sealed override bool CanBrowseWithoutMissingMetadataExceptions => true; internal sealed override RuntimeTypeHandle InternalTypeHandleIfAvailable { get { return _typeHandle; } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal sealed override TypeContext TypeContext { get { return new TypeContext(this.RuntimeGenericTypeParameters, null); } } #if ENABLE_REFLECTION_TRACE internal abstract string TraceableTypeName { get; } #endif /// <summary> /// QTypeDefRefOrSpec handle that can be used to re-acquire this type. Must be implemented /// for all metadata sourced type implementations. /// </summary> internal abstract QTypeDefRefOrSpec TypeDefinitionQHandle { get; } private readonly RuntimeTypeHandle _typeHandle; private static readonly NamedTypeToGuidTable s_namedTypeToGuidTable = new NamedTypeToGuidTable(); private sealed class NamedTypeToGuidTable : ConcurrentUnifier<RuntimeNamedTypeInfo, Tuple<Guid>> { protected sealed override Tuple<Guid> Factory(RuntimeNamedTypeInfo key) { return new Tuple<Guid>(Guid.NewGuid()); } } } }
// 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. using System; using System.Diagnostics.Contracts; using Microsoft.SpecSharp.Collections; namespace System { public class Array { public int Rank { [Pure][Reads(ReadsAttribute.Reads.Nothing)] get; } public bool IsReadOnly { [Pure][Reads(ReadsAttribute.Reads.Nothing)] get; } public object SyncRoot { get; } public bool IsSynchronized { [Pure][Reads(ReadsAttribute.Reads.Nothing)] get; } public bool IsFixedSize { [Pure][Reads(ReadsAttribute.Reads.Nothing)] get; } public int Length { [Pure][Reads(ReadsAttribute.Reads.Nothing)] get; CodeContract.Ensures(0 <= result && result <= int.MaxValue); } public long LongLength { [Pure][Reads(ReadsAttribute.Reads.Nothing)] get; CodeContract.Ensures(0 <= result && result <= long.MaxValue); } public void Initialize () { } public static void Sort (Array! keys, Array items, int index, int length, System.Collections.IComparer comparer) { CodeContract.Requires(keys != null); CodeContract.Requires(keys.Rank == 1); CodeContract.Requires(items == null || items.Rank == 1); CodeContract.Requires(items == null || keys.GetLowerBound(0) == items.GetLowerBound(0)); CodeContract.Requires(index >= keys.GetLowerBound(0)); CodeContract.Requires(length >= 0); CodeContract.Requires(keys.GetLowerBound(0) + index + length <= keys.Length); CodeContract.Requires(items == null || index + length <= items.Length); } public static void Sort (Array array, int index, int length, System.Collections.IComparer comparer) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(index >= array.GetLowerBound(0)); CodeContract.Requires(length >= 0); CodeContract.Requires(array.GetLowerBound(0) + index + length <= array.Length); } public static void Sort (Array! keys, Array items, System.Collections.IComparer comparer) { CodeContract.Requires(keys != null); CodeContract.Requires(keys.Rank == 1); CodeContract.Requires(items == null || items.Rank == 1); CodeContract.Requires(items == null || keys.GetLowerBound(0) == items.GetLowerBound(0)); } public static void Sort (Array! array, System.Collections.IComparer comparer) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); } public static void Sort (Array keys, Array items, int index, int length) { CodeContract.Requires(keys != null); CodeContract.Requires(keys.Rank == 1); CodeContract.Requires(items == null || items.Rank == 1); CodeContract.Requires(items == null || keys.GetLowerBound(0) == items.GetLowerBound(0)); CodeContract.Requires(index >= keys.GetLowerBound(0)); CodeContract.Requires(length >= 0); CodeContract.Requires(keys.GetLowerBound(0) + index + length <= keys.Length); CodeContract.Requires(items == null || index + length <= items.Length); } public static void Sort (Array array, int index, int length) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(index >= array.GetLowerBound(0)); CodeContract.Requires(length >= 0); CodeContract.Requires(array.GetLowerBound(0) + index + length <= array.Length); } public static void Sort (Array! keys, Array items) { CodeContract.Requires(keys != null); CodeContract.Requires(keys.Rank == 1); CodeContract.Requires(items == null || items.Rank == 1); CodeContract.Requires(items == null || keys.GetLowerBound(0) == items.GetLowerBound(0)); } public static void Sort (Array! array) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); } public static void Reverse (Array! array, int index, int length) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(length >= 0); CodeContract.Requires(index >= array.GetLowerBound(0)); CodeContract.Requires(array.GetLowerBound(0) + index + length <= array.Length); } public static void Reverse (Array! array) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); } public static int LastIndexOf (Array! array, object value, int startIndex, int count) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(count >= 0); CodeContract.Requires(count <= startIndex - array.GetLowerBound(0) + 1); CodeContract.Requires(startIndex >= array.GetLowerBound(0)); CodeContract.Requires(startIndex < array.Length + array.GetLowerBound(0)); CodeContract.Ensures(result == array.GetLowerBound(0)-1 || (startIndex+1 - count <= result && result <= startIndex)); return default(int); } public static int LastIndexOf (Array! array, object value, int startIndex) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(startIndex >= array.GetLowerBound(0)); CodeContract.Requires(startIndex < array.Length + array.GetLowerBound(0)); CodeContract.Ensures(array.GetLowerBound(0)-1 <= result && result <= startIndex); return default(int); } public static int LastIndexOf (Array! array, object value) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Ensures(array.GetLowerBound(0)-1 <= result && result <= array.GetUpperBound(0)); return default(int); } public static int IndexOf (Array! array, object value, int startIndex, int count) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(startIndex >= array.GetLowerBound(0)); CodeContract.Requires(startIndex <= array.GetLowerBound(0) + array.Length); CodeContract.Requires(count >= 0); CodeContract.Requires(startIndex + count <= array.GetLowerBound(0) + array.Length); CodeContract.Ensures(result == array.GetLowerBound(0)-1 || (startIndex <= result && result < startIndex + count)); return default(int); } public static int IndexOf (Array! array, object value, int startIndex) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(startIndex >= array.GetLowerBound(0)); CodeContract.Requires(startIndex <= array.GetLowerBound(0) + array.Length); CodeContract.Ensures(result == array.GetLowerBound(0)-1 || (startIndex <= result && result <= array.GetUpperBound(0))); return default(int); } public static int IndexOf (Array! array, object value) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Ensures(array.GetLowerBound(0)-1 <= result && result <= array.GetUpperBound(0)); return default(int); } [Pure] [GlobalAccess(false)] [Escapes(true,false)] public System.Collections.IEnumerator GetEnumerator () { CodeContract.Ensures(result.IsNew); CodeContract.Ensures(CodeContract.Result<System.Collections.IEnumerator>() != null); return default(System.Collections.IEnumerator); } public void CopyTo (Array! array, long index) { CodeContract.Requires(array != null); CodeContract.Requires(array.GetLowerBound(0) <= index); CodeContract.Requires(this.Rank == 1); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(this.Length <= array.GetUpperBound(0) + 1 - index); modifies this.0, array.*; } public void CopyTo (Array! array, int index) { CodeContract.Requires(array != null); CodeContract.Requires(array.GetLowerBound(0) <= index); CodeContract.Requires(this.Rank == 1); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(this.Length <= array.GetUpperBound(0) + 1 - index); modifies this.0, array.*; } public static int BinarySearch (Array! array, int index, int length, object value, System.Collections.IComparer comparer) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(index >= array.GetLowerBound(0)); CodeContract.Requires(length >= 0); CodeContract.Requires(length <= array.Length - index); CodeContract.Ensures(result == array.GetLowerBound(0)-1 || (index <= result && result < index + length)); return default(int); } public static int BinarySearch (Array! array, object value, System.Collections.IComparer comparer) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Ensures(array.GetLowerBound(0)-1 <= result && result <= array.GetUpperBound(0)); return default(int); } public static int BinarySearch (Array array, int index, int length, object value) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(index >= array.GetLowerBound(0)); CodeContract.Requires(length >= 0); CodeContract.Requires(length <= array.Length - index); CodeContract.Ensures(result == array.GetLowerBound(0)-1 || (index <= result && result < index + length)); return default(int); } public static int BinarySearch (Array! array, object value) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Ensures(array.GetLowerBound(0)-1 <= result && result <= array.GetUpperBound(0)); return default(int); } [Pure] public object Clone () { CodeContract.Ensures(result.GetType() == this.GetType()); CodeContract.Ensures(Owner.New(result)); CodeContract.Ensures(CodeContract.Result<object>() != null); return default(object); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public int GetLowerBound (int arg0) { return default(int); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public int GetUpperBound (int arg0) { return default(int); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public long GetLongLength (int dimension) { return default(long); } [Pure][Reads(ReadsAttribute.Reads.Nothing)] public int GetLength (int arg0) { return default(int); } public void SetValue (object value, long[] indices) { } public void SetValue (object value, long index1, long index2, long index3) { CodeContract.Requires(index1 <= 2147483647); CodeContract.Requires(index1 >= -2147483648); CodeContract.Requires(index2 <= 2147483647); CodeContract.Requires(index2 >= -2147483648); CodeContract.Requires(index3 <= 2147483647); CodeContract.Requires(index3 >= -2147483648); CodeContract.Requires(this.Rank == 3); CodeContract.Requires(index1 >= this.GetLowerBound(0)); CodeContract.Requires(index1 <= this.GetUpperBound(0)); CodeContract.Requires(index2 >= this.GetLowerBound(0)); CodeContract.Requires(index2 <= this.GetUpperBound(0)); CodeContract.Requires(index3 >= this.GetLowerBound(0)); CodeContract.Requires(index3 <= this.GetUpperBound(0)); } public void SetValue (object value, long index1, long index2) { CodeContract.Requires(index1 <= 2147483647); CodeContract.Requires(index1 >= -2147483648); CodeContract.Requires(index2 <= 2147483647); CodeContract.Requires(index2 >= -2147483648); CodeContract.Requires(this.Rank == 2); CodeContract.Requires(index1 >= this.GetLowerBound(0)); CodeContract.Requires(index1 <= this.GetUpperBound(0)); CodeContract.Requires(index2 >= this.GetLowerBound(0)); CodeContract.Requires(index2 <= this.GetUpperBound(0)); } public void SetValue (object value, long index) { CodeContract.Requires(index <= 2147483647); CodeContract.Requires(index >= -2147483648); CodeContract.Requires(this.Rank == 1); CodeContract.Requires(index >= this.GetLowerBound(0)); CodeContract.Requires(index <= this.GetUpperBound(0)); } public void SetValue (object value, int[]! indices) { CodeContract.Requires(indices != null); //CodeContract.Requires(Forall { int i in indices; this.GetLowerBound(i) <= indices[i] && indices[i] <= this.GetUpperBound(i) }); } public void SetValue (object value, int index1, int index2, int index3) { CodeContract.Requires(this.Rank == 3); CodeContract.Requires(index1 >= this.GetLowerBound(0)); CodeContract.Requires(index1 <= this.GetUpperBound(0)); CodeContract.Requires(index2 >= this.GetLowerBound(0)); CodeContract.Requires(index2 <= this.GetUpperBound(0)); CodeContract.Requires(index3 >= this.GetLowerBound(0)); CodeContract.Requires(index3 <= this.GetUpperBound(0)); } public void SetValue (object value, int index1, int index2) { CodeContract.Requires(this.Rank == 2); CodeContract.Requires(index1 >= this.GetLowerBound(0)); CodeContract.Requires(index1 <= this.GetUpperBound(0)); CodeContract.Requires(index2 >= this.GetLowerBound(0)); CodeContract.Requires(index2 <= this.GetUpperBound(0)); } public void SetValue (object value, int index) { CodeContract.Requires(this.Rank == 1); CodeContract.Requires(index >= this.GetLowerBound(0)); CodeContract.Requires(index <= this.GetUpperBound(0)); } public object GetValue (long[] indices) { return default(object); } public object GetValue (long index1, long index2, long index3) { CodeContract.Requires(index1 <= 2147483647); CodeContract.Requires(index1 >= -2147483648); CodeContract.Requires(index2 <= 2147483647); CodeContract.Requires(index2 >= -2147483648); CodeContract.Requires(index3 <= 2147483647); CodeContract.Requires(index3 >= -2147483648); CodeContract.Requires(this.Rank == 3); CodeContract.Requires(index1 >= this.GetLowerBound(0)); CodeContract.Requires(index1 <= this.GetUpperBound(0)); CodeContract.Requires(index2 >= this.GetLowerBound(0)); CodeContract.Requires(index2 <= this.GetUpperBound(0)); CodeContract.Requires(index3 >= this.GetLowerBound(0)); CodeContract.Requires(index3 <= this.GetUpperBound(0)); return default(object); } public object GetValue (long index1, long index2) { CodeContract.Requires(index1 <= 2147483647); CodeContract.Requires(index1 >= -2147483648); CodeContract.Requires(index2 <= 2147483647); CodeContract.Requires(index2 >= -2147483648); CodeContract.Requires(this.Rank == 2); CodeContract.Requires(index1 >= this.GetLowerBound(0)); CodeContract.Requires(index1 <= this.GetUpperBound(0)); CodeContract.Requires(index2 >= this.GetLowerBound(0)); CodeContract.Requires(index2 <= this.GetUpperBound(0)); return default(object); } public object GetValue (long index) { CodeContract.Requires(index <= 2147483647); CodeContract.Requires(index >= -2147483648); CodeContract.Requires(this.Rank == 1); CodeContract.Requires(index >= this.GetLowerBound(0)); CodeContract.Requires(index <= this.GetUpperBound(0)); return default(object); } public object GetValue (int index1, int index2, int index3) { CodeContract.Requires(this.Rank == 3); CodeContract.Requires(index1 >= this.GetLowerBound(0)); CodeContract.Requires(index1 <= this.GetUpperBound(0)); CodeContract.Requires(index2 >= this.GetLowerBound(0)); CodeContract.Requires(index2 <= this.GetUpperBound(0)); CodeContract.Requires(index3 >= this.GetLowerBound(0)); CodeContract.Requires(index3 <= this.GetUpperBound(0)); return default(object); } public object GetValue (int index1, int index2) { CodeContract.Requires(this.Rank == 2); CodeContract.Requires(index1 >= this.GetLowerBound(0)); CodeContract.Requires(index1 <= this.GetUpperBound(0)); CodeContract.Requires(index2 >= this.GetLowerBound(0)); CodeContract.Requires(index2 <= this.GetUpperBound(0)); return default(object); } public object GetValue (int index) { CodeContract.Requires(this.Rank == 1); CodeContract.Requires(index >= this.GetLowerBound(0)); CodeContract.Requires(index <= this.GetUpperBound(0)); return default(object); } public object GetValue (int[]! indices) { CodeContract.Requires(indices != null); return default(object); } public static void Clear (Array! array, int index, int length) { CodeContract.Requires(array != null); CodeContract.Requires(array.Rank == 1); CodeContract.Requires(index >= array.GetLowerBound(0)); CodeContract.Requires(length >= 0); CodeContract.Requires(array.Length - (index + array.GetLowerBound(0)) >= length); } public static void Copy (Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length) { CodeContract.Requires(sourceArray != null); CodeContract.Requires(destinationArray != null); CodeContract.Requires(sourceArray.Rank == destinationArray.Rank); CodeContract.Requires(sourceIndex >= sourceArray.GetLowerBound(0)); CodeContract.Requires(destinationIndex >= destinationArray.GetLowerBound(0)); CodeContract.Requires(length >= 0); CodeContract.Requires(sourceIndex + length <= sourceArray.GetLowerBound(0) + sourceArray.Length); CodeContract.Requires(destinationIndex + length <= destinationArray.GetLowerBound(0) + destinationArray.Length); CodeContract.Requires(sourceIndex <= 2147483647); CodeContract.Requires(sourceIndex >= -2147483648); CodeContract.Requires(destinationIndex <= 2147483647); CodeContract.Requires(destinationIndex >= -2147483648); CodeContract.Requires(length <= 2147483647); CodeContract.Requires(length >= -2147483648); modifies destinationArray.*; } public static void Copy (Array sourceArray, Array destinationArray, long length) { CodeContract.Requires(sourceArray != null); CodeContract.Requires(destinationArray != null); CodeContract.Requires(sourceArray.Rank == destinationArray.Rank); CodeContract.Requires(sourceArray.Rank == destinationArray.Rank); CodeContract.Requires(length >= 0); CodeContract.Requires(length <= sourceArray.GetLowerBound(0) + sourceArray.Length); CodeContract.Requires(length <= destinationArray.GetLowerBound(0) + destinationArray.Length); CodeContract.Requires(length <= 2147483647); CodeContract.Requires(length >= -2147483648); modifies destinationArray.*; } public static void Copy (Array! sourceArray, int sourceIndex, Array! destinationArray, int destinationIndex, int length) { CodeContract.Requires(sourceArray != null); CodeContract.Requires(destinationArray != null); CodeContract.Requires(sourceArray.Rank == destinationArray.Rank); CodeContract.Requires(sourceIndex >= sourceArray.GetLowerBound(0)); CodeContract.Requires(destinationIndex >= destinationArray.GetLowerBound(0)); CodeContract.Requires(length >= 0); CodeContract.Requires(sourceIndex + length <= sourceArray.GetLowerBound(0) + sourceArray.Length); CodeContract.Requires(destinationIndex + length <= destinationArray.GetLowerBound(0) + destinationArray.Length); modifies destinationArray.*; } public static void Copy (Array! sourceArray, Array! destinationArray, int length) { CodeContract.Requires(sourceArray != null); CodeContract.Requires(destinationArray != null); CodeContract.Requires(sourceArray.Rank == destinationArray.Rank); CodeContract.Requires(sourceArray.Rank == destinationArray.Rank); CodeContract.Requires(length >= 0); CodeContract.Requires(length <= sourceArray.GetLowerBound(0) + sourceArray.Length); CodeContract.Requires(length <= destinationArray.GetLowerBound(0) + destinationArray.Length); modifies destinationArray.*; } public static Array CreateInstance (Type! elementType, int[]! lengths, int[]! lowerBounds) { CodeContract.Requires(elementType != null); CodeContract.Requires(lengths != null); CodeContract.Requires(lowerBounds != null); CodeContract.Requires(lengths.Length == lowerBounds.Length); CodeContract.Requires(lengths.Length != 0); CodeContract.Ensures(CodeContract.Result<Array>() != null); return default(Array); } public static Array CreateInstance (Type! elementType, long[]! lengths) { CodeContract.Requires(elementType != null); CodeContract.Requires(lengths != null); CodeContract.Requires(lengths.Length > 0); // CodeContract.Requires(Forall { int i in lengths; lengths[i] >= 0; }); CodeContract.Ensures(result.Rank == lengths.Length); // CodeContract.Ensures(Forall { int i in lengths); result.GetLength(i) == length[i]); } CodeContract.Ensures(CodeContract.Result<Array>() != null); return default(Array); } public static Array CreateInstance (Type! elementType, int[]! lengths) { CodeContract.Requires(elementType != null); CodeContract.Requires(lengths != null); CodeContract.Requires(lengths.Length > 0); // CodeContract.Requires(Forall { int i in lengths; lengths[i] >= 0; }); CodeContract.Ensures(result.Rank == lengths.Length); // CodeContract.Ensures(Forall { int i in lengths); result.GetLength(i) == length[i]); } CodeContract.Ensures(CodeContract.Result<Array>() != null); return default(Array); } public static Array CreateInstance (Type! elementType, int length1, int length2, int length3) { CodeContract.Requires(elementType != null); CodeContract.Requires(length1 >= 0); CodeContract.Requires(length2 >= 0); CodeContract.Requires(length3 >= 0); CodeContract.Ensures(result.Rank == 3); CodeContract.Ensures(result.GetLength(0) == length1 && result.GetLength(1) == length2 && result.GetLength(2) == length3); CodeContract.Ensures(CodeContract.Result<Array>() != null); return default(Array); } public static Array CreateInstance (Type! elementType, int length1, int length2) { CodeContract.Requires(elementType != null); CodeContract.Requires(length1 >= 0); CodeContract.Requires(length2 >= 0); CodeContract.Ensures(result.Rank == 2); CodeContract.Ensures(result.GetLength(0) == length1 && result.GetLength(1) == length2); CodeContract.Ensures(CodeContract.Result<Array>() != null); return default(Array); } public static Array CreateInstance (Type! elementType, int length) { CodeContract.Requires(elementType != null); CodeContract.Requires(length >= 0); CodeContract.Ensures(result.Rank == 1); CodeContract.Ensures(result.GetLength(0) == length); CodeContract.Ensures(CodeContract.Result<Array>() != null); return default(Array); } } }
// ----- // Copyright 2010 Deyan Timnev // This file is part of the Matrix Platform (www.matrixplatform.com). // The Matrix Platform is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. The Matrix Platform is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public License along with the Matrix Platform. If not, see http://www.gnu.org/licenses/lgpl.html // ----- using System; using System.Collections.Generic; using System.IO; namespace Matrix.Common.Core.Serialization { /// <summary> /// Helper class to contain and make easier access to serialization data of all serializable types. /// Extended version of the System SerializationInfo class. /// </summary> [Serializable] public class SerializationInfoEx { readonly Dictionary<string, object> _objects = new Dictionary<string, object>(); public object this[string name] { get { lock (this) { object value; if (_objects.TryGetValue(name, out value)) { return value; } return null; } } set { lock (this) { _objects[name] = value; } } } /// <summary> /// Default constructor. /// </summary> public SerializationInfoEx() { } /// <summary> /// Deserialize data from stream. /// </summary> public SerializationInfoEx(MemoryStream stream) { object value; if (SerializationHelper.Deserialize(stream, out value).IsSuccess) { _objects = (Dictionary<string, object>)value; } } /// <summary> /// Clear persisted data. /// </summary> public void Clear() { lock (this) { _objects.Clear(); } } /// <summary> /// Clear persisted data by part (or all) of name. /// </summary> public void ClearByNamePart(string namePart) { lock (this) { foreach (string pairName in CommonHelper.EnumerableToArray(_objects.Keys)) { if (pairName.Contains(namePart)) { _objects.Remove(pairName); } } } } /// <summary> /// Delete the value with the given name. /// </summary> /// <param name="name"></param> public bool DeleteValue(string name) { lock (this) { return _objects.Remove(name); } } /// <summary> /// Convert persisted data to stream. /// </summary> /// <returns></returns> public MemoryStream ToStream() { lock (this) { MemoryStream stream = new MemoryStream(); SerializationHelper.Serialize(stream, _objects); return stream; } } /// <summary> /// Add new value to the list of persisted values. /// </summary> /// <param name="name"></param> /// <param name="value"></param> public void AddValue(string name, object value) { lock (this) { _objects[name] = value; } } /// <summary> /// Read string value. /// </summary> /// <param name="name"></param> /// <returns></returns> public string GetString(string name) { return GetValue<string>(name); } /// <summary> /// Read an int value. /// </summary> /// <param name="name"></param> /// <returns></returns> public int GetInt32(string name) { return GetValue<Int32>(name); } /// <summary> /// Read a single value. /// </summary> /// <param name="name"></param> /// <returns></returns> public Single GetSingle(string name) { return GetValue<Single>(name); } /// <summary> /// Read a boolean value. /// </summary> /// <param name="name"></param> /// <returns></returns> public bool GetBoolean(string name) { return GetValue<bool>(name); } /// <summary> /// Obtain a serialized value with the type T and name. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> public T GetValue<T>(string name) { lock (this) { return (T)_objects[name]; } } /// <summary> /// /// </summary> public bool TryGetValue<T>(string name, ref T value) { lock (this) { if (_objects.ContainsKey(name)) { value = (T)_objects[name]; return true; } else { return false; } } } /// <summary> /// If value is not present, create a new instance and return it. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> public T GetValueOrNew<T>(string name) where T : new() { lock (this) { if (ContainsValue(name)) { return (T)_objects[name]; } else { return new T(); } } } /// <summary> /// Helper, redefine of ContainsValue(). /// </summary> /// <param name="name"></param> /// <returns></returns> public bool HasValue(string name) { return ContainsValue(name); } /// <summary> /// Check if a value with this name is contained in the list of serialized values. /// </summary> public bool ContainsValue(string name) { lock (this) { return _objects.ContainsKey(name); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Language; // ReSharper disable UnusedMember.Local namespace System.Management.Automation { using Dbg = Diagnostics; using System.Collections.ObjectModel; internal static class VariableOps { internal static object SetVariableValue(VariablePath variablePath, object value, ExecutionContext executionContext, AttributeBaseAst[] attributeAsts) { SessionStateInternal sessionState = executionContext.EngineSessionState; CommandOrigin origin = sessionState.CurrentScope.ScopeOrigin; if (!variablePath.IsVariable) { sessionState.SetVariable(variablePath, value, true, origin); return value; } // Variable assignment is traced only if trace level 2 is specified. if (executionContext.PSDebugTraceLevel > 1) { executionContext.Debugger.TraceVariableSet(variablePath.UnqualifiedPath, value); } if (variablePath.IsUnscopedVariable) { variablePath = variablePath.CloneAndSetLocal(); } SessionStateScope scope; PSVariable var = sessionState.GetVariableItem(variablePath, out scope, origin); if (var == null) { var attributes = attributeAsts == null ? new Collection<Attribute>() : GetAttributeCollection(attributeAsts); var = new PSVariable(variablePath.UnqualifiedPath, value, ScopedItemOptions.None, attributes); // Marking untrusted values for assignments in 'ConstrainedLanguage' mode is done in // SessionStateScope.SetVariable. sessionState.SetVariable(variablePath, var, false, origin); if (executionContext._debuggingMode > 0) { executionContext.Debugger.CheckVariableWrite(variablePath.UnqualifiedPath); } } else { if (attributeAsts != null) { // Use bytewise operation directly instead of 'var.IsReadOnly || var.IsConstant' on // a hot path (setting variable with type constraint) to get better performance. if ((var.Options & (ScopedItemOptions.ReadOnly | ScopedItemOptions.Constant)) != ScopedItemOptions.None) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( var.Name, SessionStateCategory.Variable, "VariableNotWritable", SessionStateStrings.VariableNotWritable); throw e; } var attributes = GetAttributeCollection(attributeAsts); value = PSVariable.TransformValue(attributes, value); if (!PSVariable.IsValidValue(attributes, value)) { ValidationMetadataException e = new ValidationMetadataException( "ValidateSetFailure", null, Metadata.InvalidValueFailure, var.Name, ((value != null) ? value.ToString() : "$null")); throw e; } var.SetValueRaw(value, true); // Don't update the PSVariable's attributes until we successfully set the value var.Attributes.Clear(); var.AddParameterAttributesNoChecks(attributes); if (executionContext._debuggingMode > 0) { executionContext.Debugger.CheckVariableWrite(variablePath.UnqualifiedPath); } } else { // The setter will handle checking for variable writes. var.Value = value; } if (executionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) { // Mark untrusted values for assignments to 'Global:' variables, and 'Script:' variables in // a module scope, if it's necessary. ExecutionContext.MarkObjectAsUntrustedForVariableAssignment(var, scope, sessionState); } } return value; } private static bool ThrowStrictModeUndefinedVariable(ExecutionContext executionContext, VariableExpressionAst varAst) { // In some limited cases, the compiler knows we don't want an error, like when we're backing up // $foreach and $switch, which might not be set. In that case, the ast passed is null. if (varAst == null) { return false; } if (executionContext.IsStrictVersion(2)) { return true; } if (executionContext.IsStrictVersion(1)) { var parent = varAst.Parent; while (parent != null) { if (parent is ExpandableStringExpressionAst) { return false; } parent = parent.Parent; } return true; } return false; } internal static object GetAutomaticVariableValue(int tupleIndex, ExecutionContext executionContext, VariableExpressionAst varAst) { Diagnostics.Assert(tupleIndex < SpecialVariables.AutomaticVariableTypes.Length, "caller to verify a valid tuple index is used"); if (executionContext._debuggingMode > 0) { executionContext.Debugger.CheckVariableRead(SpecialVariables.AutomaticVariables[tupleIndex]); } object result = executionContext.EngineSessionState.GetAutomaticVariableValue((AutomaticVariable)tupleIndex); if (result == AutomationNull.Value) { if (ThrowStrictModeUndefinedVariable(executionContext, varAst)) { throw InterpreterError.NewInterpreterException(SpecialVariables.AutomaticVariables[tupleIndex], typeof(RuntimeException), varAst.Extent, "VariableIsUndefined", ParserStrings.VariableIsUndefined, SpecialVariables.AutomaticVariables[tupleIndex]); } result = null; } return result; } internal static object GetVariableValue(VariablePath variablePath, ExecutionContext executionContext, VariableExpressionAst varAst) { if (!variablePath.IsVariable) { CmdletProviderContext contextOut; SessionStateScope scopeOut; SessionStateInternal ss = executionContext.EngineSessionState; return ss.GetVariableValueFromProvider(variablePath, out contextOut, out scopeOut, ss.CurrentScope.ScopeOrigin); } SessionStateInternal sessionState = executionContext.EngineSessionState; CommandOrigin origin = sessionState.CurrentScope.ScopeOrigin; SessionStateScope scope; PSVariable var = sessionState.GetVariableItem(variablePath, out scope, origin); if (var != null) { return var.Value; } if (sessionState.ExecutionContext._debuggingMode > 0) { sessionState.ExecutionContext.Debugger.CheckVariableRead(variablePath.UnqualifiedPath); } if (ThrowStrictModeUndefinedVariable(executionContext, varAst)) { throw InterpreterError.NewInterpreterException(variablePath.UserPath, typeof(RuntimeException), varAst.Extent, "VariableIsUndefined", ParserStrings.VariableIsUndefined, variablePath.UserPath); } return null; } internal static PSReference GetVariableAsRef(VariablePath variablePath, ExecutionContext executionContext, Type staticType) { Diagnostics.Assert(variablePath.IsVariable, "calller to verify varpath is a variable."); SessionStateInternal sessionState = executionContext.EngineSessionState; CommandOrigin origin = sessionState.CurrentScope.ScopeOrigin; SessionStateScope scope; PSVariable var = sessionState.GetVariableItem(variablePath, out scope, origin); if (var == null) { throw InterpreterError.NewInterpreterException(variablePath, typeof(RuntimeException), null, "NonExistingVariableReference", ParserStrings.NonExistingVariableReference); } object value = var.Value; if (staticType == null && value != null) { value = PSObject.Base(value); if (value != null) { staticType = value.GetType(); } } if (staticType == null) { var declaredType = var.Attributes.OfType<ArgumentTypeConverterAttribute>().FirstOrDefault(); staticType = declaredType != null ? declaredType.TargetType : typeof(LanguagePrimitives.Null); } return PSReference.CreateInstance(var, staticType); } private static Collection<Attribute> GetAttributeCollection(AttributeBaseAst[] attributeAsts) { var result = new Collection<Attribute>(); foreach (var attributeAst in attributeAsts) { result.Add(attributeAst.GetAttribute()); } return result; } private static UsingResult GetUsingValueFromTuple(MutableTuple tuple, string usingExpressionKey, int index) { var boundParameters = tuple.GetAutomaticVariable(AutomaticVariable.PSBoundParameters) as PSBoundParametersDictionary; if (boundParameters != null) { var implicitUsingParameters = boundParameters.ImplicitUsingParameters; if (implicitUsingParameters != null) { if (implicitUsingParameters.Contains(usingExpressionKey)) { return new UsingResult { Value = implicitUsingParameters[usingExpressionKey] }; } else if (implicitUsingParameters.Contains(index)) { // Handle downlevel (V4) using variables by using index to look up using value. return new UsingResult { Value = implicitUsingParameters[index] }; } } } return null; } private sealed class UsingResult { public object Value { get; set; } } internal static object GetUsingValue(MutableTuple tuple, string usingExpressionKey, int index, ExecutionContext context) { UsingResult result = GetUsingValueFromTuple(tuple, usingExpressionKey, index); if (result != null) { return result.Value; } var scope = context.EngineSessionState.CurrentScope; while (scope != null) { result = GetUsingValueFromTuple(scope.LocalsTuple, usingExpressionKey, index); if (result != null) { return result.Value; } foreach (var dottedScope in scope.DottedScopes) { result = GetUsingValueFromTuple(dottedScope, usingExpressionKey, index); if (result != null) { return result.Value; } } scope = scope.Parent; } // $PSBoundParameters is null or not the expected type (because someone may have assigned to it), so // we can't even guess if they were mis-using $using:foo throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "UsingWithoutInvokeCommand", ParserStrings.UsingWithoutInvokeCommand); } } }
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 GurlFeed.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Copyright 2005 OpenXRI Foundation * Subsequently ported and altered by Andrew Arnott and Troels Thomsen * * 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 DotNetXri.Syntax.Xri3.Impl.Parser; namespace DotNetXri.Syntax.Xri3.Impl { public class XRI3Segment : XRI3SyntaxComponent, XRISegment { private Rule rule; private IList<XRISubSegment> subSegments; public XRI3Segment(string value) { this.rule = XRI3Util.getParser().parse("xri-segment", value); this.read(); } internal XRI3Segment(Rule rule) { this.rule = rule; this.read(); } private void reset() { this.subSegments = new List<XRISubSegment>(); } private void read() { this.reset(); object obj = this.rule; // xri_segment or xri_segment_nz or xri_segment_nc // read rel_subsegs or subsegs or rel_subseg_ncs from xri_segment or xri_segment_nz or xri_segment_nc // xri_segment or xri_segment_nz or xri_segment_nc ? if (obj is Parser.Parser.xri_segment) { // read rel_subseg or subseg from xri_segment IList<Rule> list_xri_segment = ((Parser.Parser.xri_segment)obj).rules; if (list_xri_segment.Count < 1) return; obj = list_xri_segment[0]; // rel_subseg or subseg // rel_subseg or subseg? if (obj is Parser.Parser.rel_subseg) { this.subSegments.Add(new XRI3SubSegment((Parser.Parser.rel_subseg)obj)); } else if (obj is Parser.Parser.subseg) { this.subSegments.Add(new XRI3SubSegment((Parser.Parser.subseg)obj)); } else { throw new InvalidCastException(obj.GetType().Name); } // read subsegs from xri_segment if (list_xri_segment.Count < 2) return; for (int i = 1; i < list_xri_segment.Count; i++) { obj = list_xri_segment[i]; // subseg this.subSegments.Add(new XRI3SubSegment((Parser.Parser.subseg)obj)); } } else if (obj is Parser.Parser.xri_segment_nz) { // read rel_subseg or subseg from xri_segment_nz IList<Rule> list_xri_segment_nz = ((Parser.Parser.xri_segment_nz)obj).rules; if (list_xri_segment_nz.Count < 1) return; obj = list_xri_segment_nz[0]; // rel_subseg or subseg // rel_subseg or subseg? if (obj is Parser.Parser.rel_subseg) { this.subSegments.Add(new XRI3SubSegment((Parser.Parser.rel_subseg)obj)); } else if (obj is Parser.Parser.subseg) { this.subSegments.Add(new XRI3SubSegment((Parser.Parser.subseg)obj)); } else { throw new InvalidCastException(obj.GetType().Name); } // read subsegs from xri_segment if (list_xri_segment_nz.Count < 2) return; for (int i = 1; i < list_xri_segment_nz.Count; i++) { obj = list_xri_segment_nz[i]; // subseg this.subSegments.Add(new XRI3SubSegment((Parser.Parser.subseg)obj)); } } else if (obj is Parser.Parser.xri_segment_nc) { // read rel_subseg_nc or subseg from xri_segment_nc IList<Rule> list_xri_segment_nc = ((Parser.Parser.xri_segment_nc)obj).rules; if (list_xri_segment_nc.Count < 1) return; obj = list_xri_segment_nc[0]; // rel_subseg_nc or subseg // rel_subseg_nc or subseg? if (obj is Parser.Parser.rel_subseg_nc) { this.subSegments.Add(new XRI3SubSegment((Parser.Parser.rel_subseg_nc)obj)); } else if (obj is Parser.Parser.subseg) { this.subSegments.Add(new XRI3SubSegment((Parser.Parser.subseg)obj)); } else { throw new InvalidCastException(obj.GetType().Name); } // read subsegs from xri_segment if (list_xri_segment_nc.Count < 2) return; for (int i = 1; i < list_xri_segment_nc.Count; i++) { obj = list_xri_segment_nc[i]; // subseg this.subSegments.Add(new XRI3SubSegment((Parser.Parser.subseg)obj)); } } else { throw new InvalidCastException(obj.GetType().Name); } } public Rule ParserObject { get { return this.rule; } } public IList<XRISubSegment> SubSegments { get { return this.subSegments; } } public int NumSubSegments { get { return this.subSegments.Count; } } public XRISubSegment getSubSegment(int i) { return this.subSegments[i]; } public XRISubSegment FirstSubSegment { get { if (this.subSegments.Count < 1) return null; return this.subSegments[0]; } } public XRISubSegment LastSubSegment { get { if (this.subSegments.Count < 1) return null; return this.subSegments[this.subSegments.Count - 1]; } } public bool StartsWith(XRISubSegment[] subSegments) { if (this.subSegments.Count < subSegments.Length) return (false); for (int i = 0; i < subSegments.Length; i++) { if (!(this.subSegments[i].Equals(subSegments[i]))) return (false); } return (true); } } }
//----------------------------------------------------------------------------- // <copyright file="TransferScheduler.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //----------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.DataMovement { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers; using System.Diagnostics; /// <summary> /// TransferScheduler class, used for transferring Microsoft Azure /// Storage objects. /// </summary> internal sealed class TransferScheduler : IDisposable { /// <summary> /// Main collection of transfer controllers. /// </summary> private BlockingCollection<ITransferController> controllerQueue; /// <summary> /// Internal queue for the main controllers collection. /// </summary> private ConcurrentQueue<ITransferController> internalControllerQueue; /// <summary> /// A buffer from which we select a transfer controller and add it into /// active tasks when the bucket of active tasks is not full. /// </summary> private ConcurrentDictionary<ITransferController, object> activeControllerItems = new ConcurrentDictionary<ITransferController, object>(); /// <summary> /// CancellationToken source. /// </summary> private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); /// <summary> /// Transfer options that this manager will pass to transfer controllers. /// </summary> private TransferConfigurations transferOptions; /// <summary> /// Wait handle event for completion. /// </summary> private ManualResetEventSlim controllerResetEvent = new ManualResetEventSlim(); /// <summary> /// A pool of memory buffer objects, used to limit total consumed memory. /// </summary> private MemoryManager memoryManager; /// <summary> /// Random object to generate random numbers. /// </summary> private Random randomGenerator; /// <summary> /// Used to lock disposing to avoid race condition between different disposing and other method calls. /// </summary> private object disposeLock = new object(); private SemaphoreSlim scheduleSemaphore; /// <summary> /// Indicate whether the instance has been disposed. /// </summary> private bool isDisposed = false; /// <summary> /// Initializes a new instance of the /// <see cref="TransferScheduler" /> class. /// </summary> public TransferScheduler() : this(null) { } /// <summary> /// Initializes a new instance of the /// <see cref="TransferScheduler" /> class. /// </summary> /// <param name="options">BlobTransfer options.</param> public TransferScheduler(TransferConfigurations options) { // If no options specified create a default one. this.transferOptions = options ?? new TransferConfigurations(); this.internalControllerQueue = new ConcurrentQueue<ITransferController>(); this.controllerQueue = new BlockingCollection<ITransferController>( this.internalControllerQueue); this.memoryManager = new MemoryManager( this.transferOptions.MaximumCacheSize, this.transferOptions.BlockSize); this.randomGenerator = new Random(); this.scheduleSemaphore = new SemaphoreSlim( this.transferOptions.ParallelOperations, this.transferOptions.ParallelOperations); this.StartSchedule(); } /// <summary> /// Finalizes an instance of the /// <see cref="TransferScheduler" /> class. /// </summary> ~TransferScheduler() { this.Dispose(false); } /// <summary> /// Gets the transfer options that this manager will pass to /// transfer controllers. /// </summary> internal TransferConfigurations TransferOptions { get { return this.transferOptions; } } internal CancellationTokenSource CancellationTokenSource { get { return this.cancellationTokenSource; } } internal MemoryManager MemoryManager { get { return this.memoryManager; } } /// <summary> /// Public dispose method to release all resources owned. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Execute a transfer job asynchronously. /// </summary> /// <param name="job">Transfer job to be executed.</param> /// <param name="cancellationToken">Token used to notify the job that it should stop.</param> public Task ExecuteJobAsync( TransferJob job, CancellationToken cancellationToken) { if (null == job) { throw new ArgumentNullException("job"); } lock (this.disposeLock) { this.CheckDisposed(); return ExecuteJobInternalAsync(job, cancellationToken); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Instances will be disposed in other place.")] private async Task ExecuteJobInternalAsync( TransferJob job, CancellationToken cancellationToken) { Debug.Assert( job.Status == TransferJobStatus.NotStarted || job.Status == TransferJobStatus.Monitor || job.Status == TransferJobStatus.Transfer); TransferControllerBase controller = null; switch (job.Transfer.TransferMethod) { case TransferMethod.SyncCopy: controller = new SyncTransferController(this, job, cancellationToken); break; case TransferMethod.AsyncCopy: controller = AsyncCopyController.CreateAsyncCopyController(this, job, cancellationToken); break; } Utils.CheckCancellation(this.cancellationTokenSource); this.controllerQueue.Add(controller, this.cancellationTokenSource.Token); try { await controller.TaskCompletionSource.Task; } catch(StorageException sex) { throw new TransferException(TransferErrorCode.Unknown, Resources.UncategorizedException, sex); } finally { controller.Dispose(); } } private void FillInQueue( ConcurrentDictionary<ITransferController, object> activeItems, BlockingCollection<ITransferController> collection, CancellationToken token) { while (!token.IsCancellationRequested && activeItems.Count < this.transferOptions.ParallelOperations) { if (activeItems.Count >= this.transferOptions.ParallelOperations) { return; } ITransferController transferItem = null; try { if (!collection.TryTake(out transferItem) || null == transferItem) { return; } } catch (ObjectDisposedException) { return; } activeItems.TryAdd(transferItem, null); } } /// <summary> /// Blocks until the queue is empty and all transfers have been /// completed. /// </summary> private void WaitForCompletion() { this.controllerResetEvent.Wait(); } /// <summary> /// Cancels any remaining queued work. /// </summary> private void CancelWork() { this.cancellationTokenSource.Cancel(); this.controllerQueue.CompleteAdding(); // Move following to Cancel method. // there might be running "work" when the transfer is cancelled. // wait until all running "work" is done. SpinWait sw = new SpinWait(); while (this.scheduleSemaphore.CurrentCount != this.transferOptions.ParallelOperations) { sw.SpinOnce(); } this.controllerResetEvent.Set(); } /// <summary> /// Private dispose method to release managed/unmanaged objects. /// If disposing is true clean up managed resources as well as /// unmanaged resources. /// If disposing is false only clean up unmanaged resources. /// </summary> /// <param name="disposing">Indicates whether or not to dispose /// managed resources.</param> private void Dispose(bool disposing) { if (!this.isDisposed) { lock (this.disposeLock) { // We got the lock, isDisposed is true, means that the disposing has been finished. if (this.isDisposed) { return; } this.isDisposed = true; this.CancelWork(); this.WaitForCompletion(); if (disposing) { if (null != this.controllerQueue) { this.controllerQueue.Dispose(); this.controllerQueue = null; } if (null != this.cancellationTokenSource) { this.cancellationTokenSource.Dispose(); this.cancellationTokenSource = null; } if (null != this.controllerResetEvent) { this.controllerResetEvent.Dispose(); this.controllerResetEvent = null; } if (null != this.scheduleSemaphore) { this.scheduleSemaphore.Dispose(); this.scheduleSemaphore = null; } this.memoryManager = null; } } } else { this.WaitForCompletion(); } } private void CheckDisposed() { if (this.isDisposed) { throw new ObjectDisposedException("TransferScheduler"); } } private void StartSchedule() { Task.Run(() => { SpinWait sw = new SpinWait(); while (!this.cancellationTokenSource.Token.IsCancellationRequested && (!this.controllerQueue.IsCompleted || this.activeControllerItems.Any())) { FillInQueue( this.activeControllerItems, this.controllerQueue, this.cancellationTokenSource.Token); if (!this.cancellationTokenSource.Token.IsCancellationRequested) { // If we don't have the requested amount of active tasks // running, get a task item from any active transfer item // that has work available. if (!this.DoWorkFrom(this.activeControllerItems)) { sw.SpinOnce(); } else { sw.Reset(); continue; } } } }); } private void FinishedWorkItem( ITransferController transferController) { object dummy; this.activeControllerItems.TryRemove(transferController, out dummy); } private bool DoWorkFrom( ConcurrentDictionary<ITransferController, object> activeItems) { // Filter items with work only. List<KeyValuePair<ITransferController, object>> activeItemsWithWork = new List<KeyValuePair<ITransferController, object>>( activeItems.Where(item => item.Key.HasWork && !item.Key.IsFinished)); if (0 != activeItemsWithWork.Count) { // Select random item and get work delegate. int idx = this.randomGenerator.Next(activeItemsWithWork.Count); ITransferController transferController = activeItemsWithWork[idx].Key; DoControllerWork(transferController); return true; } return false; } private async void DoControllerWork(ITransferController controller) { this.scheduleSemaphore.Wait(); bool finished = await controller.DoWorkAsync(); this.scheduleSemaphore.Release(); if (finished) { this.FinishedWorkItem(controller); } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders; using static QuantConnect.StringExtensions; using Python.Runtime; namespace QuantConnect.Securities { /// <summary> /// Algorithm Transactions Manager - Recording Transactions /// </summary> public class SecurityTransactionManager : IOrderProvider { private readonly Dictionary<DateTime, decimal> _transactionRecord; private readonly IAlgorithm _algorithm; private int _orderId; private readonly SecurityManager _securities; private TimeSpan _marketOrderFillTimeout = TimeSpan.FromSeconds(5); private IOrderProcessor _orderProcessor; /// <summary> /// Gets the time the security information was last updated /// </summary> public DateTime UtcTime { get { return _securities.UtcTime; } } /// <summary> /// Initialise the transaction manager for holding and processing orders. /// </summary> public SecurityTransactionManager(IAlgorithm algorithm, SecurityManager security) { _algorithm = algorithm; //Private reference for processing transactions _securities = security; //Internal storage for transaction records: _transactionRecord = new Dictionary<DateTime, decimal>(); } /// <summary> /// Trade record of profits and losses for each trade statistics calculations /// </summary> /// <remarks>Will return a shallow copy, modifying the returned container /// will have no effect <see cref="AddTransactionRecord"/></remarks> public Dictionary<DateTime, decimal> TransactionRecord { get { lock (_transactionRecord) { return new Dictionary<DateTime, decimal>(_transactionRecord); } } } /// <summary> /// Configurable minimum order value to ignore bad orders, or orders with unrealistic sizes /// </summary> /// <remarks>Default minimum order size is $0 value</remarks> [Obsolete("MinimumOrderSize is obsolete and will not be used, please use Settings.MinimumOrderMarginPortfolioPercentage instead")] public decimal MinimumOrderSize { get; } /// <summary> /// Configurable minimum order size to ignore bad orders, or orders with unrealistic sizes /// </summary> /// <remarks>Default minimum order size is 0 shares</remarks> [Obsolete("MinimumOrderQuantity is obsolete and will not be used, please use Settings.MinimumOrderMarginPortfolioPercentage instead")] public int MinimumOrderQuantity { get; } /// <summary> /// Get the last order id. /// </summary> public int LastOrderId { get { return _orderId; } } /// <summary> /// Configurable timeout for market order fills /// </summary> /// <remarks>Default value is 5 seconds</remarks> public TimeSpan MarketOrderFillTimeout { get { return _marketOrderFillTimeout; } set { _marketOrderFillTimeout = value; } } /// <summary> /// Processes the order request /// </summary> /// <param name="request">The request to be processed</param> /// <returns>The order ticket for the request</returns> public OrderTicket ProcessRequest(OrderRequest request) { if (_algorithm != null && _algorithm.IsWarmingUp) { throw new Exception(OrderResponse.WarmingUp(request).ToString()); } var submit = request as SubmitOrderRequest; if (submit != null) { submit.SetOrderId(GetIncrementOrderId()); } return _orderProcessor.Process(request); } /// <summary> /// Add an order to collection and return the unique order id or negative if an error. /// </summary> /// <param name="request">A request detailing the order to be submitted</param> /// <returns>New unique, increasing orderid</returns> public OrderTicket AddOrder(SubmitOrderRequest request) { return ProcessRequest(request); } /// <summary> /// Update an order yet to be filled such as stop or limit orders. /// </summary> /// <param name="request">Request detailing how the order should be updated</param> /// <remarks>Does not apply if the order is already fully filled</remarks> public OrderTicket UpdateOrder(UpdateOrderRequest request) { return ProcessRequest(request); } /// <summary> /// Added alias for RemoveOrder - /// </summary> /// <param name="orderId">Order id we wish to cancel</param> /// <param name="orderTag">Tag to indicate from where this method was called</param> public OrderTicket CancelOrder(int orderId, string orderTag = null) { return RemoveOrder(orderId, orderTag); } /// <summary> /// Cancels all open orders for all symbols /// </summary> /// <returns>List containing the cancelled order tickets</returns> public List<OrderTicket> CancelOpenOrders() { if (_algorithm != null && _algorithm.IsWarmingUp) { throw new InvalidOperationException("This operation is not allowed in Initialize or during warm up: CancelOpenOrders. Please move this code to the OnWarmupFinished() method."); } var cancelledOrders = new List<OrderTicket>(); foreach (var ticket in GetOpenOrderTickets()) { ticket.Cancel($"Canceled by CancelOpenOrders() at {_algorithm.UtcTime:o}"); cancelledOrders.Add(ticket); } return cancelledOrders; } /// <summary> /// Cancels all open orders for the specified symbol /// </summary> /// <param name="symbol">The symbol whose orders are to be cancelled</param> /// <param name="tag">Custom order tag</param> /// <returns>List containing the cancelled order tickets</returns> public List<OrderTicket> CancelOpenOrders(Symbol symbol, string tag = null) { if (_algorithm != null && _algorithm.IsWarmingUp) { throw new InvalidOperationException("This operation is not allowed in Initialize or during warm up: CancelOpenOrders. Please move this code to the OnWarmupFinished() method."); } var cancelledOrders = new List<OrderTicket>(); foreach (var ticket in GetOpenOrderTickets(x => x.Symbol == symbol)) { ticket.Cancel(tag); cancelledOrders.Add(ticket); } return cancelledOrders; } /// <summary> /// Remove this order from outstanding queue: user is requesting a cancel. /// </summary> /// <param name="orderId">Specific order id to remove</param> /// <param name="tag">Tag request</param> public OrderTicket RemoveOrder(int orderId, string tag = null) { return ProcessRequest(new CancelOrderRequest(_securities.UtcTime, orderId, tag ?? string.Empty)); } /// <summary> /// Gets an enumerable of <see cref="OrderTicket"/> matching the specified <paramref name="filter"/> /// </summary> /// <param name="filter">The filter predicate used to find the required order tickets</param> /// <returns>An enumerable of <see cref="OrderTicket"/> matching the specified <paramref name="filter"/></returns> public IEnumerable<OrderTicket> GetOrderTickets(Func<OrderTicket, bool> filter = null) { return _orderProcessor.GetOrderTickets(filter ?? (x => true)); } /// <summary> /// Gets an enumerable of <see cref="OrderTicket"/> matching the specified <paramref name="filter"/> /// </summary> /// <param name="filter">The Python function filter used to find the required order tickets</param> /// <returns>An enumerable of <see cref="OrderTicket"/> matching the specified <paramref name="filter"/></returns> public IEnumerable<OrderTicket> GetOrderTickets(PyObject filter) { return _orderProcessor.GetOrderTickets(filter.ConvertToDelegate<Func<OrderTicket, bool>>()); } /// <summary> /// Get an enumerable of open <see cref="OrderTicket"/> for the specified symbol /// </summary> /// <param name="symbol">The symbol for which to return the order tickets</param> /// <returns>An enumerable of open <see cref="OrderTicket"/>.</returns> public IEnumerable<OrderTicket> GetOpenOrderTickets(Symbol symbol) { return GetOpenOrderTickets(x => x.Symbol == symbol); } /// <summary> /// Gets an enumerable of opened <see cref="OrderTicket"/> matching the specified <paramref name="filter"/> /// </summary> /// <param name="filter">The filter predicate used to find the required order tickets</param> /// <returns>An enumerable of opened <see cref="OrderTicket"/> matching the specified <paramref name="filter"/></returns> public IEnumerable<OrderTicket> GetOpenOrderTickets(Func<OrderTicket, bool> filter = null) { return _orderProcessor.GetOpenOrderTickets(filter ?? (x => true)); } /// <summary> /// Gets an enumerable of opened <see cref="OrderTicket"/> matching the specified <paramref name="filter"/> /// However, this method can be confused with the override that takes a Symbol as parameter. For this reason /// it first checks if it can convert the parameter into a symbol. If that conversion cannot be aplied it /// assumes the parameter is a Python function object and not a Python representation of a Symbol. /// </summary> /// <param name="filter">The Python function filter used to find the required order tickets</param> /// <returns>An enumerable of opened <see cref="OrderTicket"/> matching the specified <paramref name="filter"/></returns> public IEnumerable<OrderTicket> GetOpenOrderTickets(PyObject filter) { Symbol pythonSymbol; if (filter.TryConvert(out pythonSymbol)) { return GetOpenOrderTickets(pythonSymbol); } return _orderProcessor.GetOpenOrderTickets(filter.ConvertToDelegate<Func<OrderTicket, bool>>()); } /// <summary> /// Gets the remaining quantity to be filled from open orders, i.e. order size minus quantity filled /// </summary> /// <param name="filter">Filters the order tickets to be included in the aggregate quantity remaining to be filled</param> /// <returns>Total quantity that hasn't been filled yet for all orders that were not filtered</returns> public decimal GetOpenOrdersRemainingQuantity(Func<OrderTicket, bool> filter = null) { return GetOpenOrderTickets(filter) .Aggregate(0m, (d, t) => d + t.Quantity - t.QuantityFilled); } /// <summary> /// Gets the remaining quantity to be filled from open orders, i.e. order size minus quantity filled /// However, this method can be confused with the override that takes a Symbol as parameter. For this reason /// it first checks if it can convert the parameter into a symbol. If that conversion cannot be aplied it /// assumes the parameter is a Python function object and not a Python representation of a Symbol. /// </summary> /// <param name="filter">Filters the order tickets to be included in the aggregate quantity remaining to be filled</param> /// <returns>Total quantity that hasn't been filled yet for all orders that were not filtered</returns> public decimal GetOpenOrdersRemainingQuantity(PyObject filter) { Symbol pythonSymbol; if (filter.TryConvert(out pythonSymbol)) { return GetOpenOrdersRemainingQuantity(pythonSymbol); } return GetOpenOrderTickets(filter) .Aggregate(0m, (d, t) => d + t.Quantity - t.QuantityFilled); } /// <summary> /// Gets the remaining quantity to be filled from open orders for a Symbol, i.e. order size minus quantity filled /// </summary> /// <param name="symbol">Symbol to get the remaining quantity of currently open orders</param> /// <returns>Total quantity that hasn't been filled yet for orders matching the Symbol</returns> public decimal GetOpenOrdersRemainingQuantity(Symbol symbol) { return GetOpenOrdersRemainingQuantity(t => t.Symbol == symbol); } /// <summary> /// Gets the order ticket for the specified order id. Returns null if not found /// </summary> /// <param name="orderId">The order's id</param> /// <returns>The order ticket with the specified id, or null if not found</returns> public OrderTicket GetOrderTicket(int orderId) { return _orderProcessor.GetOrderTicket(orderId); } /// <summary> /// Wait for a specific order to be either Filled, Invalid or Canceled /// </summary> /// <param name="orderId">The id of the order to wait for</param> /// <returns>True if we successfully wait for the fill, false if we were unable /// to wait. This may be because it is not a market order or because the timeout /// was reached</returns> public bool WaitForOrder(int orderId) { var orderTicket = GetOrderTicket(orderId); if (orderTicket == null) { Log.Error(Invariant( $"SecurityTransactionManager.WaitForOrder(): Unable to locate ticket for order: {orderId}" )); return false; } if (!orderTicket.OrderClosed.WaitOne(_marketOrderFillTimeout)) { Log.Error(Invariant( $"SecurityTransactionManager.WaitForOrder(): Order did not fill within {_marketOrderFillTimeout.TotalSeconds} seconds." )); return false; } return true; } /// <summary> /// Get a list of all open orders for a symbol. /// </summary> /// <param name="symbol">The symbol for which to return the orders</param> /// <returns>List of open orders.</returns> public List<Order> GetOpenOrders(Symbol symbol) { return GetOpenOrders(x => x.Symbol == symbol); } /// <summary> /// Gets open orders matching the specified filter. Specifying null will return an enumerable /// of all open orders. /// </summary> /// <param name="filter">Delegate used to filter the orders</param> /// <returns>All filtered open orders this order provider currently holds</returns> public List<Order> GetOpenOrders(Func<Order, bool> filter = null) { filter = filter ?? (x => true); return _orderProcessor.GetOpenOrders(x => filter(x)); } /// <summary> /// Gets open orders matching the specified filter. However, this method can be confused with the /// override that takes a Symbol as parameter. For this reason it first checks if it can convert /// the parameter into a symbol. If that conversion cannot be aplied it assumes the parameter is /// a Python function object and not a Python representation of a Symbol. /// </summary> /// <param name="filter">Python function object used to filter the orders</param> /// <returns>All filtered open orders this order provider currently holds</returns> public List<Order> GetOpenOrders(PyObject filter) { Symbol pythonSymbol; if (filter.TryConvert(out pythonSymbol)) { return GetOpenOrders(pythonSymbol); } Func<Order, bool> csharpFilter = filter.ConvertToDelegate<Func<Order, bool>>(); return _orderProcessor.GetOpenOrders(x => csharpFilter(x)); } /// <summary> /// Gets the current number of orders that have been processed /// </summary> public int OrdersCount { get { return _orderProcessor.OrdersCount; } } /// <summary> /// Get the order by its id /// </summary> /// <param name="orderId">Order id to fetch</param> /// <returns>A clone of the order with the specified id, or null if no match is found</returns> public Order GetOrderById(int orderId) { return _orderProcessor.GetOrderById(orderId); } /// <summary> /// Gets the order by its brokerage id /// </summary> /// <param name="brokerageId">The brokerage id to fetch</param> /// <returns>The first order matching the brokerage id, or null if no match is found</returns> public Order GetOrderByBrokerageId(string brokerageId) { return _orderProcessor.GetOrderByBrokerageId(brokerageId); } /// <summary> /// Gets all orders matching the specified filter. Specifying null will return an enumerable /// of all orders. /// </summary> /// <param name="filter">Delegate used to filter the orders</param> /// <returns>All orders this order provider currently holds by the specified filter</returns> public IEnumerable<Order> GetOrders(Func<Order, bool> filter = null) { return _orderProcessor.GetOrders(filter ?? (x => true)); } /// <summary> /// Gets all orders matching the specified filter. /// </summary> /// <param name="filter">Python function object used to filter the orders</param> /// <returns>All orders this order provider currently holds by the specified filter</returns> public IEnumerable<Order> GetOrders(PyObject filter) { return _orderProcessor.GetOrders(filter.ConvertToDelegate<Func<Order, bool>>()); } /// <summary> /// Get a new order id, and increment the internal counter. /// </summary> /// <returns>New unique int order id.</returns> public int GetIncrementOrderId() { return Interlocked.Increment(ref _orderId); } /// <summary> /// Sets the <see cref="IOrderProvider"/> used for fetching orders for the algorithm /// </summary> /// <param name="orderProvider">The <see cref="IOrderProvider"/> to be used to manage fetching orders</param> public void SetOrderProcessor(IOrderProcessor orderProvider) { _orderProcessor = orderProvider; } /// <summary> /// Record the transaction value and time in a list to later be processed for statistics creation. /// </summary> /// <remarks> /// Bit of a hack -- but using datetime as dictionary key is dangerous as you can process multiple orders within a second. /// For the accounting / statistics generating purposes its not really critical to know the precise time, so just add a millisecond while there's an identical key. /// </remarks> /// <param name="time">Time of order processed </param> /// <param name="transactionProfitLoss">Profit Loss.</param> public void AddTransactionRecord(DateTime time, decimal transactionProfitLoss) { lock (_transactionRecord) { var clone = time; while (_transactionRecord.ContainsKey(clone)) { clone = clone.AddMilliseconds(1); } _transactionRecord.Add(clone, transactionProfitLoss); } } /// <summary> /// Returns true when the specified order is in a completed state /// </summary> private static bool Completed(Order order) { return order.Status == OrderStatus.Filled || order.Status == OrderStatus.PartiallyFilled || order.Status == OrderStatus.Invalid || order.Status == OrderStatus.Canceled; } } }
// 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. // /*============================================================================= ** ** ** ** Purpose: Class to represent all synchronization objects in the runtime (that allow multiple wait) ** ** =============================================================================*/ namespace System.Threading { using System.Threading; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Diagnostics.CodeAnalysis; using Win32Native = Microsoft.Win32.Win32Native; public abstract class WaitHandle : MarshalByRefObject, IDisposable { public const int WaitTimeout = 0x102; private const int MAX_WAITHANDLES = 64; #pragma warning disable 414 // Field is not used from managed. private IntPtr waitHandle; // !!! DO NOT MOVE THIS FIELD. (See defn of WAITHANDLEREF in object.h - has hardcoded access to this field.) #pragma warning restore 414 internal volatile SafeWaitHandle safeWaitHandle; internal bool hasThreadAffinity; private static IntPtr GetInvalidHandle() { return Win32Native.INVALID_HANDLE_VALUE; } protected static readonly IntPtr InvalidHandle = GetInvalidHandle(); private const int WAIT_OBJECT_0 = 0; private const int WAIT_ABANDONED = 0x80; private const int WAIT_FAILED = 0x7FFFFFFF; private const int ERROR_TOO_MANY_POSTS = 0x12A; internal enum OpenExistingResult { Success, NameNotFound, PathNotFound, NameInvalid } protected WaitHandle() { Init(); } private void Init() { safeWaitHandle = null; waitHandle = InvalidHandle; hasThreadAffinity = false; } [Obsolete("Use the SafeWaitHandle property instead.")] public virtual IntPtr Handle { get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle(); } set { if (value == InvalidHandle) { // This line leaks a handle. However, it's currently // not perfectly clear what the right behavior is here // anyways. This preserves Everett behavior. We should // ideally do these things: // *) Expose a settable SafeHandle property on WaitHandle. // *) Expose a settable OwnsHandle property on SafeHandle. if (safeWaitHandle != null) { safeWaitHandle.SetHandleAsInvalid(); safeWaitHandle = null; } } else { safeWaitHandle = new SafeWaitHandle(value, true); } waitHandle = value; } } public SafeWaitHandle SafeWaitHandle { get { if (safeWaitHandle == null) { safeWaitHandle = new SafeWaitHandle(InvalidHandle, false); } return safeWaitHandle; } set { // Set safeWaitHandle and waitHandle in a CER so we won't take // a thread abort between the statements and leave the wait // handle in an invalid state. Note this routine is not thread // safe however. RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (value == null) { safeWaitHandle = null; waitHandle = InvalidHandle; } else { safeWaitHandle = value; waitHandle = safeWaitHandle.DangerousGetHandle(); } } } } // Assembly-private version that doesn't do a security check. Reduces the // number of link-time security checks when reading & writing to a file, // and helps avoid a link time check while initializing security (If you // call a Serialization method that requires security before security // has started up, the link time check will start up security, run // serialization code for some security attribute stuff, call into // FileStream, which will then call Sethandle, which requires a link time // security check.). While security has fixed that problem, we still // don't need to do a linktime check here. internal void SetHandleInternal(SafeWaitHandle handle) { safeWaitHandle = handle; waitHandle = handle.DangerousGetHandle(); } public virtual bool WaitOne(int millisecondsTimeout, bool exitContext) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return WaitOne((long)millisecondsTimeout, exitContext); } public virtual bool WaitOne(TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long)Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return WaitOne(tm, exitContext); } public virtual bool WaitOne() { //Infinite Timeout return WaitOne(-1, false); } public virtual bool WaitOne(int millisecondsTimeout) { return WaitOne(millisecondsTimeout, false); } public virtual bool WaitOne(TimeSpan timeout) { return WaitOne(timeout, false); } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] private bool WaitOne(long timeout, bool exitContext) { return InternalWaitOne(safeWaitHandle, timeout, hasThreadAffinity, exitContext); } internal static bool InternalWaitOne(SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext) { if (waitableSafeHandle == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); } int ret = WaitOneNative(waitableSafeHandle, (uint)millisecondsTimeout, hasThreadAffinity, exitContext); if (ret == WAIT_ABANDONED) { ThrowAbandonedMutexException(); } return (ret != WaitTimeout); } internal bool WaitOneWithoutFAS() { // version of waitone without fast application switch (FAS) support // This is required to support the Wait which FAS needs (otherwise recursive dependency comes in) if (safeWaitHandle == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); } long timeout = -1; int ret = WaitOneNative(safeWaitHandle, (uint)timeout, hasThreadAffinity, false); if (ret == WAIT_ABANDONED) { ThrowAbandonedMutexException(); } return (ret != WaitTimeout); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext); /*======================================================================== ** Waits for signal from all the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when all the object have been pulsed ** or timeout milliseonds have elapsed. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll); public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles == null) { throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles); } if (waitHandles.Length == 0) { // // Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct. // Somehow, in 2.0, this became ArgumentNullException. This was not fixed until Silverlight 2, // which went back to ArgumentException. // // Now we're in a bit of a bind. Backward-compatibility requires us to keep throwing ArgumentException // in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking // user code. // throw new ArgumentException(SR.Argument_EmptyWaithandleArray); } if (waitHandles.Length > MAX_WAITHANDLES) { throw new NotSupportedException(SR.NotSupported_MaxWaitHandles); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) throw new ArgumentNullException("waitHandles[" + i + "]", SR.ArgumentNull_ArrayElement); internalWaitHandles[i] = waitHandle; } #if DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, true /* waitall*/ ); if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret)) { //In the case of WaitAll the OS will only provide the // information that mutex was abandoned. // It won't tell us which one. So we can't set the Index or provide access to the Mutex ThrowAbandonedMutexException(); } GC.KeepAlive(internalWaitHandles); return (ret != WaitTimeout); } public static bool WaitAll( WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long)Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return WaitAll(waitHandles, (int)tm, exitContext); } /*======================================================================== ** Shorthand for WaitAll with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ public static bool WaitAll(WaitHandle[] waitHandles) { return WaitAll(waitHandles, Timeout.Infinite, true); } public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitAll(waitHandles, millisecondsTimeout, true); } public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitAll(waitHandles, timeout, true); } /*======================================================================== ** Waits for notification from any of the objects. ** timeout indicates how long to wait before the method returns. ** This method will return either when either one of the object have been ** signalled or timeout milliseonds have elapsed. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ========================================================================*/ public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { if (waitHandles == null) { throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles); } if (waitHandles.Length == 0) { throw new ArgumentException(SR.Argument_EmptyWaithandleArray); } if (MAX_WAITHANDLES < waitHandles.Length) { throw new NotSupportedException(SR.NotSupported_MaxWaitHandles); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) throw new ArgumentNullException("waitHandles[" + i + "]", SR.ArgumentNull_ArrayElement); internalWaitHandles[i] = waitHandle; } #if DEBUG // make sure we do not use waitHandles any more. waitHandles = null; #endif int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, false /* waitany*/ ); if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret)) { int mutexIndex = ret - WAIT_ABANDONED; if (0 <= mutexIndex && mutexIndex < internalWaitHandles.Length) { ThrowAbandonedMutexException(mutexIndex, internalWaitHandles[mutexIndex]); } else { ThrowAbandonedMutexException(); } } GC.KeepAlive(internalWaitHandles); return ret; } public static int WaitAny( WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long)Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return WaitAny(waitHandles, (int)tm, exitContext); } public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitAny(waitHandles, timeout, true); } /*======================================================================== ** Shorthand for WaitAny with timeout = Timeout.Infinite and exitContext = true ========================================================================*/ public static int WaitAny(WaitHandle[] waitHandles) { return WaitAny(waitHandles, Timeout.Infinite, true); } public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitAny(waitHandles, millisecondsTimeout, true); } /*================================================= == == SignalAndWait == ==================================================*/ [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal, SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout, bool hasThreadAffinity, bool exitContext); public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn) { return SignalAndWait(toSignal, toWaitOn, -1, false); } public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn, TimeSpan timeout, bool exitContext) { long tm = (long)timeout.TotalMilliseconds; if (-1 > tm || (long)Int32.MaxValue < tm) { throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return SignalAndWait(toSignal, toWaitOn, (int)tm, exitContext); } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")] public static bool SignalAndWait( WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext) { if (null == toSignal) { throw new ArgumentNullException(nameof(toSignal)); } if (null == toWaitOn) { throw new ArgumentNullException(nameof(toWaitOn)); } if (-1 > millisecondsTimeout) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } //NOTE: This API is not supporting Pause/Resume as it's not exposed in CoreCLR (not in WP or SL) int ret = SignalAndWaitOne(toSignal.safeWaitHandle, toWaitOn.safeWaitHandle, millisecondsTimeout, toWaitOn.hasThreadAffinity, exitContext); if (WAIT_ABANDONED == ret) { ThrowAbandonedMutexException(); } if (ERROR_TOO_MANY_POSTS == ret) { throw new InvalidOperationException(SR.Threading_WaitHandleTooManyPosts); } //Object was signaled if (WAIT_OBJECT_0 == ret) { return true; } //Timeout return false; } private static void ThrowAbandonedMutexException() { throw new AbandonedMutexException(); } private static void ThrowAbandonedMutexException(int location, WaitHandle handle) { throw new AbandonedMutexException(location, handle); } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool explicitDisposing) { if (safeWaitHandle != null) { safeWaitHandle.Close(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }
// 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.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedSmartCampaignSettingServiceClientTest { [Category("Autogenerated")][Test] public void GetSmartCampaignSettingRequestObject() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting response = client.GetSmartCampaignSetting(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetSmartCampaignSettingRequestObjectAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::SmartCampaignSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting responseCallSettings = await client.GetSmartCampaignSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::SmartCampaignSetting responseCancellationToken = await client.GetSmartCampaignSettingAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetSmartCampaignSetting() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting response = client.GetSmartCampaignSetting(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetSmartCampaignSettingAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::SmartCampaignSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting responseCallSettings = await client.GetSmartCampaignSettingAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::SmartCampaignSetting responseCancellationToken = await client.GetSmartCampaignSettingAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetSmartCampaignSettingResourceNames() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting response = client.GetSmartCampaignSetting(request.ResourceNameAsSmartCampaignSettingName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetSmartCampaignSettingResourceNamesAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); GetSmartCampaignSettingRequest request = new GetSmartCampaignSettingRequest { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), }; gagvr::SmartCampaignSetting expectedResponse = new gagvr::SmartCampaignSetting { ResourceNameAsSmartCampaignSettingName = gagvr::SmartCampaignSettingName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), PhoneNumber = new gagvr::SmartCampaignSetting.Types.PhoneNumber(), FinalUrl = "final_url01c3df1e", BusinessName = "business_nameba1c7bb8", BusinessLocationId = 7879742372906296557L, AdvertisingLanguageCode = "advertising_language_coded5ffed87", }; mockGrpcClient.Setup(x => x.GetSmartCampaignSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::SmartCampaignSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::SmartCampaignSetting responseCallSettings = await client.GetSmartCampaignSettingAsync(request.ResourceNameAsSmartCampaignSettingName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::SmartCampaignSetting responseCancellationToken = await client.GetSmartCampaignSettingAsync(request.ResourceNameAsSmartCampaignSettingName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateSmartCampaignSettingsRequestObject() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); MutateSmartCampaignSettingsRequest request = new MutateSmartCampaignSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new SmartCampaignSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateSmartCampaignSettingsResponse expectedResponse = new MutateSmartCampaignSettingsResponse { PartialFailureError = new gr::Status(), Results = { new MutateSmartCampaignSettingResult(), }, }; mockGrpcClient.Setup(x => x.MutateSmartCampaignSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); MutateSmartCampaignSettingsResponse response = client.MutateSmartCampaignSettings(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateSmartCampaignSettingsRequestObjectAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); MutateSmartCampaignSettingsRequest request = new MutateSmartCampaignSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new SmartCampaignSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateSmartCampaignSettingsResponse expectedResponse = new MutateSmartCampaignSettingsResponse { PartialFailureError = new gr::Status(), Results = { new MutateSmartCampaignSettingResult(), }, }; mockGrpcClient.Setup(x => x.MutateSmartCampaignSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateSmartCampaignSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); MutateSmartCampaignSettingsResponse responseCallSettings = await client.MutateSmartCampaignSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateSmartCampaignSettingsResponse responseCancellationToken = await client.MutateSmartCampaignSettingsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateSmartCampaignSettings() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); MutateSmartCampaignSettingsRequest request = new MutateSmartCampaignSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new SmartCampaignSettingOperation(), }, }; MutateSmartCampaignSettingsResponse expectedResponse = new MutateSmartCampaignSettingsResponse { PartialFailureError = new gr::Status(), Results = { new MutateSmartCampaignSettingResult(), }, }; mockGrpcClient.Setup(x => x.MutateSmartCampaignSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); MutateSmartCampaignSettingsResponse response = client.MutateSmartCampaignSettings(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateSmartCampaignSettingsAsync() { moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient> mockGrpcClient = new moq::Mock<SmartCampaignSettingService.SmartCampaignSettingServiceClient>(moq::MockBehavior.Strict); MutateSmartCampaignSettingsRequest request = new MutateSmartCampaignSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new SmartCampaignSettingOperation(), }, }; MutateSmartCampaignSettingsResponse expectedResponse = new MutateSmartCampaignSettingsResponse { PartialFailureError = new gr::Status(), Results = { new MutateSmartCampaignSettingResult(), }, }; mockGrpcClient.Setup(x => x.MutateSmartCampaignSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateSmartCampaignSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SmartCampaignSettingServiceClient client = new SmartCampaignSettingServiceClientImpl(mockGrpcClient.Object, null); MutateSmartCampaignSettingsResponse responseCallSettings = await client.MutateSmartCampaignSettingsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateSmartCampaignSettingsResponse responseCancellationToken = await client.MutateSmartCampaignSettingsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections; using System.Text; using System.Collections.Generic; using UnityEngine; /* Based on the JSON parser from * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * I simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * Additional: * Modified by Mitch Thompson to output new-line formatting to make things more readable * Also modified to parse all numbers to float or single instead of double * Also modified to support float Infinity (defaults to Positive Infinity) */ /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to doubles. /// </summary> public class MiniJSON { private const int TOKEN_NONE = 0; private const int TOKEN_CURLY_OPEN = 1; private const int TOKEN_CURLY_CLOSE = 2; private const int TOKEN_SQUARED_OPEN = 3; private const int TOKEN_SQUARED_CLOSE = 4; private const int TOKEN_COLON = 5; private const int TOKEN_COMMA = 6; private const int TOKEN_STRING = 7; private const int TOKEN_NUMBER = 8; private const int TOKEN_TRUE = 9; private const int TOKEN_FALSE = 10; private const int TOKEN_NULL = 11; //added token for infinity private const int TOKEN_INFINITY = 12; private const int BUILDER_CAPACITY = 2000; /// <summary> /// On decoding, this value holds the position at which the parse failed (-1 = no error). /// </summary> protected static int lastErrorIndex = -1; protected static string lastDecode = ""; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns> public static object jsonDecode( string json ) { // save the string for debug information MiniJSON.lastDecode = json; if( json != null ) { char[] charArray = json.ToCharArray(); int index = 0; bool success = true; object value = MiniJSON.parseValue( charArray, ref index, ref success ); if( success ) MiniJSON.lastErrorIndex = -1; else MiniJSON.lastErrorIndex = index; return value; } else { return null; } } /// <summary> /// Converts a Hashtable / ArrayList / Dictionary(string,string) object into a JSON string /// </summary> /// <param name="json">A Hashtable / ArrayList</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string jsonEncode( object json ) { indentLevel = 0; var builder = new StringBuilder( BUILDER_CAPACITY ); var success = MiniJSON.serializeValue( json, builder ); return ( success ? builder.ToString() : null ); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static bool lastDecodeSuccessful() { return ( MiniJSON.lastErrorIndex == -1 ); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static int getLastErrorIndex() { return MiniJSON.lastErrorIndex; } /// <summary> /// If a decoding error occurred, this function returns a piece of the JSON string /// at which the error took place. To ease debugging. /// </summary> /// <returns></returns> public static string getLastErrorSnippet() { if( MiniJSON.lastErrorIndex == -1 ) { return ""; } else { int startIndex = MiniJSON.lastErrorIndex - 5; int endIndex = MiniJSON.lastErrorIndex + 15; if( startIndex < 0 ) startIndex = 0; if( endIndex >= MiniJSON.lastDecode.Length ) endIndex = MiniJSON.lastDecode.Length - 1; return MiniJSON.lastDecode.Substring( startIndex, endIndex - startIndex + 1 ); } } #region Parsing protected static Hashtable parseObject( char[] json, ref int index ) { Hashtable table = new Hashtable(); int token; // { nextToken( json, ref index ); bool done = false; while( !done ) { token = lookAhead( json, index ); if( token == MiniJSON.TOKEN_NONE ) { return null; } else if( token == MiniJSON.TOKEN_COMMA ) { nextToken( json, ref index ); } else if( token == MiniJSON.TOKEN_CURLY_CLOSE ) { nextToken( json, ref index ); return table; } else { // name string name = parseString( json, ref index ); if( name == null ) { return null; } // : token = nextToken( json, ref index ); if( token != MiniJSON.TOKEN_COLON ) return null; // value bool success = true; object value = parseValue( json, ref index, ref success ); if( !success ) return null; table[name] = value; } } return table; } protected static ArrayList parseArray( char[] json, ref int index ) { ArrayList array = new ArrayList(); // [ nextToken( json, ref index ); bool done = false; while( !done ) { int token = lookAhead( json, index ); if( token == MiniJSON.TOKEN_NONE ) { return null; } else if( token == MiniJSON.TOKEN_COMMA ) { nextToken( json, ref index ); } else if( token == MiniJSON.TOKEN_SQUARED_CLOSE ) { nextToken( json, ref index ); break; } else { bool success = true; object value = parseValue( json, ref index, ref success ); if( !success ) return null; array.Add( value ); } } return array; } protected static object parseValue( char[] json, ref int index, ref bool success ) { switch( lookAhead( json, index ) ) { case MiniJSON.TOKEN_STRING: return parseString( json, ref index ); case MiniJSON.TOKEN_NUMBER: return parseNumber( json, ref index ); case MiniJSON.TOKEN_CURLY_OPEN: return parseObject( json, ref index ); case MiniJSON.TOKEN_SQUARED_OPEN: return parseArray( json, ref index ); case MiniJSON.TOKEN_TRUE: nextToken( json, ref index ); return Boolean.Parse( "TRUE" ); case MiniJSON.TOKEN_FALSE: nextToken( json, ref index ); return Boolean.Parse( "FALSE" ); case MiniJSON.TOKEN_NULL: nextToken( json, ref index ); return null; case MiniJSON.TOKEN_INFINITY: nextToken( json, ref index ); return float.PositiveInfinity; case MiniJSON.TOKEN_NONE: break; } success = false; return null; } protected static string parseString( char[] json, ref int index ) { string s = ""; char c; eatWhitespace( json, ref index ); // " c = json[index++]; bool complete = false; while( !complete ) { if( index == json.Length ) break; c = json[index++]; if( c == '"' ) { complete = true; break; } else if( c == '\\' ) { if( index == json.Length ) break; c = json[index++]; if( c == '"' ) { s += '"'; } else if( c == '\\' ) { s += '\\'; } else if( c == '/' ) { s += '/'; } else if( c == 'b' ) { s += '\b'; } else if( c == 'f' ) { s += '\f'; } else if( c == 'n' ) { s += '\n'; } else if( c == 'r' ) { s += '\r'; } else if( c == 't' ) { s += '\t'; } else if( c == 'u' ) { int remainingLength = json.Length - index; if( remainingLength >= 4 ) { char[] unicodeCharArray = new char[4]; Array.Copy( json, index, unicodeCharArray, 0, 4 ); // Drop in the HTML markup for the unicode character s += "&#x" + new string( unicodeCharArray ) + ";"; /* uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber); // convert the integer codepoint to a unicode char and add to string s += Char.ConvertFromUtf32((int)codePoint); */ // skip 4 chars index += 4; } else { break; } } } else { s += c; } } if( !complete ) return null; return s; } protected static float parseNumber( char[] json, ref int index ) { eatWhitespace( json, ref index ); int lastIndex = getLastIndexOfNumber( json, index ); int charLength = ( lastIndex - index ) + 1; char[] numberCharArray = new char[charLength]; Array.Copy( json, index, numberCharArray, 0, charLength ); index = lastIndex + 1; return float.Parse( new string( numberCharArray ) ); // , CultureInfo.InvariantCulture); } protected static int getLastIndexOfNumber( char[] json, int index ) { int lastIndex; for( lastIndex = index; lastIndex < json.Length; lastIndex++ ) if( "0123456789+-.eE".IndexOf( json[lastIndex] ) == -1 ) { break; } return lastIndex - 1; } protected static void eatWhitespace( char[] json, ref int index ) { for( ; index < json.Length; index++ ) if( " \t\n\r".IndexOf( json[index] ) == -1 ) { break; } } protected static int lookAhead( char[] json, int index ) { int saveIndex = index; return nextToken( json, ref saveIndex ); } protected static int nextToken( char[] json, ref int index ) { eatWhitespace( json, ref index ); if( index == json.Length ) { return MiniJSON.TOKEN_NONE; } char c = json[index]; index++; switch( c ) { case '{': return MiniJSON.TOKEN_CURLY_OPEN; case '}': return MiniJSON.TOKEN_CURLY_CLOSE; case '[': return MiniJSON.TOKEN_SQUARED_OPEN; case ']': return MiniJSON.TOKEN_SQUARED_CLOSE; case ',': return MiniJSON.TOKEN_COMMA; case '"': return MiniJSON.TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return MiniJSON.TOKEN_NUMBER; case ':': return MiniJSON.TOKEN_COLON; } index--; int remainingLength = json.Length - index; // Infinity if( remainingLength >= 8 ) { if( json[index] == 'I' && json[index + 1] == 'n' && json[index + 2] == 'f' && json[index + 3] == 'i' && json[index + 4] == 'n' && json[index + 5] == 'i' && json[index + 6] == 't' && json[index + 7] == 'y' ) { index += 8; return MiniJSON.TOKEN_INFINITY; } } // false if( remainingLength >= 5 ) { if( json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e' ) { index += 5; return MiniJSON.TOKEN_FALSE; } } // true if( remainingLength >= 4 ) { if( json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e' ) { index += 4; return MiniJSON.TOKEN_TRUE; } } // null if( remainingLength >= 4 ) { if( json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l' ) { index += 4; return MiniJSON.TOKEN_NULL; } } return MiniJSON.TOKEN_NONE; } #endregion #region Serialization protected static bool serializeObjectOrArray( object objectOrArray, StringBuilder builder ) { if( objectOrArray is Hashtable ) { return serializeObject( (Hashtable)objectOrArray, builder ); } else if( objectOrArray is ArrayList ) { return serializeArray( (ArrayList)objectOrArray, builder ); } else { return false; } } protected static int indentLevel = 0; protected static bool serializeObject( Hashtable anObject, StringBuilder builder ) { indentLevel++; string indentString = ""; for(int i = 0; i < indentLevel; i++) indentString += "\t"; builder.Append( "{\n" + indentString ); IDictionaryEnumerator e = anObject.GetEnumerator(); bool first = true; while( e.MoveNext() ) { string key = e.Key.ToString(); object value = e.Value; if( !first ) { builder.Append( ", \n" + indentString ); } serializeString( key, builder ); builder.Append( ":" ); if( !serializeValue( value, builder ) ) { return false; } first = false; } indentString = ""; for(int i = 0; i < indentLevel-1; i++) indentString += "\t"; builder.Append( "\n" + indentString + "}"); indentLevel--; return true; } protected static bool serializeDictionary( Dictionary<string,string> dict, StringBuilder builder ) { builder.Append( "{" ); bool first = true; foreach( var kv in dict ) { if( !first ) builder.Append( ", " ); serializeString( kv.Key, builder ); builder.Append( ":" ); serializeString( kv.Value, builder ); first = false; } builder.Append( "}" ); return true; } protected static bool serializeArray( ArrayList anArray, StringBuilder builder ) { indentLevel++; string indentString = ""; for(int i = 0; i < indentLevel; i++) indentString += "\t"; builder.Append( "[\n" + indentString ); // builder.Append( "[" ); bool first = true; for( int i = 0; i < anArray.Count; i++ ) { object value = anArray[i]; if( !first ) { builder.Append( ", \n" + indentString ); } if( !serializeValue( value, builder ) ) { return false; } first = false; } indentString = ""; for(int i = 0; i < indentLevel-1; i++) indentString += "\t"; builder.Append( "\n" + indentString + "]"); indentLevel--; return true; } protected static bool serializeValue( object value, StringBuilder builder ) { // Type t = value.GetType(); // Debug.Log("type: " + t.ToString() + " isArray: " + t.IsArray); if( value == null ) { builder.Append( "null" ); } else if( value.GetType().IsArray ) { serializeArray( new ArrayList( (ICollection)value ), builder ); } else if( value is string ) { serializeString( (string)value, builder ); } else if( value is Char ) { serializeString( Convert.ToString( (char)value ), builder ); } else if( value is Hashtable ) { serializeObject( (Hashtable)value, builder ); } else if( value is Dictionary<string,string> ) { serializeDictionary( (Dictionary<string,string>)value, builder ); } else if( value is ArrayList ) { serializeArray( (ArrayList)value, builder ); } else if( ( value is Boolean ) && ( (Boolean)value == true ) ) { builder.Append( "true" ); } else if( ( value is Boolean ) && ( (Boolean)value == false ) ) { builder.Append( "false" ); } else if( value.GetType().IsPrimitive ) { serializeNumber( Convert.ToSingle( value ), builder ); } else { return false; } return true; } protected static void serializeString( string aString, StringBuilder builder ) { builder.Append( "\"" ); char[] charArray = aString.ToCharArray(); for( int i = 0; i < charArray.Length; i++ ) { char c = charArray[i]; if( c == '"' ) { builder.Append( "\\\"" ); } else if( c == '\\' ) { builder.Append( "\\\\" ); } else if( c == '\b' ) { builder.Append( "\\b" ); } else if( c == '\f' ) { builder.Append( "\\f" ); } else if( c == '\n' ) { builder.Append( "\\n" ); } else if( c == '\r' ) { builder.Append( "\\r" ); } else if( c == '\t' ) { builder.Append( "\\t" ); } else { int codepoint = Convert.ToInt32( c ); if( ( codepoint >= 32 ) && ( codepoint <= 126 ) ) { builder.Append( c ); } else { builder.Append( "\\u" + Convert.ToString( codepoint, 16 ).PadLeft( 4, '0' ) ); } } } builder.Append( "\"" ); } protected static void serializeNumber( float number, StringBuilder builder ) { builder.Append( Convert.ToString( number ) ); // , CultureInfo.InvariantCulture)); } #endregion } #region Extension methods public static class MiniJsonExtensions { public static string toJson( this Hashtable obj ) { return MiniJSON.jsonEncode( obj ); } public static string toJson( this Dictionary<string,string> obj ) { return MiniJSON.jsonEncode( obj ); } public static ArrayList arrayListFromJson( this string json ) { return MiniJSON.jsonDecode( json ) as ArrayList; } public static Hashtable hashtableFromJson( this string json ) { return MiniJSON.jsonDecode( json ) as Hashtable; } } #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. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureResource { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for AutoRestResourceFlatteningTestService. /// </summary> public static partial class AutoRestResourceFlatteningTestServiceExtensions { /// <summary> /// Put External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> public static void PutArray(this IAutoRestResourceFlatteningTestService operations, System.Collections.Generic.IList<Resource> resourceArray = default(System.Collections.Generic.IList<Resource>)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutArrayAsync(resourceArray), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutArrayAsync(this IAutoRestResourceFlatteningTestService operations, System.Collections.Generic.IList<Resource> resourceArray = default(System.Collections.Generic.IList<Resource>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutArrayWithHttpMessagesAsync(resourceArray, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.Collections.Generic.IList<FlattenedProduct> GetArray(this IAutoRestResourceFlatteningTestService operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetArrayAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as an Array /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<FlattenedProduct>> GetArrayAsync(this IAutoRestResourceFlatteningTestService operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetArrayWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> public static void PutDictionary(this IAutoRestResourceFlatteningTestService operations, System.Collections.Generic.IDictionary<string, FlattenedProduct> resourceDictionary = default(System.Collections.Generic.IDictionary<string, FlattenedProduct>)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutDictionaryAsync(resourceDictionary), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, System.Collections.Generic.IDictionary<string, FlattenedProduct> resourceDictionary = default(System.Collections.Generic.IDictionary<string, FlattenedProduct>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutDictionaryWithHttpMessagesAsync(resourceDictionary, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.Collections.Generic.IDictionary<string, FlattenedProduct> GetDictionary(this IAutoRestResourceFlatteningTestService operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetDictionaryAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as a Dictionary /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IDictionary<string, FlattenedProduct>> GetDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetDictionaryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> public static void PutResourceCollection(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutResourceCollectionAsync(resourceComplexObject), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PutResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PutResourceCollectionWithHttpMessagesAsync(resourceComplexObject, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static ResourceCollection GetResourceCollection(this IAutoRestResourceFlatteningTestService operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetResourceCollectionAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as a ResourceCollection /// <see href="http://tempuri.org" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ResourceCollection> GetResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetResourceCollectionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// 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.Linq; using System.Net.Http.Headers; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class ContentDispositionHeaderValueTest { [Fact] public void Ctor_ContentDispositionNull_Throw() { AssertExtensions.Throws<ArgumentException>("dispositionType", () => { new ContentDispositionHeaderValue(null); }); } [Fact] public void Ctor_ContentDispositionEmpty_Throw() { // null and empty should be treated the same. So we also throw for empty strings. AssertExtensions.Throws<ArgumentException>("dispositionType", () => { new ContentDispositionHeaderValue(string.Empty); }); } [Fact] public void Ctor_ContentDispositionInvalidFormat_ThrowFormatException() { // When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed. AssertFormatException(" inline "); AssertFormatException(" inline"); AssertFormatException("inline "); AssertFormatException("\"inline\""); AssertFormatException("te xt"); AssertFormatException("te=xt"); AssertFormatException("te\u00E4xt"); AssertFormatException("text;"); AssertFormatException("te/xt;"); AssertFormatException("inline; name=someName; "); AssertFormatException("text;name=someName"); // ctor takes only disposition-type name, no parameters } [Fact] public void Ctor_ContentDispositionValidFormat_SuccessfullyCreated() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); Assert.Equal("inline", contentDisposition.DispositionType); Assert.Equal(0, contentDisposition.Parameters.Count); Assert.Null(contentDisposition.Name); Assert.Null(contentDisposition.FileName); Assert.Null(contentDisposition.CreationDate); Assert.Null(contentDisposition.ModificationDate); Assert.Null(contentDisposition.ReadDate); Assert.Null(contentDisposition.Size); } [Fact] public void Parameters_AddNull_Throw() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); Assert.Throws<ArgumentNullException>(() => { contentDisposition.Parameters.Add(null); }); } [Fact] public void ContentDisposition_SetAndGetContentDisposition_MatchExpectations() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); Assert.Equal("inline", contentDisposition.DispositionType); contentDisposition.DispositionType = "attachment"; Assert.Equal("attachment", contentDisposition.DispositionType); } [Fact] public void Name_SetNameAndValidateObject_ParametersEntryForNameAdded() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); contentDisposition.Name = "myname"; Assert.Equal("myname", contentDisposition.Name); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("name", contentDisposition.Parameters.First().Name); contentDisposition.Name = null; Assert.Null(contentDisposition.Name); Assert.Equal(0, contentDisposition.Parameters.Count); contentDisposition.Name = null; // It's OK to set it again to null; no exception. } [Fact] public void Name_AddNameParameterThenUseProperty_ParametersEntryIsOverwritten() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue name = new NameValueHeaderValue("NAME", "old_name"); contentDisposition.Parameters.Add(name); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("NAME", contentDisposition.Parameters.First().Name); contentDisposition.Name = "new_name"; Assert.Equal("new_name", contentDisposition.Name); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("NAME", contentDisposition.Parameters.First().Name); contentDisposition.Parameters.Remove(name); Assert.Null(contentDisposition.Name); } [Fact] public void FileName_AddNameParameterThenUseProperty_ParametersEntryIsOverwritten() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue fileName = new NameValueHeaderValue("FILENAME", "old_name"); contentDisposition.Parameters.Add(fileName); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name); contentDisposition.FileName = "new_name"; Assert.Equal("new_name", contentDisposition.FileName); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name); contentDisposition.Parameters.Remove(fileName); Assert.Null(contentDisposition.FileName); } [Fact] public void FileName_NeedsEncoding_EncodedAndDecodedCorrectly() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); contentDisposition.FileName = "File\u00C3Name.bat"; Assert.Equal("File\u00C3Name.bat", contentDisposition.FileName); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("filename", contentDisposition.Parameters.First().Name); Assert.Equal("\"=?utf-8?B?RmlsZcODTmFtZS5iYXQ=?=\"", contentDisposition.Parameters.First().Value); contentDisposition.Parameters.Remove(contentDisposition.Parameters.First()); Assert.Null(contentDisposition.FileName); } [Fact] public void FileName_UnknownOrBadEncoding_PropertyFails() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue fileName = new NameValueHeaderValue("FILENAME", "\"=?utf-99?Q?R=mlsZcODTmFtZS5iYXQ=?=\""); contentDisposition.Parameters.Add(fileName); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name); Assert.Equal("\"=?utf-99?Q?R=mlsZcODTmFtZS5iYXQ=?=\"", contentDisposition.Parameters.First().Value); Assert.Equal("\"=?utf-99?Q?R=mlsZcODTmFtZS5iYXQ=?=\"", contentDisposition.FileName); contentDisposition.FileName = "new_name"; Assert.Equal("new_name", contentDisposition.FileName); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("FILENAME", contentDisposition.Parameters.First().Name); contentDisposition.Parameters.Remove(fileName); Assert.Null(contentDisposition.FileName); } [Fact] public void FileNameStar_AddNameParameterThenUseProperty_ParametersEntryIsOverwritten() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue fileNameStar = new NameValueHeaderValue("FILENAME*", "old_name"); contentDisposition.Parameters.Add(fileNameStar); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name); Assert.Null(contentDisposition.FileNameStar); // Decode failure contentDisposition.FileNameStar = "new_name"; Assert.Equal("new_name", contentDisposition.FileNameStar); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name); Assert.Equal("utf-8\'\'new_name", contentDisposition.Parameters.First().Value); contentDisposition.Parameters.Remove(fileNameStar); Assert.Null(contentDisposition.FileNameStar); } [Theory] [InlineData("no_quotes")] [InlineData("one'quote")] [InlineData("'triple'quotes'")] public void FileNameStar_NotTwoQuotes_IsNull(string value) { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue fileNameStar = new NameValueHeaderValue("FILENAME*", value); contentDisposition.Parameters.Add(fileNameStar); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Same(fileNameStar, contentDisposition.Parameters.First()); Assert.Null(contentDisposition.FileNameStar); // Decode failure } [Fact] public void FileNameStar_NeedsEncoding_EncodedAndDecodedCorrectly() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); contentDisposition.FileNameStar = "File\u00C3Name.bat"; Assert.Equal("File\u00C3Name.bat", contentDisposition.FileNameStar); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("filename*", contentDisposition.Parameters.First().Name); Assert.Equal("utf-8\'\'File%C3%83Name.bat", contentDisposition.Parameters.First().Value); contentDisposition.Parameters.Remove(contentDisposition.Parameters.First()); Assert.Null(contentDisposition.FileNameStar); } [Fact] public void FileNameStar_UnknownOrBadEncoding_PropertyFails() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue fileNameStar = new NameValueHeaderValue("FILENAME*", "utf-99'lang'File%CZName.bat"); contentDisposition.Parameters.Add(fileNameStar); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Same(fileNameStar, contentDisposition.Parameters.First()); Assert.Null(contentDisposition.FileNameStar); // Decode failure contentDisposition.FileNameStar = "new_name"; Assert.Equal("new_name", contentDisposition.FileNameStar); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("FILENAME*", contentDisposition.Parameters.First().Name); contentDisposition.Parameters.Remove(fileNameStar); Assert.Null(contentDisposition.FileNameStar); } [Fact] public void Dates_AddDateParameterThenUseProperty_ParametersEntryIsOverwritten() { string validDateString = "\"Tue, 15 Nov 1994 08:12:31 GMT\""; DateTimeOffset validDate = DateTimeOffset.Parse("Tue, 15 Nov 1994 08:12:31 GMT"); ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue dateParameter = new NameValueHeaderValue("Creation-DATE", validDateString); contentDisposition.Parameters.Add(dateParameter); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("Creation-DATE", contentDisposition.Parameters.First().Name); Assert.Equal(validDate, contentDisposition.CreationDate); DateTimeOffset newDate = validDate.AddSeconds(1); contentDisposition.CreationDate = newDate; Assert.Equal(newDate, contentDisposition.CreationDate); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("Creation-DATE", contentDisposition.Parameters.First().Name); Assert.Equal("\"Tue, 15 Nov 1994 08:12:32 GMT\"", contentDisposition.Parameters.First().Value); contentDisposition.Parameters.Remove(dateParameter); Assert.Null(contentDisposition.CreationDate); } [Fact] public void Dates_InvalidDates_PropertyFails() { string invalidDateString = "\"Tue, 15 Nov 94 08:12 GMT\""; ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue dateParameter = new NameValueHeaderValue("read-DATE", invalidDateString); contentDisposition.Parameters.Add(dateParameter); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("read-DATE", contentDisposition.Parameters.First().Name); Assert.Null(contentDisposition.ReadDate); contentDisposition.ReadDate = null; Assert.Null(contentDisposition.ReadDate); Assert.Equal(0, contentDisposition.Parameters.Count); } [Fact] public void Size_AddSizeParameterThenUseProperty_ParametersEntryIsOverwritten() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue sizeParameter = new NameValueHeaderValue("SIZE", "279172874239"); contentDisposition.Parameters.Add(sizeParameter); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("SIZE", contentDisposition.Parameters.First().Name); Assert.Equal(279172874239, contentDisposition.Size); contentDisposition.Size = 279172874240; Assert.Equal(279172874240, contentDisposition.Size); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("SIZE", contentDisposition.Parameters.First().Name); contentDisposition.Parameters.Remove(sizeParameter); Assert.Null(contentDisposition.Size); } [Fact] public void Size_InvalidSizes_PropertyFails() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); // Note that uppercase letters are used. Comparison should happen case-insensitive. NameValueHeaderValue sizeParameter = new NameValueHeaderValue("SIZE", "-279172874239"); contentDisposition.Parameters.Add(sizeParameter); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("SIZE", contentDisposition.Parameters.First().Name); Assert.Null(contentDisposition.Size); // Negatives not allowed Assert.Throws<ArgumentOutOfRangeException>(() => { contentDisposition.Size = -279172874240; }); Assert.Null(contentDisposition.Size); Assert.Equal(1, contentDisposition.Parameters.Count); Assert.Equal("SIZE", contentDisposition.Parameters.First().Name); contentDisposition.Parameters.Remove(sizeParameter); Assert.Null(contentDisposition.Size); } [Theory] [InlineData(null)] [InlineData(66)] public void Size_ValueSetGet_RoundtripsSuccessfully(int? value) { var contentDisposition = new ContentDispositionHeaderValue("inline") { Size = value }; Assert.Equal(value, contentDisposition.Size); } [Fact] public void ToString_UseDifferentContentDispositions_AllSerializedCorrectly() { ContentDispositionHeaderValue contentDisposition = new ContentDispositionHeaderValue("inline"); Assert.Equal("inline", contentDisposition.ToString()); contentDisposition.Name = "myname"; Assert.Equal("inline; name=myname", contentDisposition.ToString()); contentDisposition.FileName = "my File Name"; Assert.Equal("inline; name=myname; filename=\"my File Name\"", contentDisposition.ToString()); contentDisposition.CreationDate = new DateTimeOffset(new DateTime(2011, 2, 15, 8, 0, 0, DateTimeKind.Utc)); Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date=" + "\"Tue, 15 Feb 2011 08:00:00 GMT\"", contentDisposition.ToString()); contentDisposition.Parameters.Add(new NameValueHeaderValue("custom", "\"custom value\"")); Assert.Equal("inline; name=myname; filename=\"my File Name\"; creation-date=" + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"", contentDisposition.ToString()); contentDisposition.Name = null; Assert.Equal("inline; filename=\"my File Name\"; creation-date=" + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"", contentDisposition.ToString()); contentDisposition.FileNameStar = "File%Name"; Assert.Equal("inline; filename=\"my File Name\"; creation-date=" + "\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\"; filename*=utf-8\'\'File%25Name", contentDisposition.ToString()); contentDisposition.FileName = null; Assert.Equal("inline; creation-date=\"Tue, 15 Feb 2011 08:00:00 GMT\"; custom=\"custom value\";" + " filename*=utf-8\'\'File%25Name", contentDisposition.ToString()); contentDisposition.CreationDate = null; Assert.Equal("inline; custom=\"custom value\"; filename*=utf-8\'\'File%25Name", contentDisposition.ToString()); } [Fact] public void GetHashCode_UseContentDispositionWithAndWithoutParameters_SameOrDifferentHashCodes() { ContentDispositionHeaderValue contentDisposition1 = new ContentDispositionHeaderValue("inline"); ContentDispositionHeaderValue contentDisposition2 = new ContentDispositionHeaderValue("inline"); contentDisposition2.Name = "myname"; ContentDispositionHeaderValue contentDisposition3 = new ContentDispositionHeaderValue("inline"); contentDisposition3.Parameters.Add(new NameValueHeaderValue("name", "value")); ContentDispositionHeaderValue contentDisposition4 = new ContentDispositionHeaderValue("INLINE"); ContentDispositionHeaderValue contentDisposition5 = new ContentDispositionHeaderValue("INLINE"); contentDisposition5.Parameters.Add(new NameValueHeaderValue("NAME", "MYNAME")); Assert.NotEqual(contentDisposition1.GetHashCode(), contentDisposition2.GetHashCode()); // "No params vs. name." Assert.NotEqual(contentDisposition1.GetHashCode(), contentDisposition3.GetHashCode()); // "No params vs. custom param." Assert.NotEqual(contentDisposition2.GetHashCode(), contentDisposition3.GetHashCode()); // "name vs. custom param." Assert.Equal(contentDisposition1.GetHashCode(), contentDisposition4.GetHashCode()); // "Different casing." Assert.Equal(contentDisposition2.GetHashCode(), contentDisposition5.GetHashCode()); // "Different casing in name." } [Fact] public void Equals_UseContentDispositionWithAndWithoutParameters_EqualOrNotEqualNoExceptions() { ContentDispositionHeaderValue contentDisposition1 = new ContentDispositionHeaderValue("inline"); ContentDispositionHeaderValue contentDisposition2 = new ContentDispositionHeaderValue("inline"); contentDisposition2.Name = "myName"; ContentDispositionHeaderValue contentDisposition3 = new ContentDispositionHeaderValue("inline"); contentDisposition3.Parameters.Add(new NameValueHeaderValue("name", "value")); ContentDispositionHeaderValue contentDisposition4 = new ContentDispositionHeaderValue("INLINE"); ContentDispositionHeaderValue contentDisposition5 = new ContentDispositionHeaderValue("INLINE"); contentDisposition5.Parameters.Add(new NameValueHeaderValue("NAME", "MYNAME")); ContentDispositionHeaderValue contentDisposition6 = new ContentDispositionHeaderValue("INLINE"); contentDisposition6.Parameters.Add(new NameValueHeaderValue("NAME", "MYNAME")); contentDisposition6.Parameters.Add(new NameValueHeaderValue("custom", "value")); ContentDispositionHeaderValue contentDisposition7 = new ContentDispositionHeaderValue("attachment"); Assert.False(contentDisposition1.Equals(contentDisposition2)); // "No params vs. name." Assert.False(contentDisposition2.Equals(contentDisposition1)); // "name vs. no params." Assert.False(contentDisposition1.Equals(null)); // "No params vs. <null>." Assert.False(contentDisposition1.Equals(contentDisposition3)); // "No params vs. custom param." Assert.False(contentDisposition2.Equals(contentDisposition3)); // "name vs. custom param." Assert.True(contentDisposition1.Equals(contentDisposition4)); // "Different casing." Assert.True(contentDisposition2.Equals(contentDisposition5)); // "Different casing in name." Assert.False(contentDisposition5.Equals(contentDisposition6)); // "name vs. custom param." Assert.False(contentDisposition1.Equals(contentDisposition7)); // "inline vs. text/other." } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { ContentDispositionHeaderValue source = new ContentDispositionHeaderValue("attachment"); ContentDispositionHeaderValue clone = (ContentDispositionHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.DispositionType, clone.DispositionType); Assert.Equal(0, clone.Parameters.Count); source.Name = "myName"; clone = (ContentDispositionHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.DispositionType, clone.DispositionType); Assert.Equal("myName", clone.Name); Assert.Equal(1, clone.Parameters.Count); source.Parameters.Add(new NameValueHeaderValue("custom", "customValue")); clone = (ContentDispositionHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.DispositionType, clone.DispositionType); Assert.Equal("myName", clone.Name); Assert.Equal(2, clone.Parameters.Count); Assert.Equal("custom", clone.Parameters.ElementAt(1).Name); Assert.Equal("customValue", clone.Parameters.ElementAt(1).Value); } [Fact] public void GetDispositionTypeLength_DifferentValidScenarios_AllReturnNonZero() { object result = null; ContentDispositionHeaderValue value = null; Assert.Equal(7, ContentDispositionHeaderValue.GetDispositionTypeLength("inline , other/name", 0, out result)); value = (ContentDispositionHeaderValue)result; Assert.Equal("inline", value.DispositionType); Assert.Equal(0, value.Parameters.Count); Assert.Equal(6, ContentDispositionHeaderValue.GetDispositionTypeLength("inline", 0, out result)); value = (ContentDispositionHeaderValue)result; Assert.Equal("inline", value.DispositionType); Assert.Equal(0, value.Parameters.Count); Assert.Equal(19, ContentDispositionHeaderValue.GetDispositionTypeLength("inline; name=MyName", 0, out result)); value = (ContentDispositionHeaderValue)result; Assert.Equal("inline", value.DispositionType); Assert.Equal("MyName", value.Name); Assert.Equal(1, value.Parameters.Count); Assert.Equal(32, ContentDispositionHeaderValue.GetDispositionTypeLength(" inline; custom=value;name=myName", 1, out result)); value = (ContentDispositionHeaderValue)result; Assert.Equal("inline", value.DispositionType); Assert.Equal("myName", value.Name); Assert.Equal(2, value.Parameters.Count); Assert.Equal(14, ContentDispositionHeaderValue.GetDispositionTypeLength(" inline; custom, next", 1, out result)); value = (ContentDispositionHeaderValue)result; Assert.Equal("inline", value.DispositionType); Assert.Null(value.Name); Assert.Equal(1, value.Parameters.Count); Assert.Equal("custom", value.Parameters.ElementAt(0).Name); Assert.Null(value.Parameters.ElementAt(0).Value); Assert.Equal(40, ContentDispositionHeaderValue.GetDispositionTypeLength( "inline ; custom =\r\n \"x\" ; name = myName , next", 0, out result)); value = (ContentDispositionHeaderValue)result; Assert.Equal("inline", value.DispositionType); Assert.Equal("myName", value.Name); Assert.Equal(2, value.Parameters.Count); Assert.Equal("custom", value.Parameters.ElementAt(0).Name); Assert.Equal("\"x\"", value.Parameters.ElementAt(0).Value); Assert.Equal("name", value.Parameters.ElementAt(1).Name); Assert.Equal("myName", value.Parameters.ElementAt(1).Value); Assert.Equal(29, ContentDispositionHeaderValue.GetDispositionTypeLength( "inline;custom=\"x\";name=myName,next", 0, out result)); value = (ContentDispositionHeaderValue)result; Assert.Equal("inline", value.DispositionType); Assert.Equal("myName", value.Name); Assert.Equal(2, value.Parameters.Count); Assert.Equal("custom", value.Parameters.ElementAt(0).Name); Assert.Equal("\"x\"", value.Parameters.ElementAt(0).Value); Assert.Equal("name", value.Parameters.ElementAt(1).Name); Assert.Equal("myName", value.Parameters.ElementAt(1).Value); } [Fact] public void GetDispositionTypeLength_DifferentInvalidScenarios_AllReturnZero() { object result = null; Assert.Equal(0, ContentDispositionHeaderValue.GetDispositionTypeLength(" inline", 0, out result)); Assert.Null(result); Assert.Equal(0, ContentDispositionHeaderValue.GetDispositionTypeLength("inline;", 0, out result)); Assert.Null(result); Assert.Equal(0, ContentDispositionHeaderValue.GetDispositionTypeLength("inline;name=", 0, out result)); Assert.Null(result); Assert.Equal(0, ContentDispositionHeaderValue.GetDispositionTypeLength("inline;name=value;", 0, out result)); Assert.Null(result); Assert.Equal(0, ContentDispositionHeaderValue.GetDispositionTypeLength("inline;", 0, out result)); Assert.Null(result); Assert.Equal(0, ContentDispositionHeaderValue.GetDispositionTypeLength(null, 0, out result)); Assert.Null(result); Assert.Equal(0, ContentDispositionHeaderValue.GetDispositionTypeLength(string.Empty, 0, out result)); Assert.Null(result); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { ContentDispositionHeaderValue expected = new ContentDispositionHeaderValue("inline"); CheckValidParse("\r\n inline ", expected); CheckValidParse("inline", expected); // We don't have to test all possible input strings, since most of the pieces are handled by other parsers. // The purpose of this test is to verify that these other parsers are combined correctly to build a // Content-Disposition parser. expected.Name = "myName"; CheckValidParse("\r\n inline ; name = myName ", expected); CheckValidParse(" inline;name=myName", expected); expected.Name = null; expected.DispositionType = "attachment"; expected.FileName = "foo-ae.html"; expected.Parameters.Add(new NameValueHeaderValue("filename*", "UTF-8''foo-%c3%a4.html")); CheckValidParse(@"attachment; filename*=UTF-8''foo-%c3%a4.html; filename=foo-ae.html", expected); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse(""); CheckInvalidParse(" "); CheckInvalidParse(null); CheckInvalidParse("inline\u4F1A"); CheckInvalidParse("inline ,"); CheckInvalidParse("inline,"); CheckInvalidParse("inline; name=myName ,"); CheckInvalidParse("inline; name=myName,"); CheckInvalidParse("inline; name=my\u4F1AName"); CheckInvalidParse("inline/"); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { ContentDispositionHeaderValue expected = new ContentDispositionHeaderValue("inline"); CheckValidTryParse("\r\n inline ", expected); CheckValidTryParse("inline", expected); // We don't have to test all possible input strings, since most of the pieces are handled by other parsers. // The purpose of this test is to verify that these other parsers are combined correctly to build a // Content-Disposition parser. expected.Name = "myName"; CheckValidTryParse("\r\n inline ; name = myName ", expected); CheckValidTryParse(" inline;name=myName", expected); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse(""); CheckInvalidTryParse(" "); CheckInvalidTryParse(null); CheckInvalidTryParse("inline\u4F1A"); CheckInvalidTryParse("inline ,"); CheckInvalidTryParse("inline,"); CheckInvalidTryParse("inline; name=myName ,"); CheckInvalidTryParse("inline; name=myName,"); CheckInvalidTryParse("text/"); } #region Tests from HenrikN private static Dictionary<string, ContentDispositionValue> ContentDispositionTestCases = new Dictionary<string, ContentDispositionValue>() { // Valid values { "valid1", new ContentDispositionValue(@"inline", @"This should be equivalent to not including the header at all.", true) }, { "valid2", new ContentDispositionValue(@"inline; filename=""foo.html""", @"'inline', specifying a filename of foo.html", true) }, { "valid3", new ContentDispositionValue(@"inline; filename=""Not an attachment!""", @"'inline', specifying a filename of Not an attachment! - this checks for proper parsing for disposition types.", true) }, { "valid4", new ContentDispositionValue(@"inline; filename=""foo.pdf""", @"'inline', specifying a filename of foo.pdf", true) }, { "valid5", new ContentDispositionValue(@"attachment", @"'attachment' only", true) }, { "valid6", new ContentDispositionValue(@"ATTACHMENT", @"'ATTACHMENT' only", true) }, { "valid7", new ContentDispositionValue(@"attachment; filename=""foo.html""", @"'attachment', specifying a filename of foo.html", true) }, { "valid8", new ContentDispositionValue(@"attachment; filename=""f\oo.html""", @"'attachment', specifying a filename of f\oo.html (the first 'o' being escaped)", true) }, { "valid9", new ContentDispositionValue(@"attachment; filename=""\""quoting\"" tested.html""", @"'attachment', specifying a filename of \""quoting\"" tested.html (using double quotes around ""quoting"" to test... quoting)", true) }, { "valid10", new ContentDispositionValue(@"attachment; filename=""Here's a semicolon;.html""", @"'attachment', specifying a filename of Here's a semicolon;.html - this checks for proper parsing for parameters. ", true) }, { "valid11", new ContentDispositionValue(@"attachment; foo=""bar""; filename=""foo.html""", @"'attachment', specifying a filename of foo.html and an extension parameter ""foo"" which should be ignored (see <a href=""http://greenbytes.de/tech/webdav/rfc2183.html#rfc.section.2.8"">Section 2.8 of RFC 2183</a>.).", true) }, { "valid12", new ContentDispositionValue(@"attachment; foo=""\""\\"";filename=""foo.html""", @"'attachment', specifying a filename of foo.html and an extension parameter ""foo"" which should be ignored (see <a href=""http://greenbytes.de/tech/webdav/rfc2183.html#rfc.section.2.8"">Section 2.8 of RFC 2183</a>.). The extension parameter actually uses backslash-escapes. This tests whether the UA properly skips the parameter.", true) }, { "valid13", new ContentDispositionValue(@"attachment; FILENAME=""foo.html""", @"'attachment', specifying a filename of foo.html", true) }, { "valid14", new ContentDispositionValue(@"attachment; filename=foo.html", @"'attachment', specifying a filename of foo.html using a token instead of a quoted-string.", true) }, { "valid15", new ContentDispositionValue(@"attachment; filename='foo.bar'", @"'attachment', specifying a filename of 'foo.bar' using single quotes. ", true) }, { "valid16", new ContentDispositionValue(@"attachment; filename=""foo-\u00E4.html""", @"'attachment', specifying a filename of foo-\u00E4.html, using plain ISO-8859-1", true) }, { "valid17", new ContentDispositionValue(@"attachment; filename=""foo-&#xc3;&#xa4;.html""", @"'attachment', specifying a filename of foo-&#xc3;&#xa4;.html, which happens to be foo-\u00E4.html using UTF-8 encoding.", true) }, { "valid18", new ContentDispositionValue(@"attachment; filename=""foo-%41.html""", @"'attachment', specifying a filename of foo-%41.html", true) }, { "valid19", new ContentDispositionValue(@"attachment; filename=""50%.html""", @"'attachment', specifying a filename of 50%.html", true) }, { "valid20", new ContentDispositionValue(@"attachment; filename=""foo-%\41.html""", @"'attachment', specifying a filename of foo-%41.html, using an escape character (this tests whether adding an escape character inside a %xx sequence can be used to disable the non-conformant %xx-unescaping).", true) }, { "valid21", new ContentDispositionValue(@"attachment; name=""foo-%41.html""", @"'attachment', specifying a <i>name</i> parameter of foo-%41.html. (this test was added to observe the behavior of the (unspecified) treatment of ""name"" as synonym for ""filename""; see <a href=""http://www.imc.org/ietf-smtp/mail-archive/msg05023.html"">Ned Freed's summary</a> where this comes from in MIME messages)", true) }, { "valid22", new ContentDispositionValue(@"attachment; filename=""\u00E4-%41.html""", @"'attachment', specifying a filename parameter of \u00E4-%41.html. (this test was added to observe the behavior when non-ASCII characters and percent-hexdig sequences are combined)", true) }, { "valid23", new ContentDispositionValue(@"attachment; filename=""foo-%c3%a4-%e2%82%ac.html""", @"'attachment', specifying a filename of foo-%c3%a4-%e2%82%ac.html, using raw percent encoded UTF-8 to represent foo-\u00E4-&#x20ac;.html", true) }, { "valid24", new ContentDispositionValue(@"attachment; filename =""foo.html""", @"'attachment', specifying a filename of foo.html, with one blank space <em>before</em> the equals character.", true) }, { "valid25", new ContentDispositionValue(@"attachment; xfilename=foo.html", @"'attachment', specifying an ""xfilename"" parameter.", true) }, { "valid26", new ContentDispositionValue(@"attachment; filename=""/foo.html""", @"'attachment', specifying an absolute filename in the filesystem root.", true) }, { "valid27", new ContentDispositionValue(@"attachment; filename=""\\foo.html""", @"'attachment', specifying an absolute filename in the filesystem root.", true) }, { "valid28", new ContentDispositionValue(@"attachment; creation-date=""Wed, 12 Feb 1997 16:29:51 -0500""", @"'attachment', plus creation-date (see <a href=""http://greenbytes.de/tech/webdav/rfc2183.html#rfc.section.2.4"">Section 2.4 of RFC 2183</a>)", true) }, { "valid29", new ContentDispositionValue(@"attachment; modification-date=""Wed, 12 Feb 1997 16:29:51 -0500""", @"'attachment', plus modification-date (see <a href=""http://greenbytes.de/tech/webdav/rfc2183.html#rfc.section.2.5"">Section 2.5 of RFC 2183</a>)", true) }, { "valid30", new ContentDispositionValue(@"foobar", @"This should be equivalent to using ""attachment"".", true) }, { "valid31", new ContentDispositionValue(@"attachment; example=""filename=example.txt""", @"'attachment', with no filename parameter", true) }, { "valid32", new ContentDispositionValue(@"attachment; filename*=iso-8859-1''foo-%E4.html", @"'attachment', specifying a filename of foo-\u00E4.html, using RFC2231 encoded ISO-8859-1", true) }, { "valid33", new ContentDispositionValue(@"attachment; filename*=UTF-8''foo-%c3%a4-%e2%82%ac.html", @"'attachment', specifying a filename of foo-\u00E4-&#x20ac;.html, using RFC2231 encoded UTF-8", true) }, { "valid34", new ContentDispositionValue(@"attachment; filename*=''foo-%c3%a4-%e2%82%ac.html", @"Behavior is undefined in RFC 2231, the charset part is missing, although UTF-8 was used.", true) }, { "valid35", new ContentDispositionValue(@"attachment; filename*=UTF-8''foo-a%cc%88.html", @"'attachment', specifying a filename of foo-\u00E4.html, using RFC2231 encoded UTF-8, but choosing the decomposed form (lowercase a plus COMBINING DIAERESIS) -- on a Windows target system, this should be translated to the preferred Unicode normal form (composed).", true) }, { "valid36", new ContentDispositionValue(@"attachment; filename*= UTF-8''foo-%c3%a4.html", @"'attachment', specifying a filename of foo-\u00E4.html, using RFC2231 encoded UTF-8, with whitespace after ""*=""", true) }, { "valid37", new ContentDispositionValue(@"attachment; filename* =UTF-8''foo-%c3%a4.html", @"'attachment', specifying a filename of foo-\u00E4.html, using RFC2231 encoded UTF-8, with whitespace inside ""* =""", true) }, { "valid38", new ContentDispositionValue(@"attachment; filename*=UTF-8''A-%2541.html", @"'attachment', specifying a filename of A-%41.html, using RFC2231 encoded UTF-8.", true) }, { "valid39", new ContentDispositionValue(@"attachment; filename*=UTF-8''%5cfoo.html", @"'attachment', specifying a filename of /foo.html, using RFC2231 encoded UTF-8.", true) }, { "valid40", new ContentDispositionValue(@"attachment; filename*0=""foo.""; filename*1=""html""", @"'attachment', specifying a filename of foo.html, using RFC2231-style parameter continuations.", true) }, { "valid41", new ContentDispositionValue(@"attachment; filename*0*=UTF-8''foo-%c3%a4; filename*1="".html""", @"'attachment', specifying a filename of foo-\u00E4.html, using both RFC2231-style parameter continuations and UTF-8 encoding.", true) }, { "valid42", new ContentDispositionValue(@"attachment; filename*0=""foo""; filename*01=""bar""", @"'attachment', specifying a filename of foo (the parameter filename*01 should be ignored because of the leading zero)", true) }, { "valid43", new ContentDispositionValue(@"attachment; filename*0=""foo""; filename*2=""bar""", @"'attachment', specifying a filename of foo (the parameter filename*2 should be ignored because there's no filename*1 parameter)", true) }, { "valid44", new ContentDispositionValue(@"attachment; filename*1=""foo.""; filename*2=""html""", @"'attachment' (the filename* parameters should be ignored because filename*0 is missing)", true) }, { "valid45", new ContentDispositionValue(@"attachment; filename*1=""bar""; filename*0=""foo""", "'attachment', specifying a filename of foobar", true) }, { "valid46", new ContentDispositionValue(@"attachment; filename=""foo-ae.html""; filename*=UTF-8''foo-%c3%a4.html", @"'attachment', specifying a filename of foo-ae.html in the traditional format, and foo-\u00E4.html in RFC2231 format.", true) }, { "valid47", new ContentDispositionValue(@"attachment; filename*=UTF-8''foo-%c3%a4.html; filename=""foo-ae.html""", @"'attachment', specifying a filename of foo-ae.html in the traditional format, and foo-\u00E4.html in RFC2231 format.", true) }, { "valid48", new ContentDispositionValue(@"attachment; foobar=x; filename=""foo.html""", @"'attachment', specifying a new parameter ""foobar"", plus a filename of foo.html in the traditional format.", true) }, { "valid49", new ContentDispositionValue(@"attachment; filename=""=?ISO-8859-1?Q?foo-=E4.html?=""", @"attachment; filename=""=?ISO-8859-1?Q?foo-=E4.html?=""", true) }, { "valid50", new ContentDispositionValue(@"attachment; filename=""=?utf-8?B?Zm9vLeQuaHRtbA==?=""", @"attachment; filename=""=?utf-8?B?Zm9vLeQuaHRtbA==?=""", true) }, // Invalid values { "invalid1", new ContentDispositionValue(@"""inline""", @"'inline' only, using double quotes", false) }, { "invalid2", new ContentDispositionValue(@"""attachment""", @"'attachment' only, using double quotes", false) }, { "invalid3", new ContentDispositionValue(@"attachment; filename=foo.html ;", @"'attachment', specifying a filename of foo.html using a token instead of a quoted-string, and adding a trailing semicolon.", false) }, { "invalid4", new ContentDispositionValue(@"attachment; filename=foo bar.html", @"'attachment', specifying a filename of foo bar.html without using quoting.", false) }, { "invalid6", new ContentDispositionValue(@"attachment; filename=foo[1](2).html", @"'attachment', specifying a filename of foo[1](2).html, but missing the quotes. Also, ""["", ""]"", ""("" and "")"" are not allowed in the HTTP <a href=""http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p1-messaging-latest.html#rfc.section.1.2.2"">token</a> production.", false) }, { "invalid7", new ContentDispositionValue(@"attachment; filename=foo-\u00E4.html", @"'attachment', specifying a filename of foo-\u00E4.html, but missing the quotes.", false) }, { "invalid9", new ContentDispositionValue(@"filename=foo.html", @"Disposition type missing, filename specified.", false) }, { "invalid10", new ContentDispositionValue(@"x=y; filename=foo.html", @"Disposition type missing, filename specified after extension parameter.", false) }, { "invalid11", new ContentDispositionValue(@"""foo; filename=bar;baz""; filename=qux", @"Disposition type missing, filename ""qux"". Can it be more broken? (Probably)", false) }, { "invalid12", new ContentDispositionValue(@"filename=foo.html, filename=bar.html", @"Disposition type missing, two filenames specified separated by a comma (this is syntactically equivalent to have two instances of the header with one filename parameter each).", false) }, { "invalid13", new ContentDispositionValue(@"; filename=foo.html", @"Disposition type missing (but delimiter present), filename specified.", false) }, { "invalid16", new ContentDispositionValue(@"attachment; filename=""foo.html"".txt", @"'attachment', specifying a filename parameter that is broken (quoted-string followed by more characters). This is invalid syntax. ", false) }, { "invalid17", new ContentDispositionValue(@"attachment; filename=""bar", @"'attachment', specifying a filename parameter that is broken (missing ending double quote). This is invalid syntax.", false) }, { "invalid18", new ContentDispositionValue(@"attachment; filename=foo""bar;baz""qux", @"'attachment', specifying a filename parameter that is broken (disallowed characters in token syntax). This is invalid syntax.", false) }, { "invalid19", new ContentDispositionValue(@"attachment; filename=foo.html, attachment; filename=bar.html", @"'attachment', two comma-separated instances of the header field. As Content-Disposition doesn't use a list-style syntax, this is invalid syntax and, according to <a href=""http://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.4.2.p.5"">RFC 2616, Section 4.2</a>, roughly equivalent to having two separate header field instances.", false) }, { "invalid20", new ContentDispositionValue(@"filename=foo.html; attachment", @"filename parameter and disposition type reversed.", false) }, { "invalid24", new ContentDispositionValue(@"attachment; filename==?ISO-8859-1?Q?foo-=E4.html?=", @"Uses RFC 2047 style encoded word. ""="" is invalid inside the token production, so this is invalid.", false) }, { "invalid25", new ContentDispositionValue(@"attachment; filename==?utf-8?B?Zm9vLeQuaHRtbA==?=", @"Uses RFC 2047 style encoded word. ""="" is invalid inside the token production, so this is invalid.", false) }, }; #region Parsing [Fact] public void ContentDispositionHeaderValue_Parse_ExpectedResult() { foreach (var cd in ContentDispositionTestCases.Values) { ContentDispositionHeaderValue header = Parse(cd); } } [Fact] public void ContentDispositionHeaderValue_TryParse_ExpectedResult() { foreach (var cd in ContentDispositionTestCases.Values) { ContentDispositionHeaderValue header = TryParse(cd); } } [Fact] public void ContentDispositionHeader_Valid1_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid1"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "inline", null); } [Fact] public void ContentDispositionHeader_Valid2_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid2"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "inline", @"""foo.html"""); } [Fact] public void ContentDispositionHeader_Valid3_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid3"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "inline", @"""Not an attachment!"""); } [Fact] public void ContentDispositionHeader_Valid4_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid4"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "inline", @"""foo.pdf"""); } [Fact] public void ContentDispositionHeader_Valid5_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid5"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); } [Fact] public void ContentDispositionHeader_Valid6_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid6"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "ATTACHMENT", null); } [Fact] public void ContentDispositionHeader_Valid7_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid7"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo.html"""); } [Fact] public void ContentDispositionHeader_Valid8_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid8"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""f\oo.html"""); } [Fact] public void ContentDispositionHeader_Valid9_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid9"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""\""quoting\"" tested.html"""); } [Fact] public void ContentDispositionHeader_Valid10_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid10"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""Here's a semicolon;.html"""); } [Fact] public void ContentDispositionHeader_Valid11_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid11"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo.html"""); ValidateExtensionParameter(header, "foo", @"""bar"""); } [Fact] public void ContentDispositionHeader_Valid12_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid12"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo.html"""); ValidateExtensionParameter(header, "foo", @"""\""\\"""); } [Fact] public void ContentDispositionHeader_Valid13_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid13"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo.html"""); } [Fact] public void ContentDispositionHeader_Valid14_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid14"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"foo.html"); } [Fact] public void ContentDispositionHeader_Valid15_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid15"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"'foo.bar'"); } [Fact] public void ContentDispositionHeader_Valid16_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid16"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo-\u00E4.html"""); } [Fact] public void ContentDispositionHeader_Valid17_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid17"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo-&#xc3;&#xa4;.html"""); } [Fact] public void ContentDispositionHeader_Valid18_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid18"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo-%41.html"""); } [Fact] public void ContentDispositionHeader_Valid19_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid19"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""50%.html"""); } [Fact] public void ContentDispositionHeader_Valid20_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid20"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo-%\41.html"""); } [Fact] public void ContentDispositionHeader_Valid21_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid21"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "name", @"""foo-%41.html"""); } [Fact] public void ContentDispositionHeader_Valid22_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid22"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""\u00E4-%41.html"""); } [Fact] public void ContentDispositionHeader_Valid23_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid23"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo-%c3%a4-%e2%82%ac.html"""); } [Fact] public void ContentDispositionHeader_Valid24_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid24"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo.html"""); } [Fact] public void ContentDispositionHeader_Valid25_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid25"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "xfilename", @"foo.html"); } [Fact] public void ContentDispositionHeader_Valid26_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid26"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""/foo.html"""); } [Fact] public void ContentDispositionHeader_Valid27_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid27"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""\\foo.html"""); } [Fact] public void ContentDispositionHeader_Valid28_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid28"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "creation-date", @"""Wed, 12 Feb 1997 16:29:51 -0500"""); } [Fact] public void ContentDispositionHeader_Valid29_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid29"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "modification-date", @"""Wed, 12 Feb 1997 16:29:51 -0500"""); } [Fact] public void ContentDispositionHeader_Valid30_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid30"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "foobar", null); } [Fact] public void ContentDispositionHeader_Valid31_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid31"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "example", @"""filename=example.txt"""); } [Fact] public void ContentDispositionHeader_Valid32_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid32"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*", @"iso-8859-1''foo-%E4.html"); } [Fact] public void ContentDispositionHeader_Valid33_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid33"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*", @"UTF-8''foo-%c3%a4-%e2%82%ac.html"); } [Fact] public void ContentDispositionHeader_Valid34_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid34"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*", @"''foo-%c3%a4-%e2%82%ac.html"); } [Fact] public void ContentDispositionHeader_Valid35_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid35"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*", @"UTF-8''foo-a%cc%88.html"); } [Fact] public void ContentDispositionHeader_Valid36_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid36"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*", @"UTF-8''foo-%c3%a4.html"); } [Fact] public void ContentDispositionHeader_Valid37_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid37"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*", @"UTF-8''foo-%c3%a4.html"); } [Fact] public void ContentDispositionHeader_Valid38_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid38"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*", @"UTF-8''A-%2541.html"); } [Fact] public void ContentDispositionHeader_Valid39_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid39"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*", @"UTF-8''%5cfoo.html"); } [Fact] public void ContentDispositionHeader_Valid40_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid40"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*0", @"""foo."""); ValidateExtensionParameter(header, "filename*1", @"""html"""); } [Fact] public void ContentDispositionHeader_Valid41_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid41"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*0*", @"UTF-8''foo-%c3%a4"); ValidateExtensionParameter(header, "filename*1", @""".html"""); } [Fact] public void ContentDispositionHeader_Valid42_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid42"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*0", @"""foo"""); ValidateExtensionParameter(header, "filename*01", @"""bar"""); } [Fact] public void ContentDispositionHeader_Valid43_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid43"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*0", @"""foo"""); ValidateExtensionParameter(header, "filename*2", @"""bar"""); } [Fact] public void ContentDispositionHeader_Valid44_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid44"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*1", @"""foo."""); ValidateExtensionParameter(header, "filename*2", @"""html"""); } [Fact] public void ContentDispositionHeader_Valid45_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid45"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", null); ValidateExtensionParameter(header, "filename*0", @"""foo"""); ValidateExtensionParameter(header, "filename*1", @"""bar"""); } [Fact] public void ContentDispositionHeader_Valid46_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid46"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo-ae.html"""); ValidateExtensionParameter(header, "filename*", @"UTF-8''foo-%c3%a4.html"); } [Fact] public void ContentDispositionHeader_Valid47_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid47"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo-ae.html"""); ValidateExtensionParameter(header, "filename*", @"UTF-8''foo-%c3%a4.html"); } [Fact] public void ContentDispositionHeader_Valid48_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid48"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""foo.html"""); ValidateExtensionParameter(header, "foobar", @"x"); } [Fact] public void ContentDispositionHeader_Valid49_Success() { ContentDispositionValue cd = ContentDispositionTestCases["valid49"]; ContentDispositionHeaderValue header = TryParse(cd); ValidateHeaderValues(header, "attachment", @"""=?ISO-8859-1?Q?foo-=E4.html?="""); } #endregion private static void ValidateHeaderValues(ContentDispositionHeaderValue header, string expectedDispositionType, string expectedFilename) { Assert.NotNull(header); Assert.Equal(expectedDispositionType, header.DispositionType); Assert.Equal(expectedFilename, header.FileName); } private static void ValidateExtensionParameter(ContentDispositionHeaderValue header, string name, string expectedValue) { Assert.NotNull(header); NameValueHeaderValue parameter = FindParameter(header.Parameters, name); Assert.NotNull(parameter); Assert.Equal(expectedValue, parameter.Value); } private static NameValueHeaderValue FindParameter(ICollection<NameValueHeaderValue> values, string name) { if ((values == null) || (values.Count == 0)) { return null; } foreach (var value in values) { if (string.Equals(value.Name, name, StringComparison.OrdinalIgnoreCase)) { return value; } } return null; } private static ContentDispositionHeaderValue Parse(ContentDispositionValue cd) { Assert.NotNull(cd); ContentDispositionHeaderValue header = null; if (cd.Valid) { header = ContentDispositionHeaderValue.Parse(cd.Value); Assert.NotNull(header); } else { Assert.Throws<FormatException>(() => { header = ContentDispositionHeaderValue.Parse(cd.Value); }); } return header; } private static ContentDispositionHeaderValue TryParse(ContentDispositionValue cd) { Assert.NotNull(cd); ContentDispositionHeaderValue header; if (cd.Valid) { Assert.True(ContentDispositionHeaderValue.TryParse(cd.Value, out header)); Assert.NotNull(header); } else { Assert.False(ContentDispositionHeaderValue.TryParse(cd.Value, out header)); Assert.Null(header); } return header; } public class ContentDispositionValue { public ContentDispositionValue(string value, string description, bool valid) { this.Value = value; this.Description = description; this.Valid = valid; } public string Value { get; private set; } public string Description { get; private set; } public bool Valid { get; private set; } } #endregion Tests from HenrikN #region Helper methods private void CheckValidParse(string input, ContentDispositionHeaderValue expectedResult) { ContentDispositionHeaderValue result = ContentDispositionHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { ContentDispositionHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, ContentDispositionHeaderValue expectedResult) { ContentDispositionHeaderValue result = null; Assert.True(ContentDispositionHeaderValue.TryParse(input, out result), input); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { ContentDispositionHeaderValue result = null; Assert.False(ContentDispositionHeaderValue.TryParse(input, out result), input); Assert.Null(result); } private static void AssertFormatException(string contentDisposition) { Assert.Throws<FormatException>(() => { new ContentDispositionHeaderValue(contentDisposition); }); } #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/log.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/log.proto</summary> public static partial class LogReflection { #region Descriptor /// <summary>File descriptor for google/api/log.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static LogReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChRnb29nbGUvYXBpL2xvZy5wcm90bxIKZ29vZ2xlLmFwaRoWZ29vZ2xlL2Fw", "aS9sYWJlbC5wcm90byJ1Cg1Mb2dEZXNjcmlwdG9yEgwKBG5hbWUYASABKAkS", "KwoGbGFiZWxzGAIgAygLMhsuZ29vZ2xlLmFwaS5MYWJlbERlc2NyaXB0b3IS", "EwoLZGVzY3JpcHRpb24YAyABKAkSFAoMZGlzcGxheV9uYW1lGAQgASgJQmoK", "DmNvbS5nb29nbGUuYXBpQghMb2dQcm90b1ABWkVnb29nbGUuZ29sYW5nLm9y", "Zy9nZW5wcm90by9nb29nbGVhcGlzL2FwaS9zZXJ2aWNlY29uZmlnO3NlcnZp", "Y2Vjb25maWeiAgRHQVBJYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.LabelReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.LogDescriptor), global::Google.Api.LogDescriptor.Parser, new[]{ "Name", "Labels", "Description", "DisplayName" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// A description of a log type. Example in YAML format: /// /// - name: library.googleapis.com/activity_history /// description: The history of borrowing and returning library items. /// display_name: Activity /// labels: /// - key: /customer_id /// description: Identifier of a library customer /// </summary> public sealed partial class LogDescriptor : pb::IMessage<LogDescriptor> { private static readonly pb::MessageParser<LogDescriptor> _parser = new pb::MessageParser<LogDescriptor>(() => new LogDescriptor()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<LogDescriptor> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.LogReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogDescriptor() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogDescriptor(LogDescriptor other) : this() { name_ = other.name_; labels_ = other.labels_.Clone(); description_ = other.description_; displayName_ = other.displayName_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LogDescriptor Clone() { return new LogDescriptor(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The name of the log. It must be less than 512 characters long and can /// include the following characters: upper- and lower-case alphanumeric /// characters [A-Za-z0-9], and punctuation characters including /// slash, underscore, hyphen, period [/_-.]. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "labels" field.</summary> public const int LabelsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Api.LabelDescriptor> _repeated_labels_codec = pb::FieldCodec.ForMessage(18, global::Google.Api.LabelDescriptor.Parser); private readonly pbc::RepeatedField<global::Google.Api.LabelDescriptor> labels_ = new pbc::RepeatedField<global::Google.Api.LabelDescriptor>(); /// <summary> /// The set of labels that are available to describe a specific log entry. /// Runtime requests that contain labels not specified here are /// considered invalid. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.LabelDescriptor> Labels { get { return labels_; } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 3; private string description_ = ""; /// <summary> /// A human-readable description of this log. This information appears in /// the documentation and can contain details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "display_name" field.</summary> public const int DisplayNameFieldNumber = 4; private string displayName_ = ""; /// <summary> /// The human-readable name for this log. This information appears on /// the user interface and should be concise. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string DisplayName { get { return displayName_; } set { displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as LogDescriptor); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(LogDescriptor other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if(!labels_.Equals(other.labels_)) return false; if (Description != other.Description) return false; if (DisplayName != other.DisplayName) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); hash ^= labels_.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); if (DisplayName.Length != 0) hash ^= DisplayName.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 (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } labels_.WriteTo(output, _repeated_labels_codec); if (Description.Length != 0) { output.WriteRawTag(26); output.WriteString(Description); } if (DisplayName.Length != 0) { output.WriteRawTag(34); output.WriteString(DisplayName); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } size += labels_.CalculateSize(_repeated_labels_codec); if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } if (DisplayName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(LogDescriptor other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } labels_.Add(other.labels_); if (other.Description.Length != 0) { Description = other.Description; } if (other.DisplayName.Length != 0) { DisplayName = other.DisplayName; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { labels_.AddEntriesFrom(input, _repeated_labels_codec); break; } case 26: { Description = input.ReadString(); break; } case 34: { DisplayName = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Data.Common; using System.Reflection; using System.Text; using System.Web; using MySql.Data.MySqlClient; using EmergeTk.Model; namespace EmergeTk.Model.Providers { public class MySqlProvider : DataProvider, IDataProvider { private static readonly EmergeTkLog queryLog = EmergeTkLogManager.GetLogger("MySqlQueries"); bool synchronizing = false; bool outOfSync = false; public bool Synchronizing { get { return synchronizing; } } public bool OutOfSync { get { return outOfSync; } } const string UidGenTableName = "uid"; const string LongStringDataType = "text"; const string ShortStringDataType = "varchar(20)"; const string StringDataType = "varchar(500)"; const string VarStringDataTypeMask = "varchar({0})"; const string IntDataType = "int"; //IVersioned stmts const string IdentityColumnSignature = "`ROWID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY"; const string CreateTableFormat = "CREATE TABLE `{0}` ( " + IdentityColumnSignature + " {1} )"; const string InsertTableFormat = "REPLACE `{0}`({2}) VALUES( {1} );"; const string DeleteFormat = "DELETE FROM `{0}` WHERE ROWID = {1}"; const string CreateTableNoRowIdFormat = "CREATE TABLE `{0}` ( {1} )"; const string UpdateTableFormat = "UPDATE `{0}` SET {1} WHERE ROWID = {2}"; //Non-IVersioned stmts const string VersionedCreateTableFormat = "CREATE TABLE `{0}` ( `ROWID` INTEGER UNSIGNED NOT NULL, Version INTEGER UNSIGNED NOT NULL {1},PRIMARY KEY(`ROWID`) )"; const string VersionedUpdateTableFormat = "UPDATE `{0}` SET {1} WHERE ROWID = {2} AND Version = {3}"; const string DropFormat = "DROP TABLE `{0}`"; const string RenameFormat = "ALTER TABLE `{0}` RENAME TO {1}"; const string SelectColumnFormat = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}' AND COLUMN_NAME = '{2}'"; // private static new readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(MySqlProvider)); private static readonly MySqlProvider provider = new MySqlProvider(); static public MySqlProvider Provider { get { if (DataProvider.DisableDataProvider) return null; if( DataProvider.DefaultProvider is MySqlProvider ) return DataProvider.DefaultProvider as MySqlProvider; return provider; } } string connectionString = ConfigurationManager.AppSettings["mysqlConnectionString"]; public string ConnectionString { get { //log.Debug("got connection string: ", connectionString, ConfigurationManager.AppSettings["mysqlConnectionString"] ); return connectionString; } set { connectionString = value; } } public void SetConnectionString(String cString) { connectionString = cString; } string dbName = null; public string DatabaseName { get { if( dbName == null ) { if (DisableDataProvider) return null; MySqlConnection c = CreateConnection(); dbName = c.Database; log.DebugFormat("Connection: {0}, dbname: {1}", c, dbName); } return dbName; } } public MySqlConnection CreateConnection() { if (DisableDataProvider) return null; return new MySqlConnection(connectionString); } public DbConnection CreateNewConnection() { return CreateConnection(); } public IDataParameter CreateParameter() { return new MySqlParameter(); } T Execute<T>(string sql, SqlExecutionType mode) where T : class { return Execute<T>(sql, mode, CreateConnection() ); } public T Execute<T>(string sql, SqlExecutionType mode, MySqlConnection conn, params IDataParameter[] parms) where T : class { if (DataProvider.DisableDataProvider) return null; #if DEBUG log.Debug(string.Format("executing {0} in mode {1}", sql, mode ) ); // queryLog.Debug(string.Format("executing {0} in mode {1}", sql, mode)); #endif StopWatch watch = new StopWatch("Execute<T>", this.GetType().Name); watch.Start(); if( conn.State != ConnectionState.Open ) conn.Open(); MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.CommandText = sql; if (parms != null && parms.GetLength(0) > 0) { if (mode != SqlExecutionType.DataSet) { watch.Stop(); throw new NotImplementedException(String.Format("MySqlProvider.Execute<T> not implemented with parameters for execution mode {0}", mode.ToString())); } cmd.CommandType = CommandType.StoredProcedure; foreach (IDataParameter parm in parms) { MySqlParameter myParm = new MySqlParameter(); myParm.SourceColumn = parm.SourceColumn; myParm.Direction = parm.Direction; myParm.ParameterName = "?" + parm.ParameterName; myParm.DbType = parm.DbType; myParm.Value = parm.Value; cmd.Parameters.Add(myParm); } } T retVal = null; try { watch.Lap("Done setting up, now executing"); switch (mode) { case SqlExecutionType.Scalar: retVal = (T)cmd.ExecuteScalar(); break; case SqlExecutionType.NonQuery: cmd.ExecuteNonQuery(); break; case SqlExecutionType.Reader: retVal = cmd.ExecuteReader() as T; break; case SqlExecutionType.DataTable: MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataTable t= new DataTable(); da.Fill(t); retVal = t as T; break; case SqlExecutionType.DataSet: da = new MySqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); retVal = ds as T; break; } } catch(Exception e ) { log.Error( sql, Util.BuildExceptionOutput(e) ); if (e is MySqlException && ((MySqlException)e).Number == 1062) { // we want to distinguish and catch the duplicateRecordException. throw new DuplicateRecordException(e as MySqlException); } throw new Exception("error executing sql", e); } finally { if (mode != SqlExecutionType.Reader) { cmd.Dispose(); conn.Close(); conn.Dispose(); } watch.Stop(); } //TODO: need to release resources after reader is complete. return retVal; } public object ExecuteScalar(string sql) { return Execute<object>(sql, SqlExecutionType.Scalar); } public List<int> ExecuteVectorInt(string sql) { MySqlConnection conn = CreateConnection(); IDataReader r = ExecuteReader(sql,conn); List<int> ts = new List<int>(); while( r.Read() ) { ts.Add( r.GetInt32(0) ); } conn.Dispose(); return ts; } public object ExecuteScalar(string sql, MySqlConnection conn) { return Execute<object>(sql, SqlExecutionType.Scalar, conn); } public void ExecuteNonQuery(string sql) { Execute<object>(sql, SqlExecutionType.NonQuery); } public void ExecuteNonQuery(string sql, MySqlConnection conn) { Execute<object>(sql, SqlExecutionType.NonQuery, conn); } public void ExecuteReader(string sql, ReaderDelegate del) { using( MySqlConnection conn = CreateConnection() ) { conn.Open(); using( MySqlCommand comm = new MySqlCommand(sql, conn) ) { using(IDataReader r = comm.ExecuteReader()) { while(r.Read()) { del(r); } } conn.Close(); } } } public void ExecuteCommandReader(MySqlCommand comm, Action<IDataReader> del) { if (comm.Connection == null) comm.Connection = CreateConnection (); using(IDataReader r = comm.ExecuteReader()) { while(r.Read()) { del(r); } } } public void ExecuteReader(string sql, MySqlConnection conn, ReaderDelegate del) { using( MySqlCommand comm = new MySqlCommand(sql, conn) ) { using(IDataReader r = comm.ExecuteReader()) { while(r.Read()) { del(r); } } } } public IDataReader ExecuteReader(string sql, MySqlConnection conn) { return Execute<MySqlDataReader>(sql, SqlExecutionType.Reader, conn); } public DataTable ExecuteDataTable(string sql) { return Execute<DataTable>(sql, SqlExecutionType.DataTable); } public DataTable ExecuteDataTable(string sql, MySqlConnection conn ) { return Execute<DataTable>(sql, SqlExecutionType.DataTable, conn); } public DataSet ExecuteDataSet(string sql) { return Execute<DataSet>(sql, SqlExecutionType.DataSet, CreateConnection()); } public DataSet ExecuteDataSet(string sql, IDataParameter[] parms) { return Execute<DataSet>(sql, SqlExecutionType.DataSet, CreateConnection(), parms); } public DataSet ExecuteDataSet(string sql, MySqlConnection conn, IDataParameter[] parms) { return Execute<DataSet>(sql, SqlExecutionType.DataSet, conn, parms); } public IRecordList<T> Load<T>() where T : AbstractRecord, new() { return Load<T>("","ROWID"); } public IRecordList<T> Load<T>(params SortInfo[] sortInfos) where T : AbstractRecord, new() { return Load<T>(string.Empty, Util.Join(sortInfos)); } public IRecordList<T> Load<T>(string whereClause, string orderByClause) where T : AbstractRecord, new() { return Load<T>(whereClause, orderByClause, "*"); } public IRecordList<T> Load<T>(List<int> ids) where T : AbstractRecord, new() { //preserve order //get all records from cache first //then get records that aren't in cache as ONE database call // RecordList<T> records = new RecordList<T>(); bool isDerived = AbstractRecord.IsDerived(typeof(T)); string name = null; if( ! isDerived ) { name = GetTableNameT<T>(); if (name == null) { return records; } } else { //name only used for caching at this point. name = typeof(T).FullName; } // keep a map of who got found in cache, and who didn't. Dictionary<int, T> recordMap = new Dictionary<int, T>(); List<int> unCachedIds = new List<int>(); foreach (int id in ids) { var cacheKey = AbstractRecord.CreateStandardCacheKey(name, id); T r = (T) CacheProvider.Instance.GetLocalRecord(cacheKey); recordMap[id] = r; // add to the recordMap, whether it's a hit or miss. if (r == null) { unCachedIds.Add(id); } } if (unCachedIds.Count > 0) { if (AbstractRecord.IsDerived(typeof(T))) { foreach( int id in unCachedIds ) { Type t = GetTypeForId(id); if( t == null ) { log.Warn("Did not find type for id " + id); continue; } log.Debug ("loading derived record", t, id); T r = AbstractRecord.Load(t,id) as T; if( r != null ) { recordMap[r.Id] = r; AbstractRecord.PutRecordInCache(r); } else log.WarnFormat("Did not load a record for id {0} and type {1}", id, t); } } else { String sql = String.Format("SELECT * FROM {0} WHERE ROWID IN ({1});", EscapeEntity(name), Util.JoinToString<int>(unCachedIds, ",")); DataTable result = MySqlProvider.Provider.ExecuteDataTable(sql); for (int i = 0; i < result.Rows.Count; i++) { T r = AbstractRecord.LoadFromDataRow<T>(result.Rows[i]); recordMap[r.Id] = r; AbstractRecord.PutRecordInCache(r); } } } foreach (KeyValuePair<int, T> kvp in recordMap) { if (kvp.Value != null) records.Add(kvp.Value); } return records; } private String GetTableNameT<T>() where T : AbstractRecord, new() { string name = AbstractRecord.GetDbSafeModelName(typeof(T)); if (!TableExists(name)) { log.Warn("TablenotFoundException ModelName:" + name ); return null; } return name; } public IRecordList<T> Load<T>(string whereClause, string orderByClause, String selectColumns ) where T : AbstractRecord, new() { if (whereClause != null && whereClause.Length > 0) { whereClause = " WHERE " + whereClause; } if (orderByClause != null && orderByClause.Length > 0) { orderByClause = " ORDER BY " + orderByClause; } RecordList<T> records = new RecordList<T>(); String name = GetTableNameT<T>(); if (name == null) return records; // we've already logged this. bool wildcard = selectColumns == "*"; string sql = null; string selectCols = String.IsNullOrEmpty(selectColumns) ? String.Empty : selectColumns + ", "; if( wildcard ) sql = "SELECT " + selectCols + " ROWID FROM " + EscapeEntity(name) + whereClause + orderByClause; else sql = "SELECT * FROM " + EscapeEntity(name) + whereClause + orderByClause; DataTable result = ExecuteDataTable(sql); for (int i = 0; i < result.Rows.Count; i++) { T r; string cacheKey = AbstractRecord.CreateStandardCacheKey (name, Convert.ToInt32(result.Rows[i]["ROWID"])); r = (T)CacheProvider.Instance.GetLocalRecord(cacheKey); if( r == null ) { if( selectColumns != String.Empty ) { r = AbstractRecord.LoadFromDataRow<T>(result.Rows[i]); } else { r = AbstractRecord.Load<T>(Convert.ToInt32(result.Rows[i]["ROWID"])); } if( wildcard || selectCols == string.Empty ) { //store this object in the local cache if we have a full version of the objcet. //format is name.rowid = N //CacheProvider.Instance.Set(name + ".rowid = " + r.Id, r); AbstractRecord.PutRecordInCache(r); } } if( r != null ) records.Add(r); } records.Clean = true; return records; } public IRecordList<T> Load<T>(params FilterInfo[] filterInfos) where T : AbstractRecord, new() { return Load<T>(MySqlFilterFormatter.BuildWhereClause(filterInfos), string.Empty); } public IRecordList<T> Load<T>(FilterInfo[] filterInfos, SortInfo[] sortInfos ) where T : AbstractRecord, new() { return Load<T>(MySqlFilterFormatter.BuildWhereClause(filterInfos), Util.Join(sortInfos)); } public new int GetRowCount<T>() where T : AbstractRecord, new() { throw new NotImplementedException(); } public int GetNewId(string typeName) { string table = UidGenTableName; if( string.IsNullOrEmpty(typeName ) ) { throw new ArgumentNullException("Must specify a valid type name."); } int newId = Convert.ToInt32( ExecuteScalar( string.Format( "insert into `{0}` (type) values ('{1}'); SELECT LAST_INSERT_ID();", UidGenTableName, typeName ) ) ); log.Debug("GetNewId: ", newId ); return newId; } Dictionary<int, string> typesForIds = new Dictionary<int, string>(); public Type GetTypeForId (int id) { if (typesForIds.Count == 0 ) { ExecuteReader ("SELECT ID, type FROM uid", r => { typesForIds [r.GetInt32 (0)] = r.GetString (1); } ); } string type = null; if (typesForIds.ContainsKey (id)) { type = typesForIds [id]; } else { type = (string)ExecuteScalar ("SELECT type FROM uid WHERE ID = " + id); if (type != null) typesForIds[id] = type; } if( type == null ) return null; else { return AbstractRecord.GetTypeFromDbSafeName(type); } } public int GetLatestVersion( AbstractRecord r ) { if( r == null ) throw new ArgumentNullException("r", "Record cannot be null." ); return Convert.ToInt32( ExecuteScalar(string.Format( "SELECT Version FROM `{0}` WHERE ROWID = {1}", r.DbSafeModelName, r.Id ) ) ); } public int GetLatestVersion( string modelName, int id ) { return Convert.ToInt32( ExecuteScalar(string.Format( "SELECT Version FROM `{0}` WHERE ROWID = {1}", modelName, id ) ) ); } //INVERSION OF CONTROL METHODS public void Save(AbstractRecord record, bool SaveChildren) { if (!DataProvider.DisableDataProvider) { using (MySqlConnection conn = CreateConnection()) { conn.Open(); this.Save(record, SaveChildren, true, conn); } } } public void Save(AbstractRecord record, bool SaveChildren, bool IncrementVersion, DbConnection conn) { if (DataProvider.DisableDataProvider) return; string sql = ""; List<string> parameterKeys = new List<string>(); List<string> keys = new List<string>(); bool invalidateCache = false; if( record.Id == 0 ) { record.EnsureId(); } else { invalidateCache = true; } MySqlCommand comm = new MySqlCommand(); keys.Add( "ROWID" ); parameterKeys.Add( record.Id.ToString() ); if( record is IVersioned && IncrementVersion) { keys.Add( "Version" ); parameterKeys.Add( (record.Version + 1).ToString() ); } bool persisted = record.Persisted; foreach( ColumnInfo col in record.Fields ) { if (col.ReadOnly || col.DataType == DataType.Volatile || col.DataType == DataType.RecordList || GetSqlTypeFromType(col, record.DbSafeModelName) == null ) continue; //log.Debug("adding column for SAVE ", record.DbSafeModelName, col.Name ); keys.Add( Util.Surround(col.Name, "`" ) ); if (col.Type.IsSubclassOf(typeof(AbstractRecord))) { AbstractRecord r = record[col.Name] as AbstractRecord; record.AddToLoadedProperties (col.Name); //TODO: there should be an option to decide if they want to allow adding nulls or not here. if (r != null) { if( SaveChildren ) r.Save(); comm.Parameters.Add( new MySqlParameter("?"+ col.Name,r.ObjectId) ); parameterKeys.Add("?" + col.Name); record.SetOriginalValue(col.Name, r.Id); } else { comm.Parameters.Add( new MySqlParameter("?"+ col.Name,null) ); parameterKeys.Add("?" + col.Name); } } else //string, enum, etc. { if (col.DataType != DataType.Json || record[col.Name] == null) { comm.Parameters.Add( new MySqlParameter("?"+ col.Name,record[col.Name] ) ); } else if (col.Type == typeof(DateTime)) { DateTime v = (DateTime)record[col.Name]; comm.Parameters.Add( new MySqlParameter("?"+ col.Name, v.ToString ("u") ) ); } else { comm.Parameters.Add( new MySqlParameter("?"+ col.Name, JSON.Serialize (record[col.Name]) ) ); } parameterKeys.Add("?" + col.Name); record.SetOriginalValue(col.Name, record[col.Name]); } } if( ! persisted || synchronizing ) sql = string.Format(InsertTableFormat, record.DbSafeModelName, Util.Join(parameterKeys, ","), Util.Join(keys) ); else { List<string> updateFields = new List<string>(); for( int i = 0; i < keys.Count; i++ ) { updateFields.Add(string.Format( "{0} = {1}", keys[i], parameterKeys[i] ) ); } if( ! ( record is IVersioned ) || !IncrementVersion) { sql = string.Format(UpdateTableFormat, record.DbSafeModelName, string.Join( ",", updateFields.ToArray() ), record.Id ); } else { sql = string.Format(VersionedUpdateTableFormat, record.DbSafeModelName, string.Join( ",", updateFields.ToArray() ), record.Id, record.Version ); } } StopWatch watch = new StopWatch("MySqlProvider.Save", this.GetType().Name); watch.Start(); comm.CommandText = sql; //log.Debug( sql ); comm.Connection = (MySqlConnection) conn; comm.Prepare(); log.Debug( comm.CommandText ); foreach( MySqlParameter p in comm.Parameters ) { log.Debug(string.Format("{0}: {1}", p.ParameterName, p.Value) ); } int result = -1; try { //we may get an exception here if the model has changed. if so, resynchronize. result = comm.ExecuteNonQuery(); //log.Debug("result is ", result ); } catch (Exception e) { log.Error("Error saving record", record, Util.BuildExceptionOutput(e)); string preserveAtAllCosts = Setting.Get("preserveAtAllCosts").DataValue; if (preserveAtAllCosts != null && !bool.Parse(preserveAtAllCosts)) { SynchronizeModel(record.GetType()); //try again, if another exception, let it throw out. result = comm.ExecuteNonQuery(); } else { //we are past the point where it's acceptable to re-create the tables. throw new Exception("error saving record", e); } } finally { watch.Stop(); } if( record is IVersioned && IncrementVersion) { if( result < 1 ) { log.Error("No record was modified. ", result, record, record.Version ); throw new VersionOutOfDateException( "No record was modified. Probably attempting to save an old version of record." ); } record.Version++; } if( SaveChildren ) { foreach( ColumnInfo col in record.Fields ) { if( AbstractRecord.TypeIsRecordList(col.Type) ) { TypeLoader.InvokeGenericMethod (typeof(AbstractRecord),"SaveChildRecordList",new Type[]{col.ListRecordType},record,new object[]{col.Name,record[col.Name]}); } } } if (invalidateCache) { //N.B. it's very important here that we MUST NOT mark 'record' as stale. //it's correct to mark the prior version, the one that is currently in the cache, as stale. CacheProvider.Instance.Update(record); } } public void SaveSingleRelation( string childTableName, string parent_id, string child_id ) { // TODO: check for already saved? try { provider.ExecuteNonQuery(string.Format("INSERT IGNORE INTO {0} VALUES( '{1}', '{2}' )", childTableName, parent_id, child_id)); } catch( Exception ex ) { if( ex.InnerException != null && ex.InnerException.Message.Contains("Column count doesn't match value count" ) ) { if( ColumnList(childTableName).Contains("ROWID") ) { provider.ExecuteNonQuery(GenerateRemoveColStatement("ROWID", childTableName)); SaveSingleRelation(childTableName, parent_id, child_id); } } } } public void RemoveSingleRelation( string childTableName, string parent_id, string child_id ) { provider.ExecuteNonQuery(string.Format("DELETE FROM {0} WHERE Parent_Id = '{1}' AND Child_Id = '{2}'", childTableName, parent_id, child_id )); } public void RemoveRelations( string childTableName, string parent_id ) { provider.ExecuteNonQuery(string.Format("DELETE FROM {0} WHERE Parent_Id = '{1}'", childTableName, parent_id)); } public void Delete( AbstractRecord r ) { ExecuteNonQuery(string.Format(DeleteFormat, r.DbSafeModelName, r.Id)); } public void SynchronizeModel(Type t) { log.Debug("attempting to synchronize model ", t ); MethodInfo mi = this.GetType().GetMethod("SynchronizeModelType", BindingFlags.Public | BindingFlags.Instance); mi = mi.MakeGenericMethod(t); mi.Invoke(this, null); } public void SynchronizeModelType<T>() where T : AbstractRecord, new() { synchronizing = true; int oldTimeout = 0; if( HttpContext.Current != null ) { oldTimeout = HttpContext.Current.Server.ScriptTimeout; HttpContext.Current.Server.ScriptTimeout = 10000; } T record = new T(); record.EnsureTablesCreated(); //TODO: flush cache IRecordList<T> oldRecords = Load<T>(); try { ExecuteNonQuery(string.Format(RenameFormat, record.DbSafeModelName, record.DbSafeModelName + "_backup")); } catch( Exception e ) { throw new Exception("BAD ERROR! Attempting to rename table on backup, and a failure occurred (is there already a backup table?)! Please shutdown the server and examine table: " + record.DbSafeModelName,e ); } existingTables[record.DbSafeModelName] = false; try { record.EnsureTablesCreated(); if (oldRecords != null && oldRecords.Count > 0) { foreach (T r in oldRecords) { r.Save(); } } } catch( Exception e ) { //need to restore ExecuteNonQuery(string.Format(DropFormat, record.DbSafeModelName)); ExecuteNonQuery(string.Format(RenameFormat, record.DbSafeModelName + "_backup", record.DbSafeModelName)); outOfSync = true; log.Error( "BACKUP ERROR!", Util.BuildExceptionOutput( e ) ); throw new Exception( "Synchronization failed. Database may be out of sync. Backup attempted.", e ); } finally { if( HttpContext.Current != null ) { HttpContext.Current.Server.ScriptTimeout = oldTimeout; } } //everything went well. drop the backup table. ExecuteNonQuery(string.Format(DropFormat, record.DbSafeModelName + "_backup")); record.EnsureTablesCreated(); synchronizing = false; } public string GetSqlType( DataType dt ) { switch( dt ) { case DataType.Text: return "varchar(256)"; } return null; } public void CreateTable(Type modelType, string tableName) { if ( LowerCaseTableNames ) tableName = tableName.ToLower(); ArrayList pairs = new ArrayList(); ColumnInfo[] columns = ColumnInfoManager.RequestColumns(modelType); foreach (ColumnInfo col in columns ) { if (AbstractRecord.TypeIsRecordList(col.Type)) { CreateChildTable(tableName + "_" + col.Name, col); } else { AddColumnPair( pairs, tableName, col ); } } string propString = pairs.Count == 0 ? String.Empty : "," + Util.Join(pairs, ", "); if( modelType.GetInterface("IVersioned") != null ) ExecuteNonQuery(string.Format(VersionedCreateTableFormat, tableName, propString)); else ExecuteNonQuery(string.Format(CreateTableFormat, tableName, propString)); RegisterTable(tableName); } private void AddColumnPair( ArrayList pairs, string tableName, ColumnInfo col ) { string dataType = GetSqlTypeFromType(col, tableName); //log.Debug("adding column for CREATE ", tableName, col.Name, dataType ); if (dataType != null) { pairs.Add(Util.Surround(col.Name, "`") + " " + dataType); } } public void RegisterTable( string tableName ) { existingTables[tableName] = true; } public string EscapeEntity(string entity) { return Util.Surround(entity, "`"); } public string GetSqlTypeFromType (ColumnInfo col, string tableName) { if (LowerCaseTableNames) tableName = tableName.ToLower (); string dataType = null; //"int"; if (col.Type == typeof(string)) { if (col.DataType == DataType.LargeText || col.DataType == DataType.Xml) dataType = LongStringDataType; else if (col.DataType == DataType.SmallText) dataType = ShortStringDataType; else { if (col.Length == null) dataType = StringDataType; else dataType = String.Format(VarStringDataTypeMask, col.Length); } } else if (col.Type == typeof(int) || col.Type == typeof(int?)) { dataType = "int(11)"; } else if (col.Type == typeof(decimal) || col.Type == typeof(decimal?)) { dataType = "decimal(20,2)"; } else if (col.Type == typeof(float) || col.Type == typeof(float?)) { dataType = "float"; } else if (col.Type == typeof(double) || col.Type == typeof(double?)) { dataType = "double"; } else if (col.Type == typeof(DateTime) || col.Type == typeof(DateTime?)) { dataType = "datetime"; } else if (col.Type == typeof(TimeSpan) || col.Type == typeof(TimeSpan?)) { dataType = "bigint(20)"; } else if (col.Type.IsSubclassOf(typeof(Enum)) || col.IsNullableEnum) { dataType = "varchar(128)"; } else if (col.Type.IsSubclassOf(typeof(AbstractRecord))) { dataType = "int(11)"; } else if (col.Type == typeof(bool) || col.Type == typeof(bool?)) { dataType = "tinyint(1)"; } else if (col.Type == typeof(long) || col.Type == typeof(long?)) { dataType = "bigint"; } else if (AbstractRecord.TypeIsRecordList (col.Type)) { // TODO: this may be bad to create a child table here CreateChildTable (tableName + "_" + col.Name, col); } else if (col.DataType == DataType.Json) { dataType = "text"; } return dataType; } public void CreateChildTable(string tableName, ColumnInfo col) { if (LowerCaseTableNames) tableName = tableName.ToLower(); if (!TableExists(tableName)) { ExecuteNonQuery(string.Format(CreateTableNoRowIdFormat, tableName, "Parent_Id int, Child_Id int")); existingTables[tableName] = true; bool uniqueChildItems = false; if (col.PropertyInfo != null) { // see if the property on the object is decorated with a [UniqueValues] attribute. If it // is, we're going to add a database unique index to the Child_Id column of the // join table. if (col.PropertyInfo.GetCustomAttributes(typeof(UniqueValuesAttribute), false).Length > 0) uniqueChildItems = true; } CreateChildTableIndex(tableName, uniqueChildItems); } } #region publicly_exposed_jointable_index_helpers // N.B. these are exposed publicly even though they are NOT part of the DataProvider interface, because it makes // it easy to write tests to verify the SQL Unique Index generating code for the // ORM. public String GenerateChildTableIndexName(String tableName) { return String.Format("IX_{0}_PARENTID_CHILDID", tableName.ToUpper()); } public String GenerateChildTableUniqueChildIndexName(String tableName) { return String.Format("IX_{0}_UNIQUE_CHILDID", tableName.ToUpper()); } public bool ChildTableIndexExists(String tableName, String indexName) { long indexExists = 1; try { String sql = String.Format("SELECT COUNT(1) FROM information_schema.statistics WHERE table_name = '{0}' AND index_name = '{1}';", tableName, indexName); indexExists = (long)this.ExecuteScalar(sql); } catch (Exception ex) { log.ErrorFormat("Error trying to determine if index {0} exists on table {1}, err = {2}, stack = {3}, will refrain from creating it since we don't know", indexName, tableName, ex.Message, ex.StackTrace); indexExists = 1; // just pretend the index exists; the main thing is not to hold things up. } return indexExists == 0 ? false : true; } #endregion private void CreateChildTableIndex(String tableName, bool uniqueChildItems) { String indexName = GenerateChildTableIndexName(tableName); if (!ChildTableIndexExists(tableName, indexName)) { try { this.ExecuteNonQuery(String.Format("ALTER IGNORE TABLE `{0}` ADD UNIQUE INDEX `{1}` (Parent_Id, Child_Id);", tableName, indexName)); } catch (Exception ex) { log.ErrorFormat("Error creating index {0} on table {1}, error = {2}, stack = {3}, continuing on", indexName, tableName, ex.Message, ex.StackTrace); } } if (uniqueChildItems) { // this means we're going to add a unique index to the Child_Id column of the join table. We only do that for // relationships that have business semantics such that the child column is // unique (perhaps this is too obvious, but...for people reading this later). // For example, the Advertiser->Creative relationship in AppNexus is such that // there should never be more than one instance of a Creative Id in the Child_Id // column of the Advertiser_Creatives table. This is not true for all join // tables, e.g., the User_Roles and Role_Permissions table are inherently cases // where there will be dups in the Child_ID column. indexName = GenerateChildTableUniqueChildIndexName(tableName); if (!ChildTableIndexExists(tableName, indexName)) { try { this.ExecuteNonQuery(String.Format("ALTER IGNORE TABLE `{0}` ADD UNIQUE INDEX `{1}` (Child_Id);", tableName, indexName)); } catch (Exception ex) { log.ErrorFormat("Error creating unique child index {0} on table {1}, error = {2}, stack = {3}, continuing on", indexName, tableName, ex.Message, ex.StackTrace); } } } } Dictionary<string, bool> existingTables; public bool TableExists( string name ) { if ( LowerCaseTableNames ) name = name.ToLower(); if (existingTables == null) existingTables = new Dictionary<string, bool>(); else if (existingTables.ContainsKey(name) ) return existingTables[name]; return existingTables[name] = Convert.ToBoolean(ExecuteScalar("SELECT COUNT(*) FROM information_schema.TABLES WHERE Table_Schema = '" + DatabaseName + "' and Table_Name = '" + name + "'")); } public bool TableExistsNoCache( string name ) { if ( LowerCaseTableNames ) name = name.ToLower(); return Convert.ToBoolean(ExecuteScalar("SELECT COUNT(*) FROM information_schema.TABLES WHERE Table_Schema = '" + DatabaseName + "' and Table_Name = '" + name + "'")); } public List<string> ColumnList( string tableName ) { if ( LowerCaseTableNames ) tableName = tableName.ToLower(); if ( ! TableExists( tableName ) ) return null; else { DataTable dt = ExecuteDataTable("SELECT SQL_NO_CACHE Column_Name FROM information_schema.COLUMNS WHERE Table_Schema = '" + DatabaseName + "' and Table_Name = '" + tableName + "'"); List<string> result = new List<string>(); foreach( DataRow r in dt.Rows ) { result.Add( r[0].ToString() ); } return result; } } public DataTable GetColumnTable( string tableName ) { if ( LowerCaseTableNames ) tableName = tableName.ToLower(); if ( ! TableExists( tableName ) ) return null; else { DataTable dt = ExecuteDataTable("SELECT Column_Name, Column_Type FROM information_schema.COLUMNS WHERE Table_Schema = '" + DatabaseName + "' and Table_Name = '" + tableName + "'"); return dt; } } public List<string> TableList() { DataTable dt = ExecuteDataTable("SELECT SQL_NO_CACHE Table_Name FROM information_schema.TABLES WHERE Table_Schema = '" + DatabaseName + "'"); List<string> result = new List<string>(); foreach ( DataRow r in dt.Rows ) { result.Add( r[0].ToString() ); } return result; } // wrap this, because we don't have DatabaseName at construction time private string AlterStatement { get { return "ALTER TABLE " + DatabaseName + ".`{0}` {1}{2}{3};"; } } public string GenerateAddColStatement( ColumnInfo col, string table ) { if ( LowerCaseTableNames ) table = table.ToLower(); return String.Format(AlterStatement, table, "ADD ", "`" + col.Name + "`", " " + GetSqlTypeFromType(col, table)); } public string GenerateRemoveColStatement( string col, string table ) { if ( LowerCaseTableNames ) table = table.ToLower(); return String.Format(AlterStatement, table, "DROP ", "`" + col + "`", ""); } public string GenerateFixColTypeStatement( ColumnInfo col, string table ) { if ( LowerCaseTableNames ) table = table.ToLower(); return String.Format(AlterStatement, table, "MODIFY ", "`" + col.Name + "`", " " + GetSqlTypeFromType(col, table)); } public string GenerateAddIdColStatement(string table) { if ( LowerCaseTableNames ) table = table.ToLower(); return String.Format(AlterStatement, table, "ADD", " ", IdentityColumnSignature); } public string GenerateModifyIdColStatement(string table) { if ( LowerCaseTableNames ) table = table.ToLower(); return String.Format(AlterStatement, table, "MODIFY", " ", IdentityColumnSignature); } private string GenerateTableFormat { get { return "CREATE TABLE " + DatabaseName + ".`{0}` ( " + IdentityColumnSignature + ", {1} );"; } } public string GenerateAddTableStatement( Type addTable ) { string result = ""; ArrayList pairs = new ArrayList(); string tableName = ( Activator.CreateInstance( addTable ) as AbstractRecord ).DbSafeModelName; ColumnInfo[] columns = ColumnInfoManager.RequestColumns( addTable ); foreach ( ColumnInfo c in columns ) { // ignore record lists if ( ! AbstractRecord.TypeIsRecordList(c.Type) ) AddColumnPair( pairs, tableName, c ); } string propString = Util.Join(pairs, ", "); return result + string.Format(GenerateTableFormat, tableName, propString); } private string GenerateChildTableFormat { get { return "CREATE TABLE " + DatabaseName + ".`{0}` ( {1} );"; } } public string GenerateAddChildTableStatement( string tableName, bool isDerived ) { if ( LowerCaseTableNames ) tableName = tableName.ToLower(); return string.Format(GenerateChildTableFormat, tableName, "Parent_Id int, Child_Id int"); } public string CheckIdColumn( string table ) { DataTable dt = ExecuteDataTable("SELECT Column_Type, Is_Nullable, Column_Key, Extra FROM information_schema.COLUMNS WHERE Table_Schema = '" + DatabaseName + "' and Table_Name = '" + table + "' and Column_Name='ROWID'"); if (dt.Rows.Count == 0) return GenerateAddIdColStatement( table ); DataRow r = dt.Rows[0]; bool goodIdCol = (r[0] as string).ToLower().Equals("int(10) unsigned") && (r[1] as string).ToLower().Equals("no") && (r[2] as string).ToLower().Equals("pri") && (r[3] as string).ToLower().Equals("auto_increment"); if ( ! goodIdCol ) return GenerateModifyIdColStatement( table ); else return ""; } public string BuildWhereClause(FilterInfo[] filters ) { return MySqlFilterFormatter.BuildWhereClause( filters ); } public string GetIdentityColumn() { return "ROWID"; } public string GetCommentCharacter() { return "#"; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Controller class for LAB_Temp_ResultadoDetalle /// </summary> [System.ComponentModel.DataObject] public partial class LabTempResultadoDetalleController { // Preload our schema.. LabTempResultadoDetalle thisSchemaLoad = new LabTempResultadoDetalle(); private string userName = String.Empty; protected string UserName { get { if (userName.Length == 0) { if (System.Web.HttpContext.Current != null) { userName=System.Web.HttpContext.Current.User.Identity.Name; } else { userName=System.Threading.Thread.CurrentPrincipal.Identity.Name; } } return userName; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public LabTempResultadoDetalleCollection FetchAll() { LabTempResultadoDetalleCollection coll = new LabTempResultadoDetalleCollection(); Query qry = new Query(LabTempResultadoDetalle.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public LabTempResultadoDetalleCollection FetchByID(object IdProtocolo) { LabTempResultadoDetalleCollection coll = new LabTempResultadoDetalleCollection().Where("idProtocolo", IdProtocolo).Load(); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public LabTempResultadoDetalleCollection FetchByQuery(Query qry) { LabTempResultadoDetalleCollection coll = new LabTempResultadoDetalleCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(object IdProtocolo) { return (LabTempResultadoDetalle.Delete(IdProtocolo) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, false)] public bool Destroy(object IdProtocolo) { return (LabTempResultadoDetalle.Destroy(IdProtocolo) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(int IdProtocolo,int IdEfector,int IdDetalleProtocolo) { Query qry = new Query(LabTempResultadoDetalle.Schema); qry.QueryType = QueryType.Delete; qry.AddWhere("IdProtocolo", IdProtocolo).AND("IdEfector", IdEfector).AND("IdDetalleProtocolo", IdDetalleProtocolo); qry.Execute(); return (true); } /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Insert, true)] public void Insert(int IdProtocolo,int IdEfector,int IdDetalleProtocolo,string CodigoNomenclador,string Codigo,int OrdenArea,int Orden,string Area,string Grupo,string Item,string Observaciones,string EsTitulo,string Derivado,string Unidad,bool? Hiv,string Metodo,string ValorReferencia,int Orden1,string Muestra,int Conresultado,string Resultado,string Codigo2,string ProfesionalVal) { LabTempResultadoDetalle item = new LabTempResultadoDetalle(); item.IdProtocolo = IdProtocolo; item.IdEfector = IdEfector; item.IdDetalleProtocolo = IdDetalleProtocolo; item.CodigoNomenclador = CodigoNomenclador; item.Codigo = Codigo; item.OrdenArea = OrdenArea; item.Orden = Orden; item.Area = Area; item.Grupo = Grupo; item.Item = Item; item.Observaciones = Observaciones; item.EsTitulo = EsTitulo; item.Derivado = Derivado; item.Unidad = Unidad; item.Hiv = Hiv; item.Metodo = Metodo; item.ValorReferencia = ValorReferencia; item.Orden1 = Orden1; item.Muestra = Muestra; item.Conresultado = Conresultado; item.Resultado = Resultado; item.Codigo2 = Codigo2; item.ProfesionalVal = ProfesionalVal; item.Save(UserName); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Update, true)] public void Update(int IdProtocolo,int IdEfector,int IdDetalleProtocolo,string CodigoNomenclador,string Codigo,int OrdenArea,int Orden,string Area,string Grupo,string Item,string Observaciones,string EsTitulo,string Derivado,string Unidad,bool? Hiv,string Metodo,string ValorReferencia,int Orden1,string Muestra,int Conresultado,string Resultado,string Codigo2,string ProfesionalVal) { LabTempResultadoDetalle item = new LabTempResultadoDetalle(); item.MarkOld(); item.IsLoaded = true; item.IdProtocolo = IdProtocolo; item.IdEfector = IdEfector; item.IdDetalleProtocolo = IdDetalleProtocolo; item.CodigoNomenclador = CodigoNomenclador; item.Codigo = Codigo; item.OrdenArea = OrdenArea; item.Orden = Orden; item.Area = Area; item.Grupo = Grupo; item.Item = Item; item.Observaciones = Observaciones; item.EsTitulo = EsTitulo; item.Derivado = Derivado; item.Unidad = Unidad; item.Hiv = Hiv; item.Metodo = Metodo; item.ValorReferencia = ValorReferencia; item.Orden1 = Orden1; item.Muestra = Muestra; item.Conresultado = Conresultado; item.Resultado = Resultado; item.Codigo2 = Codigo2; item.ProfesionalVal = ProfesionalVal; item.Save(UserName); } } }
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using Stormancer; using Stormancer.Core; using Stormancer.EditorPlugin; namespace Stormancer.EditorPluginWindow { internal class Folds { public bool client = false; public bool logs = false; public bool scene = false; public List<SceneFolds> scenes = new List<SceneFolds>(); } internal class SceneFolds { public bool connected = false; public bool scene = false; public bool logs = false; public bool routes = false; public bool serverRoutes = false; public bool localRoutes = false; } public class StormancerEditorWindow : EditorWindow { static ConcurrentDictionary<string, StormancerClientViewModel> clients; private Vector2 scroll_pos = new Vector2(0, 0); private Vector2 log_scroll = new Vector2(0, 0); private List<Folds> folds = new List<Folds>(); static private StormancerEditorWindow window; private bool initiated = false; private StormancerEditorLogViewModel logsToShow = null; private StormancerRouteViewModel routeToShow = null; private LineChart chart; private float ChartSlider; [MenuItem ("Window/Stormancer Editor Window")] static void Init () { window = (StormancerEditorWindow)EditorWindow.GetWindow (typeof (StormancerEditorWindow)); window.Show(); } void OnGUI () { ShowStormancerDebug (); } void ShowStormancerDebug() { if (window == null) window = (StormancerEditorWindow)EditorWindow.GetWindow (typeof (StormancerEditorWindow)); if (initiated == false) return; if (logsToShow != null) { ShowLogs(); } else if (routeToShow != null) { ShowChart(); } else { ShowClients(); } } private void ShowClients() { int i = 1; GUILayout.Label("Client informations", EditorStyles.boldLabel); EditorGUILayout.Separator(); scroll_pos = GUILayout.BeginScrollView(scroll_pos, GUILayout.Width(window.position.width), GUILayout.Height(window.position.height - (window.position.height / 10))); EditorGUI.indentLevel++; if (clients == null) return; foreach (StormancerClientViewModel c in clients.Values) { EditorGUILayout.Separator(); while (folds.Count - 1 < i) folds.Add(new Folds()); GUILayout.BeginHorizontal(GUILayout.Width(200), GUILayout.Height(20), GUILayout.MinWidth(200), GUILayout.MaxWidth(200)); folds[i].client = EditorGUILayout.Foldout(folds[i].client, "client" + i.ToString()); if (GUILayout.Button("show logs", GUILayout.Width(70)) && logsToShow == null) { logsToShow = c.log; log_scroll = Vector2.zero; } if (c.exportLogs == false && GUILayout.Button("record", GUILayout.Width(50))) { c.dateOfRecord = DateTime.UtcNow.ToString("yyyyMMdd-HH-mm-ss"); c.exportLogs = true; } else if (c.exportLogs == true && GUILayout.Button("stop", GUILayout.Width(50))) { c.exportLogs = false; } GUILayout.EndHorizontal(); if (folds[i].client == true) { EditorGUI.indentLevel++; ShowScene(i, c); EditorGUI.indentLevel--; } i++; } GUILayout.EndScrollView(); } private void ShowScene(int i, StormancerClientViewModel c) { int j = 0; folds[i].scene = EditorGUILayout.Foldout(folds[i].scene, "scenes"); if (folds[i].scene) { EditorGUI.indentLevel++; foreach(StormancerSceneViewModel v in c.scenes.Values) { if (folds[i].scenes.Count - 1 < j) folds[i].scenes.Add(new SceneFolds()); EditorGUI.indentLevel++; EditorGUILayout.BeginHorizontal(GUILayout.Width(200), GUILayout.Height(20), GUILayout.MinWidth(100), GUILayout.MaxWidth(300)); folds[i].scenes[j].routes = EditorGUILayout.Foldout(folds[i].scenes[j].routes, v.scene.Id); //EditorGUILayout.Toggle(" ", v.connected); if (GUILayout.Button("show logs", GUILayout.Width(100)) && logsToShow == null) { logsToShow = v.log; log_scroll = Vector2.zero; } EditorGUILayout.EndHorizontal(); if (folds[i].scenes[j].routes == true) { EditorGUI.indentLevel++; folds[i].scenes[j].serverRoutes = EditorGUILayout.Foldout(folds[i].scenes[j].serverRoutes, "server routes"); if (folds[i].scenes[j].serverRoutes == true) { EditorGUI.indentLevel++; foreach (StormancerRouteViewModel route in v.remotes.Values.OrderBy(r=>r.Name)) { GUILayout.BeginHorizontal(GUILayout.Width(400), GUILayout.Height(20), GUILayout.MinWidth(400), GUILayout.MaxWidth(window.position.width / 4)); EditorGUILayout.LabelField(route.Name + " " + route.debit.ToString() + " b/s"); if (GUILayout.Button("Show Chart", GUILayout.Width(90))) { routeToShow = route; } //EditorGUILayout.CurveField(route.curve); GUILayout.EndHorizontal(); } EditorGUI.indentLevel--; } folds[i].scenes[j].localRoutes = EditorGUILayout.Foldout(folds[i].scenes[j].localRoutes, "local routes"); if (folds[i].scenes[j].localRoutes == true) { EditorGUI.indentLevel++; foreach (StormancerRouteViewModel route in v.routes.Values.OrderBy(r => r.Name)) { GUILayout.BeginHorizontal(GUILayout.Width(300), GUILayout.Height(20), GUILayout.MinWidth(150), GUILayout.MaxWidth(400)); EditorGUILayout.LabelField(route.Name + " " + route.debit.ToString() + " b/s"); if (GUILayout.Button("Show Chart", GUILayout.Width(90))) { routeToShow = route; } //EditorGUILayout.CurveField(route.curve); GUILayout.EndHorizontal(); } EditorGUI.indentLevel--; } EditorGUI.indentLevel--; } EditorGUI.indentLevel--; j++; } EditorGUI.indentLevel--; } } private void ShowChart() { GUILayout.BeginHorizontal(GUILayout.Width(200), GUILayout.Height(20), GUILayout.MinWidth(100), GUILayout.MaxWidth(300)); if (GUILayout.Button("back", GUILayout.Width(80), GUILayout.Height(20), GUILayout.MinWidth(40), GUILayout.MaxWidth(160))) { routeToShow = null; return; } if (GUILayout.Button("clear", GUILayout.Width(80), GUILayout.Height(20), GUILayout.MinWidth(40), GUILayout.MaxWidth(160))) { while (routeToShow.averageSizeChart.Count > 0) { routeToShow.dataChart.RemoveAt(0); routeToShow.averageSizeChart.RemoveAt(0); routeToShow.messageNbrChart.RemoveAt(0); } } if (GUILayout.Button("Export", GUILayout.Width(80), GUILayout.Height(20), GUILayout.MinWidth(40), GUILayout.MaxWidth(160))) { int i = 0; while (System.IO.File.Exists("Export" + i.ToString() + ".csv")) i++; var file = System.IO.File.CreateText("Export" + i.ToString() + ".csv"); i = 0; while (i < routeToShow.averageSizeChart.Count) { file.WriteLine(string.Join(";", new string[] { routeToShow.dataChart[i].ToString(), routeToShow.averageSizeChart[i].ToString(), routeToShow.messageNbrChart[i].ToString() })); i++; } } GUILayout.EndHorizontal(); ChartSlider = GUILayout.HorizontalSlider(ChartSlider, 0, routeToShow.dataChart.Count - 1); if (ChartSlider >= routeToShow.dataChart.Count - 2) ChartSlider = routeToShow.dataChart.Count - 1; if (routeToShow.dataChart.Count > 0) { int count = 60; int pos = (int)ChartSlider; calcRange(routeToShow.dataChart.Count - 1, ref pos, ref count); if (chart == null) chart = new LineChart(window, window.position.height - window.position.height / 10); chart.data = new List<float>[3]; chart.data[0] = routeToShow.dataChart.GetRange(pos, count); chart.data[1] = routeToShow.averageSizeChart.GetRange(pos, count); chart.data[2] = routeToShow.messageNbrChart.GetRange(pos, count); chart.dataLabels = new List<string> { "bytes per seconds", "average packet size", "number of messages" }; chart.axisLabels = new List<string> { "0" }; chart.DrawChart(); } } private void ShowLogs() { GUILayout.BeginHorizontal(); if (GUILayout.Button("back", GUILayout.Width(80), GUILayout.Height(20), GUILayout.MinWidth(40), GUILayout.MaxWidth(160))) { logsToShow = null; return; } if (GUILayout.Button("clear", GUILayout.Width(80), GUILayout.Height(20), GUILayout.MinWidth(40), GUILayout.MaxWidth(160))) logsToShow.Clear(); GUILayout.EndHorizontal(); log_scroll = EditorGUILayout.BeginScrollView(log_scroll, GUILayout.Width (window.position.width), GUILayout.Height(window.position.height)); GUILayout.Label(""); foreach (StormancerEditorLog log in logsToShow.log) { EditorGUILayout.BeginVertical(GUILayout.Width(window.position.width), GUILayout.Height(20)); EditorGUILayout.SelectableLabel(log.logLevel + ": " + log.message); EditorGUILayout.EndVertical(); } EditorGUILayout.EndScrollView(); } private void calcRange(int max, ref int pos, ref int count) { if (max < 0) max = 0; if (count > max) count = max; if (pos + count > max) pos = pos - ((pos + count) - max); } private void myInit() { initiated = true; clients = StormancerEditorDataCollector.Instance.clients; } private void UpdateRouteData(StormancerClientViewModel clientVM, StormancerRouteViewModel route) { if (route.dataChart.Count >= 3600) route.dataChart.RemoveAt(0); if (route.messageNbrChart.Count >= 3600) route.messageNbrChart.RemoveAt(0); if (route.averageSizeChart.Count >= 3600) route.averageSizeChart.RemoveAt(0); route.debit = route.sizeStack; route.curve.AddKey(clientVM.client.Clock, route.sizeStack); route.dataChart.Add(route.sizeStack); route.messageNbrChart.Add(route.messageNbr); route.averageSizeChart.Add(route.averageSize); route.messageNbr = 0; route.sizeStack = 0; } void Update() { if (initiated == false) myInit(); clients = StormancerEditorDataCollector.Instance.clients; foreach (StormancerClientViewModel c in clients.Values) { c.WriteLog(); if (c.lastUpdate + 1000 < c.client.Clock) { c.lastUpdate = c.client.Clock; foreach (StormancerSceneViewModel s in c.scenes.Values) { if (s.scene.Connected == true) { foreach (StormancerRouteViewModel r in s.routes.Values) { UpdateRouteData(c, r); } foreach (StormancerRouteViewModel r in s.remotes.Values) { UpdateRouteData(c, r); } } } } } Repaint(); } } } #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.Runtime.InteropServices; namespace System.Management { //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Contains information about a WMI method.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example shows how to obtain meta data /// // about a WMI method with a given name in a given WMI class /// /// class Sample_MethodData /// { /// public static int Main(string[] args) { /// /// // Get the "SetPowerState" method in the Win32_LogicalDisk class /// ManagementClass diskClass = new ManagementClass("win32_logicaldisk"); /// MethodData m = diskClass.Methods["SetPowerState"]; /// /// // Get method name (albeit we already know it) /// Console.WriteLine("Name: " + m.Name); /// /// // Get the name of the top-most class where this specific method was defined /// Console.WriteLine("Origin: " + m.Origin); /// /// // List names and types of input parameters /// ManagementBaseObject inParams = m.InParameters; /// foreach(PropertyData pdata in inParams.Properties) { /// Console.WriteLine(); /// Console.WriteLine("InParam_Name: " + pdata.Name); /// Console.WriteLine("InParam_Type: " + pdata.Type); /// } /// /// // List names and types of output parameters /// ManagementBaseObject outParams = m.OutParameters; /// foreach(PropertyData pdata in outParams.Properties) { /// Console.WriteLine(); /// Console.WriteLine("OutParam_Name: " + pdata.Name); /// Console.WriteLine("OutParam_Type: " + pdata.Type); /// } /// /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example shows how to obtain meta data /// ' about a WMI method with a given name in a given WMI class /// /// Class Sample_ManagementClass /// Overloads Public Shared Function Main(args() As String) As Integer /// /// ' Get the "SetPowerState" method in the Win32_LogicalDisk class /// Dim diskClass As New ManagementClass("Win32_LogicalDisk") /// Dim m As MethodData = diskClass.Methods("SetPowerState") /// /// ' Get method name (albeit we already know it) /// Console.WriteLine("Name: " &amp; m.Name) /// /// ' Get the name of the top-most class where /// ' this specific method was defined /// Console.WriteLine("Origin: " &amp; m.Origin) /// /// ' List names and types of input parameters /// Dim inParams As ManagementBaseObject /// inParams = m.InParameters /// Dim pdata As PropertyData /// For Each pdata In inParams.Properties /// Console.WriteLine() /// Console.WriteLine("InParam_Name: " &amp; pdata.Name) /// Console.WriteLine("InParam_Type: " &amp; pdata.Type) /// Next pdata /// /// ' List names and types of output parameters /// Dim outParams As ManagementBaseObject /// outParams = m.OutParameters /// For Each pdata in outParams.Properties /// Console.WriteLine() /// Console.WriteLine("OutParam_Name: " &amp; pdata.Name) /// Console.WriteLine("OutParam_Type: " &amp; pdata.Type) /// Next pdata /// /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class MethodData { private ManagementObject parent; //needed to be able to get method qualifiers private string methodName; private IWbemClassObjectFreeThreaded wmiInParams; private IWbemClassObjectFreeThreaded wmiOutParams; private QualifierDataCollection qualifiers; internal MethodData(ManagementObject parent, string methodName) { this.parent = parent; this.methodName = methodName; RefreshMethodInfo(); qualifiers = null; } //This private function is used to refresh the information from the Wmi object before returning the requested data private void RefreshMethodInfo() { int status = (int)ManagementStatus.Failed; try { status = parent.wbemObject.GetMethod_(methodName, 0, out wmiInParams, out wmiOutParams); } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } /// <summary> /// <para>Gets or sets the name of the method.</para> /// </summary> /// <value> /// <para>The name of the method.</para> /// </value> public string Name { get { return methodName != null ? methodName : ""; } } /// <summary> /// <para> Gets or sets the input parameters to the method. Each /// parameter is described as a property in the object. If a parameter is both in /// and out, it appears in both the <see cref='System.Management.MethodData.InParameters'/> and <see cref='System.Management.MethodData.OutParameters'/> /// properties.</para> /// </summary> /// <value> /// <para> /// A <see cref='System.Management.ManagementBaseObject'/> /// containing all the input parameters to the /// method.</para> /// </value> /// <remarks> /// <para>Each parameter in the object should have an /// <see langword='ID'/> /// qualifier, identifying the order of the parameters in the method call.</para> /// </remarks> public ManagementBaseObject InParameters { get { RefreshMethodInfo(); return (null == wmiInParams) ? null : new ManagementBaseObject(wmiInParams); } } /// <summary> /// <para> Gets or sets the output parameters to the method. Each /// parameter is described as a property in the object. If a parameter is both in /// and out, it will appear in both the <see cref='System.Management.MethodData.InParameters'/> and <see cref='System.Management.MethodData.OutParameters'/> /// properties.</para> /// </summary> /// <value> /// <para>A <see cref='System.Management.ManagementBaseObject'/> containing all the output parameters to the method. </para> /// </value> /// <remarks> /// <para>Each parameter in this object should have an /// <see langword='ID'/> qualifier to identify the /// order of the parameters in the method call.</para> /// <para>The ReturnValue property is a special property of /// the <see cref='System.Management.MethodData.OutParameters'/> /// object and /// holds the return value of the method.</para> /// </remarks> public ManagementBaseObject OutParameters { get { RefreshMethodInfo(); return (null == wmiOutParams) ? null : new ManagementBaseObject(wmiOutParams); } } /// <summary> /// <para>Gets the name of the management class in which the method was first /// introduced in the class inheritance hierarchy.</para> /// </summary> /// <value> /// A string representing the originating /// management class name. /// </value> public string Origin { get { string className = null; int status = parent.wbemObject.GetMethodOrigin_(methodName, out className); if (status < 0) { if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_OBJECT) className = string.Empty; // Interpret as an unspecified property - return "" else if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return className; } } /// <summary> /// <para>Gets a collection of qualifiers defined in the /// method. Each element is of type <see cref='System.Management.QualifierData'/> /// and contains information such as the qualifier name, value, and /// flavor.</para> /// </summary> /// <value> /// A <see cref='System.Management.QualifierDataCollection'/> containing the /// qualifiers for this method. /// </value> /// <seealso cref='System.Management.QualifierData'/> public QualifierDataCollection Qualifiers { get { if (qualifiers == null) qualifiers = new QualifierDataCollection(parent, methodName, QualifierType.MethodQualifier); return qualifiers; } } }//MethodData }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// An IVisualStudioDocument which represents the secondary buffer to the workspace API. /// </summary> internal sealed class ContainedDocument : ForegroundThreadAffinitizedObject, IVisualStudioHostDocument { private const string ReturnReplacementString = @"{|r|}"; private const string NewLineReplacementString = @"{|n|}"; private const string HTML = nameof(HTML); private const string HTMLX = nameof(HTMLX); private const string Razor = nameof(Razor); private const string XOML = nameof(XOML); private const char RazorExplicit = '@'; private const string CSharpRazorBlock = "{"; private const string VBRazorBlock = "code"; private const string HelperRazor = "helper"; private const string FunctionsRazor = "functions"; private static readonly EditOptions s_venusEditOptions = new EditOptions(new StringDifferenceOptions { DifferenceType = StringDifferenceTypes.Character, IgnoreTrimWhiteSpace = false }); private readonly AbstractContainedLanguage _containedLanguage; private readonly SourceCodeKind _sourceCodeKind; private readonly IComponentModel _componentModel; private readonly Workspace _workspace; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly HostType _hostType; private readonly ReiteratedVersionSnapshotTracker _snapshotTracker; private readonly IFormattingRule _vbHelperFormattingRule; private readonly string _itemMoniker; public AbstractProject Project { get { return _containedLanguage.Project; } } public bool SupportsRename { get { return _hostType == HostType.Razor; } } public DocumentId Id { get; } public IReadOnlyList<string> Folders { get; } public TextLoader Loader { get; } public DocumentKey Key { get; } public ContainedDocument( AbstractContainedLanguage containedLanguage, SourceCodeKind sourceCodeKind, Workspace workspace, IVsHierarchy hierarchy, uint itemId, IComponentModel componentModel, IFormattingRule vbHelperFormattingRule) { Contract.ThrowIfNull(containedLanguage); _containedLanguage = containedLanguage; _sourceCodeKind = sourceCodeKind; _componentModel = componentModel; _workspace = workspace; _hostType = GetHostType(); string filePath; if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemId, out filePath))) { // we couldn't look up the document moniker from an hierarchy for an itemid. // Since we only use this moniker as a key, we could fall back to something else, like the document name. Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy."); if (!hierarchy.TryGetItemName(itemId, out filePath)) { Environment.FailFast("Failed to get document moniker for a contained document"); } } if (Project.Hierarchy != null) { string moniker; Project.Hierarchy.GetCanonicalName(itemId, out moniker); _itemMoniker = moniker; } this.Key = new DocumentKey(Project, filePath); this.Id = DocumentId.CreateNewId(Project.Id, filePath); this.Folders = containedLanguage.Project.GetFolderNames(itemId); this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath); _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>(); _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer); _vbHelperFormattingRule = vbHelperFormattingRule; } private HostType GetHostType() { var projectionBuffer = _containedLanguage.DataBuffer as IProjectionBuffer; if (projectionBuffer != null) { // For TypeScript hosted in HTML the source buffers will have type names // HTMLX and TypeScript. RazorCSharp has an HTMLX base type but should // not be associated with the HTML host type. Use ContentType.TypeName // instead of ContentType.IsOfType for HTMLX to ensure the Razor host // type is identified correctly. if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(HTML) || string.Compare(HTMLX, b.ContentType.TypeName, StringComparison.OrdinalIgnoreCase) == 0)) { return HostType.HTML; } if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(Razor))) { return HostType.Razor; } } else { // XOML is set up differently. For XOML, the secondary buffer (i.e. SubjectBuffer) // is a projection buffer, while the primary buffer (i.e. DataBuffer) is not. Instead, // the primary buffer is a regular unprojected ITextBuffer with the HTML content type. if (_containedLanguage.DataBuffer.CurrentSnapshot.ContentType.IsOfType(HTML)) { return HostType.XOML; } } throw ExceptionUtilities.Unreachable; } public DocumentInfo GetInitialState() { return DocumentInfo.Create( this.Id, this.Name, folders: this.Folders, sourceCodeKind: _sourceCodeKind, loader: this.Loader, filePath: this.Key.Moniker); } public bool IsOpen { get { return true; } } #pragma warning disable 67 public event EventHandler UpdatedOnDisk; public event EventHandler<bool> Opened; public event EventHandler<bool> Closing; #pragma warning restore 67 IVisualStudioHostProject IVisualStudioHostDocument.Project { get { return this.Project; } } public ITextBuffer GetOpenTextBuffer() { return _containedLanguage.SubjectBuffer; } public SourceTextContainer GetOpenTextContainer() { return this.GetOpenTextBuffer().AsTextContainer(); } public IContentType ContentType { get { return _containedLanguage.SubjectBuffer.ContentType; } } public string Name { get { try { return Path.GetFileName(this.FilePath); } catch (ArgumentException) { return this.FilePath; } } } public SourceCodeKind SourceCodeKind { get { return _sourceCodeKind; } } public string FilePath { get { return Key.Moniker; } } public AbstractContainedLanguage ContainedLanguage { get { return _containedLanguage; } } public void Dispose() { _snapshotTracker.StopTracking(_containedLanguage.SubjectBuffer); this.ContainedLanguage.Dispose(); } public DocumentId FindProjectDocumentIdWithItemId(uint itemidInsertionPoint) { return Project.GetCurrentDocuments().SingleOrDefault(d => d.GetItemId() == itemidInsertionPoint).Id; } public uint FindItemIdOfDocument(Document document) { return Project.GetDocumentOrAdditionalDocument(document.Id).GetItemId(); } public void UpdateText(SourceText newText) { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var originalSnapshot = subjectBuffer.CurrentSnapshot; var originalText = originalSnapshot.AsText(); var changes = newText.GetTextChanges(originalText); IEnumerable<int> affectedVisibleSpanIndices = null; var editorVisibleSpansInOriginal = SharedPools.Default<List<TextSpan>>().AllocateAndClear(); try { var originalDocument = _workspace.CurrentSolution.GetDocument(this.Id); editorVisibleSpansInOriginal.AddRange(GetEditorVisibleSpans()); var newChanges = FilterTextChanges(originalText, editorVisibleSpansInOriginal, changes).ToList(); if (newChanges.Count == 0) { // no change to apply return; } ApplyChanges(subjectBuffer, newChanges, editorVisibleSpansInOriginal, out affectedVisibleSpanIndices); AdjustIndentation(subjectBuffer, affectedVisibleSpanIndices); } finally { SharedPools.Default<HashSet<int>>().ClearAndFree((HashSet<int>)affectedVisibleSpanIndices); SharedPools.Default<List<TextSpan>>().ClearAndFree(editorVisibleSpansInOriginal); } } private IEnumerable<TextChange> FilterTextChanges(SourceText originalText, List<TextSpan> editorVisibleSpansInOriginal, IReadOnlyList<TextChange> changes) { // no visible spans or changes if (editorVisibleSpansInOriginal.Count == 0 || changes.Count == 0) { // return empty one yield break; } using (var pooledObject = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var changeQueue = pooledObject.Object; changeQueue.AddRange(changes); var spanIndex = 0; var changeIndex = 0; for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++) { var visibleSpan = editorVisibleSpansInOriginal[spanIndex]; var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true); for (; changeIndex < changeQueue.Count; changeIndex++) { var change = changeQueue[changeIndex]; // easy case first if (change.Span.End < visibleSpan.Start) { // move to next change continue; } if (visibleSpan.End < change.Span.Start) { // move to next visible span break; } // make sure we are not replacing whitespace around start and at the end of visible span if (WhitespaceOnEdges(originalText, visibleTextSpan, change)) { continue; } if (visibleSpan.Contains(change.Span)) { yield return change; continue; } // now it is complex case where things are intersecting each other var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList(); if (subChanges.Count > 0) { if (subChanges.Count == 1 && subChanges[0] == change) { // we can't break it. not much we can do here. just don't touch and ignore this change continue; } changeQueue.InsertRange(changeIndex + 1, subChanges); continue; } } } } } private bool WhitespaceOnEdges(SourceText text, TextSpan visibleTextSpan, TextChange change) { if (!string.IsNullOrWhiteSpace(change.NewText)) { return false; } if (change.Span.End <= visibleTextSpan.Start) { return true; } if (visibleTextSpan.End <= change.Span.Start) { return true; } return false; } private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextChange changeInOriginalText, TextSpan visibleSpanInOriginalText) { using (var changes = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var leftText = originalText.ToString(changeInOriginalText.Span); var rightText = changeInOriginalText.NewText; var offsetInOriginalText = changeInOriginalText.Span.Start; if (TryGetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText, changes.Object)) { return changes.Object.ToList(); } return GetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText); } } private bool TryGetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes) { // these are expensive. but hopefully we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spansInLeftText = leftPool.Object; var spansInRightText = rightPool.Object; if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText)) { for (var i = 0; i < spansInLeftText.Count; i++) { var spanInLeftText = spansInLeftText[i]; var spanInRightText = spansInRightText[i]; if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty) { continue; } var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); TextChange textChange; if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out textChange)) { changes.Add(textChange); } } return true; } return false; } } private IEnumerable<TextChange> GetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText) { // these are expensive. but hopefully we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) { var leftReplacementMap = leftPool.Object; var rightReplacementMap = rightPool.Object; string leftTextWithReplacement, rightTextWithReplacement; GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out leftTextWithReplacement, out rightTextWithReplacement); var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement); foreach (var difference in diffResult) { var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap); var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap); var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); TextChange textChange; if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out textChange)) { yield return textChange; } } } } private bool TryGetWhitespaceOnlyChanges(string leftText, string rightText, List<TextSpan> spansInLeftText, List<TextSpan> spansInRightText) { return TryGetWhitespaceGroup(leftText, spansInLeftText) && TryGetWhitespaceGroup(rightText, spansInRightText) && spansInLeftText.Count == spansInRightText.Count; } private bool TryGetWhitespaceGroup(string text, List<TextSpan> groups) { if (text.Length == 0) { groups.Add(new TextSpan(0, 0)); return true; } var start = 0; for (var i = 0; i < text.Length; i++) { var ch = text[i]; switch (ch) { case ' ': if (!TextAt(text, i - 1, ' ')) { start = i; } break; case '\r': case '\n': if (i == 0) { groups.Add(TextSpan.FromBounds(0, 0)); } else if (TextAt(text, i - 1, ' ')) { groups.Add(TextSpan.FromBounds(start, i)); } else if (TextAt(text, i - 1, '\n')) { groups.Add(TextSpan.FromBounds(start, i)); } start = i + 1; break; default: return false; } } if (start <= text.Length) { groups.Add(TextSpan.FromBounds(start, text.Length)); } return true; } private bool TextAt(string text, int index, char ch) { if (index < 0 || text.Length <= index) { return false; } return text[index] == ch; } private bool TryGetSubTextChange( SourceText originalText, TextSpan visibleSpanInOriginalText, string rightText, TextSpan spanInOriginalText, TextSpan spanInRightText, out TextChange textChange) { textChange = default(TextChange); var visibleFirstLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.Start); var visibleLastLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.End); // skip easy case // 1. things are out of visible span if (!visibleSpanInOriginalText.IntersectsWith(spanInOriginalText)) { return false; } // 2. there are no intersects var snippetInRightText = rightText.Substring(spanInRightText.Start, spanInRightText.Length); if (visibleSpanInOriginalText.Contains(spanInOriginalText) && visibleSpanInOriginalText.End != spanInOriginalText.End) { textChange = new TextChange(spanInOriginalText, snippetInRightText); return true; } // okay, more complex case. things are intersecting boundaries. var firstLineOfRightTextSnippet = snippetInRightText.GetFirstLineText(); var lastLineOfRightTextSnippet = snippetInRightText.GetLastLineText(); // there are 4 complex cases - these are all heuristic. not sure what better way I have. and the heuristic is heavily based on // text differ's behavior. // 1. it is a single line if (visibleFirstLineInOriginalText.LineNumber == visibleLastLineInOriginalText.LineNumber) { // don't do anything return false; } // 2. replacement contains visible spans if (spanInOriginalText.Contains(visibleSpanInOriginalText)) { // header // don't do anything // body textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length, snippetInRightText.Length - firstLineOfRightTextSnippet.Length - lastLineOfRightTextSnippet.Length)); // footer // don't do anything return true; } // 3. replacement intersects with start if (spanInOriginalText.Start < visibleSpanInOriginalText.Start && visibleSpanInOriginalText.Start <= spanInOriginalText.End && spanInOriginalText.End < visibleSpanInOriginalText.End) { // header // don't do anything // body if (visibleFirstLineInOriginalText.EndIncludingLineBreak <= spanInOriginalText.End) { textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, spanInOriginalText.End), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length)); return true; } return false; } // 4. replacement intersects with end if (visibleSpanInOriginalText.Start < spanInOriginalText.Start && spanInOriginalText.Start <= visibleSpanInOriginalText.End && visibleSpanInOriginalText.End <= spanInOriginalText.End) { // body if (spanInOriginalText.Start <= visibleLastLineInOriginalText.Start) { textChange = new TextChange( TextSpan.FromBounds(spanInOriginalText.Start, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(0, snippetInRightText.Length - lastLineOfRightTextSnippet.Length)); return true; } // footer // don't do anything return false; } // if it got hit, then it means there is a missing case throw ExceptionUtilities.Unreachable; } private IHierarchicalDifferenceCollection DiffStrings(string leftTextWithReplacement, string rightTextWithReplacement) { var diffService = _differenceSelectorService.GetTextDifferencingService( _workspace.Services.GetLanguageServices(this.Project.Language).GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(leftTextWithReplacement, rightTextWithReplacement, s_venusEditOptions.DifferenceOptions); } private void GetTextWithReplacements( string leftText, string rightText, List<ValueTuple<int, int>> leftReplacementMap, List<ValueTuple<int, int>> rightReplacementMap, out string leftTextWithReplacement, out string rightTextWithReplacement) { // to make diff works better, we choose replacement strings that don't appear in both texts. var returnReplacement = GetReplacementStrings(leftText, rightText, ReturnReplacementString); var newLineReplacement = GetReplacementStrings(leftText, rightText, NewLineReplacementString); leftTextWithReplacement = GetTextWithReplacementMap(leftText, returnReplacement, newLineReplacement, leftReplacementMap); rightTextWithReplacement = GetTextWithReplacementMap(rightText, returnReplacement, newLineReplacement, rightReplacementMap); } private static string GetReplacementStrings(string leftText, string rightText, string initialReplacement) { if (leftText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0) { return initialReplacement; } // okay, there is already one in the given text. const string format = "{{|{0}|{1}|{0}|}}"; for (var i = 0; true; i++) { var replacement = string.Format(format, i.ToString(), initialReplacement); if (leftText.IndexOf(replacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(replacement, StringComparison.Ordinal) < 0) { return replacement; } } } private string GetTextWithReplacementMap(string text, string returnReplacement, string newLineReplacement, List<ValueTuple<int, int>> replacementMap) { var delta = 0; var returnLength = returnReplacement.Length; var newLineLength = newLineReplacement.Length; var sb = StringBuilderPool.Allocate(); for (var i = 0; i < text.Length; i++) { var ch = text[i]; if (ch == '\r') { sb.Append(returnReplacement); delta += returnLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } else if (ch == '\n') { sb.Append(newLineReplacement); delta += newLineLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } sb.Append(ch); } return StringBuilderPool.ReturnAndFree(sb); } private Span AdjustSpan(Span span, List<ValueTuple<int, int>> replacementMap) { var start = span.Start; var end = span.End; for (var i = 0; i < replacementMap.Count; i++) { var positionAndDelta = replacementMap[i]; if (positionAndDelta.Item1 <= span.Start) { start = span.Start - positionAndDelta.Item2; } if (positionAndDelta.Item1 <= span.End) { end = span.End - positionAndDelta.Item2; } if (positionAndDelta.Item1 > span.End) { break; } } return Span.FromBounds(start, end); } public IEnumerable<TextSpan> GetEditorVisibleSpans() { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var projectionDataBuffer = _containedLanguage.DataBuffer as IProjectionBuffer; if (projectionDataBuffer != null) { return projectionDataBuffer.CurrentSnapshot .GetSourceSpans() .Where(ss => ss.Snapshot.TextBuffer == subjectBuffer) .Select(s => s.Span.ToTextSpan()) .OrderBy(s => s.Start); } else { return SpecializedCollections.EmptyEnumerable<TextSpan>(); } } private static void ApplyChanges( IProjectionBuffer subjectBuffer, IEnumerable<TextChange> changes, IList<TextSpan> visibleSpansInOriginal, out IEnumerable<int> affectedVisibleSpansInNew) { using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear(); affectedVisibleSpansInNew = affectedSpans; var currentVisibleSpanIndex = 0; foreach (var change in changes) { // Find the next visible span that either overlaps or intersects with while (currentVisibleSpanIndex < visibleSpansInOriginal.Count && visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start) { currentVisibleSpanIndex++; } // no more place to apply text changes if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count) { break; } var newText = change.NewText; var span = change.Span.ToSpan(); edit.Replace(span, newText); affectedSpans.Add(currentVisibleSpanIndex); } edit.Apply(); } } private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int> visibleSpanIndex) { if (!visibleSpanIndex.Any()) { return; } var snapshot = subjectBuffer.CurrentSnapshot; var document = _workspace.CurrentSolution.GetDocument(this.Id); if (!document.SupportsSyntaxTree) { return; } var originalText = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); Contract.Requires(object.ReferenceEquals(originalText, snapshot.AsText())); var root = document.GetSyntaxRootSynchronously(CancellationToken.None); var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var options = _workspace.Options .WithChangedOption(FormattingOptions.UseTabs, root.Language, !editorOptions.IsConvertTabsToSpacesEnabled()) .WithChangedOption(FormattingOptions.TabSize, root.Language, editorOptions.GetTabSize()) .WithChangedOption(FormattingOptions.IndentationSize, root.Language, editorOptions.GetIndentSize()); using (var pooledObject = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spans = pooledObject.Object; spans.AddRange(this.GetEditorVisibleSpans()); using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { foreach (var spanIndex in visibleSpanIndex) { var rule = GetBaseIndentationRule(root, originalText, spans, spanIndex); var visibleSpan = spans[spanIndex]; AdjustIndentationForSpan(document, edit, visibleSpan, rule, options); } edit.Apply(); } } } private void AdjustIndentationForSpan( Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options) { var root = document.GetSyntaxRootSynchronously(CancellationToken.None); using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject()) using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var venusFormattingRules = rulePool.Object; var visibleSpans = spanPool.Object; venusFormattingRules.Add(baseIndentationRule); venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance); var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document)); var workspace = document.Project.Solution.Workspace; var changes = Formatter.GetFormattedTextChanges( root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) }, workspace, options, formattingRules, CancellationToken.None); visibleSpans.Add(visibleSpan); var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span)); foreach (var change in newChanges) { edit.Replace(change.Span.ToSpan(), change.NewText); } } } public BaseIndentationFormattingRule GetBaseIndentationRule(SyntaxNode root, SourceText text, List<TextSpan> spans, int spanIndex) { if (_hostType == HostType.Razor) { var currentSpanIndex = spanIndex; TextSpan visibleSpan; TextSpan visibleTextSpan; GetVisibleAndTextSpan(text, spans, currentSpanIndex, out visibleSpan, out visibleTextSpan); var end = visibleSpan.End; var current = root.FindToken(visibleTextSpan.Start).Parent; while (current != null) { if (current.Span.Start == visibleTextSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Explicit) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } } if (current.Span.Start < visibleSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Block || blockType == RazorCodeBlockType.Helper) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } if (currentSpanIndex == 0) { break; } GetVisibleAndTextSpan(text, spans, --currentSpanIndex, out visibleSpan, out visibleTextSpan); continue; } current = current.Parent; } } var span = spans[spanIndex]; var indentation = GetBaseIndentation(root, text, span); return new BaseIndentationFormattingRule(root, span, indentation, _vbHelperFormattingRule); } private void GetVisibleAndTextSpan(SourceText text, List<TextSpan> spans, int spanIndex, out TextSpan visibleSpan, out TextSpan visibleTextSpan) { visibleSpan = spans[spanIndex]; visibleTextSpan = GetVisibleTextSpan(text, visibleSpan); if (visibleTextSpan.IsEmpty) { // span has no text in them visibleTextSpan = visibleSpan; } } private int GetBaseIndentation(SyntaxNode root, SourceText text, TextSpan span) { // Is this right? We should probably get this from the IVsContainedLanguageHost instead. var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var additionalIndentation = GetAdditionalIndentation(root, text, span); string baseIndentationString; int parent, indentSize, useTabs = 0, tabSize = 0; // Skip over the first line, since it's in "Venus space" anyway. var startingLine = text.Lines.GetLineFromPosition(span.Start); for (var line = startingLine; line.Start < span.End; line = text.Lines[line.LineNumber + 1]) { Marshal.ThrowExceptionForHR( this.ContainedLanguage.ContainedLanguageHost.GetLineIndent( line.LineNumber, out baseIndentationString, out parent, out indentSize, out useTabs, out tabSize)); if (!string.IsNullOrEmpty(baseIndentationString)) { return baseIndentationString.GetColumnFromLineOffset(baseIndentationString.Length, editorOptions.GetTabSize()) + additionalIndentation; } } return additionalIndentation; } private TextSpan GetVisibleTextSpan(SourceText text, TextSpan visibleSpan, bool uptoFirstAndLastLine = false) { var start = visibleSpan.Start; for (; start < visibleSpan.End; start++) { if (!char.IsWhiteSpace(text[start])) { break; } } var end = visibleSpan.End - 1; if (start <= end) { for (; start <= end; end--) { if (!char.IsWhiteSpace(text[end])) { break; } } } if (uptoFirstAndLastLine) { var firstLine = text.Lines.GetLineFromPosition(visibleSpan.Start); var lastLine = text.Lines.GetLineFromPosition(visibleSpan.End); if (firstLine.LineNumber < lastLine.LineNumber) { start = (start < firstLine.End) ? start : firstLine.End; end = (lastLine.Start < end + 1) ? end : lastLine.Start - 1; } } return (start <= end) ? TextSpan.FromBounds(start, end + 1) : default(TextSpan); } private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan span) { if (_hostType == HostType.HTML) { return _workspace.Options.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } if (_hostType == HostType.Razor) { var type = GetRazorCodeBlockType(span.Start); // razor block if (type == RazorCodeBlockType.Block) { // more workaround for csharp razor case. when } for csharp razor code block is just typed, "}" exist // in both subject and surface buffer and there is no easy way to figure out who owns } just typed. // in this case, we let razor owns it. later razor will remove } from subject buffer if it is something // razor owns. if (this.Project.Language == LanguageNames.CSharp) { var textSpan = GetVisibleTextSpan(text, span); var end = textSpan.End - 1; if (end >= 0 && text[end] == '}') { var token = root.FindToken(end); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.Start == end && syntaxFact != null) { SyntaxToken openBrace; if (syntaxFact.TryGetCorrespondingOpenBrace(token, out openBrace) && !textSpan.Contains(openBrace.Span)) { return 0; } } } } // same as C#, but different text is in the buffer if (this.Project.Language == LanguageNames.VisualBasic) { var textSpan = GetVisibleTextSpan(text, span); var subjectSnapshot = _containedLanguage.SubjectBuffer.CurrentSnapshot; var end = textSpan.End - 1; if (end >= 0) { var ch = subjectSnapshot[end]; if (CheckCode(subjectSnapshot, textSpan.End, ch, VBRazorBlock, checkAt: false) || CheckCode(subjectSnapshot, textSpan.End, ch, FunctionsRazor, checkAt: false)) { var token = root.FindToken(end, findInsideTrivia: true); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.End == textSpan.End && syntaxFact != null) { if (syntaxFact.IsSkippedTokensTrivia(token.Parent)) { return 0; } } } } } return _workspace.Options.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } } return 0; } private RazorCodeBlockType GetRazorCodeBlockType(int position) { Debug.Assert(_hostType == HostType.Razor); var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var subjectSnapshot = subjectBuffer.CurrentSnapshot; var surfaceSnapshot = ((IProjectionBuffer)_containedLanguage.DataBuffer).CurrentSnapshot; var surfacePoint = surfaceSnapshot.MapFromSourceSnapshot(new SnapshotPoint(subjectSnapshot, position), PositionAffinity.Predecessor); if (!surfacePoint.HasValue) { // how this can happen? return RazorCodeBlockType.Implicit; } var ch = char.ToLower(surfaceSnapshot[Math.Max(surfacePoint.Value - 1, 0)]); // razor block if (IsCodeBlock(surfaceSnapshot, surfacePoint.Value, ch)) { return RazorCodeBlockType.Block; } if (ch == RazorExplicit) { return RazorCodeBlockType.Explicit; } if (CheckCode(surfaceSnapshot, surfacePoint.Value, HelperRazor)) { return RazorCodeBlockType.Helper; } return RazorCodeBlockType.Implicit; } private bool IsCodeBlock(ITextSnapshot surfaceSnapshot, int position, char ch) { if (this.Project.Language == LanguageNames.CSharp) { return CheckCode(surfaceSnapshot, position, ch, CSharpRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor, CSharpRazorBlock); } if (this.Project.Language == LanguageNames.VisualBasic) { return CheckCode(surfaceSnapshot, position, ch, VBRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor); } return false; } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag, bool checkAt = true) { if (ch != tag[tag.Length - 1] || position < tag.Length) { return false; } var start = position - tag.Length; var razorTag = snapshot.GetText(start, tag.Length); return string.Equals(razorTag, tag, StringComparison.OrdinalIgnoreCase) && (!checkAt || snapshot[start - 1] == RazorExplicit); } private bool CheckCode(ITextSnapshot snapshot, int position, string tag) { int i = position - 1; if (i < 0) { return false; } for (; i >= 0; i--) { if (!char.IsWhiteSpace(snapshot[i])) { break; } } var ch = snapshot[i]; position = i + 1; return CheckCode(snapshot, position, ch, tag); } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag1, string tag2) { if (!CheckCode(snapshot, position, ch, tag2, checkAt: false)) { return false; } return CheckCode(snapshot, position - tag2.Length, tag1); } public ITextUndoHistory GetTextUndoHistory() { // In Venus scenarios, the undo history is associated with the data buffer return _componentModel.GetService<ITextUndoHistoryRegistry>().GetHistory(_containedLanguage.DataBuffer); } public uint GetItemId() { AssertIsForeground(); if (_itemMoniker == null) { return (uint)VSConstants.VSITEMID.Nil; } uint itemId; return Project.Hierarchy.ParseCanonicalName(_itemMoniker, out itemId) == VSConstants.S_OK ? itemId : (uint)VSConstants.VSITEMID.Nil; } private enum RazorCodeBlockType { Block, Explicit, Implicit, Helper } private enum HostType { HTML, Razor, XOML } } }
// 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.Xunit.Performance; using System; using System.Linq; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using Xunit; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] namespace Inlining { public static class ConstantArgsDouble { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 100000; #endif // Doubles feeding math operations. // // Inlining in Bench0xp should enable constant folding // Inlining in Bench0xn will not enable constant folding static double Five = 5; static double Ten = 10; static double Id(double x) { return x; } static double F00(double x) { return x * x; } static bool Bench00p() { double t = 10; double f = F00(t); return (f == 100); } static bool Bench00n() { double t = Ten; double f = F00(t); return (f == 100); } static bool Bench00p1() { double t = Id(10); double f = F00(t); return (f == 100); } static bool Bench00n1() { double t = Id(Ten); double f = F00(t); return (f == 100); } static bool Bench00p2() { double t = Id(10); double f = F00(Id(t)); return (f == 100); } static bool Bench00n2() { double t = Id(Ten); double f = F00(Id(t)); return (f == 100); } static bool Bench00p3() { double t = 10; double f = F00(Id(Id(t))); return (f == 100); } static bool Bench00n3() { double t = Ten; double f = F00(Id(Id(t))); return (f == 100); } static bool Bench00p4() { double t = 5; double f = F00(2 * t); return (f == 100); } static bool Bench00n4() { double t = Five; double f = F00(2 * t); return (f == 100); } static double F01(double x) { return 1000 / x; } static bool Bench01p() { double t = 10; double f = F01(t); return (f == 100); } static bool Bench01n() { double t = Ten; double f = F01(t); return (f == 100); } static double F02(double x) { return 20 * (x / 2); } static bool Bench02p() { double t = 10; double f = F02(t); return (f == 100); } static bool Bench02n() { double t = Ten; double f = F02(t); return (f == 100); } static double F03(double x) { return 91 + 1009 % x; } static bool Bench03p() { double t = 10; double f = F03(t); return (f == 100); } static bool Bench03n() { double t = Ten; double f = F03(t); return (f == 100); } static double F04(double x) { return 50 * (x % 4); } static bool Bench04p() { double t = 10; double f = F04(t); return (f == 100); } static bool Bench04n() { double t = Ten; double f = F04(t); return (f == 100); } static double F06(double x) { return -x + 110; } static bool Bench06p() { double t = 10; double f = F06(t); return (f == 100); } static bool Bench06n() { double t = Ten; double f = F06(t); return (f == 100); } // Doubles feeding comparisons. // // Inlining in Bench1xp should enable branch optimization // Inlining in Bench1xn will not enable branch optimization static double F10(double x) { return x == 10 ? 100 : 0; } static bool Bench10p() { double t = 10; double f = F10(t); return (f == 100); } static bool Bench10n() { double t = Ten; double f = F10(t); return (f == 100); } static double F101(double x) { return x != 10 ? 0 : 100; } static bool Bench10p1() { double t = 10; double f = F101(t); return (f == 100); } static bool Bench10n1() { double t = Ten; double f = F101(t); return (f == 100); } static double F102(double x) { return x >= 10 ? 100 : 0; } static bool Bench10p2() { double t = 10; double f = F102(t); return (f == 100); } static bool Bench10n2() { double t = Ten; double f = F102(t); return (f == 100); } static double F103(double x) { return x <= 10 ? 100 : 0; } static bool Bench10p3() { double t = 10; double f = F103(t); return (f == 100); } static bool Bench10n3() { double t = Ten; double f = F102(t); return (f == 100); } static double F11(double x) { if (x == 10) { return 100; } else { return 0; } } static bool Bench11p() { double t = 10; double f = F11(t); return (f == 100); } static bool Bench11n() { double t = Ten; double f = F11(t); return (f == 100); } static double F111(double x) { if (x != 10) { return 0; } else { return 100; } } static bool Bench11p1() { double t = 10; double f = F111(t); return (f == 100); } static bool Bench11n1() { double t = Ten; double f = F111(t); return (f == 100); } static double F112(double x) { if (x > 10) { return 0; } else { return 100; } } static bool Bench11p2() { double t = 10; double f = F112(t); return (f == 100); } static bool Bench11n2() { double t = Ten; double f = F112(t); return (f == 100); } static double F113(double x) { if (x < 10) { return 0; } else { return 100; } } static bool Bench11p3() { double t = 10; double f = F113(t); return (f == 100); } static bool Bench11n3() { double t = Ten; double f = F113(t); return (f == 100); } // Ununsed (or effectively unused) parameters // // Simple callee analysis may overstate inline benefit static double F20(double x) { return 100; } static bool Bench20p() { double t = 10; double f = F20(t); return (f == 100); } static bool Bench20p1() { double t = Ten; double f = F20(t); return (f == 100); } static double F21(double x) { return -x + 100 + x; } static bool Bench21p() { double t = 10; double f = F21(t); return (f == 100); } static bool Bench21n() { double t = Ten; double f = F21(t); return (f == 100); } static double F211(double x) { return x - x + 100; } static bool Bench21p1() { double t = 10; double f = F211(t); return (f == 100); } static bool Bench21n1() { double t = Ten; double f = F211(t); return (f == 100); } static double F22(double x) { if (x > 0) { return 100; } return 100; } static bool Bench22p() { double t = 10; double f = F22(t); return (f == 100); } static bool Bench22p1() { double t = Ten; double f = F22(t); return (f == 100); } static double F23(double x) { if (x > 0) { return 90 + x; } return 100; } static bool Bench23p() { double t = 10; double f = F23(t); return (f == 100); } static bool Bench23n() { double t = Ten; double f = F23(t); return (f == 100); } // Multiple parameters static double F30(double x, double y) { return y * y; } static bool Bench30p() { double t = 10; double f = F30(t, t); return (f == 100); } static bool Bench30n() { double t = Ten; double f = F30(t, t); return (f == 100); } static bool Bench30p1() { double s = Ten; double t = 10; double f = F30(s, t); return (f == 100); } static bool Bench30n1() { double s = 10; double t = Ten; double f = F30(s, t); return (f == 100); } static bool Bench30p2() { double s = 10; double t = 10; double f = F30(s, t); return (f == 100); } static bool Bench30n2() { double s = Ten; double t = Ten; double f = F30(s, t); return (f == 100); } static bool Bench30p3() { double s = 10; double t = s; double f = F30(s, t); return (f == 100); } static bool Bench30n3() { double s = Ten; double t = s; double f = F30(s, t); return (f == 100); } static double F31(double x, double y, double z) { return z * z; } static bool Bench31p() { double t = 10; double f = F31(t, t, t); return (f == 100); } static bool Bench31n() { double t = Ten; double f = F31(t, t, t); return (f == 100); } static bool Bench31p1() { double r = Ten; double s = Ten; double t = 10; double f = F31(r, s, t); return (f == 100); } static bool Bench31n1() { double r = 10; double s = 10; double t = Ten; double f = F31(r, s, t); return (f == 100); } static bool Bench31p2() { double r = 10; double s = 10; double t = 10; double f = F31(r, s, t); return (f == 100); } static bool Bench31n2() { double r = Ten; double s = Ten; double t = Ten; double f = F31(r, s, t); return (f == 100); } static bool Bench31p3() { double r = 10; double s = r; double t = s; double f = F31(r, s, t); return (f == 100); } static bool Bench31n3() { double r = Ten; double s = r; double t = s; double f = F31(r, s, t); return (f == 100); } // Two args, both used static double F40(double x, double y) { return x * x + y * y - 100; } static bool Bench40p() { double t = 10; double f = F40(t, t); return (f == 100); } static bool Bench40n() { double t = Ten; double f = F40(t, t); return (f == 100); } static bool Bench40p1() { double s = Ten; double t = 10; double f = F40(s, t); return (f == 100); } static bool Bench40p2() { double s = 10; double t = Ten; double f = F40(s, t); return (f == 100); } static double F41(double x, double y) { return x * y; } static bool Bench41p() { double t = 10; double f = F41(t, t); return (f == 100); } static bool Bench41n() { double t = Ten; double f = F41(t, t); return (f == 100); } static bool Bench41p1() { double s = 10; double t = Ten; double f = F41(s, t); return (f == 100); } static bool Bench41p2() { double s = Ten; double t = 10; double f = F41(s, t); return (f == 100); } private static IEnumerable<object[]> MakeArgs(params string[] args) { return args.Select(arg => new object[] { arg }); } public static IEnumerable<object[]> TestFuncs = MakeArgs( "Bench00p", "Bench00n", "Bench00p1", "Bench00n1", "Bench00p2", "Bench00n2", "Bench00p3", "Bench00n3", "Bench00p4", "Bench00n4", "Bench01p", "Bench01n", "Bench02p", "Bench02n", "Bench03p", "Bench03n", "Bench04p", "Bench04n", "Bench06p", "Bench06n", "Bench10p", "Bench10n", "Bench10p1", "Bench10n1", "Bench10p2", "Bench10n2", "Bench10p3", "Bench10n3", "Bench11p", "Bench11n", "Bench11p1", "Bench11n1", "Bench11p2", "Bench11n2", "Bench11p3", "Bench11n3", "Bench20p", "Bench20p1", "Bench21p", "Bench21n", "Bench21p1", "Bench21n1", "Bench22p", "Bench22p1", "Bench23p", "Bench23n", "Bench30p", "Bench30n", "Bench30p1", "Bench30n1", "Bench30p2", "Bench30n2", "Bench30p3", "Bench30n3", "Bench31p", "Bench31n", "Bench31p1", "Bench31n1", "Bench31p2", "Bench31n2", "Bench31p3", "Bench31n3", "Bench40p", "Bench40n", "Bench40p1", "Bench40p2", "Bench41p", "Bench41n", "Bench41p1", "Bench41p2" ); static Func<bool> LookupFunc(object o) { TypeInfo t = typeof(ConstantArgsDouble).GetTypeInfo(); MethodInfo m = t.GetDeclaredMethod((string) o); return m.CreateDelegate(typeof(Func<bool>)) as Func<bool>; } [Benchmark] [MemberData(nameof(TestFuncs))] public static void Test(object funcName) { Func<bool> f = LookupFunc(funcName); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Iterations; i++) { f(); } } } } static bool TestBase(Func<bool> f) { bool result = true; for (int i = 0; i < Iterations; i++) { result &= f(); } return result; } public static int Main() { bool result = true; foreach(object[] o in TestFuncs) { string funcName = (string) o[0]; Func<bool> func = LookupFunc(funcName); bool thisResult = TestBase(func); if (!thisResult) { Console.WriteLine("{0} failed", funcName); } result &= thisResult; } return (result ? 100 : -1); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/devtools/cloudtrace/v2/tracing.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Trace.V2 { /// <summary>Holder for reflection information generated from google/devtools/cloudtrace/v2/tracing.proto</summary> public static partial class TracingReflection { #region Descriptor /// <summary>File descriptor for google/devtools/cloudtrace/v2/tracing.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TracingReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Citnb29nbGUvZGV2dG9vbHMvY2xvdWR0cmFjZS92Mi90cmFjaW5nLnByb3Rv", "Eh1nb29nbGUuZGV2dG9vbHMuY2xvdWR0cmFjZS52MhocZ29vZ2xlL2FwaS9h", "bm5vdGF0aW9ucy5wcm90bxopZ29vZ2xlL2RldnRvb2xzL2Nsb3VkdHJhY2Uv", "djIvdHJhY2UucHJvdG8aG2dvb2dsZS9wcm90b2J1Zi9lbXB0eS5wcm90bxof", "Z29vZ2xlL3Byb3RvYnVmL3RpbWVzdGFtcC5wcm90byJaChZCYXRjaFdyaXRl", "U3BhbnNSZXF1ZXN0EgwKBG5hbWUYASABKAkSMgoFc3BhbnMYAiADKAsyIy5n", "b29nbGUuZGV2dG9vbHMuY2xvdWR0cmFjZS52Mi5TcGFuMq8CCgxUcmFjZVNl", "cnZpY2USlAEKD0JhdGNoV3JpdGVTcGFucxI1Lmdvb2dsZS5kZXZ0b29scy5j", "bG91ZHRyYWNlLnYyLkJhdGNoV3JpdGVTcGFuc1JlcXVlc3QaFi5nb29nbGUu", "cHJvdG9idWYuRW1wdHkiMoLT5JMCLCInL3YyL3tuYW1lPXByb2plY3RzLyp9", "L3RyYWNlczpiYXRjaFdyaXRlOgEqEocBCgpDcmVhdGVTcGFuEiMuZ29vZ2xl", "LmRldnRvb2xzLmNsb3VkdHJhY2UudjIuU3BhbhojLmdvb2dsZS5kZXZ0b29s", "cy5jbG91ZHRyYWNlLnYyLlNwYW4iL4LT5JMCKSIkL3YyL3tuYW1lPXByb2pl", "Y3RzLyovdHJhY2VzLyp9L3NwYW5zOgEqQqwBCiFjb20uZ29vZ2xlLmRldnRv", "b2xzLmNsb3VkdHJhY2UudjJCDFRyYWNpbmdQcm90b1ABWkdnb29nbGUuZ29s", "YW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2RldnRvb2xzL2Nsb3VkdHJh", "Y2UvdjI7Y2xvdWR0cmFjZaoCFUdvb2dsZS5DbG91ZC5UcmFjZS5WMsoCFUdv", "b2dsZVxDbG91ZFxUcmFjZVxWMmIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Cloud.Trace.V2.TraceReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Trace.V2.BatchWriteSpansRequest), global::Google.Cloud.Trace.V2.BatchWriteSpansRequest.Parser, new[]{ "Name", "Spans" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// The request message for the `BatchWriteSpans` method. /// </summary> public sealed partial class BatchWriteSpansRequest : pb::IMessage<BatchWriteSpansRequest> { private static readonly pb::MessageParser<BatchWriteSpansRequest> _parser = new pb::MessageParser<BatchWriteSpansRequest>(() => new BatchWriteSpansRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<BatchWriteSpansRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Trace.V2.TracingReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BatchWriteSpansRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BatchWriteSpansRequest(BatchWriteSpansRequest other) : this() { name_ = other.name_; spans_ = other.spans_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BatchWriteSpansRequest Clone() { return new BatchWriteSpansRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Required. The name of the project where the spans belong. The format is /// `projects/[PROJECT_ID]`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "spans" field.</summary> public const int SpansFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Cloud.Trace.V2.Span> _repeated_spans_codec = pb::FieldCodec.ForMessage(18, global::Google.Cloud.Trace.V2.Span.Parser); private readonly pbc::RepeatedField<global::Google.Cloud.Trace.V2.Span> spans_ = new pbc::RepeatedField<global::Google.Cloud.Trace.V2.Span>(); /// <summary> /// A list of new spans. The span names must not match existing /// spans, or the results are undefined. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Cloud.Trace.V2.Span> Spans { get { return spans_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as BatchWriteSpansRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(BatchWriteSpansRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if(!spans_.Equals(other.spans_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); hash ^= spans_.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 (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } spans_.WriteTo(output, _repeated_spans_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } size += spans_.CalculateSize(_repeated_spans_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(BatchWriteSpansRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } spans_.Add(other.spans_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { spans_.AddEntriesFrom(input, _repeated_spans_codec); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Extensions.EnumExtensions; using osu.Framework.Input; using osuTK.Input; using SDL2; namespace osu.Framework.Platform.SDL2 { public static class SDL2Extensions { public static Key ToKey(this SDL.SDL_Keysym sdlKeysym) { // Apple devices don't have the notion of NumLock (they have a Clear key instead). // treat them as if they always have NumLock on (the numpad always performs its primary actions). bool numLockOn = sdlKeysym.mod.HasFlagFast(SDL.SDL_Keymod.KMOD_NUM) || RuntimeInfo.IsApple; switch (sdlKeysym.scancode) { default: case SDL.SDL_Scancode.SDL_SCANCODE_UNKNOWN: return Key.Unknown; case SDL.SDL_Scancode.SDL_SCANCODE_KP_COMMA: return Key.Comma; case SDL.SDL_Scancode.SDL_SCANCODE_KP_TAB: return Key.Tab; case SDL.SDL_Scancode.SDL_SCANCODE_KP_BACKSPACE: return Key.BackSpace; case SDL.SDL_Scancode.SDL_SCANCODE_KP_A: return Key.A; case SDL.SDL_Scancode.SDL_SCANCODE_KP_B: return Key.B; case SDL.SDL_Scancode.SDL_SCANCODE_KP_C: return Key.C; case SDL.SDL_Scancode.SDL_SCANCODE_KP_D: return Key.D; case SDL.SDL_Scancode.SDL_SCANCODE_KP_E: return Key.E; case SDL.SDL_Scancode.SDL_SCANCODE_KP_F: return Key.F; case SDL.SDL_Scancode.SDL_SCANCODE_KP_SPACE: return Key.Space; case SDL.SDL_Scancode.SDL_SCANCODE_KP_CLEAR: return Key.Clear; case SDL.SDL_Scancode.SDL_SCANCODE_RETURN: return Key.Enter; case SDL.SDL_Scancode.SDL_SCANCODE_ESCAPE: return Key.Escape; case SDL.SDL_Scancode.SDL_SCANCODE_BACKSPACE: return Key.BackSpace; case SDL.SDL_Scancode.SDL_SCANCODE_TAB: return Key.Tab; case SDL.SDL_Scancode.SDL_SCANCODE_SPACE: return Key.Space; case SDL.SDL_Scancode.SDL_SCANCODE_APOSTROPHE: return Key.Quote; case SDL.SDL_Scancode.SDL_SCANCODE_COMMA: return Key.Comma; case SDL.SDL_Scancode.SDL_SCANCODE_MINUS: return Key.Minus; case SDL.SDL_Scancode.SDL_SCANCODE_PERIOD: return Key.Period; case SDL.SDL_Scancode.SDL_SCANCODE_SLASH: return Key.Slash; case SDL.SDL_Scancode.SDL_SCANCODE_0: return Key.Number0; case SDL.SDL_Scancode.SDL_SCANCODE_1: return Key.Number1; case SDL.SDL_Scancode.SDL_SCANCODE_2: return Key.Number2; case SDL.SDL_Scancode.SDL_SCANCODE_3: return Key.Number3; case SDL.SDL_Scancode.SDL_SCANCODE_4: return Key.Number4; case SDL.SDL_Scancode.SDL_SCANCODE_5: return Key.Number5; case SDL.SDL_Scancode.SDL_SCANCODE_6: return Key.Number6; case SDL.SDL_Scancode.SDL_SCANCODE_7: return Key.Number7; case SDL.SDL_Scancode.SDL_SCANCODE_8: return Key.Number8; case SDL.SDL_Scancode.SDL_SCANCODE_9: return Key.Number9; case SDL.SDL_Scancode.SDL_SCANCODE_SEMICOLON: return Key.Semicolon; case SDL.SDL_Scancode.SDL_SCANCODE_EQUALS: return Key.Plus; case SDL.SDL_Scancode.SDL_SCANCODE_LEFTBRACKET: return Key.BracketLeft; case SDL.SDL_Scancode.SDL_SCANCODE_BACKSLASH: return Key.BackSlash; case SDL.SDL_Scancode.SDL_SCANCODE_RIGHTBRACKET: return Key.BracketRight; case SDL.SDL_Scancode.SDL_SCANCODE_GRAVE: return Key.Tilde; case SDL.SDL_Scancode.SDL_SCANCODE_A: return Key.A; case SDL.SDL_Scancode.SDL_SCANCODE_B: return Key.B; case SDL.SDL_Scancode.SDL_SCANCODE_C: return Key.C; case SDL.SDL_Scancode.SDL_SCANCODE_D: return Key.D; case SDL.SDL_Scancode.SDL_SCANCODE_E: return Key.E; case SDL.SDL_Scancode.SDL_SCANCODE_F: return Key.F; case SDL.SDL_Scancode.SDL_SCANCODE_G: return Key.G; case SDL.SDL_Scancode.SDL_SCANCODE_H: return Key.H; case SDL.SDL_Scancode.SDL_SCANCODE_I: return Key.I; case SDL.SDL_Scancode.SDL_SCANCODE_J: return Key.J; case SDL.SDL_Scancode.SDL_SCANCODE_K: return Key.K; case SDL.SDL_Scancode.SDL_SCANCODE_L: return Key.L; case SDL.SDL_Scancode.SDL_SCANCODE_M: return Key.M; case SDL.SDL_Scancode.SDL_SCANCODE_N: return Key.N; case SDL.SDL_Scancode.SDL_SCANCODE_O: return Key.O; case SDL.SDL_Scancode.SDL_SCANCODE_P: return Key.P; case SDL.SDL_Scancode.SDL_SCANCODE_Q: return Key.Q; case SDL.SDL_Scancode.SDL_SCANCODE_R: return Key.R; case SDL.SDL_Scancode.SDL_SCANCODE_S: return Key.S; case SDL.SDL_Scancode.SDL_SCANCODE_T: return Key.T; case SDL.SDL_Scancode.SDL_SCANCODE_U: return Key.U; case SDL.SDL_Scancode.SDL_SCANCODE_V: return Key.V; case SDL.SDL_Scancode.SDL_SCANCODE_W: return Key.W; case SDL.SDL_Scancode.SDL_SCANCODE_X: return Key.X; case SDL.SDL_Scancode.SDL_SCANCODE_Y: return Key.Y; case SDL.SDL_Scancode.SDL_SCANCODE_Z: return Key.Z; case SDL.SDL_Scancode.SDL_SCANCODE_CAPSLOCK: return Key.CapsLock; case SDL.SDL_Scancode.SDL_SCANCODE_F1: return Key.F1; case SDL.SDL_Scancode.SDL_SCANCODE_F2: return Key.F2; case SDL.SDL_Scancode.SDL_SCANCODE_F3: return Key.F3; case SDL.SDL_Scancode.SDL_SCANCODE_F4: return Key.F4; case SDL.SDL_Scancode.SDL_SCANCODE_F5: return Key.F5; case SDL.SDL_Scancode.SDL_SCANCODE_F6: return Key.F6; case SDL.SDL_Scancode.SDL_SCANCODE_F7: return Key.F7; case SDL.SDL_Scancode.SDL_SCANCODE_F8: return Key.F8; case SDL.SDL_Scancode.SDL_SCANCODE_F9: return Key.F9; case SDL.SDL_Scancode.SDL_SCANCODE_F10: return Key.F10; case SDL.SDL_Scancode.SDL_SCANCODE_F11: return Key.F11; case SDL.SDL_Scancode.SDL_SCANCODE_F12: return Key.F12; case SDL.SDL_Scancode.SDL_SCANCODE_PRINTSCREEN: return Key.PrintScreen; case SDL.SDL_Scancode.SDL_SCANCODE_SCROLLLOCK: return Key.ScrollLock; case SDL.SDL_Scancode.SDL_SCANCODE_PAUSE: return Key.Pause; case SDL.SDL_Scancode.SDL_SCANCODE_INSERT: return Key.Insert; case SDL.SDL_Scancode.SDL_SCANCODE_HOME: return Key.Home; case SDL.SDL_Scancode.SDL_SCANCODE_PAGEUP: return Key.PageUp; case SDL.SDL_Scancode.SDL_SCANCODE_DELETE: return Key.Delete; case SDL.SDL_Scancode.SDL_SCANCODE_END: return Key.End; case SDL.SDL_Scancode.SDL_SCANCODE_PAGEDOWN: return Key.PageDown; case SDL.SDL_Scancode.SDL_SCANCODE_RIGHT: return Key.Right; case SDL.SDL_Scancode.SDL_SCANCODE_LEFT: return Key.Left; case SDL.SDL_Scancode.SDL_SCANCODE_DOWN: return Key.Down; case SDL.SDL_Scancode.SDL_SCANCODE_UP: return Key.Up; case SDL.SDL_Scancode.SDL_SCANCODE_NUMLOCKCLEAR: return Key.NumLock; case SDL.SDL_Scancode.SDL_SCANCODE_KP_DIVIDE: return Key.KeypadDivide; case SDL.SDL_Scancode.SDL_SCANCODE_KP_MULTIPLY: return Key.KeypadMultiply; case SDL.SDL_Scancode.SDL_SCANCODE_KP_MINUS: return Key.KeypadMinus; case SDL.SDL_Scancode.SDL_SCANCODE_KP_PLUS: return Key.KeypadPlus; case SDL.SDL_Scancode.SDL_SCANCODE_KP_ENTER: return Key.KeypadEnter; case SDL.SDL_Scancode.SDL_SCANCODE_KP_1: return numLockOn ? Key.Keypad1 : Key.End; case SDL.SDL_Scancode.SDL_SCANCODE_KP_2: return numLockOn ? Key.Keypad2 : Key.Down; case SDL.SDL_Scancode.SDL_SCANCODE_KP_3: return numLockOn ? Key.Keypad3 : Key.PageDown; case SDL.SDL_Scancode.SDL_SCANCODE_KP_4: return numLockOn ? Key.Keypad4 : Key.Left; case SDL.SDL_Scancode.SDL_SCANCODE_KP_5: return Key.Keypad5; case SDL.SDL_Scancode.SDL_SCANCODE_KP_6: return numLockOn ? Key.Keypad6 : Key.Right; case SDL.SDL_Scancode.SDL_SCANCODE_KP_7: return numLockOn ? Key.Keypad7 : Key.Home; case SDL.SDL_Scancode.SDL_SCANCODE_KP_8: return numLockOn ? Key.Keypad8 : Key.Up; case SDL.SDL_Scancode.SDL_SCANCODE_KP_9: return numLockOn ? Key.Keypad9 : Key.PageUp; case SDL.SDL_Scancode.SDL_SCANCODE_KP_0: return numLockOn ? Key.Keypad0 : Key.Insert; case SDL.SDL_Scancode.SDL_SCANCODE_KP_PERIOD: return numLockOn ? Key.KeypadPeriod : Key.Delete; case SDL.SDL_Scancode.SDL_SCANCODE_NONUSBACKSLASH: return Key.NonUSBackSlash; case SDL.SDL_Scancode.SDL_SCANCODE_F13: return Key.F13; case SDL.SDL_Scancode.SDL_SCANCODE_F14: return Key.F14; case SDL.SDL_Scancode.SDL_SCANCODE_F15: return Key.F15; case SDL.SDL_Scancode.SDL_SCANCODE_F16: return Key.F16; case SDL.SDL_Scancode.SDL_SCANCODE_F17: return Key.F17; case SDL.SDL_Scancode.SDL_SCANCODE_F18: return Key.F18; case SDL.SDL_Scancode.SDL_SCANCODE_F19: return Key.F19; case SDL.SDL_Scancode.SDL_SCANCODE_F20: return Key.F20; case SDL.SDL_Scancode.SDL_SCANCODE_F21: return Key.F21; case SDL.SDL_Scancode.SDL_SCANCODE_F22: return Key.F22; case SDL.SDL_Scancode.SDL_SCANCODE_F23: return Key.F23; case SDL.SDL_Scancode.SDL_SCANCODE_F24: return Key.F24; case SDL.SDL_Scancode.SDL_SCANCODE_MENU: return Key.Menu; case SDL.SDL_Scancode.SDL_SCANCODE_STOP: return Key.Stop; case SDL.SDL_Scancode.SDL_SCANCODE_MUTE: return Key.Mute; case SDL.SDL_Scancode.SDL_SCANCODE_VOLUMEUP: return Key.VolumeUp; case SDL.SDL_Scancode.SDL_SCANCODE_VOLUMEDOWN: return Key.VolumeDown; case SDL.SDL_Scancode.SDL_SCANCODE_CLEAR: return Key.Clear; case SDL.SDL_Scancode.SDL_SCANCODE_DECIMALSEPARATOR: return Key.KeypadDecimal; case SDL.SDL_Scancode.SDL_SCANCODE_LCTRL: return Key.ControlLeft; case SDL.SDL_Scancode.SDL_SCANCODE_LSHIFT: return Key.ShiftLeft; case SDL.SDL_Scancode.SDL_SCANCODE_LALT: return Key.AltLeft; case SDL.SDL_Scancode.SDL_SCANCODE_LGUI: return Key.WinLeft; case SDL.SDL_Scancode.SDL_SCANCODE_RCTRL: return Key.ControlRight; case SDL.SDL_Scancode.SDL_SCANCODE_RSHIFT: return Key.ShiftRight; case SDL.SDL_Scancode.SDL_SCANCODE_RALT: return Key.AltRight; case SDL.SDL_Scancode.SDL_SCANCODE_RGUI: return Key.WinRight; case SDL.SDL_Scancode.SDL_SCANCODE_AUDIONEXT: return Key.TrackNext; case SDL.SDL_Scancode.SDL_SCANCODE_AUDIOPREV: return Key.TrackPrevious; case SDL.SDL_Scancode.SDL_SCANCODE_AUDIOSTOP: return Key.Stop; case SDL.SDL_Scancode.SDL_SCANCODE_AUDIOPLAY: return Key.PlayPause; case SDL.SDL_Scancode.SDL_SCANCODE_AUDIOMUTE: return Key.Mute; case SDL.SDL_Scancode.SDL_SCANCODE_SLEEP: return Key.Sleep; } } public static WindowState ToWindowState(this SDL.SDL_WindowFlags windowFlags) { // NOTE: on macOS, SDL2 does not differentiate between "maximised" and "fullscreen desktop" if (windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP) || windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS) || windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_MAXIMIZED) && RuntimeInfo.OS == RuntimeInfo.Platform.macOS) return WindowState.FullscreenBorderless; if (windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_MINIMIZED)) return WindowState.Minimised; if (windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN)) return WindowState.Fullscreen; if (windowFlags.HasFlagFast(SDL.SDL_WindowFlags.SDL_WINDOW_MAXIMIZED)) return WindowState.Maximised; return WindowState.Normal; } public static SDL.SDL_WindowFlags ToFlags(this WindowState state) { switch (state) { case WindowState.Normal: return 0; case WindowState.Fullscreen: return SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN; case WindowState.Maximised: return RuntimeInfo.OS == RuntimeInfo.Platform.macOS ? SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP : SDL.SDL_WindowFlags.SDL_WINDOW_MAXIMIZED; case WindowState.Minimised: return SDL.SDL_WindowFlags.SDL_WINDOW_MINIMIZED; case WindowState.FullscreenBorderless: return SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP; } return 0; } public static JoystickAxisSource ToJoystickAxisSource(this SDL.SDL_GameControllerAxis axis) { switch (axis) { default: case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_INVALID: return 0; case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTX: return JoystickAxisSource.GamePadLeftStickX; case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_LEFTY: return JoystickAxisSource.GamePadLeftStickY; case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERLEFT: return JoystickAxisSource.GamePadLeftTrigger; case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTX: return JoystickAxisSource.GamePadRightStickX; case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_RIGHTY: return JoystickAxisSource.GamePadRightStickY; case SDL.SDL_GameControllerAxis.SDL_CONTROLLER_AXIS_TRIGGERRIGHT: return JoystickAxisSource.GamePadRightTrigger; } } public static JoystickButton ToJoystickButton(this SDL.SDL_GameControllerButton button) { switch (button) { default: case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_INVALID: return 0; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_A: return JoystickButton.GamePadA; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_B: return JoystickButton.GamePadB; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_X: return JoystickButton.GamePadX; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_Y: return JoystickButton.GamePadY; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_BACK: return JoystickButton.GamePadBack; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_GUIDE: return JoystickButton.GamePadGuide; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_START: return JoystickButton.GamePadStart; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSTICK: return JoystickButton.GamePadLeftStick; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSTICK: return JoystickButton.GamePadRightStick; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_LEFTSHOULDER: return JoystickButton.GamePadLeftShoulder; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: return JoystickButton.GamePadRightShoulder; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_UP: return JoystickButton.GamePadDPadUp; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_DOWN: return JoystickButton.GamePadDPadDown; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_LEFT: return JoystickButton.GamePadDPadLeft; case SDL.SDL_GameControllerButton.SDL_CONTROLLER_BUTTON_DPAD_RIGHT: return JoystickButton.GamePadDPadRight; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using IxMilia.Iges.Entities; namespace IxMilia.Iges { internal class IgesFileWriter { public void Write(IgesFile file, Stream stream) { var writer = new StreamWriter(stream); // prepare entities var startLines = new List<string>(); var globalLines = new List<string>(); var writerState = new IgesEntity.WriterState( new Dictionary<IgesEntity, int>(), new List<string>(), new List<string>(), file.FieldDelimiter, file.RecordDelimiter); startLines.Add(new string(' ', IgesFile.MaxDataLength)); foreach (var entity in file.Entities) { if (!writerState.EntityMap.ContainsKey(entity)) { entity.AddDirectoryAndParameterLines(writerState); } } PopulateGlobalLines(file, globalLines); // write start line WriteLines(writer, IgesSectionType.Start, startLines); // write global lines WriteLines(writer, IgesSectionType.Global, globalLines); // write directory lines WriteLines(writer, IgesSectionType.Directory, writerState.DirectoryLines); // write parameter lines WriteLines(writer, IgesSectionType.Parameter, writerState.ParameterLines); // TODO: ensure space in column 65 and directory pointer in next 7 // write terminator line writer.Write(MakeFileLine(IgesSectionType.Terminate, string.Format("{0}{1,7}{2}{3,7}{4}{5,7}{6}{7,7}", SectionTypeChar(IgesSectionType.Start), startLines.Count, SectionTypeChar(IgesSectionType.Global), globalLines.Count, SectionTypeChar(IgesSectionType.Directory), writerState.DirectoryLines.Count, SectionTypeChar(IgesSectionType.Parameter), writerState.ParameterLines.Count), 1)); writer.Flush(); } private static void PopulateGlobalLines(IgesFile file, List<string> globalLines) { var fields = new object[26]; fields[0] = file.FieldDelimiter.ToString(); fields[1] = file.RecordDelimiter.ToString(); fields[2] = file.Identification; fields[3] = file.FullFileName; fields[4] = file.SystemIdentifier; fields[5] = file.SystemVersion; fields[6] = file.IntegerSize; fields[7] = file.SingleSize; fields[8] = file.DecimalDigits; fields[9] = file.DoubleMagnitude; fields[10] = file.DoublePrecision; fields[11] = file.Identifier; fields[12] = file.ModelSpaceScale; fields[13] = (int)file.ModelUnits; fields[14] = file.CustomModelUnits; fields[15] = file.MaxLineWeightGraduations; fields[16] = file.MaxLineWeight; fields[17] = file.TimeStamp; fields[18] = file.MinimumResolution; fields[19] = file.MaxCoordinateValue; fields[20] = file.Author; fields[21] = file.Organization; fields[22] = (int)file.IgesVersion; fields[23] = (int)file.DraftingStandard; fields[24] = file.ModifiedTime; fields[25] = file.ApplicationProtocol; AddParametersToStringList(fields, globalLines, file.FieldDelimiter, file.RecordDelimiter); } internal static int AddParametersToStringList(object[] parameters, List<string> stringList, char fieldDelimiter, char recordDelimiter, int maxLength = IgesFile.MaxDataLength, string lineSuffix = null, string comment = null) { int suffixLength = lineSuffix == null ? 0 : lineSuffix.Length; var sb = new StringBuilder(); int addedLines = 0; Action addLine = () => { // ensure proper length sb.Append(new string(' ', maxLength - sb.Length - suffixLength)); // add suffix sb.Append(lineSuffix); stringList.Add(sb.ToString()); sb.Clear(); addedLines++; }; for (int i = 0; i < parameters.Length; i++) { var delim = (i == parameters.Length - 1) ? recordDelimiter : fieldDelimiter; var parameter = parameters[i]; var paramString = ParameterToString(parameter) + delim; if (sb.Length + paramString.Length + suffixLength <= maxLength) { // if there's enough space on the current line, do it sb.Append(paramString); } else if (paramString.Length + suffixLength <= maxLength) { // else if it will fit onto a new line, commit the current line and start a new one addLine(); sb.Append(paramString); } else { // otherwise, write as much as we can and wrap the rest while (paramString.Length > 0) { var allowed = maxLength - sb.Length - suffixLength; if (paramString.Length <= allowed) { // write all of it and be done sb.Append(paramString); paramString = string.Empty; } else { // write as much as possible sb.Append(paramString.Substring(0, allowed)); Debug.Assert(sb.Length == maxLength - suffixLength, "This should have been a full line"); // and commit it addLine(); paramString = paramString.Substring(allowed); } } } } // add comment if (comment != null) { // escape things comment = comment.Replace("\\", "\\\\"); comment = comment.Replace("\n", "\\n"); comment = comment.Replace("\r", "\\r"); comment = comment.Replace("\t", "\\t"); comment = comment.Replace("\v", "\\v"); comment = comment.Replace("\f", "\\f"); // write as much of the comment as possible while (comment.Length > 0) { var allowed = maxLength - sb.Length - suffixLength; if (comment.Length <= allowed) { // write the whole thing sb.Append(comment); comment = string.Empty; } else { // write as much as possible sb.Append(comment.Substring(0, allowed)); addLine(); comment = comment.Substring(allowed); } } } // commit any remaining text if (sb.Length > 0) addLine(); return addedLines; } private static string ParameterToString(object parameter) { if (parameter == null) return string.Empty; else if (parameter.GetType() == typeof(int)) return ParameterToString((int)parameter); else if (parameter.GetType() == typeof(double)) return ParameterToString((double)parameter); else if (parameter.GetType() == typeof(string)) return ParameterToString((string)parameter); else if (parameter.GetType() == typeof(DateTime)) return ParameterToString((DateTime)parameter); else if (parameter.GetType() == typeof(bool)) return ParameterToString((bool)parameter); else { Debug.Assert(false, "Unsupported parameter type: " + parameter.GetType().ToString()); return string.Empty; } } private static string ParameterToString(int parameter) { return parameter.ToString(CultureInfo.InvariantCulture); } private static string ParameterToString(double parameter) { var str = parameter.ToString(CultureInfo.InvariantCulture); if (!(str.Contains(".") || str.Contains("e") || str.Contains("E") || str.Contains("d") || str.Contains("D"))) str += '.'; // add trailing decimal point return str; } private static string ParameterToString(string parameter) { if (string.IsNullOrEmpty(parameter)) return string.Empty; else return string.Format("{0}H{1}", parameter.Length, parameter); } internal static string ParameterToString(DateTime parameter) { return ParameterToString(parameter.ToString("yyyyMMdd.HHmmss")); } private static string ParameterToString(bool parameter) { return parameter ? "1" : string.Empty; } private static void WriteLines(StreamWriter writer, IgesSectionType sectionType, List<string> lines) { for (int i = 0; i < lines.Count; i++) { var line = MakeFileLine(sectionType, lines[i], i + 1); writer.Write(line); } } private static string MakeFileLine(IgesSectionType sectionType, string line, int lineNumber) { line = line ?? string.Empty; if (line.Length > 72) throw new IgesException("Line is too long"); var fullLine = string.Format("{0,-72}{1}{2,7}\n", line, SectionTypeChar(sectionType), lineNumber); return fullLine; } private static char SectionTypeChar(IgesSectionType type) { switch (type) { case IgesSectionType.Start: return 'S'; case IgesSectionType.Global: return 'G'; case IgesSectionType.Directory: return 'D'; case IgesSectionType.Parameter: return 'P'; case IgesSectionType.Terminate: return 'T'; default: throw new IgesException("Unexpected section type " + type); } } } }
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Mozu.Api.Contracts.Fulfillment { /// <summary> /// /// </summary> [DataContract] public class EntityModelOfShipment { /// <summary> /// Gets or Sets Links /// </summary> [DataMember(Name="_links", EmitDefaultValue=false)] [JsonProperty(PropertyName = "_links")] public Links Links { get; set; } /// <summary> /// Gets or Sets AcceptedDate /// </summary> [DataMember(Name="acceptedDate", EmitDefaultValue=false)] [JsonProperty(PropertyName = "acceptedDate")] public DateTime? AcceptedDate { get; set; } /// <summary> /// Gets or Sets Attributes /// </summary> [DataMember(Name="attributes", EmitDefaultValue=false)] [JsonProperty(PropertyName = "attributes")] public Dictionary<string, Object> Attributes { get; set; } /// <summary> /// Gets or Sets AuditInfo /// </summary> [DataMember(Name="auditInfo", EmitDefaultValue=false)] [JsonProperty(PropertyName = "auditInfo")] public AuditInfo AuditInfo { get; set; } /// <summary> /// Gets or Sets CanceledItems /// </summary> [DataMember(Name="canceledItems", EmitDefaultValue=false)] [JsonProperty(PropertyName = "canceledItems")] public List<CanceledItem> CanceledItems { get; set; } /// <summary> /// Gets or Sets ChangeMessages /// </summary> [DataMember(Name="changeMessages", EmitDefaultValue=false)] [JsonProperty(PropertyName = "changeMessages")] public List<ChangeMessage> ChangeMessages { get; set; } /// <summary> /// Gets or Sets ChildShipmentNumbers /// </summary> [DataMember(Name="childShipmentNumbers", EmitDefaultValue=false)] [JsonProperty(PropertyName = "childShipmentNumbers")] public List<int?> ChildShipmentNumbers { get; set; } /// <summary> /// Gets or Sets CurrencyCode /// </summary> [DataMember(Name="currencyCode", EmitDefaultValue=false)] [JsonProperty(PropertyName = "currencyCode")] public string CurrencyCode { get; set; } /// <summary> /// Gets or Sets CustomerAccountId /// </summary> [DataMember(Name="customerAccountId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "customerAccountId")] public int? CustomerAccountId { get; set; } /// <summary> /// Gets or Sets CustomerAddressId /// </summary> [DataMember(Name="customerAddressId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "customerAddressId")] public int? CustomerAddressId { get; set; } /// <summary> /// Gets or Sets CustomerTaxId /// </summary> [DataMember(Name="customerTaxId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "customerTaxId")] public string CustomerTaxId { get; set; } /// <summary> /// Gets or Sets Data /// </summary> [DataMember(Name="data", EmitDefaultValue=false)] [JsonProperty(PropertyName = "data")] public Dictionary<string, Object> Data { get; set; } /// <summary> /// Gets or Sets Destination /// </summary> [DataMember(Name="destination", EmitDefaultValue=false)] [JsonProperty(PropertyName = "destination")] public Destination Destination { get; set; } /// <summary> /// Gets or Sets DutyAdjustment /// </summary> [DataMember(Name="dutyAdjustment", EmitDefaultValue=false)] [JsonProperty(PropertyName = "dutyAdjustment")] public Nullable<decimal> DutyAdjustment { get; set; } /// <summary> /// Gets or Sets DutyTotal /// </summary> [DataMember(Name="dutyTotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "dutyTotal")] public Nullable<decimal> DutyTotal { get; set; } /// <summary> /// Gets or Sets Email /// </summary> [DataMember(Name="email", EmitDefaultValue=false)] [JsonProperty(PropertyName = "email")] public string Email { get; set; } /// <summary> /// Gets or Sets ExternalOrderId /// </summary> [DataMember(Name="externalOrderId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "externalOrderId")] public string ExternalOrderId { get; set; } /// <summary> /// Gets or Sets FulfillmentDate /// </summary> [DataMember(Name="fulfillmentDate", EmitDefaultValue=false)] [JsonProperty(PropertyName = "fulfillmentDate")] public DateTime? FulfillmentDate { get; set; } /// <summary> /// Gets or Sets FulfillmentLocationCode /// </summary> [DataMember(Name="fulfillmentLocationCode", EmitDefaultValue=false)] [JsonProperty(PropertyName = "fulfillmentLocationCode")] public string FulfillmentLocationCode { get; set; } /// <summary> /// Gets or Sets FulfillmentStatus /// </summary> [DataMember(Name="fulfillmentStatus", EmitDefaultValue=false)] [JsonProperty(PropertyName = "fulfillmentStatus")] public string FulfillmentStatus { get; set; } /// <summary> /// Gets or Sets HandlingAdjustment /// </summary> [DataMember(Name="handlingAdjustment", EmitDefaultValue=false)] [JsonProperty(PropertyName = "handlingAdjustment")] public Nullable<decimal> HandlingAdjustment { get; set; } /// <summary> /// Gets or Sets HandlingSubtotal /// </summary> [DataMember(Name="handlingSubtotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "handlingSubtotal")] public Nullable<decimal> HandlingSubtotal { get; set; } /// <summary> /// Gets or Sets HandlingTaxAdjustment /// </summary> [DataMember(Name="handlingTaxAdjustment", EmitDefaultValue=false)] [JsonProperty(PropertyName = "handlingTaxAdjustment")] public Nullable<decimal> HandlingTaxAdjustment { get; set; } /// <summary> /// Gets or Sets HandlingTaxTotal /// </summary> [DataMember(Name="handlingTaxTotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "handlingTaxTotal")] public Nullable<decimal> HandlingTaxTotal { get; set; } /// <summary> /// Gets or Sets HandlingTotal /// </summary> [DataMember(Name="handlingTotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "handlingTotal")] public Nullable<decimal> HandlingTotal { get; set; } /// <summary> /// Gets or Sets IsExpress /// </summary> [DataMember(Name="isExpress", EmitDefaultValue=false)] [JsonProperty(PropertyName = "isExpress")] public bool? IsExpress { get; set; } /// <summary> /// Gets or Sets Items /// </summary> [DataMember(Name="items", EmitDefaultValue=false)] [JsonProperty(PropertyName = "items")] public List<Item> Items { get; set; } /// <summary> /// Gets or Sets LineItemSubtotal /// </summary> [DataMember(Name="lineItemSubtotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lineItemSubtotal")] public Nullable<decimal> LineItemSubtotal { get; set; } /// <summary> /// Gets or Sets LineItemTaxAdjustment /// </summary> [DataMember(Name="lineItemTaxAdjustment", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lineItemTaxAdjustment")] public Nullable<decimal> LineItemTaxAdjustment { get; set; } /// <summary> /// Gets or Sets LineItemTaxTotal /// </summary> [DataMember(Name="lineItemTaxTotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lineItemTaxTotal")] public Nullable<decimal> LineItemTaxTotal { get; set; } /// <summary> /// Gets or Sets LineItemTotal /// </summary> [DataMember(Name="lineItemTotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "lineItemTotal")] public Nullable<decimal> LineItemTotal { get; set; } /// <summary> /// Gets or Sets OrderId /// </summary> [DataMember(Name="orderId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "orderId")] public string OrderId { get; set; } /// <summary> /// Gets or Sets OrderNumber /// </summary> [DataMember(Name="orderNumber", EmitDefaultValue=false)] [JsonProperty(PropertyName = "orderNumber")] public int? OrderNumber { get; set; } /// <summary> /// Gets or Sets OrderSubmitDate /// </summary> [DataMember(Name="orderSubmitDate", EmitDefaultValue=false)] [JsonProperty(PropertyName = "orderSubmitDate")] public DateTime? OrderSubmitDate { get; set; } /// <summary> /// Gets or Sets OriginalShipmentNumber /// </summary> [DataMember(Name="originalShipmentNumber", EmitDefaultValue=false)] [JsonProperty(PropertyName = "originalShipmentNumber")] public int? OriginalShipmentNumber { get; set; } /// <summary> /// Gets or Sets Packages /// </summary> [DataMember(Name="packages", EmitDefaultValue=false)] [JsonProperty(PropertyName = "packages")] public List<Package> Packages { get; set; } /// <summary> /// Gets or Sets ParentShipmentNumber /// </summary> [DataMember(Name="parentShipmentNumber", EmitDefaultValue=false)] [JsonProperty(PropertyName = "parentShipmentNumber")] public int? ParentShipmentNumber { get; set; } /// <summary> /// Gets or Sets PickStatus /// </summary> [DataMember(Name="pickStatus", EmitDefaultValue=false)] [JsonProperty(PropertyName = "pickStatus")] public string PickStatus { get; set; } /// <summary> /// Gets or Sets PickType /// </summary> [DataMember(Name="pickType", EmitDefaultValue=false)] [JsonProperty(PropertyName = "pickType")] public string PickType { get; set; } /// <summary> /// Gets or Sets PickWaveNumber /// </summary> [DataMember(Name="pickWaveNumber", EmitDefaultValue=false)] [JsonProperty(PropertyName = "pickWaveNumber")] public int? PickWaveNumber { get; set; } /// <summary> /// Gets or Sets ReadyForPickup /// </summary> [DataMember(Name="readyForPickup", EmitDefaultValue=false)] [JsonProperty(PropertyName = "readyForPickup")] public bool? ReadyForPickup { get; set; } /// <summary> /// Gets or Sets ReadyForPickupDate /// </summary> [DataMember(Name="readyForPickupDate", EmitDefaultValue=false)] [JsonProperty(PropertyName = "readyForPickupDate")] public DateTime? ReadyForPickupDate { get; set; } /// <summary> /// Gets or Sets ReassignedItems /// </summary> [DataMember(Name="reassignedItems", EmitDefaultValue=false)] [JsonProperty(PropertyName = "reassignedItems")] public List<ReassignItem> ReassignedItems { get; set; } /// <summary> /// Gets or Sets ReceivedDate /// </summary> [DataMember(Name="receivedDate", EmitDefaultValue=false)] [JsonProperty(PropertyName = "receivedDate")] public DateTime? ReceivedDate { get; set; } /// <summary> /// Gets or Sets RejectedItems /// </summary> [DataMember(Name="rejectedItems", EmitDefaultValue=false)] [JsonProperty(PropertyName = "rejectedItems")] public List<RejectedItem> RejectedItems { get; set; } /// <summary> /// Gets or Sets ShipmentAdjustment /// </summary> [DataMember(Name="shipmentAdjustment", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shipmentAdjustment")] public Nullable<decimal> ShipmentAdjustment { get; set; } /// <summary> /// Gets or Sets ShipmentNumber /// </summary> [DataMember(Name="shipmentNumber", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shipmentNumber")] public int? ShipmentNumber { get; set; } /// <summary> /// Gets or Sets ShipmentStatus /// </summary> [DataMember(Name="shipmentStatus", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shipmentStatus")] public string ShipmentStatus { get; set; } /// <summary> /// Gets or Sets ShipmentStatusReason /// </summary> [DataMember(Name="shipmentStatusReason", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shipmentStatusReason")] public ShipmentStatusReason ShipmentStatusReason { get; set; } /// <summary> /// Gets or Sets ShipmentType /// </summary> [DataMember(Name="shipmentType", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shipmentType")] public string ShipmentType { get; set; } /// <summary> /// Gets or Sets ShippingAdjustment /// </summary> [DataMember(Name="shippingAdjustment", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shippingAdjustment")] public Nullable<decimal> ShippingAdjustment { get; set; } /// <summary> /// Gets or Sets ShippingMethodCode /// </summary> [DataMember(Name="shippingMethodCode", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shippingMethodCode")] public string ShippingMethodCode { get; set; } /// <summary> /// Gets or Sets ShippingMethodName /// </summary> [DataMember(Name="shippingMethodName", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shippingMethodName")] public string ShippingMethodName { get; set; } /// <summary> /// Gets or Sets ShippingSubtotal /// </summary> [DataMember(Name="shippingSubtotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shippingSubtotal")] public Nullable<decimal> ShippingSubtotal { get; set; } /// <summary> /// Gets or Sets ShippingTaxAdjustment /// </summary> [DataMember(Name="shippingTaxAdjustment", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shippingTaxAdjustment")] public Nullable<decimal> ShippingTaxAdjustment { get; set; } /// <summary> /// Gets or Sets ShippingTaxTotal /// </summary> [DataMember(Name="shippingTaxTotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shippingTaxTotal")] public Nullable<decimal> ShippingTaxTotal { get; set; } /// <summary> /// Gets or Sets ShippingTotal /// </summary> [DataMember(Name="shippingTotal", EmitDefaultValue=false)] [JsonProperty(PropertyName = "shippingTotal")] public Nullable<decimal> ShippingTotal { get; set; } /// <summary> /// Gets or Sets SiteId /// </summary> [DataMember(Name="siteId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "siteId")] public int? SiteId { get; set; } /// <summary> /// Gets or Sets TaxData /// </summary> [DataMember(Name="taxData", EmitDefaultValue=false)] [JsonProperty(PropertyName = "taxData")] public Object TaxData { get; set; } /// <summary> /// Gets or Sets TenantId /// </summary> [DataMember(Name="tenantId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "tenantId")] public int? TenantId { get; set; } /// <summary> /// Gets or Sets Total /// </summary> [DataMember(Name="total", EmitDefaultValue=false)] [JsonProperty(PropertyName = "total")] public Nullable<decimal> Total { get; set; } /// <summary> /// Gets or Sets TransferShipmentNumbers /// </summary> [DataMember(Name="transferShipmentNumbers", EmitDefaultValue=false)] [JsonProperty(PropertyName = "transferShipmentNumbers")] public List<int?> TransferShipmentNumbers { get; set; } /// <summary> /// Gets or Sets TransitTime /// </summary> [DataMember(Name="transitTime", EmitDefaultValue=false)] [JsonProperty(PropertyName = "transitTime")] public string TransitTime { get; set; } /// <summary> /// Gets or Sets UserId /// </summary> [DataMember(Name="userId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "userId")] public string UserId { get; set; } /// <summary> /// Gets or Sets WorkflowProcessContainerId /// </summary> [DataMember(Name="workflowProcessContainerId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "workflowProcessContainerId")] public string WorkflowProcessContainerId { get; set; } /// <summary> /// Gets or Sets WorkflowProcessId /// </summary> [DataMember(Name="workflowProcessId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "workflowProcessId")] public string WorkflowProcessId { get; set; } /// <summary> /// Gets or Sets WorkflowState /// </summary> [DataMember(Name="workflowState", EmitDefaultValue=false)] [JsonProperty(PropertyName = "workflowState")] public WorkflowState WorkflowState { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class EntityModelOfShipment {\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append(" AcceptedDate: ").Append(AcceptedDate).Append("\n"); sb.Append(" Attributes: ").Append(Attributes).Append("\n"); sb.Append(" AuditInfo: ").Append(AuditInfo).Append("\n"); sb.Append(" CanceledItems: ").Append(CanceledItems).Append("\n"); sb.Append(" ChangeMessages: ").Append(ChangeMessages).Append("\n"); sb.Append(" ChildShipmentNumbers: ").Append(ChildShipmentNumbers).Append("\n"); sb.Append(" CurrencyCode: ").Append(CurrencyCode).Append("\n"); sb.Append(" CustomerAccountId: ").Append(CustomerAccountId).Append("\n"); sb.Append(" CustomerAddressId: ").Append(CustomerAddressId).Append("\n"); sb.Append(" CustomerTaxId: ").Append(CustomerTaxId).Append("\n"); sb.Append(" Data: ").Append(Data).Append("\n"); sb.Append(" Destination: ").Append(Destination).Append("\n"); sb.Append(" DutyAdjustment: ").Append(DutyAdjustment).Append("\n"); sb.Append(" DutyTotal: ").Append(DutyTotal).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" ExternalOrderId: ").Append(ExternalOrderId).Append("\n"); sb.Append(" FulfillmentDate: ").Append(FulfillmentDate).Append("\n"); sb.Append(" FulfillmentLocationCode: ").Append(FulfillmentLocationCode).Append("\n"); sb.Append(" FulfillmentStatus: ").Append(FulfillmentStatus).Append("\n"); sb.Append(" HandlingAdjustment: ").Append(HandlingAdjustment).Append("\n"); sb.Append(" HandlingSubtotal: ").Append(HandlingSubtotal).Append("\n"); sb.Append(" HandlingTaxAdjustment: ").Append(HandlingTaxAdjustment).Append("\n"); sb.Append(" HandlingTaxTotal: ").Append(HandlingTaxTotal).Append("\n"); sb.Append(" HandlingTotal: ").Append(HandlingTotal).Append("\n"); sb.Append(" IsExpress: ").Append(IsExpress).Append("\n"); sb.Append(" Items: ").Append(Items).Append("\n"); sb.Append(" LineItemSubtotal: ").Append(LineItemSubtotal).Append("\n"); sb.Append(" LineItemTaxAdjustment: ").Append(LineItemTaxAdjustment).Append("\n"); sb.Append(" LineItemTaxTotal: ").Append(LineItemTaxTotal).Append("\n"); sb.Append(" LineItemTotal: ").Append(LineItemTotal).Append("\n"); sb.Append(" OrderId: ").Append(OrderId).Append("\n"); sb.Append(" OrderNumber: ").Append(OrderNumber).Append("\n"); sb.Append(" OrderSubmitDate: ").Append(OrderSubmitDate).Append("\n"); sb.Append(" OriginalShipmentNumber: ").Append(OriginalShipmentNumber).Append("\n"); sb.Append(" Packages: ").Append(Packages).Append("\n"); sb.Append(" ParentShipmentNumber: ").Append(ParentShipmentNumber).Append("\n"); sb.Append(" PickStatus: ").Append(PickStatus).Append("\n"); sb.Append(" PickType: ").Append(PickType).Append("\n"); sb.Append(" PickWaveNumber: ").Append(PickWaveNumber).Append("\n"); sb.Append(" ReadyForPickup: ").Append(ReadyForPickup).Append("\n"); sb.Append(" ReadyForPickupDate: ").Append(ReadyForPickupDate).Append("\n"); sb.Append(" ReassignedItems: ").Append(ReassignedItems).Append("\n"); sb.Append(" ReceivedDate: ").Append(ReceivedDate).Append("\n"); sb.Append(" RejectedItems: ").Append(RejectedItems).Append("\n"); sb.Append(" ShipmentAdjustment: ").Append(ShipmentAdjustment).Append("\n"); sb.Append(" ShipmentNumber: ").Append(ShipmentNumber).Append("\n"); sb.Append(" ShipmentStatus: ").Append(ShipmentStatus).Append("\n"); sb.Append(" ShipmentStatusReason: ").Append(ShipmentStatusReason).Append("\n"); sb.Append(" ShipmentType: ").Append(ShipmentType).Append("\n"); sb.Append(" ShippingAdjustment: ").Append(ShippingAdjustment).Append("\n"); sb.Append(" ShippingMethodCode: ").Append(ShippingMethodCode).Append("\n"); sb.Append(" ShippingMethodName: ").Append(ShippingMethodName).Append("\n"); sb.Append(" ShippingSubtotal: ").Append(ShippingSubtotal).Append("\n"); sb.Append(" ShippingTaxAdjustment: ").Append(ShippingTaxAdjustment).Append("\n"); sb.Append(" ShippingTaxTotal: ").Append(ShippingTaxTotal).Append("\n"); sb.Append(" ShippingTotal: ").Append(ShippingTotal).Append("\n"); sb.Append(" SiteId: ").Append(SiteId).Append("\n"); sb.Append(" TaxData: ").Append(TaxData).Append("\n"); sb.Append(" TenantId: ").Append(TenantId).Append("\n"); sb.Append(" Total: ").Append(Total).Append("\n"); sb.Append(" TransferShipmentNumbers: ").Append(TransferShipmentNumbers).Append("\n"); sb.Append(" TransitTime: ").Append(TransitTime).Append("\n"); sb.Append(" UserId: ").Append(UserId).Append("\n"); sb.Append(" WorkflowProcessContainerId: ").Append(WorkflowProcessContainerId).Append("\n"); sb.Append(" WorkflowProcessId: ").Append(WorkflowProcessId).Append("\n"); sb.Append(" WorkflowState: ").Append(WorkflowState).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
/* Copyright 2006-2017 Cryptany, 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.Text; using System.Reflection; using Cryptany.Core.DPO.MetaObjects.Attributes; namespace Cryptany.Core.DPO.MetaObjects { [Serializable] public class PropertyDescription { private PropertyInfo _property = null; private Attribute[] _attrs = null; private bool _isInternal = false; private bool _isRelation = false; private bool _isOneToOneRelation = false; private bool _isOneToManyRelation = false; private bool _isManyToManyRelation = false; private bool _isReadOnly = false; private bool _isNonPersistent = false; private bool _isId = false; private RelationAttribute _relationAttribute; private ObjectDescription _reflectedObject; private Type _relatedType; private bool _isObligatory = false; private string _caption; private object _propertyDefaultValue = null; private class DefaultValue<T> { public T Value = default(T); } internal PropertyDescription(ObjectDescription objectDescription, PropertyInfo property, Configuration.EntityPropertyConfiguration epc) { _property = property; CreateAttributeArray(); if ( epc != null && epc.Attributes.Count > 0 ) { } else foreach ( Attribute attr in _attrs ) { if ( attr is InternalAttribute ) _isInternal = true; if ( attr is RelationAttribute ) { _isRelation = true; _relationAttribute = (RelationAttribute)attr; if ( (attr as RelationAttribute).RelationType == RelationType.OneToOne ) _isOneToOneRelation = true; if ( (attr as RelationAttribute).RelationType == RelationType.OneToMany ) _isOneToManyRelation = true; if ( (attr as RelationAttribute).RelationType == RelationType.ManyToMany ) _isManyToManyRelation = true; _relatedType = _relationAttribute.RelatedType; } if ( attr is ReadOnlyFieldAttribute ) _isReadOnly = true; if ( attr is NonPersistentAttribute ) _isNonPersistent = true; if ( attr is ObligatoryFieldAttribute ) _isObligatory = true; if ( attr is CaptionAttribute ) _caption = (attr as CaptionAttribute).Caption; } if ( _property.GetCustomAttributes(typeof(IdFieldAttribute), true) != null && _property.GetCustomAttributes(typeof(IdFieldAttribute), true).Length > 0 ) _isId = true; else _isId = false; foreach ( Attribute attr in objectDescription.ObjectType.GetCustomAttributes(typeof(IdFieldNameAttribute), true) ) _isId = (attr as IdFieldNameAttribute).Name == Name; _reflectedObject = objectDescription; if ( IsReadOnly ) _isObligatory = true; if ( string.IsNullOrEmpty(_caption) ) _caption = Name; _propertyDefaultValue = GetDefaultValue(PropertyType); } public PropertyInfo Property { get { return _property; } } public string Name { get { return _property.Name; } } public Type PropertyType { get { return _property.PropertyType; } } public Attribute[] Attributes { get { return _attrs; } } public bool IsInternal { get { return _isInternal; } } public bool IsRelation { get { return _isRelation; } } public bool IsOneToOneRelation { get { return _isOneToOneRelation; } } public bool IsOneToManyRelation { get { return _isOneToManyRelation; } } public bool IsManyToManyRelation { get { return _isManyToManyRelation; } } public bool IsReadOnly { get { return _isReadOnly; } } public bool IsNonPersistent { get { return _isNonPersistent; } } public bool IsId { get { return _isId; } } public bool IsMapped { get { return !IsInternal && !IsNonPersistent && !IsManyToManyRelation && !IsOneToManyRelation; } } public Type RelatedType { get { return _relatedType; } } public RelationAttribute RelationAttribute { get { return _relationAttribute; } } public ObjectDescription ReflectedObject { get { return _reflectedObject; } } public bool IsObligatory { get { return _isObligatory; } } public string Caption { get { return _caption; } } public object PropertyDefaultValue { get { return _propertyDefaultValue; } } private void CreateAttributeArray() { _attrs = new Attribute[_property.GetCustomAttributes(true).Length]; for ( int i = 0; i < _attrs.Length; i++ ) _attrs.SetValue(_property.GetCustomAttributes(true)[i], i); } public Attribute GetAttribute(Type t) { foreach ( object attr in _attrs ) if ( attr.GetType() == t ) return attr as Attribute; return null; } public T GetAttribute<T>() { foreach ( object attr in _attrs ) if ( attr.GetType() == typeof(T) ) return (T)attr; return default(T); } public object GetValue(object o) { return o == null ? null : _property.GetValue(o, null); } public T GetValue<T>(object o) { return (T)_property.GetValue(o, null); } public object GetValue(object o, params object[] index) { return _property.GetValue(o, index); } public T GetValue<T>(object o, params object[] index) { return (T)_property.GetValue(o, index); } public void SetValue(object o, object value) { if ( value == DBNull.Value ) { if ( !_property.PropertyType.IsValueType ) value = null; else value = GetDefaultValue(_property.PropertyType); } //try //{ _property.SetValue(o, value, null); //} //catch //{ //} } public void SetValue(object o, object value, params object[] index) { _property.SetValue(o, value, index); } public List<EntityBase> GetAllRelatedValues(PersistentStorage ps) { return ps.GetEntities(this.RelatedType); } private object GetDefaultValue(Type propertyType) { Type t = typeof (DefaultValue<>); t = t.MakeGenericType(propertyType); object defaultValue = t.GetConstructor(new Type[0]).Invoke(null); return defaultValue.GetType().GetField("Value").GetValue(defaultValue); } } }
// 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 Microsoft.DotNet.Cli.Utils; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace Microsoft.DotNet.Tools.Test.Utilities { public class TestCommand { private string _baseDirectory; private List<string> _cliGeneratedEnvironmentVariables = new List<string> { "MSBuildSDKsPath" }; protected string _command; public Process CurrentProcess { get; private set; } public Dictionary<string, string> Environment { get; } = new Dictionary<string, string>(); public event DataReceivedEventHandler ErrorDataReceived; public event DataReceivedEventHandler OutputDataReceived; public string WorkingDirectory { get; set; } public TestCommand(string command) { _command = command; _baseDirectory = GetBaseDirectory(); } public void KillTree() { if (CurrentProcess == null) { throw new InvalidOperationException("No process is available to be killed"); } CurrentProcess.KillTree(); } public virtual CommandResult Execute(string args = "") { return Task.Run(async () => await ExecuteAsync(args)).Result; } public async virtual Task<CommandResult> ExecuteAsync(string args = "") { var resolvedCommand = _command; ResolveCommand(ref resolvedCommand, ref args); Console.WriteLine($"Executing - {resolvedCommand} {args} - {WorkingDirectoryInfo()}"); return await ExecuteAsyncInternal(resolvedCommand, args); } public virtual CommandResult ExecuteWithCapturedOutput(string args = "") { var resolvedCommand = _command; ResolveCommand(ref resolvedCommand, ref args); var commandPath = Env.GetCommandPath(resolvedCommand, ".exe", ".cmd", "") ?? Env.GetCommandPathFromRootPath(_baseDirectory, resolvedCommand, ".exe", ".cmd", ""); Console.WriteLine($"Executing (Captured Output) - {commandPath} {args} - {WorkingDirectoryInfo()}"); return Task.Run(async () => await ExecuteAsyncInternal(resolvedCommand, args)).Result; } private async Task<CommandResult> ExecuteAsyncInternal(string executable, string args) { var stdOut = new List<String>(); var stdErr = new List<String>(); CurrentProcess = CreateProcess(executable, args); CurrentProcess.ErrorDataReceived += (s, e) => { stdErr.Add(e.Data); var handler = ErrorDataReceived; if (handler != null) { handler(s, e); } }; CurrentProcess.OutputDataReceived += (s, e) => { stdOut.Add(e.Data); var handler = OutputDataReceived; if (handler != null) { handler(s, e); } }; var completionTask = CurrentProcess.StartAndWaitForExitAsync(); CurrentProcess.BeginOutputReadLine(); CurrentProcess.BeginErrorReadLine(); await completionTask; CurrentProcess.WaitForExit(); RemoveNullTerminator(stdOut); RemoveNullTerminator(stdErr); return new CommandResult( CurrentProcess.StartInfo, CurrentProcess.ExitCode, String.Join(System.Environment.NewLine, stdOut), String.Join(System.Environment.NewLine, stdErr)); } private Process CreateProcess(string executable, string args) { var psi = new ProcessStartInfo { FileName = executable, Arguments = args, RedirectStandardError = true, RedirectStandardOutput = true, RedirectStandardInput = true, UseShellExecute = false }; RemoveCliGeneratedEnvironmentVariablesFrom(psi); AddEnvironmentVariablesTo(psi); AddWorkingDirectoryTo(psi); var process = new Process { StartInfo = psi }; process.EnableRaisingEvents = true; return process; } private string WorkingDirectoryInfo() { if (WorkingDirectory == null) { return ""; } return $" in pwd {WorkingDirectory}"; } private void RemoveNullTerminator(List<string> strings) { var count = strings.Count; if (count < 1) { return; } if (strings[count - 1] == null) { strings.RemoveAt(count - 1); } } private string GetBaseDirectory() { #if NET451 return AppDomain.CurrentDomain.BaseDirectory; #else return AppContext.BaseDirectory; #endif } private void ResolveCommand(ref string executable, ref string args) { if (executable.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { var newArgs = ArgumentEscaper.EscapeSingleArg(executable); if (!string.IsNullOrEmpty(args)) { newArgs += " " + args; } args = newArgs; executable = "dotnet"; } if (!Path.IsPathRooted(executable)) { executable = Env.GetCommandPath(executable) ?? Env.GetCommandPathFromRootPath(_baseDirectory, executable); } } private void RemoveCliGeneratedEnvironmentVariablesFrom(ProcessStartInfo psi) { foreach (var name in _cliGeneratedEnvironmentVariables) { #if NET451 psi.EnvironmentVariables.Remove(name); #else psi.Environment.Remove(name); #endif } } private void AddEnvironmentVariablesTo(ProcessStartInfo psi) { foreach (var item in Environment) { #if NET451 psi.EnvironmentVariables[item.Key] = item.Value; #else psi.Environment[item.Key] = item.Value; #endif } } private void AddWorkingDirectoryTo(ProcessStartInfo psi) { if (!string.IsNullOrWhiteSpace(WorkingDirectory)) { psi.WorkingDirectory = WorkingDirectory; } } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.IO; using System.Text; using System.Diagnostics; using System.Collections.Generic; using Autodesk.Revit; using Autodesk.Revit.DB.Events; using Autodesk.Revit.DB; namespace Revit.SDK.Samples.AutoStamp.CS { /// <summary> /// This class consists of two handler methods which will be subscribed to ViewPrinting and ViewPrinted events separately, /// The pre-event handler will create TextNote element when event is raised, and the post-event handler will delete it. /// Meanwhile, these two handler methods will be used to dump designed information to log file. /// /// It contains other methods which are used to dump related information(like events arguments and sequences) /// to log file PrintEventsLog.txt. /// </summary> public sealed class EventsReactor { #region Class Member Variables /// <summary> /// This listener is used to monitor the events raising sequences and arguments of events. /// it will be bound to log file PrintEventsLog.txt, it will be added to Trace.Listeners. /// /// This log file will only contain information of event raising sequence, event arguments, etc. /// This file can be used to check if events work well in different platforms, for example: /// By this sample, if user printed something, Revit journal will record all operation of users, /// meanwhile PrintEventsLog.txt will be generated. If user run the journal in other machine, user will get another /// PrintEventsLog.txt, by comparing the two files user can figure out easily if the two prints work equally. /// </summary> private TextWriterTraceListener m_eventsLog; /// <summary> /// Current assembly path /// </summary> String m_assemblyPath; /// <summary> /// Reserves the id of TextNote created by ViewPrinting and delete it in ViewPrinted event. /// </summary> Autodesk.Revit.DB.ElementId m_newTextNoteId; #endregion #region Class Constructor Method /// <summary> /// Constructor method, it will only initialize m_assemblyPath. /// Notice that this method won't open log files at this time. /// </summary> public EventsReactor() { // Get assembly path m_assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); } /// <summary> /// Close log files now /// </summary> public void CloseLogFiles() { // Flush trace and close it Trace.Flush(); Trace.Close(); // // Close listeners Trace.Flush(); if (null != m_eventsLog) { Trace.Listeners.Remove(m_eventsLog); m_eventsLog.Flush(); m_eventsLog.Close(); } } #endregion #region Class Handler Methods /// <summary> /// Handler method for ViewPrinting event. /// This method will dump EventArgument information of event firstly and then create TextNote element for this view. /// View print will be cancelled if TextNote creation failed. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments of ViewPrinting event.</param> public void AppViewPrinting(object sender, Autodesk.Revit.DB.Events.ViewPrintingEventArgs e) { // Setup log file if it still is empty if (null == m_eventsLog) { SetupLogFiles(); } // // header information Trace.WriteLine(System.Environment.NewLine + "View Print Start: ------------------------"); // // Dump the events arguments DumpEventArguments(e); // // Create TextNote for current view, cancel the event if TextNote creation failed bool faileOccur = false; // Reserves whether failure occurred when create TextNote try { String strText = String.Format("Printer Name: {0}{1}User Name: {2}", e.Document.PrintManager.PrinterName, System.Environment.NewLine, System.Environment.UserName); // // Use non-debug compile symbol to write constant text note #if !(Debug || DEBUG) strText = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; #endif //now event framework will not provide transaction, user need start by self(2009/11/18) Transaction eventTransaction = new Transaction(e.Document, "External Tool"); eventTransaction.Start(); TextNote newTextNote = e.Document.Create.NewTextNote( e.View, // View new Autodesk.Revit.DB.XYZ (0, 0, 0), // origin new Autodesk.Revit.DB.XYZ (1.0, 0.0, 0.0), // baseVec new Autodesk.Revit.DB.XYZ (0.0, 1.0, 0.0), // upVec 1.0, // lineWidth Autodesk.Revit.DB.TextAlignFlags.TEF_ALIGN_CENTER, // textAlign strText ); eventTransaction.Commit(); // // Check to see whether TextNote creation succeeded if(null != newTextNote) { Trace.WriteLine("Create TextNote element successfully..."); m_newTextNoteId = new ElementId(newTextNote.Id.IntegerValue); } else { faileOccur = true; } } catch (System.Exception ex) { faileOccur = true; Trace.WriteLine("Exception occurred when creating TextNote, print will be cancelled, ex: " + ex.Message); } finally { // Cancel the TextNote creation when failure occurred, meantime the event is cancellable if(faileOccur && e.Cancellable) { e.Cancel(); } } } /// <summary> /// Handler method for ViewPrinted event. /// This handler will dump information of printed view firstly and then delete the TextNote created in pre-event handler. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event arguments of ViewPrinted event.</param> public void AppViewPrinted(object sender, Autodesk.Revit.DB.Events.ViewPrintedEventArgs e) { // header information Trace.WriteLine(System.Environment.NewLine + "View Print End: -------"); // // Dump the events arguments DumpEventArguments(e); // // Delete the TextNote element created in ViewPrinting only when view print process succeeded or failed. // We don't care about the delete when event status is Cancelled because no TextNote element // will be created when cancelling occurred. if(RevitAPIEventStatus.Cancelled != e.Status) { //now event framework will not provide transaction, user need start by self(2009/11/18) Transaction eventTransaction = new Transaction(e.Document, "External Tool"); eventTransaction.Start(); e.Document.Delete(m_newTextNoteId); eventTransaction.Commit(); Trace.WriteLine("Succeeded to delete the created TextNote element."); } } #endregion #region Class Implementations /// <summary> /// For singleton consideration, setup log file only when ViewPrinting is raised. /// m_eventsLog will be initialized and added to Trace.Listeners, /// PrintEventsLog.txt will be removed if it already existed. /// </summary> private void SetupLogFiles() { // singleton instance for log file if (null != m_eventsLog) { return; } // // delete existed log files String printEventsLogFile = Path.Combine(m_assemblyPath, "PrintEventsLog.txt"); if (File.Exists(printEventsLogFile)) { File.Delete(printEventsLogFile); } // // Create listener and add to Trace.Listeners to monitor the string to be emitted m_eventsLog = new TextWriterTraceListener(printEventsLogFile); Trace.Listeners.Add(m_eventsLog); Trace.AutoFlush = true; // set auto flush to ensure the emitted string can be dumped in time } /// <summary> /// Dump the events arguments to log file PrintEventsLog.txt. /// This method will only dump EventArguments of ViewPrint, two event arguments will be handled: /// ViewPrintingEventArgs and ViewPrintedEventArgs. /// Typical properties of EventArgs of them will be dumped to log file. /// </summary> /// <param name="eventArgs">Event argument to be dumped. </param> private static void DumpEventArguments(RevitAPIEventArgs eventArgs) { // Dump parameters now: // white space is for align purpose. if (eventArgs.GetType().Equals(typeof(ViewPrintingEventArgs))) { Trace.WriteLine("ViewPrintingEventArgs Parameters ------>"); ViewPrintingEventArgs args = eventArgs as ViewPrintingEventArgs; Trace.WriteLine(" TotalViews : " + args.TotalViews); Trace.WriteLine(" View Index : " + args.Index); Trace.WriteLine(" View Information :"); DumpViewInfo(args.View, " "); } else if (eventArgs.GetType().Equals(typeof(ViewPrintedEventArgs))) { Trace.WriteLine("ViewPrintedEventArgs Parameters ------>"); ViewPrintedEventArgs args = eventArgs as ViewPrintedEventArgs; Trace.WriteLine(" Event Status : " + args.Status); Trace.WriteLine(" TotalViews : " + args.TotalViews); Trace.WriteLine(" View Index : " + args.Index); Trace.WriteLine(" View Information :"); DumpViewInfo(args.View, " "); } else { // no handling for other arguments } } /// <summary> /// Dump information of view(View name and type) to log file. /// </summary> /// <param name="view">View element to be dumped to log files.</param> /// <param name="prefix">Prefix mark for each line dumped to log files.</param> private static void DumpViewInfo(View view, String prefix) { Trace.WriteLine(String.Format("{0} ViewName: {1}, ViewType: {2}", prefix, view.ViewName, view.ViewType)); } #endregion } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.ML.Data; using Encog.Util; using Encog.Util.Validate; namespace Encog.Neural.Networks.Training.Propagation.Quick { /// <summary> /// QPROP is an efficient training method that is based on Newton's Method. /// QPROP was introduced in a paper: /// /// An Empirical Study of Learning Speed in Back-Propagation Networks" (Scott E. Fahlman, 1988) /// /// /// http://www.heatonresearch.com/wiki/Quickprop /// </summary> public sealed class QuickPropagation : Propagation, ILearningRate { /// <summary> /// This factor times the current weight is added to the slope /// at the start of each output epoch. Keeps weights from growing /// too big. /// </summary> public double Decay { get; set; } /// <summary> /// Used to scale for the size of the training set. /// </summary> public double EPS { get; set; } /// <summary> /// The last deltas. /// </summary> public double[] LastDelta { get; set; } /// <summary> /// The learning rate. /// </summary> public double LearningRate { get; set; } /// <summary> /// Controls the amount of linear gradient descent /// to use in updating output weights. /// </summary> public double OutputEpsilon { get; set; } /// <summary> /// Used in computing whether the proposed step is /// too large. Related to learningRate. /// </summary> public double Shrink { get; set; } /// <summary> /// Continuation tag for the last gradients. /// </summary> public const String LastGradients = "LAST_GRADIENTS"; /// <summary> /// Construct a QPROP trainer for flat networks. Uses a learning rate of 2. /// </summary> /// <param name="network">The network to train.</param> /// <param name="training">The training data.</param> public QuickPropagation(IContainsFlat network, IMLDataSet training) : this(network, training, 2.0) { } /// <summary> /// Construct a QPROP trainer for flat networks. /// </summary> /// <param name="network">The network to train.</param> /// <param name="training">The training data.</param> /// <param name="learnRate">The learning rate. 2 is a good suggestion as /// a learning rate to start with. If it fails to converge, /// then drop it. Just like backprop, except QPROP can /// take higher learning rates.</param> public QuickPropagation(IContainsFlat network, IMLDataSet training, double learnRate) : base(network, training) { ValidateNetwork.ValidateMethodToData(network, training); LearningRate = learnRate; LastDelta = new double[Network.Flat.Weights.Length]; OutputEpsilon = 1.0; } /// <inheritdoc /> public override bool CanContinue { get { return true; } } /// <summary> /// Determine if the specified continuation object is valid to resume with. /// </summary> /// <param name="state">The continuation object to check.</param> /// <returns>True if the specified continuation object is valid for this /// training method and network.</returns> public bool IsValidResume(TrainingContinuation state) { if (!state.Contents.ContainsKey(LastGradients)) { return false; } if (!state.TrainingType.Equals(GetType().Name)) { return false; } var d = (double[]) state.Contents[LastGradients]; return d.Length == ((IContainsFlat) Method).Flat.Weights.Length; } /// <summary> /// Pause the training. /// </summary> /// <returns>A training continuation object to continue with.</returns> public override TrainingContinuation Pause() { var result = new TrainingContinuation {TrainingType = (GetType().Name)}; result.Contents[LastGradients] = LastGradient; return result; } /// <summary> /// Resume training. /// </summary> /// <param name="state">The training state to return to.</param> public override void Resume(TrainingContinuation state) { if (!IsValidResume(state)) { throw new TrainingError("Invalid training resume data length"); } var lastGradient = (double[]) state.Contents[ LastGradients]; EngineArray.ArrayCopy(lastGradient,LastGradient); } /// <summary> /// Called to init the QPROP. /// </summary> public override void InitOthers() { EPS = OutputEpsilon / Training.Count; Shrink = LearningRate / (1.0 + LearningRate); } /// <summary> /// Update a weight. /// </summary> /// <param name="gradients">The gradients.</param> /// <param name="lastGradient">The last gradients.</param> /// <param name="index">The index.</param> /// <returns>The weight delta.</returns> public override double UpdateWeight(double[] gradients, double[] lastGradient, int index) { double w = Network.Flat.Weights[index]; double d = LastDelta[index]; double s = -Gradients[index] + Decay * w; double p = -lastGradient[index]; double nextStep = 0.0; // The step must always be in direction opposite to the slope. if (d < 0.0) { // If last step was negative... if (s > 0.0) { // Add in linear term if current slope is still positive. nextStep -= EPS * s; } // If current slope is close to or larger than prev slope... if (s >= (Shrink * p)) { // Take maximum size negative step. nextStep += LearningRate * d; } else { // Else, use quadratic estimate. nextStep += d * s / (p - s); } } else if (d > 0.0) { // If last step was positive... if (s < 0.0) { // Add in linear term if current slope is still negative. nextStep -= EPS * s; } // If current slope is close to or more neg than prev slope... if (s <= (Shrink * p)) { // Take maximum size negative step. nextStep += LearningRate * d; } else { // Else, use quadratic estimate. nextStep += d * s / (p - s); } } else { // Last step was zero, so use only linear term. nextStep -= EPS * s; } // update global data arrays LastDelta[index] = nextStep; LastGradient[index] = gradients[index]; return nextStep; } } }
// 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.Net.Sockets; namespace System.Net { /// <devdoc> /// <para> /// Provides an Internet Protocol (IP) address. /// </para> /// </devdoc> public class IPAddress { public static readonly IPAddress Any = new IPAddress(0x0000000000000000); public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F); public static readonly IPAddress Broadcast = new IPAddress(0x00000000FFFFFFFF); public static readonly IPAddress None = Broadcast; internal const long LoopbackMask = 0x00000000000000FF; public static readonly IPAddress IPv6Any = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0); public static readonly IPAddress IPv6Loopback = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 0); public static readonly IPAddress IPv6None = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0); /// <summary> /// For IPv4 addresses, this field stores the Address. /// For IPv6 addresses, this field stores the ScopeId. /// Instead of accessing this field directly, use the <see cref="PrivateAddress"/> or <see cref="PrivateScopeId"/> properties. /// </summary> private uint _addressOrScopeId; /// <summary> /// This field is only used for IPv6 addresses. A null value indicates that this instance is an IPv4 address. /// </summary> private readonly ushort[] _numbers; /// <summary> /// A lazily initialized cache of the result of calling <see cref="ToString"/>. /// </summary> private string _toString; /// <summary> /// This field is only used for IPv6 addresses. A lazily initialized cache of the <see cref="GetHashCode"/> value. /// </summary> private int _hashCode; // Maximum length of address literals (potentially including a port number) // generated by any address-to-string conversion routine. This length can // be used when declaring buffers used with getnameinfo, WSAAddressToString, // inet_ntoa, etc. We just provide one define, rather than one per api, // to avoid confusion. // // The totals are derived from the following data: // 15: IPv4 address // 45: IPv6 address including embedded IPv4 address // 11: Scope Id // 2: Brackets around IPv6 address when port is present // 6: Port (including colon) // 1: Terminating null byte internal const int NumberOfLabels = IPAddressParserStatics.IPv6AddressBytes / 2; private bool IsIPv4 { get { return _numbers == null; } } private bool IsIPv6 { get { return _numbers != null; } } private uint PrivateAddress { get { Debug.Assert(IsIPv4); return _addressOrScopeId; } set { Debug.Assert(IsIPv4); _addressOrScopeId = value; } } private uint PrivateScopeId { get { Debug.Assert(IsIPv6); return _addressOrScopeId; } set { Debug.Assert(IsIPv6); _addressOrScopeId = value; } } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.IPAddress'/> /// class with the specified address. /// </para> /// </devdoc> public IPAddress(long newAddress) { if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF) { throw new ArgumentOutOfRangeException(nameof(newAddress)); } PrivateAddress = (uint)newAddress; } /// <devdoc> /// <para> /// Constructor for an IPv6 Address with a specified Scope. /// </para> /// </devdoc> public IPAddress(byte[] address, long scopeid) { if (address == null) { throw new ArgumentNullException(nameof(address)); } if (address.Length != IPAddressParserStatics.IPv6AddressBytes) { throw new ArgumentException(SR.dns_bad_ip_address, nameof(address)); } _numbers = new ushort[NumberOfLabels]; for (int i = 0; i < NumberOfLabels; i++) { _numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]); } // Consider: Since scope is only valid for link-local and site-local // addresses we could implement some more robust checking here if (scopeid < 0 || scopeid > 0x00000000FFFFFFFF) { throw new ArgumentOutOfRangeException(nameof(scopeid)); } PrivateScopeId = (uint)scopeid; } private IPAddress(ushort[] numbers, uint scopeid) { Debug.Assert(numbers != null); _numbers = numbers; PrivateScopeId = scopeid; } /// <devdoc> /// <para> /// Constructor for IPv4 and IPv6 Address. /// </para> /// </devdoc> public IPAddress(byte[] address) { if (address == null) { throw new ArgumentNullException(nameof(address)); } if (address.Length != IPAddressParserStatics.IPv4AddressBytes && address.Length != IPAddressParserStatics.IPv6AddressBytes) { throw new ArgumentException(SR.dns_bad_ip_address, nameof(address)); } if (address.Length == IPAddressParserStatics.IPv4AddressBytes) { PrivateAddress = (uint)((address[3] << 24 | address[2] << 16 | address[1] << 8 | address[0]) & 0x0FFFFFFFF); } else { _numbers = new ushort[NumberOfLabels]; for (int i = 0; i < NumberOfLabels; i++) { _numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]); } } } // We need this internally since we need to interface with winsock, // and winsock only understands Int32. internal IPAddress(int newAddress) { PrivateAddress = (uint)newAddress; } /// <devdoc> /// <para> /// Converts an IP address string to an <see cref='System.Net.IPAddress'/> instance. /// </para> /// </devdoc> public static bool TryParse(string ipString, out IPAddress address) { address = IPAddressParser.Parse(ipString, true); return (address != null); } public static IPAddress Parse(string ipString) { return IPAddressParser.Parse(ipString, false); } /// <devdoc> /// <para> /// Provides a copy of the IPAddress internals as an array of bytes. /// </para> /// </devdoc> public byte[] GetAddressBytes() { byte[] bytes; if (IsIPv6) { bytes = new byte[NumberOfLabels * 2]; int j = 0; for (int i = 0; i < NumberOfLabels; i++) { bytes[j++] = (byte)((_numbers[i] >> 8) & 0xFF); bytes[j++] = (byte)((_numbers[i]) & 0xFF); } } else { uint address = PrivateAddress; bytes = new byte[IPAddressParserStatics.IPv4AddressBytes]; bytes[0] = (byte)(address); bytes[1] = (byte)(address >> 8); bytes[2] = (byte)(address >> 16); bytes[3] = (byte)(address >> 24); } return bytes; } public AddressFamily AddressFamily { get { return IsIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6; } } // When IPv6 support was added to the .NET Framework, the public Address property was marked as Obsolete. // The public obsolete Address property has not been carried forward in .NET Core, but remains here as // internal to allow internal types that understand IPv4 to still access it without obsolete warnings. internal long Address { get { return PrivateAddress; } } /// <devdoc> /// <para> /// IPv6 Scope identifier. This is really a uint32, but that isn't CLS compliant /// </para> /// </devdoc> public long ScopeId { get { // Not valid for IPv4 addresses if (IsIPv4) { throw new SocketException(SocketError.OperationNotSupported); } return PrivateScopeId; } set { // Not valid for IPv4 addresses if (IsIPv4) { throw new SocketException(SocketError.OperationNotSupported); } // Consider: Since scope is only valid for link-local and site-local // addresses we could implement some more robust checking here if (value < 0 || value > 0x00000000FFFFFFFF) { throw new ArgumentOutOfRangeException(nameof(value)); } PrivateScopeId = (uint)value; } } /// <devdoc> /// <para> /// Converts the Internet address to either standard dotted quad format /// or standard IPv6 representation. /// </para> /// </devdoc> public override string ToString() { if (_toString == null) { _toString = IsIPv4 ? IPAddressParser.IPv4AddressToString(GetAddressBytes()) : IPAddressParser.IPv6AddressToString(GetAddressBytes(), PrivateScopeId); } return _toString; } public static long HostToNetworkOrder(long host) { #if BIGENDIAN return host; #else return (((long)HostToNetworkOrder((int)host) & 0xFFFFFFFF) << 32) | ((long)HostToNetworkOrder((int)(host >> 32)) & 0xFFFFFFFF); #endif } public static int HostToNetworkOrder(int host) { #if BIGENDIAN return host; #else return (((int)HostToNetworkOrder((short)host) & 0xFFFF) << 16) | ((int)HostToNetworkOrder((short)(host >> 16)) & 0xFFFF); #endif } public static short HostToNetworkOrder(short host) { #if BIGENDIAN return host; #else return (short)((((int)host & 0xFF) << 8) | (int)((host >> 8) & 0xFF)); #endif } public static long NetworkToHostOrder(long network) { return HostToNetworkOrder(network); } public static int NetworkToHostOrder(int network) { return HostToNetworkOrder(network); } public static short NetworkToHostOrder(short network) { return HostToNetworkOrder(network); } public static bool IsLoopback(IPAddress address) { if (address == null) { throw new ArgumentNullException(nameof(address)); } if (address.IsIPv6) { // Do Equals test for IPv6 addresses return address.Equals(IPv6Loopback); } else { return ((address.PrivateAddress & LoopbackMask) == (Loopback.PrivateAddress & LoopbackMask)); } } /// <devdoc> /// <para> /// Determines if an address is an IPv6 Multicast address /// </para> /// </devdoc> public bool IsIPv6Multicast { get { return IsIPv6 && ((_numbers[0] & 0xFF00) == 0xFF00); } } /// <devdoc> /// <para> /// Determines if an address is an IPv6 Link Local address /// </para> /// </devdoc> public bool IsIPv6LinkLocal { get { return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFE80); } } /// <devdoc> /// <para> /// Determines if an address is an IPv6 Site Local address /// </para> /// </devdoc> public bool IsIPv6SiteLocal { get { return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFEC0); } } public bool IsIPv6Teredo { get { return IsIPv6 && (_numbers[0] == 0x2001) && (_numbers[1] == 0); } } // 0:0:0:0:0:FFFF:x.x.x.x public bool IsIPv4MappedToIPv6 { get { if (IsIPv4) { return false; } for (int i = 0; i < 5; i++) { if (_numbers[i] != 0) { return false; } } return (_numbers[5] == 0xFFFF); } } internal bool Equals(object comparandObj, bool compareScopeId) { IPAddress comparand = comparandObj as IPAddress; if (comparand == null) { return false; } // Compare families before address representations if (AddressFamily != comparand.AddressFamily) { return false; } if (IsIPv6) { // For IPv6 addresses, we must compare the full 128-bit representation. for (int i = 0; i < NumberOfLabels; i++) { if (comparand._numbers[i] != _numbers[i]) { return false; } } // The scope IDs must also match return comparand.PrivateScopeId == PrivateScopeId || !compareScopeId; } else { // For IPv4 addresses, compare the integer representation. return comparand.PrivateAddress == PrivateAddress; } } /// <devdoc> /// <para> /// Compares two IP addresses. /// </para> /// </devdoc> public override bool Equals(object comparand) { return Equals(comparand, true); } public override int GetHashCode() { // For IPv6 addresses, we cannot simply return the integer // representation as the hashcode. Instead, we calculate // the hashcode from the string representation of the address. if (IsIPv6) { if (_hashCode == 0) { _hashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(ToString()); } return _hashCode; } else { // For IPv4 addresses, we can simply use the integer representation. return unchecked((int)PrivateAddress); } } // For security, we need to be able to take an IPAddress and make a copy that's immutable and not derived. internal IPAddress Snapshot() { return IsIPv4 ? new IPAddress(PrivateAddress) : new IPAddress(_numbers, PrivateScopeId); } // IPv4 192.168.1.1 maps as ::FFFF:192.168.1.1 public IPAddress MapToIPv6() { if (IsIPv6) { return this; } uint address = PrivateAddress; ushort[] labels = new ushort[NumberOfLabels]; labels[5] = 0xFFFF; labels[6] = (ushort)(((address & 0x0000FF00) >> 8) | ((address & 0x000000FF) << 8)); labels[7] = (ushort)(((address & 0xFF000000) >> 24) | ((address & 0x00FF0000) >> 8)); return new IPAddress(labels, 0); } // Takes the last 4 bytes of an IPv6 address and converts it to an IPv4 address. // This does not restrict to address with the ::FFFF: prefix because other types of // addresses display the tail segments as IPv4 like Terado. public IPAddress MapToIPv4() { if (IsIPv4) { return this; } // Cast the ushort values to a uint and mask with unsigned literal before bit shifting. // Otherwise, we can end up getting a negative value for any IPv4 address that ends with // a byte higher than 127 due to sign extension of the most significant 1 bit. long address = ((((uint)_numbers[6] & 0x0000FF00u) >> 8) | (((uint)_numbers[6] & 0x000000FFu) << 8)) | (((((uint)_numbers[7] & 0x0000FF00u) >> 8) | (((uint)_numbers[7] & 0x000000FFu) << 8)) << 16); return new IPAddress(address); } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; namespace Ivy { /// <summary> /// This is the main type for your game /// </summary> public abstract class IvyGame : Microsoft.Xna.Framework.Game, IMessageSender, IMessageReceiver { private static IvyGame m_instance = null; public enum GameState { Pause, Play, GameOver, }; public GameState State { get; protected set; } GraphicsDeviceManager IvyGraphics; SpriteBatch IvySpriteBatch; // World Data private WorldZone m_currentZone; public Camera2D Camera { get; private set; } public Entity m_cameraTarget; // refactor into Console class public string ConsoleStr { get; set; } private SpriteFont consoleFont; private Vector2 consolePos; private float m_fpsValue; private string m_fpsStr; protected Texture2D CameraGel { get; set; } protected Color GelTint { get; set; } // Debug Options private bool DrawCollisionRects { get; set; } protected IvyGame() { State = GameState.Play; DrawCollisionRects = false; m_fpsValue = 0.0f; IvyGraphics = new GraphicsDeviceManager(this); IvyGraphics.PreferredBackBufferWidth = 800; IvyGraphics.PreferredBackBufferHeight = 600; IvyGraphics.ApplyChanges(); ///@todo is this needed? Content.RootDirectory = "Content"; if (m_instance != null) { // @todo error! exception? } m_instance = this; } public static IvyGame Get() { if (m_instance == null) { //@TODO exception! // uh oh! shouldn't even happen! } return m_instance; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // Initialize components base.Initialize(); Camera = new Camera2D(); GelTint = Color.White; ConsoleStr = "\n"; m_fpsStr = "\n"; InputMgr.Get().RegisterKey(Keys.P, OnKeyboardEvent); // Pause/Play InputMgr.Get().RegisterKey(Keys.Q, OnKeyboardEvent); // Quit InputMgr.Get().RegisterKey(Keys.F1, OnKeyboardEvent); // Debug - Collision Rects InputMgr.Get().RegisterGamePadButton(Buttons.Back, OnGamePadButtonEvent); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. IvySpriteBatch = new SpriteBatch(GraphicsDevice); ///@todo move to console class consoleFont = Content.Load<SpriteFont>(@"Fonts\\Console"); consolePos = new Vector2(40, 50); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here Content.Unload(); } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { ConsoleStr = "\n\n"; // Dispatch queued messages MessageDispatcher.Get().Update(gameTime); // Input InputMgr.Get().Update(); if (State == GameState.Play) { if (m_currentZone != null) { m_currentZone.Update(gameTime); } // if multiple rooms are active in a game, they should all be updated here } else if (State == GameState.GameOver) { this.Exit(); } // Update Camera based on Player Position Camera.Update(gameTime); // Update Sound FX? base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { m_fpsValue = (m_fpsValue * 3) + ((1 / (float)gameTime.ElapsedGameTime.Milliseconds) * 1000); m_fpsValue /= 4.0f; m_fpsStr = "FPS: " + (int)m_fpsValue + "\n"; GraphicsDevice.Clear(Color.Black); IvySpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend); SamplerState pointSampler = new SamplerState(); pointSampler.Filter = TextureFilter.Point; IvyGraphics.GraphicsDevice.SamplerStates[0] = pointSampler; // if multiple rooms are active, only the current one is drawn if (m_currentZone != null) { m_currentZone.Draw(IvySpriteBatch); } // Draw 'Camera Gel' to tint screen if (CameraGel != null) { IvySpriteBatch.Draw(CameraGel, Camera.ScreenRect, GelTint); } // Draw Console // Find the center of the string Vector2 FontCenter = consoleFont.MeasureString(ConsoleStr) / 2; Vector2 drawConsolePos = new Vector2(consolePos.X + FontCenter.X, consolePos.Y); // Draw the string IvySpriteBatch.DrawString(consoleFont, ConsoleStr, drawConsolePos, Color.LimeGreen, 0, FontCenter, 1.2f, SpriteEffects.None, 0.5f); string dataString = m_fpsStr; Vector2 FpsDims = consoleFont.MeasureString(dataString); Vector2 drawFpsPos = new Vector2((Camera.ScreenRect.Right - (FpsDims.X * 2)), FpsDims.Y); IvySpriteBatch.DrawString(consoleFont, dataString, drawFpsPos, Color.LimeGreen, 0, FpsDims / 2, 2.0f, SpriteEffects.None, 0.5f); IvySpriteBatch.End(); if ((m_currentZone != null) && DrawCollisionRects) { m_currentZone.Draw3D(); } base.Draw(gameTime); } protected void SetCameraTarget(Entity target) { m_cameraTarget = target; Camera.SetTarget(target); } public WorldZone GetCurrentZone() { return m_currentZone; } public void SetCurrentZone(WorldZone room) { m_currentZone = room; } public virtual void ReceiveMessage(Message msg) { if (msg.Type == MessageType.ChangeZone) { HandleChangeZoneMsg((ChangeZoneMsg)msg); } else if (msg.Type == MessageType.PauseGame) { State = GameState.Pause; } else if (msg.Type == MessageType.PlayGame) { State = GameState.Play; } else if (msg.Type == MessageType.EndGame) { HandleGameEndMsg(msg);; } } private void HandleChangeZoneMsg(ChangeZoneMsg msg) { // Pause, Transition Room, Then Pass Message onto both rooms if (m_currentZone != null) { MessageDispatcher.Get().SendMessage( new ChangeZoneMsg(this, m_currentZone, msg.Entity, msg.DestZone, msg.DestPosition, 1)); } if (msg.Entity == m_cameraTarget) { WorldZone destZone = new WorldZone(msg.DestZone); destZone.SetEscapeMode(GetCurrentZone().EscapeMode); SetCurrentZone(destZone); Camera.SetZoneBounds(destZone.Bounds); Camera.SetTarget(msg.Entity); if (msg.DestZone != null) { MessageDispatcher.Get().SendMessage( new ChangeZoneMsg(this, destZone, msg.Entity, msg.DestZone, msg.DestPosition, 1)); } } } protected virtual void HandleGameEndMsg(Message msg) { if (msg.Type == MessageType.EndGame) { State = GameState.GameOver; } } protected virtual bool OnKeyboardEvent(KeyboardEvent e) { if (e.Key == Keys.P) { if (e.EventType == InputEventType.Pressed) { if (State == GameState.Pause) { MessageDispatcher.Get().SendMessage(new Message(MessageType.PlayGame, this, this)); } else if (State == GameState.Play) { MessageDispatcher.Get().SendMessage(new Message(MessageType.PauseGame, this, this)); } } } else if (e.Key == Keys.Q) { if (e.EventType == InputEventType.Pressed) { MessageDispatcher.Get().SendMessage(new Message(MessageType.EndGame, this, this)); } } else if (e.Key == Keys.F1) { if (e.EventType == InputEventType.Pressed) { DrawCollisionRects = !DrawCollisionRects; } } return true; } protected virtual bool OnGamePadButtonEvent(GamePadButtonEvent e) { // Allows the game to exit if (e.Button == Buttons.Back && e.EventType == InputEventType.Pressed) { MessageDispatcher.Get().SendMessage(new Message(MessageType.EndGame, this, this)); } return true; } } }
using System; using System.IO; using AltinnApp.Core.Models; using AltinnApp.Core.Util; using AltinnApp.iOS.CorePlatform; using AltinnApp.iOS.Util; using BigTed; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace AltinnApp.iOS { /// <summary> /// Class responsible for handling the opening of print view and attachments /// </summary> public partial class AttachmentController : UIViewController { //private NSMutableUrlRequest _theRequest; internal string AttachmentFilename; //private readonly PlattformService _service; private Translate _trans; /// <summary> /// Default constructor for Attachent /// </summary> /// <param name="handle"></param> public AttachmentController(IntPtr handle) : base(handle) { //_service = new PlattformService(); } // ReSharper disable once UnusedMember.Local // ReSharper disable once UnusedParameter.Local async partial void OpenIn(NSObject sender) { try { if (SelectedMessage.SavedFileName == null) { BTProgressHUD.Show(); string filename; if (SelectedMessage.Type == Constants.MessageType.FormTask.ToString()) { if (SelectedMessage.Links.Print != null && SelectedMessage.Links.Print.Mimetype == "text/html") { //opening html forms has some isues string data = await PlattformService.Service.GetAttachmentAsString(SelectedMessage.Links.Print.Href); string attachment = data; var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); filename = Path.Combine(documents, SelectedMessage.MessageId + ".html"); if (attachment != null) { File.WriteAllText(filename, attachment); SelectedMessage.SavedFileName = filename; } } else { if (SelectedMessage.Links.Print != null) { byte[] data = await PlattformService.Service.GetAttachment(SelectedMessage.Links.Print.Href); byte[] attachment = data; var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); filename = Path.Combine(documents, SelectedMessage.MessageId + ".pdf"); if (attachment != null) { File.WriteAllBytes(filename, attachment); SelectedMessage.SavedFileName = filename; } } } } else if (SelectedMessage.Type == Constants.MessageType.Correspondence.ToString()) { if (SelectedMessage.Links.Attachment != null) { byte[] data = await PlattformService.Service.GetAttachment(SelectedMessage.Links.Attachment[0].Href); byte[] attachment = data; var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); filename = Path.Combine(documents, SelectedMessage.Links.Attachment[0].Name); if (attachment != null) { File.WriteAllBytes(filename, attachment); SelectedMessage.SavedFileName = filename; } } } BTProgressHUD.Dismiss(); } if (SelectedMessage.SavedFileName != null) { NSUrl fileUrl = NSUrl.FromFilename(SelectedMessage.SavedFileName); var viewer = UIDocumentInteractionController.FromUrl(fileUrl); viewer.ViewControllerForPreview = c => this; viewer.PresentOptionsMenu(View.Bounds, View, true); } } catch (Exception ex) { Logger.Logg("Failed to openWith attachment: " + ex); BTProgressHUD.Dismiss(); } } /// <summary> /// Gets or sets the Selected Message /// </summary> public Message SelectedMessage { get; set; } public int Status { get; set; } public override void ViewDidLoad() { base.ViewDidLoad(); webview.AutosizesSubviews = true; BTProgressHUD.Show(); View.AutosizesSubviews = true; _trans = new Translate(); } public override bool ShouldAutorotate() { return true; } public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() { return UIInterfaceOrientationMask.All; } public override async void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); BTProgressHUD.Show(); try { if (Reachability.IsHostReachable(AppContext.LoginUrl)) { //Check that all the necessary information is in place if (SelectedMessage != null && (SelectedMessage.Links.Print != null || SelectedMessage.Links.Attachment != null)) { //Distinguish between FormTask and Correspondence if (SelectedMessage.Type == Constants.MessageType.Correspondence.ToString()) { if (SelectedMessage.Links.Attachment != null) { if (SelectedMessage.Links.Attachment != null) { byte[] data = await PlattformService.Service.GetAttachment( SelectedMessage.Links.Attachment[0].Href); webview.LoadData(NSData.FromArray(data), SelectedMessage.Links.Attachment[0].Mimetype, "UTF-8", new NSUrl(SelectedMessage.Links.Self.Href)); } } } else if (SelectedMessage.Type == Constants.MessageType.FormTask.ToString()) { if (SelectedMessage.Links.Print != null) { if (SelectedMessage.Links.Print.Mimetype != null) { string mimeType = SelectedMessage.Links.Print.Mimetype; if (!(mimeType == "application/pdf" || mimeType == "text/html")) { throw new AppException("0", ErrorMessages.PrintFailed); } if (mimeType == "text/html") { string data = await PlattformService.Service.GetAttachmentAsString( SelectedMessage.Links.Print.Href); // webview.LoadHtmlString(NSData.FromString(attachment), // SelectedMessage.Links.Print.Mimetype, "UTF-8", // new NSUrl(SelectedMessage.Links.Print.Href)); webview.LoadHtmlString(data, new NSUrl(SelectedMessage.Links.Print.Href)); } else { byte[] data = await PlattformService.Service.GetAttachment(SelectedMessage.Links.Print.Href); webview.LoadData(NSData.FromArray(data), SelectedMessage.Links.Print.Mimetype, "UTF-8", new NSUrl(SelectedMessage.Links.Print.Href)); } } } } BTProgressHUD.Dismiss(); } } else { Util.Util.ShowAlert(ErrorMessages.NoNetworkAvailable); } } catch (AppException app) { Util.Util.HandleAppException(app, this); } catch (Exception ex) { Logger.Logg("Failed to load the data for the webview" + ex); Util.Util.ShowAlert(ErrorMessages.GeneralError); } BTProgressHUD.Dismiss(); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); if (SelectedMessage != null) { if (SelectedMessage.Type == Constants.MessageType.Correspondence.ToString()) { _backLabel.Text = _backLabel.Text = _trans.GetString("CorrespondenceController_Header"); _openIn.Hidden = false; if (SelectedMessage.Links.Attachment != null) { _headerLabel.Text = SelectedMessage.Links.Attachment[0].Name; } } else if (SelectedMessage.Type == Constants.MessageType.FormTask.ToString()) { _backLabel.Text = _backLabel.Text = _trans.GetString("FormController_Header"); _openIn.Hidden = false; if (SelectedMessage.Links.Print != null) { _headerLabel.Text = SelectedMessage.Subject; } } } } // ReSharper disable once UnusedMember.Local // ReSharper disable once UnusedParameter.Local partial void GoBack(NSObject sender) { BTProgressHUD.Dismiss(); NavigationController.PopViewControllerAnimated(true); } } }
using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; namespace WebApp.Migrations { public partial class REnameCitiesToCityInCustomer : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_HousingCall_Housing_HousingId", table: "HousingCall"); migrationBuilder.DropForeignKey(name: "FK_Sms_Customer_ClientId", table: "Sms"); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Customer_City_CityId", table: "Customer", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_City_CityId", table: "Housing", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_District_DistrictId", table: "Housing", column: "DistrictId", principalTable: "District", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_Street_StreetId", table: "Housing", column: "StreetId", principalTable: "Street", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing", column: "TypesHousingId", principalTable: "TypesHousing", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_HousingCall_Housing_HousingId", table: "HousingCall", column: "HousingId", principalTable: "Housing", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Sms_Customer_ClientId", table: "Sms", column: "ClientId", principalTable: "Customer", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer"); migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing"); migrationBuilder.DropForeignKey(name: "FK_HousingCall_Housing_HousingId", table: "HousingCall"); migrationBuilder.DropForeignKey(name: "FK_Sms_Customer_ClientId", table: "Sms"); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Customer_City_CityId", table: "Customer", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_City_CityId", table: "Housing", column: "CityId", principalTable: "City", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_District_DistrictId", table: "Housing", column: "DistrictId", principalTable: "District", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_Street_StreetId", table: "Housing", column: "StreetId", principalTable: "Street", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing", column: "TypesHousingId", principalTable: "TypesHousing", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_HousingCall_Housing_HousingId", table: "HousingCall", column: "HousingId", principalTable: "Housing", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Sms_Customer_ClientId", table: "Sms", column: "ClientId", principalTable: "Customer", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <summary> /// ConversationAction class that represents ConversationActionType in the request XML. /// This class really is meant for representing single ConversationAction that needs to /// be taken on a conversation. /// </summary> internal class ConversationAction { /// <summary> /// Gets or sets conversation action /// </summary> internal ConversationActionType Action { get; set; } /// <summary> /// Gets or sets conversation id /// </summary> internal ConversationId ConversationId { get; set; } /// <summary> /// Gets or sets ProcessRightAway /// </summary> internal bool ProcessRightAway { get; set; } /// <summary> /// Gets or set conversation categories for Always Categorize action /// </summary> internal StringList Categories { get; set; } /// <summary> /// Gets or sets Enable Always Delete value for Always Delete action /// </summary> internal bool EnableAlwaysDelete { get; set; } /// <summary> /// Gets or sets the IsRead state. /// </summary> internal bool? IsRead { get; set; } /// <summary> /// Gets or sets the SuppressReadReceipts flag. /// </summary> internal bool? SuppressReadReceipts { get; set; } /// <summary> /// Gets or sets the Deletion mode. /// </summary> internal DeleteMode? DeleteType { get; set; } /// <summary> /// Gets or sets the flag. /// </summary> internal Flag Flag { get; set; } /// <summary> /// ConversationLastSyncTime is used in one time action to determine the items /// on which to take the action. /// </summary> internal DateTime? ConversationLastSyncTime { get; set; } /// <summary> /// Gets or sets folder id ContextFolder /// </summary> internal FolderIdWrapper ContextFolderId { get; set; } /// <summary> /// Gets or sets folder id for Move action /// </summary> internal FolderIdWrapper DestinationFolderId { get; set; } /// <summary> /// Gets or sets the retention policy type. /// </summary> internal RetentionType? RetentionPolicyType { get; set; } /// <summary> /// Gets or sets the retention policy tag id. /// </summary> internal Guid? RetentionPolicyTagId { get; set; } /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name.</returns> internal string GetXmlElementName() { return XmlElementNames.ApplyConversationAction; } /// <summary> /// Validate request. /// </summary> internal void Validate() { EwsUtilities.ValidateParam(this.ConversationId, "conversationId"); } /// <summary> /// Writes XML elements. /// </summary> /// <param name="writer">The writer.</param> internal void WriteElementsToXml(EwsServiceXmlWriter writer) { writer.WriteStartElement( XmlNamespace.Types, XmlElementNames.ConversationAction); try { string actionValue = String.Empty; switch (this.Action) { case ConversationActionType.AlwaysCategorize: actionValue = XmlElementNames.AlwaysCategorize; break; case ConversationActionType.AlwaysDelete: actionValue = XmlElementNames.AlwaysDelete; break; case ConversationActionType.AlwaysMove: actionValue = XmlElementNames.AlwaysMove; break; case ConversationActionType.Delete: actionValue = XmlElementNames.Delete; break; case ConversationActionType.Copy: actionValue = XmlElementNames.Copy; break; case ConversationActionType.Move: actionValue = XmlElementNames.Move; break; case ConversationActionType.SetReadState: actionValue = XmlElementNames.SetReadState; break; case ConversationActionType.SetRetentionPolicy: actionValue = XmlElementNames.SetRetentionPolicy; break; case ConversationActionType.Flag: actionValue = XmlElementNames.Flag; break; default: throw new ArgumentException("ConversationAction"); } // Emit the action element writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Action, actionValue); // Emit the conversation id element this.ConversationId.WriteToXml( writer, XmlNamespace.Types, XmlElementNames.ConversationId); if (this.Action == ConversationActionType.AlwaysCategorize || this.Action == ConversationActionType.AlwaysDelete || this.Action == ConversationActionType.AlwaysMove) { // Emit the ProcessRightAway element writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.ProcessRightAway, EwsUtilities.BoolToXSBool(this.ProcessRightAway)); } if (this.Action == ConversationActionType.AlwaysCategorize) { // Emit the categories element if (this.Categories != null && this.Categories.Count > 0) { this.Categories.WriteToXml( writer, XmlNamespace.Types, XmlElementNames.Categories); } } else if (this.Action == ConversationActionType.AlwaysDelete) { // Emit the EnableAlwaysDelete element writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.EnableAlwaysDelete, EwsUtilities.BoolToXSBool(this.EnableAlwaysDelete)); } else if (this.Action == ConversationActionType.AlwaysMove) { // Emit the Move Folder Id if (this.DestinationFolderId != null) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.DestinationFolderId); this.DestinationFolderId.WriteToXml(writer); writer.WriteEndElement(); } } else { if (this.ContextFolderId != null) { writer.WriteStartElement( XmlNamespace.Types, XmlElementNames.ContextFolderId); this.ContextFolderId.WriteToXml(writer); writer.WriteEndElement(); } if (this.ConversationLastSyncTime.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.ConversationLastSyncTime, this.ConversationLastSyncTime.Value); } if (this.Action == ConversationActionType.Copy) { EwsUtilities.Assert( this.DestinationFolderId != null, "ApplyconversationActionRequest", "DestinationFolderId should be set when performing copy action"); writer.WriteStartElement( XmlNamespace.Types, XmlElementNames.DestinationFolderId); this.DestinationFolderId.WriteToXml(writer); writer.WriteEndElement(); } else if (this.Action == ConversationActionType.Move) { EwsUtilities.Assert( this.DestinationFolderId != null, "ApplyconversationActionRequest", "DestinationFolderId should be set when performing move action"); writer.WriteStartElement( XmlNamespace.Types, XmlElementNames.DestinationFolderId); this.DestinationFolderId.WriteToXml(writer); writer.WriteEndElement(); } else if (this.Action == ConversationActionType.Delete) { EwsUtilities.Assert( this.DeleteType.HasValue, "ApplyconversationActionRequest", "DeleteType should be specified when deleting a conversation."); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DeleteType, this.DeleteType.Value); } else if (this.Action == ConversationActionType.SetReadState) { EwsUtilities.Assert( this.IsRead.HasValue, "ApplyconversationActionRequest", "IsRead should be specified when marking/unmarking a conversation as read."); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.IsRead, this.IsRead.Value); if (this.SuppressReadReceipts.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.SuppressReadReceipts, this.SuppressReadReceipts.Value); } } else if (this.Action == ConversationActionType.SetRetentionPolicy) { EwsUtilities.Assert( this.RetentionPolicyType.HasValue, "ApplyconversationActionRequest", "RetentionPolicyType should be specified when setting a retention policy on a conversation."); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.RetentionPolicyType, this.RetentionPolicyType.Value); if (this.RetentionPolicyTagId.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.RetentionPolicyTagId, this.RetentionPolicyTagId.Value); } } else if (this.Action == ConversationActionType.Flag) { EwsUtilities.Assert( this.Flag != null, "ApplyconversationActionRequest", "Flag should be specified when flagging conversation items."); writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Flag); this.Flag.WriteElementsToXml(writer); writer.WriteEndElement(); } } } finally { writer.WriteEndElement(); } } } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.IO; using System.ComponentModel; namespace Microsoft.DirectX.DirectSound { public class Buffer : MarshalByRefObject, IDisposable { public event EventHandler Disposing { add { throw new NotImplementedException (); } remove { throw new NotImplementedException (); } } public bool Disposed { get { throw new NotImplementedException (); } } public bool NotVirtualized { get { throw new NotImplementedException (); } } public int WritePosition { get { throw new NotImplementedException (); } } public int PlayPosition { get { throw new NotImplementedException (); } } public BufferStatus Status { get { throw new NotImplementedException (); } } public int Frequency { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int Pan { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public int Volume { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public WaveFormat Format { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public BufferCaps Caps { get { throw new NotImplementedException (); } } public Buffer (Stream source, int length, Device parent) { throw new NotImplementedException (); } public Buffer (Stream source, Device parent) { throw new NotImplementedException (); } public Buffer (string fileName, Device parent) { throw new NotImplementedException (); } public Buffer (Stream source, BufferDescription desc, Device parent) { throw new NotImplementedException (); } public Buffer (Stream source, int length, BufferDescription desc, Device parent) { throw new NotImplementedException (); } public Buffer (string fileName, BufferDescription desc, Device parent) { throw new NotImplementedException (); } public Buffer (IntPtr lp, Device parent) { throw new NotImplementedException (); } public Buffer (BufferDescription desc, Device parent) { throw new NotImplementedException (); } public Buffer Clone (Device parent) { throw new NotImplementedException (); } public override bool Equals (object compare) { throw new NotImplementedException (); } public static bool operator == (Buffer left, Buffer right) { throw new NotImplementedException (); } public static bool operator != (Buffer left, Buffer right) { throw new NotImplementedException (); } public override int GetHashCode () { throw new NotImplementedException (); } public void Dispose () { throw new NotImplementedException (); } [EditorBrowsable(EditorBrowsableState.Never)] public IntPtr GetObjectByValue (int objId) { throw new NotImplementedException (); } public void GetCurrentPosition (out int currentPlayPosition, out int currentWritePosition) { throw new NotImplementedException (); } public void SetCurrentPosition (int newPosition) { throw new NotImplementedException (); } public void Stop () { throw new NotImplementedException (); } public void Restore () { throw new NotImplementedException (); } public void Play (int priority, BufferPlayFlags flags) { throw new NotImplementedException (); } public Array Read (int bufferStartingLocation, Type returnedDataType, LockFlag flag, params int[] ranks) { throw new NotImplementedException (); } public void Read (int bufferStartingLocation, Stream data, int numberBytesToRead, LockFlag flag) { throw new NotImplementedException (); } public void Write (int bufferStartingLocation, Array data, LockFlag flag) { throw new NotImplementedException (); } public void Write (int bufferStartingLocation, Stream data, int numberBytesToWrite, LockFlag flag) { throw new NotImplementedException (); } } }
/* ArcGIS Service Non-Direct-Connect Checker Copyright (C) 2011 Washington State Department of Transportation This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Web.Script.Serialization; using ArcGisServiceDCChecker.Properties; using ESRI.ArcGIS.ADF.Connection.AGS; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Server; namespace ArcGisServiceDCChecker { class Program { private static LicenseInitializer _aoLicenseInitializer = new ArcGisServiceDCChecker.LicenseInitializer(); private static readonly string _jsonFile = Settings.Default.OutputJson, _csvFile = Settings.Default.OutputCsv; [STAThread()] static void Main(string[] args) { Dictionary<string, List<MapServiceInfo>> output; JavaScriptSerializer serializer; // Get the server names from the config. string[] servers = Settings.Default.Servers.Split(','); Console.Error.WriteLine("Getting license..."); //ESRI License Initializer generated code. if (!_aoLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeArcView }, new esriLicenseExtensionCode[] { })) { Console.Error.WriteLine(_aoLicenseInitializer.LicenseMessage()); Console.Error.WriteLine("This application could not initialize with the correct ArcGIS license and will shutdown."); _aoLicenseInitializer.ShutdownApplication(); return; } Console.Error.WriteLine("License acquired."); output = CollectMapServerInfo(servers); serializer = new JavaScriptSerializer(); string json = serializer.Serialize(output); File.WriteAllText(_jsonFile, json); // Write to CSV... using (StreamWriter writer = new StreamWriter(_csvFile)) { output.ToCsv(writer); } //ESRI License Initializer generated code. //Do not make any call to ArcObjects after ShutDownApplication() _aoLicenseInitializer.ShutdownApplication(); } private static Dictionary<string, List<MapServiceInfo>> CollectMapServerInfo(IEnumerable<string> servers) { Dictionary<string, List<MapServiceInfo>> output; output = new Dictionary<string, List<MapServiceInfo>>(); AGSServerConnection connection = null; IServerObjectManager4 som = null; IServerContext ctxt = null; IMapServer mapServer = null; IEnumServerObjectConfigurationInfo socInfos; IServerObjectConfigurationInfo2 socInfo; MapServiceInfo mapServiceInfo; try { // Loop through all of the hosts (servers) and create a div for each one containing map service test results. foreach (var host in servers) { var mapServiceInfos = new List<MapServiceInfo>(); output.Add(host, mapServiceInfos); // Create the connection object connection = new AGSServerConnection(host, null, false, true); try { // Attempt to connect to the server. connection.Connect(false); if (connection.IsConnected) { // Get the Server Object Manager (SOM) for the current ArcGIS Server. som = (IServerObjectManager4)connection.ServerObjectManager; // Get a list of the services on the server. socInfos = som.GetConfigurationInfos(); // Get the first service from the list. socInfo = socInfos.Next() as IServerObjectConfigurationInfo2; // Loop through the list of services... while (socInfo != null) { mapServiceInfo = new MapServiceInfo { MapServiceName = socInfo.Name }; try { // Proceed only if the current service is a "MapServer". if (string.Compare(socInfo.TypeName, "MapServer", true) == 0) { // Create a div for the current map service. Console.Error.WriteLine("{0}", socInfo.Name); try { // Create a server context for the current map service. ctxt = som.CreateServerContext(socInfo.Name, socInfo.TypeName); // Cast the context object to an IMapServer. mapServer = (IMapServer)ctxt.ServerObject; // Get the document name IMapServerInit2 msInit = null; msInit = mapServer as IMapServerInit2; string sourceDocName = msInit != null ? msInit.FilePath : null; if (sourceDocName != null) { mapServiceInfo.SourceDocumentPath = sourceDocName; } // Create a dictionary of the properties for all of the layers in the map service. mapServiceInfo.ConnectionProperties = mapServer.GetConnectionProperties(); } catch (COMException comEx) { // See if the exception was caused by a stopped service. Just write the message in this case. if (comEx.ErrorCode == -2147467259) { mapServiceInfo.ErrorMessage = comEx.Message; } else { mapServiceInfo.ErrorMessage = string.Format("{0}: {1}", comEx.ErrorCode, comEx.Message); } } } } catch (Exception ex) { mapServiceInfo.ErrorMessage = ex.ToString(); } finally { // Release the server context. if (ctxt != null) { ctxt.ReleaseContext(); } // Go to the next soc info. socInfo = socInfos.Next() as IServerObjectConfigurationInfo2; } mapServiceInfos.Add(mapServiceInfo); } } } finally { connection.Dispose(); } } } finally { // Release any COM objects that have been created. if (mapServer != null) { Marshal.ReleaseComObject(mapServer); } if (ctxt != null) { Marshal.ReleaseComObject(ctxt); } if (som != null) { Marshal.ReleaseComObject(som); } } return output; } } }
using System.Diagnostics; using System; using System.Management; using System.Collections; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Web.UI.Design; using System.Data; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.CodeDom; using System.Drawing; namespace ACSGhana.Web.Framework { namespace UI { namespace Controls { /// <summary> /// Mimics the Macromedia flash movie "quality" parameter. /// </summary> public enum FlashMovieQuality { /// <summary> /// [Macromedia Default] Outputs "high" as the value of the quality parameter. /// </summary> High = 0, /// <summary> /// Outputs "best" as the value of the "quality" parameter. /// </summary> Best = 1, /// <summary> /// Outputs "autolow" as the value of the "quality" parameter. /// </summary> AutoLow = 2, /// <summary> /// Outputs "autohigh" as the value of the "quality" parameter. /// </summary> AutoHigh = 3, /// <summary> /// Outputs "medium" as the value of the "quality" parameter. /// </summary> Medium = 4, /// <summary> /// Outputs "low" as the value of the "quality" parameter. /// </summary> Low = 5 } /// <summary> /// Mimics the Macromedia flash movie "scale" parameter. /// </summary> public enum FlashMovieScale { /// <summary> /// [Macromedia Default] Does not render the "scale" parameter. /// </summary> ShowAll = 0, /// <summary> /// Outputs "noscale" as the value of the "scale" parameter. /// </summary> NoScale = 1, /// <summary> /// Outputs "exactfit" as the value of the "scale" parameter. /// </summary> ExactFit = 2, /// <summary> /// Outputs "noborder" as the value of the "scale" parameter. /// </summary> NoBorder = 3 } /// <summary> /// Mimics the Macromedia flash movie "wmode" parameter. /// </summary> public enum FlashMovieWindowMode { /// <summary> /// [Macromedia Default] Does not render the "wmode" parameter. /// </summary> Window = 0, /// <summary> /// Outputs "opaque" as the value of the "wmode" parameter. /// </summary> Opaque = 1, /// <summary> /// Outputs "transparent" as the value of the "wmode" parameter. /// </summary> Transparent = 2 } /// <summary> /// Determins how your control will be rendered to the browser /// </summary> public enum FlashOutputType { /// <summary> /// Adds version detection script in html output. /// </summary> ClientScriptVersionDection = 0, /// <summary> /// Outputs special flash object tag for SWF version detection. /// </summary> SWFVersionDetection = 1, /// <summary> /// Ouputs only the html code nessesary to play embed your flash Movie. /// </summary> FlashOnly = 2, /// <summary> /// Not currently supported. /// </summary> FlashOnlyForPocketPC2002 = 3, /// <summary> /// Not currently supported. /// </summary> FlashWithAICCTracking = 4, /// <summary> /// Not currently supported. /// </summary> FlashWithSCORMTracking = 5, /// <summary> /// Not currently supported. /// </summary> FlashWithNamedAnchors = 6 } /// <summary> /// Mimics the Macromedia flash movie "salign" parameter. Should be implemented in conjunction with FlashVerticalAlignment since /// both enumerations make up the full salign parameter for the flash movie. When used with FlashVerticalAlignment possible values /// are (RT R RB T B LT L LB). If both values are set to "Center" the parameter is not rendered to the browser. /// </summary> public enum FlashHorizontalAlignment { /// <summary> /// Outputs "L" as the first character in the "salign" parameter. /// </summary> Left = 0, /// <summary> /// [Macromedia Default] Does not render as part of the "salign" parameter value. /// </summary> Center = 1, /// <summary> /// Outputs "R" as the first character in the "salign" parameter. /// </summary> Right = 2 } /// <summary> /// Mimics the Macromedia flash movie "salign" parameter. Should be implemented in conjunction with FlashHorizontalAlignment since both /// enumerations make up the full salign parameter for the flash movie. When used with FlashHorizontalAlignment possible values /// are (RT R RB T B LT L LB). If both values are set to "Center" the parameter is not rendered to the browser. /// </summary> public enum FlashVerticalAlignment { /// <summary> /// Outputs "T" as the second character in the "salign" parameter. /// </summary> Top = 0, /// <summary> /// [Macromedia Default] Does not render as part of the "salign" parameter value. /// </summary> Center = 1, /// <summary> /// Outputs "B" as the second character in the "salign" parameter. /// </summary> Bottom = 2 } /// <summary> /// Mimics the HTML "align" attribute for the Macromedia flash movie. /// </summary> public enum FlashHtmlAlignment { /// <summary> /// [Macromedia Default] Outputs empty quotes as the "Align" attribute value. /// </summary> None = 0, /// <summary> /// Outputs "top" as the "Align" attribute value. /// </summary> Top = 1, /// <summary> /// Outputs "bottom" as the "Align" attribute value. /// </summary> Bottom = 2, /// <summary> /// Outputs "left" as the "Align" attribute value. /// </summary> Left = 3, /// <summary> /// Outputs "right" as the "Align" attribute value. /// </summary> Right = 4 } /// <summary> /// Mimics the allowScriptAccess attributer to the Macromedia flash movie. /// </summary> public enum FlashScriptAccessControl { /// <summary> /// Outputs sameDomain as the "allowScriptAccess" parameter. /// </summary> SameDomain = 0, /// <summary> /// Outputs never as the "allowScriptAccess" parameter. /// </summary> Never = 1, /// <summary> /// Outputs always as the "allowScriptAccess" parameter. /// </summary> Always = 2 } /// <summary> /// It is suggested to use this class instead of using the FlashHorizontalAlignment and FlashVerticalAlignment Enumerations directly. /// This class is simply a wrapper to organize the flash alignment enumerations and to keep them togeather, which is how they should be implemented. /// </summary> public class FlashMovieAlignment { private FlashHorizontalAlignment _halign; private FlashVerticalAlignment _valign; /// <summary> /// Gets or Sets the FlashHorizontalAlignment enumeration. /// </summary> public FlashHorizontalAlignment HorizontalAlign { get { return this._halign; } set { this._halign = value; } } /// <summary> /// Gets or Sets the FlashVerticalAlignment enumeration. /// </summary> public FlashVerticalAlignment VerticalAlign { get { return this._valign; } set { this._valign = value; } } /// <summary> /// Initializes both enumerations to a default value of "Center". /// This is in correlation to the Macromedia Flash default publishing settings. /// </summary> public FlashMovieAlignment() { this.Initialize(FlashHorizontalAlignment.Center, FlashVerticalAlignment.Center); } /// <summary> /// Defaults the FlashVerticalAlignment enumeration to "Center" and allows you to initialize the class with a specific HorizontalAlign value. /// </summary> /// <param name="h">The value to initialize the HorizontalAlign property with.</param> public FlashMovieAlignment(FlashHorizontalAlignment h) { this.Initialize(h, FlashVerticalAlignment.Center); } /// <summary> /// Defaults the FlashHorizontalAlignment enumeration to "Center" and allows you to initialize the class with a specific VerticalAlign value. /// </summary> /// <param name="v">The value to initialize the VerticalAlign property with.</param> public FlashMovieAlignment(FlashVerticalAlignment v) { this.Initialize(FlashHorizontalAlignment.Center, v); } /// <summary> /// Allows you to initialize the class with a specific VerticalAlign and HorizontalAlign value. /// </summary> /// <param name="h">The value to initialize the HorizontalAlign property with.</param> /// <param name="v">The value to initialize the VerticalAlign property with.</param> public FlashMovieAlignment(FlashHorizontalAlignment h, FlashVerticalAlignment v) { this.Initialize(h, v); } /// <summary> /// Sets the private alignment fields during initialization. /// </summary> /// <param name="h">The value to initialize the HorizontalAlign property with.</param> /// <param name="v">The value to initialize the VerticalAlign property with.</param> protected void Initialize(FlashHorizontalAlignment h, FlashVerticalAlignment v) { this._halign = h; this._valign = v; } /// <summary> /// Outputs the standard flash alignment format value. /// </summary> /// <returns>A two character string used to set the flash salign parameter</returns> public override string ToString() { string s = ""; switch (this.HorizontalAlign) { case FlashHorizontalAlignment.Center: s = ""; break; case FlashHorizontalAlignment.Left: s = "L"; break; case FlashHorizontalAlignment.Right: s = "R"; break; } switch (this.VerticalAlign) { case FlashVerticalAlignment.Center: s += ""; break; case FlashVerticalAlignment.Top: s += "T"; break; case FlashVerticalAlignment.Bottom: s += "B"; break; } return s; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.ComponentModel.EventBasedAsync.Tests { public class BackgroundWorkerTests { private const int TimeoutShort = 300; private const int TimeoutLong = 30000; [Fact] public void TestBackgroundWorkerBasic() { var orignal = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const int expectedResult = 42; const int expectedReportCallsCount = 5; int actualReportCallsCount = 0; var worker = new BackgroundWorker() { WorkerReportsProgress = true }; var progressBarrier = new Barrier(2, barrier => ++actualReportCallsCount); var workerCompletedEvent = new ManualResetEventSlim(false); worker.DoWork += (sender, e) => { for (int i = 0; i < expectedReportCallsCount; i++) { worker.ReportProgress(i); progressBarrier.SignalAndWait(); } e.Result = expectedResult; }; worker.RunWorkerCompleted += (sender, e) => { try { Assert.Equal(expectedResult, (int)e.Result); Assert.False(worker.IsBusy); } finally { workerCompletedEvent.Set(); } }; worker.ProgressChanged += (sender, e) => { progressBarrier.SignalAndWait(); }; worker.RunWorkerAsync(); // wait for signal from WhenRunWorkerCompleted Assert.True(workerCompletedEvent.Wait(TimeoutLong)); Assert.False(worker.IsBusy); Assert.Equal(expectedReportCallsCount, actualReportCallsCount); } finally { SynchronizationContext.SetSynchronizationContext(orignal); } } [Fact] public async Task RunWorkerAsync_NoOnWorkHandler_SetsResultToNull() { var tcs = new TaskCompletionSource<bool>(); var backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true }; backgroundWorker.RunWorkerCompleted += (sender, e) => { Assert.Null(e.Result); Assert.False(backgroundWorker.IsBusy); tcs.SetResult(true); }; backgroundWorker.RunWorkerAsync(); await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(10))); // Usually takes 100th of a sec Assert.True(tcs.Task.IsCompleted); } #region TestCancelAsync private ManualResetEventSlim manualResetEvent3; [Fact] public void TestCancelAsync() { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += DoWorkExpectCancel; bw.WorkerSupportsCancellation = true; manualResetEvent3 = new ManualResetEventSlim(false); bw.RunWorkerAsync("Message"); bw.CancelAsync(); bool ret = manualResetEvent3.Wait(TimeoutLong); Assert.True(ret); // there could be race condition between worker thread cancellation and completion which will set the CancellationPending to false // if it is completed already, we don't check cancellation if (bw.IsBusy) // not complete { if (!bw.CancellationPending) { for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } } // Check again if (bw.IsBusy) Assert.True(bw.CancellationPending, "Cancellation in Main thread"); } } private void DoWorkExpectCancel(object sender, DoWorkEventArgs e) { Assert.Equal("Message", e.Argument); var bw = sender as BackgroundWorker; if (bw.CancellationPending) { manualResetEvent3.Set(); return; } // we want to wait for cancellation - wait max (1000 * TimeoutShort) milliseconds for (int i = 0; i < 1000; i++) { Wait(TimeoutShort); if (bw.CancellationPending) { break; } } Assert.True(bw.CancellationPending, "Cancellation in Worker thread"); // signal no matter what, even if it's not cancelled by now manualResetEvent3.Set(); } #endregion [Fact] public void TestThrowExceptionInDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); const string expectedArgument = "Exception"; const string expectedExceptionMsg = "Exception from DoWork"; var bw = new BackgroundWorker(); var workerCompletedEvent = new ManualResetEventSlim(false); bw.DoWork += (sender, e) => { Assert.Same(bw, sender); Assert.Same(expectedArgument, e.Argument); throw new TestException(expectedExceptionMsg); }; bw.RunWorkerCompleted += (sender, e) => { try { TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => e.Result); Assert.True(ex.InnerException is TestException); Assert.Equal(expectedExceptionMsg, ex.InnerException.Message); } finally { workerCompletedEvent.Set(); } }; bw.RunWorkerAsync(expectedArgument); Assert.True(workerCompletedEvent.Wait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void CtorTest() { var bw = new BackgroundWorker(); Assert.False(bw.IsBusy); Assert.False(bw.WorkerReportsProgress); Assert.False(bw.WorkerSupportsCancellation); Assert.False(bw.CancellationPending); } [Fact] public void RunWorkerAsyncTwice() { var bw = new BackgroundWorker(); var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); try { Assert.True(bw.IsBusy); Assert.Throws<InvalidOperationException>(() => bw.RunWorkerAsync()); } finally { barrier.SignalAndWait(); } } [Fact] public void TestCancelInsideDoWork() { var original = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(null); var bw = new BackgroundWorker() { WorkerSupportsCancellation = true }; var barrier = new Barrier(2); bw.DoWork += (sender, e) => { barrier.SignalAndWait(); barrier.SignalAndWait(); if (bw.CancellationPending) { e.Cancel = true; } }; bw.RunWorkerCompleted += (sender, e) => { Assert.True(e.Cancelled); barrier.SignalAndWait(); }; bw.RunWorkerAsync(); barrier.SignalAndWait(); bw.CancelAsync(); barrier.SignalAndWait(); Assert.True(barrier.SignalAndWait(TimeoutLong), "Background work timeout"); } finally { SynchronizationContext.SetSynchronizationContext(original); } } [Fact] public void TestCancelAsyncWithoutCancellationSupport() { var bw = new BackgroundWorker() { WorkerSupportsCancellation = false }; Assert.Throws<InvalidOperationException>(() => bw.CancelAsync()); } [Fact] public void TestReportProgressSync() { var bw = new BackgroundWorker() { WorkerReportsProgress = true }; var expectedProgress = new int[] { 1, 2, 3, 4, 5 }; var actualProgress = new List<int>(); bw.ProgressChanged += (sender, e) => { actualProgress.Add(e.ProgressPercentage); }; foreach (int i in expectedProgress) { bw.ReportProgress(i); } Assert.Equal(expectedProgress, actualProgress); } [Fact] public void ReportProgress_NoProgressHandle_Nop() { var backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true }; foreach (int i in new int[] { 1, 2, 3, 4, 5 }) { backgroundWorker.ReportProgress(i); } } [Fact] public void TestReportProgressWithWorkerReportsProgressFalse() { var bw = new BackgroundWorker() { WorkerReportsProgress = false }; Assert.Throws<InvalidOperationException>(() => bw.ReportProgress(42)); } [Fact] public void DisposeTwiceShouldNotThrow() { var bw = new BackgroundWorker(); bw.Dispose(); bw.Dispose(); } [Fact] public void TestFinalization() { // BackgroundWorker has a finalizer that exists purely for backwards compatibility // with existing code that may override Dispose to clean up native resources. // https://github.com/dotnet/corefx/pull/752 ManualResetEventSlim mres = SetEventWhenFinalizedBackgroundWorker.CreateAndThrowAway(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.True(mres.Wait(10000)); } private sealed class SetEventWhenFinalizedBackgroundWorker : BackgroundWorker { private ManualResetEventSlim _setWhenFinalized; internal static ManualResetEventSlim CreateAndThrowAway() { var mres = new ManualResetEventSlim(); new SetEventWhenFinalizedBackgroundWorker() { _setWhenFinalized = mres }; return mres; } protected override void Dispose(bool disposing) { _setWhenFinalized.Set(); } } private static void Wait(int milliseconds) { Task.Delay(milliseconds).Wait(); } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.Net; #if !(NET_1_1) using System.Collections.Generic; using FluorineFx.Collections.Generic; #endif #if !SILVERLIGHT using log4net; #endif using FluorineFx.Collections; using FluorineFx.Messaging.Api; using FluorineFx.Threading; using FluorineFx.Util; namespace FluorineFx.Messaging { /// <summary> /// Base abstract class for connections. /// </summary> [CLSCompliant(false)] public abstract class BaseConnection : AttributeStore, IConnection { #if !SILVERLIGHT private static ILog log = LogManager.GetLogger(typeof(BaseConnection)); #endif private FastReaderWriterLock _readerWriterLock; //object _syncLock = new object(); /// <summary> /// Connection id. /// </summary> protected string _connectionId; /// <summary> /// AMF version. /// </summary> protected ObjectEncoding _objectEncoding; /// <summary> /// Path of scope client connected to. /// </summary> protected string _path; /// <summary> /// Number of read messages. /// </summary> protected AtomicLong _readMessages; /// <summary> /// Number of written messages. /// </summary> protected AtomicLong _writtenMessages; /// <summary> /// Number of dropped messages. /// </summary> protected AtomicLong _droppedMessages; /// <summary> /// Connection params passed from client with NetConnection.connect call. /// </summary> protected IDictionary _parameters; /// <summary> /// Client bound to connection. /// </summary> protected IClient _client; /// <summary> /// Session bound to connection. /// </summary> protected ISession _session; /// <summary> /// Scope that connection belongs to. /// </summary> private IScope _scope; #if !(NET_1_1) /// <summary> /// Set of basic scopes. /// </summary> protected CopyOnWriteArraySet<IBasicScope> _basicScopes = new CopyOnWriteArraySet<IBasicScope>(); #else /// <summary> /// Set of basic scopes. /// </summary> protected CopyOnWriteArraySet _basicScopes = new CopyOnWriteArraySet(); #endif /// <summary> /// State bit field. /// 1 IsClosed /// 2 IsClosing /// 4 /// 8 IsFlexClient /// 16 IsTunnelingDetected /// 32 IsTunneled /// 64 RtmpServerConnection: IsDisconnecting /// 128 /// </summary> protected byte __fields; /// <summary> /// Initializes a new instance of the BaseConnection class. /// </summary> /// <param name="path">Scope path on server.</param> /// <param name="parameters">Parameters passed from client.</param> public BaseConnection(string path, IDictionary parameters) :this(path, Guid.NewGuid().ToString("N").Remove(12, 1), parameters) { //V4 GUID should be safe to remove the 4 so we can use the id for rtmpt } /// <summary> /// Initializes a new instance of the BaseConnection class. /// </summary> /// <param name="path">Scope path on server.</param> /// <param name="connectionId">Connection id.</param> /// <param name="parameters">Parameters passed from client.</param> internal BaseConnection(string path, string connectionId, IDictionary parameters) { _readerWriterLock = new FastReaderWriterLock(); _readMessages = new AtomicLong(); _writtenMessages = new AtomicLong(); _droppedMessages = new AtomicLong(); //V4 GUID should be safe to remove the 4 so we can use the id for rtmpt _connectionId = connectionId; _objectEncoding = ObjectEncoding.AMF0; _path = path; _parameters = parameters; SetIsClosed(false); } /// <summary> /// Gets the network endpoint. /// </summary> public abstract IPEndPoint RemoteEndPoint { get; } /// <summary> /// Gets the path for this connection. This is not updated if you switch scope. /// </summary> public string Path { get { return _path; } } /// <summary> /// Gets whether the connection is closed. /// </summary> public bool IsClosed { get { return (__fields & 1) == 1; } } internal void SetIsClosed(bool value) { __fields = (value) ? (byte)(__fields | 1) : (byte)(__fields & ~1); } /// <summary> /// Gets whether the connection is being closed. /// </summary> public bool IsClosing { get { return (__fields & 2) == 2; } } internal void SetIsClosing(bool value) { __fields = (value) ? (byte)(__fields | 2) : (byte)(__fields & ~2); } /// <summary> /// Gets whether the connected client is a Flex client (swf). /// </summary> public bool IsFlexClient { get { return (__fields & 8) == 8; } } internal void SetIsFlexClient(bool value) { __fields = (value) ? (byte)(__fields | 8) : (byte)(__fields & ~8); } /// <summary> /// Initializes client. /// </summary> /// <param name="client">Client bound to connection.</param> public void Initialize(IClient client) { try { _readerWriterLock.AcquireWriterLock(); if (this.Client != null) { // Unregister old client this.Client.Unregister(this); } _client = client; // Register new client _client.Register(this); } finally { _readerWriterLock.ReleaseWriterLock(); } } #region IConnection Members /// <summary> /// Connect to another scope on server. /// </summary> /// <param name="scope">New scope.</param> /// <returns>true on success, false otherwise.</returns> public bool Connect(IScope scope) { return Connect(scope, null); } /// <summary> /// Connect to another scope on server with given parameters. /// </summary> /// <param name="scope">New scope.</param> /// <param name="parameters">Parameters to connect with.</param> /// <returns>true on success, false otherwise.</returns> public virtual bool Connect(IScope scope, object[] parameters) { try { _readerWriterLock.AcquireWriterLock(); IScope oldScope = _scope; _scope = scope; if (_scope.Connect(this, parameters)) { if (oldScope != null) { oldScope.Disconnect(this); } return true; } else { _scope = oldScope; return false; } } finally { _readerWriterLock.ReleaseWriterLock(); } } /// <summary> /// Checks whether connection is alive. /// </summary> public virtual bool IsConnected { get { return _scope != null; } } /// <summary> /// Closes connection. /// </summary> public virtual void Close() { try { _readerWriterLock.AcquireWriterLock(); if (IsClosed) return; SetIsClosed(true); } finally { _readerWriterLock.ReleaseWriterLock(); } #if !SILVERLIGHT log.Debug("Close, disconnect from scope, and children"); #endif if (_basicScopes != null) { try { //Close, disconnect from scope, and children foreach (IBasicScope basicScope in _basicScopes) { UnregisterBasicScope(basicScope); } } catch (Exception ex) { #if !SILVERLIGHT log.Error(__Res.GetString(__Res.Scope_UnregisterError), ex); #endif } } try { _readerWriterLock.AcquireWriterLock(); if (_scope != null) { try { _scope.Disconnect(this); } catch (Exception ex) { #if !SILVERLIGHT log.Error(__Res.GetString(__Res.Scope_DisconnectError, _scope), ex); #endif } } if (_client != null) { _client.Unregister(this); _client = null; } if (_session != null) { _session.Invalidate(); _session = null; } _scope = null; } finally { _readerWriterLock.ReleaseWriterLock(); } } /// <summary> /// This method supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public virtual void Timeout() { } /* /// <summary> /// This property supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> public virtual int ClientLeaseTime { get { return 0; } } */ /// <summary> /// Gets connection parameters. /// </summary> public IDictionary Parameters { get { return _parameters; } } /// <summary> /// Gets the client object associated with this connection. /// </summary> public IClient Client { get{ return _client; } } /// <summary> /// Gets the session object associated with this connection. /// </summary> public ISession Session { get { return _session; } } /// <summary> /// Get the scope this client is connected to. /// </summary> public IScope Scope { get{ return _scope; } } /// <summary> /// Gets the basic scopes this connection has subscribed. This list will /// contain the shared objects and broadcast streams the connection connected to. /// </summary> public IEnumerator BasicScopes { get{ return _basicScopes.GetEnumerator(); } } /// <summary> /// Gets the connection id. /// </summary> public string ConnectionId { get { return _connectionId; } } /// <summary> /// Gets the session id. /// </summary> public string SessionId { get { return _connectionId; } } /// <summary> /// Gets the object encoding (AMF version) for this connection. /// </summary> public ObjectEncoding ObjectEncoding { get { return _objectEncoding; } } /// <summary> /// Gets an object that can be used to synchronize access to the connection. /// </summary> //public object SyncRoot { get { return _syncLock; } } internal FastReaderWriterLock ReaderWriterLock { get { return _readerWriterLock; } } /// <summary> /// Start measuring the roundtrip time for a packet on the connection. /// </summary> public virtual void Ping() { } #endregion #region IEventDispatcher Members /// <summary> /// Dispatches event. /// </summary> /// <param name="evt">Event.</param> public virtual void DispatchEvent(FluorineFx.Messaging.Api.Event.IEvent evt) { } #endregion #region IEventHandler Members /// <summary> /// Handles event /// </summary> /// <param name="evt">Event.</param> /// <returns>true if associated scope was able to handle event, false otherwise.</returns> public virtual bool HandleEvent(FluorineFx.Messaging.Api.Event.IEvent evt) { return this.Scope.HandleEvent(evt); } #endregion #region IEventListener Members /// <summary> /// Notified on event. /// </summary> /// <param name="evt">Event.</param> public virtual void NotifyEvent(FluorineFx.Messaging.Api.Event.IEvent evt) { } #endregion /// <summary> /// Registers basic scope. /// </summary> /// <param name="basicScope">Basic scope to register.</param> public void RegisterBasicScope(IBasicScope basicScope) { _basicScopes.Add(basicScope); basicScope.AddEventListener(this); } /// <summary> /// Unregister basic scope. /// </summary> /// <param name="basicScope">Unregister basic scope.</param> public void UnregisterBasicScope(IBasicScope basicScope) { _basicScopes.Remove(basicScope); basicScope.RemoveEventListener(this); } /// <summary> /// Gets the total number of bytes read from the connection. /// </summary> public abstract long ReadBytes { get; } /// <summary> /// Gets the total number of bytes written to the connection. /// </summary> public abstract long WrittenBytes { get; } /// <summary> /// Gets the total number of messages read from the connection. /// </summary> public long ReadMessages { get { return _readMessages.Value; } } /// <summary> /// Gets the total number of messages written to the connection. /// </summary> public long WrittenMessages { get { return _writtenMessages.Value; } } /// <summary> /// Gets the total number of messages that have been dropped. /// </summary> public long DroppedMessages { get { return _droppedMessages.Value; } } /// <summary> /// Gets the total number of messages that are pending to be sent to the connection. /// </summary> public virtual long PendingMessages { get { return 0; } } /// <summary> /// Get the total number of video messages that are pending to be sent to a stream. /// </summary> /// <param name="streamId">The stream id.</param> /// <returns>Number of pending video messages.</returns> public virtual long GetPendingVideoMessages(int streamId) { return 0; } /// <summary> /// Gets the number of written bytes the client reports to have received. /// This is the last value of the BytesRead message received from a client. /// </summary> public virtual long ClientBytesRead { get { return 0; } } /// <summary> /// Gets roundtrip time of last ping command. /// </summary> public abstract int LastPingTime { get; } } }