context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary.Metadata { using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Binary; /// <summary> /// Binary metadata implementation. /// </summary> internal class BinaryType : IBinaryType { /** Empty metadata. */ public static readonly BinaryType Empty = new BinaryType(BinaryUtils.TypeObject, BinaryTypeNames.TypeNameObject, null, null, false); /** Empty dictionary. */ private static readonly IDictionary<string, int> EmptyDict = new Dictionary<string, int>(); /** Empty list. */ private static readonly ICollection<string> EmptyList = new List<string>().AsReadOnly(); /** Type name map. */ private static readonly string[] TypeNames = new string[byte.MaxValue]; /** Fields. */ private readonly IDictionary<string, int> _fields; /** Enum flag. */ private readonly bool _isEnum; /** Type id. */ private readonly int _typeId; /** Type name. */ private readonly string _typeName; /** Aff key field name. */ private readonly string _affinityKeyFieldName; /// <summary> /// Initializes the <see cref="BinaryType"/> class. /// </summary> static BinaryType() { TypeNames[BinaryUtils.TypeBool] = BinaryTypeNames.TypeNameBool; TypeNames[BinaryUtils.TypeByte] = BinaryTypeNames.TypeNameByte; TypeNames[BinaryUtils.TypeShort] = BinaryTypeNames.TypeNameShort; TypeNames[BinaryUtils.TypeChar] = BinaryTypeNames.TypeNameChar; TypeNames[BinaryUtils.TypeInt] = BinaryTypeNames.TypeNameInt; TypeNames[BinaryUtils.TypeLong] = BinaryTypeNames.TypeNameLong; TypeNames[BinaryUtils.TypeFloat] = BinaryTypeNames.TypeNameFloat; TypeNames[BinaryUtils.TypeDouble] = BinaryTypeNames.TypeNameDouble; TypeNames[BinaryUtils.TypeDecimal] = BinaryTypeNames.TypeNameDecimal; TypeNames[BinaryUtils.TypeString] = BinaryTypeNames.TypeNameString; TypeNames[BinaryUtils.TypeGuid] = BinaryTypeNames.TypeNameGuid; TypeNames[BinaryUtils.TypeTimestamp] = BinaryTypeNames.TypeNameTimestamp; TypeNames[BinaryUtils.TypeEnum] = BinaryTypeNames.TypeNameEnum; TypeNames[BinaryUtils.TypeObject] = BinaryTypeNames.TypeNameObject; TypeNames[BinaryUtils.TypeArrayBool] = BinaryTypeNames.TypeNameArrayBool; TypeNames[BinaryUtils.TypeArrayByte] = BinaryTypeNames.TypeNameArrayByte; TypeNames[BinaryUtils.TypeArrayShort] = BinaryTypeNames.TypeNameArrayShort; TypeNames[BinaryUtils.TypeArrayChar] = BinaryTypeNames.TypeNameArrayChar; TypeNames[BinaryUtils.TypeArrayInt] = BinaryTypeNames.TypeNameArrayInt; TypeNames[BinaryUtils.TypeArrayLong] = BinaryTypeNames.TypeNameArrayLong; TypeNames[BinaryUtils.TypeArrayFloat] = BinaryTypeNames.TypeNameArrayFloat; TypeNames[BinaryUtils.TypeArrayDouble] = BinaryTypeNames.TypeNameArrayDouble; TypeNames[BinaryUtils.TypeArrayDecimal] = BinaryTypeNames.TypeNameArrayDecimal; TypeNames[BinaryUtils.TypeArrayString] = BinaryTypeNames.TypeNameArrayString; TypeNames[BinaryUtils.TypeArrayGuid] = BinaryTypeNames.TypeNameArrayGuid; TypeNames[BinaryUtils.TypeArrayTimestamp] = BinaryTypeNames.TypeNameArrayTimestamp; TypeNames[BinaryUtils.TypeArrayEnum] = BinaryTypeNames.TypeNameArrayEnum; TypeNames[BinaryUtils.TypeArray] = BinaryTypeNames.TypeNameArrayObject; TypeNames[BinaryUtils.TypeCollection] = BinaryTypeNames.TypeNameCollection; TypeNames[BinaryUtils.TypeDictionary] = BinaryTypeNames.TypeNameMap; } /// <summary> /// Get type name by type ID. /// </summary> /// <param name="typeId">Type ID.</param> /// <returns>Type name.</returns> private static string GetTypeName(int typeId) { var typeName = (typeId >= 0 && typeId < TypeNames.Length) ? TypeNames[typeId] : null; if (typeName != null) return typeName; throw new BinaryObjectException("Invalid type ID: " + typeId); } /// <summary> /// Initializes a new instance of the <see cref="BinaryType" /> class. /// </summary> /// <param name="reader">The reader.</param> public BinaryType(IBinaryRawReader reader) { _typeId = reader.ReadInt(); _typeName = reader.ReadString(); _affinityKeyFieldName = reader.ReadString(); _fields = reader.ReadDictionaryAsGeneric<string, int>(); _isEnum = reader.ReadBoolean(); } /// <summary> /// Initializes a new instance of the <see cref="BinaryType"/> class. /// </summary> /// <param name="desc">Descriptor.</param> /// <param name="fields">Fields.</param> public BinaryType(IBinaryTypeDescriptor desc, IDictionary<string, int> fields = null) : this (desc.TypeId, desc.TypeName, fields, desc.AffinityKeyFieldName, desc.IsEnum) { // No-op. } /// <summary> /// Constructor. /// </summary> /// <param name="typeId">Type ID.</param> /// <param name="typeName">Type name.</param> /// <param name="fields">Fields.</param> /// <param name="affKeyFieldName">Affinity key field name.</param> /// <param name="isEnum">Enum flag.</param> public BinaryType(int typeId, string typeName, IDictionary<string, int> fields, string affKeyFieldName, bool isEnum) { _typeId = typeId; _typeName = typeName; _affinityKeyFieldName = affKeyFieldName; _fields = fields; _isEnum = isEnum; } /// <summary> /// Type ID. /// </summary> /// <returns></returns> public int TypeId { get { return _typeId; } } /// <summary> /// Gets type name. /// </summary> public string TypeName { get { return _typeName; } } /// <summary> /// Gets field names for that type. /// </summary> public ICollection<string> Fields { get { return _fields != null ? _fields.Keys : EmptyList; } } /// <summary> /// Gets field type for the given field name. /// </summary> /// <param name="fieldName">Field name.</param> /// <returns> /// Field type. /// </returns> public string GetFieldTypeName(string fieldName) { if (_fields != null) { int typeId; _fields.TryGetValue(fieldName, out typeId); return GetTypeName(typeId); } return null; } /// <summary> /// Gets optional affinity key field name. /// </summary> public string AffinityKeyFieldName { get { return _affinityKeyFieldName; } } /** <inheritdoc /> */ public bool IsEnum { get { return _isEnum; } } /// <summary> /// Gets fields map. /// </summary> /// <returns>Fields map.</returns> public IDictionary<string, int> GetFieldsMap() { return _fields ?? EmptyDict; } } }
using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Dwm { #region Enumerations // Specifies which command is passed through the BlurBehindProperties structure [Flags()] internal enum BlurBehindFlags { Enable = 0x0001, // Enable Blur Behind BlurRegion = 0x0002, // Define blur region TransitionOnMaximized = 0x0004 // Color transition to maximized } #endregion #region Structures /// <summary> /// Stores a set of four integers defining the margins of an extended frame /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Margins { // Private members private int leftWidth; private int rightWidth; private int topHeight; private int bottomHeight; /// <summary> /// </summary> /// <param name="leftWidth">Left width of the extended frame</param> /// <param name="rightWidth">Right width of the extended frame</param> /// <param name="topHeight">Top height of the extended frame</param> /// <param name="bottomHeight">Bottom height of the extended frame</param> public Margins(int leftWidth, int rightWidth, int topHeight, int bottomHeight) { this.leftWidth = leftWidth; this.rightWidth = rightWidth; this.topHeight = topHeight; this.bottomHeight = bottomHeight; } /// <summary> /// Gets or sets the left width /// </summary> public int LeftWidth { get { return leftWidth; } set { leftWidth = value; } } /// <summary> /// Gets or sets the right width /// </summary> public int RightWidth { get { return rightWidth; } set { rightWidth = value; } } /// <summary> /// Gets or sets the top height /// </summary> public int TopHeight { get { return topHeight; } set { topHeight = value; } } /// <summary> /// Gets or sets the bottom height /// </summary> public int BottomHeight { get { return bottomHeight; } set { bottomHeight = value; } } } // Stores the Blur Behind properties and a flag to indicate which properties // are set by the DwmEnableBlurBehindWindow method [StructLayout(LayoutKind.Sequential)] internal struct BlurBehindProperties { public BlurBehindFlags flags; // Flag public bool enable; // Enable or disable Blur Behind public IntPtr rgnBlur; // Region to which blur is applied public bool transitionOnMaximized; // Enable or disable transition on maximized } #endregion /// <summary> /// Provides Blur Behind functionality to a form /// <remarks>Although it is a part of Blur Behind, extending the frame into the client /// area is actually mutually exclusive with the blur effect so only one of them can /// be applied to a form at any time.</remarks> /// </summary> public class BlurBehind { // Form handle private IntPtr hwnd; // Stores the state of Blur Behind private bool enabled = false; // Existance of extended frame private bool extendedFrame = false; // Properties - this structure is passed to the DwmEnableBlurBehindWindow method private BlurBehindProperties properties; /// <summary> /// Creates a new instance of BlurBehind from the given handle /// </summary> /// <param name="hwnd">Handle of a form to which Blur Behind will be applied</param> public BlurBehind(IntPtr hwnd) { this.hwnd = hwnd; // Create properties structure properties = new BlurBehindProperties(); } /// <summary> /// Creates a new instance of BlurBehind from the given form /// </summary> /// <param name="form">Form to which Blur Behind will be applied</param> public BlurBehind(Form form) : this(form.Handle) { } /// <summary> /// Sets the status of Blur Behind /// </summary> /// <param name="enabled">True to enable Blur Behind, false to disable Blur Behind</param> public void SetBlurBehind(bool enabled) { // Extended frames and blur are mutually exclusive so extended frame must be // deactivated when blur is activated if (enabled && extendedFrame) { RemoveExtendedFrame(); } // Prepare command properties.flags = BlurBehindFlags.Enable; properties.enable = enabled; // Retain Blur Behind state this.enabled = enabled; // Native API call DwmEnableBlurBehindWindow(hwnd, ref properties); } /// <summary> /// Sets the region to which blur is applied /// </summary> /// <param name="region">Region that defines the area to which blur will be applied.</param> public void SetBlurBehindRegion(Region region) { // Check if Blur Behind is disabled and enable it if (!enabled) { SetBlurBehind(true); } // Prepare command properties.flags = BlurBehindFlags.BlurRegion; // A null region means the whole form will be blurred if (region != null) { // A Graphics reference is also needed to identify the surface this region // belongs to but we get that from the form handle properties.rgnBlur = region.GetHrgn(Graphics.FromHwnd(hwnd)); } else { // Set property to NULL so the whole form will be blurred properties.rgnBlur = IntPtr.Zero; } // Native API call DwmEnableBlurBehindWindow(hwnd, ref properties); } /// <summary> /// Sets the color transition to maximized /// </summary> /// <param name="transition">True to perform the color transition, false otherwise</param> public void SetTransitionOnMaximized(bool transition) { // Prepare command properties.flags = BlurBehindFlags.TransitionOnMaximized; properties.transitionOnMaximized = transition; // Native API call DwmEnableBlurBehindWindow(hwnd, ref properties); } /// <summary> /// Extends the frame of the form into the client area /// </summary> /// <param name="margins">The margins that define the frame extention</param> public void ExtendFrameIntoClientArea(Margins margins) { // We check if all margin elements are 0, because that means the extended frame // will be disabled extendedFrame = !((margins.LeftWidth == 0) && (margins.RightWidth == 0) && (margins.TopHeight == 0) && (margins.BottomHeight == 0)); // If Blur Behind is enabled it must be disabled because it is mutually exclusive // with the extended frame. if (enabled && extendedFrame) { // Deactivate Blur Behind SetBlurBehind(false); } // Native API call DwmExtendFrameIntoClientArea(hwnd, ref margins); } /// <summary> /// Removes the extended frame /// </summary> public void RemoveExtendedFrame() { // We just need to call ExtendFrameIntoClientArea with all margin elements set to 0 ExtendFrameIntoClientArea(new Margins()); } /// <summary> /// Gets a value indicating if Blur Behind is enabled /// </summary> public bool Enabled { get { return enabled; } } /// <summary> /// Gets a value indicating if the frame is extended /// </summary> public bool ExtendedFrame { get { return extendedFrame; } } #region API imports [DllImport("dwmapi.dll", PreserveSig = false)] private static extern void DwmEnableBlurBehindWindow(IntPtr hwnd, ref BlurBehindProperties blurBehind); [DllImport("dwmapi.dll", PreserveSig = false)] private static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Margins margins); #endregion } }
namespace Oculus.Platform.Samples.VrVoiceChat { using UnityEngine; using System; using Oculus.Platform; using Oculus.Platform.Models; // Helper class to manage a Peer-to-Peer connection to the other user. // The connection is used to send and received the Transforms for the // Avatars. The Transforms are sent via unreliable UDP at a fixed // frequency. public class P2PManager { // number of seconds to delay between transform updates private static readonly float UPDATE_DELAY = 0.1f; // the ID of the remote player we expect to be connected to private ulong m_remoteID; // the result of the last connection state update message private PeerConnectionState m_state = PeerConnectionState.Unknown; // the next time to send an updated transform to the remote User private float m_timeForNextUpdate; // the size of the packet we are sending and receiving private static readonly byte PACKET_SIZE = 29; // packet format type just in case we want to add new future packet types private static readonly byte PACKET_FORMAT = 0; // reusable buffer to serialize the Transform into private readonly byte[] sendTransformBuffer = new byte[PACKET_SIZE]; // reusable buffer to deserialize the Transform into private readonly byte[] receiveTransformBuffer = new byte[PACKET_SIZE]; // the last received position update private Vector3 receivedPosition; // the previous received position to interpolate from private Vector3 receivedPositionPrior; // the last received rotation update private Quaternion receivedRotation; // the previous received rotation to interpolate from private Quaternion receivedRotationPrior; // when the last transform was received private float receivedTime; public P2PManager(Transform initialHeadTransform) { receivedPositionPrior = receivedPosition = initialHeadTransform.localPosition; receivedRotationPrior = receivedRotation = initialHeadTransform.localRotation; Net.SetPeerConnectRequestCallback(PeerConnectRequestCallback); Net.SetConnectionStateChangedCallback(ConnectionStateChangedCallback); } #region Connection Management public void ConnectTo(ulong userID) { m_remoteID = userID; // ID comparison is used to decide who calls Connect and who calls Accept if (PlatformManager.MyID < userID) { Net.Connect(userID); } } public void Disconnect() { if (m_remoteID != 0) { Net.Close(m_remoteID); m_remoteID = 0; m_state = PeerConnectionState.Unknown; } } public bool Connected { get { return m_state == PeerConnectionState.Connected; } } void PeerConnectRequestCallback(Message<NetworkingPeer> msg) { Debug.LogFormat("Connection request from {0}, authorized is {1}", msg.Data.ID, m_remoteID); if (msg.Data.ID == m_remoteID) { Net.Accept(msg.Data.ID); } } void ConnectionStateChangedCallback(Message<NetworkingPeer> msg) { Debug.LogFormat("Connection state to {0} changed to {1}", msg.Data.ID, msg.Data.State); if (msg.Data.ID == m_remoteID) { m_state = msg.Data.State; if (m_state == PeerConnectionState.Timeout && // ID comparison is used to decide who calls Connect and who calls Accept PlatformManager.MyID < m_remoteID) { // keep trying until hangup! Net.Connect(m_remoteID); } } PlatformManager.SetBackgroundColorForState(); } #endregion #region Send Update public bool ShouldSendHeadUpdate { get { return Time.time >= m_timeForNextUpdate && m_state == PeerConnectionState.Connected; } } public void SendHeadTransform(Transform headTransform) { m_timeForNextUpdate = Time.time + UPDATE_DELAY; sendTransformBuffer[0] = PACKET_FORMAT; int offset = 1; PackFloat(headTransform.localPosition.x, sendTransformBuffer, ref offset); PackFloat(headTransform.localPosition.y, sendTransformBuffer, ref offset); PackFloat(headTransform.localPosition.z, sendTransformBuffer, ref offset); PackFloat(headTransform.localRotation.x, sendTransformBuffer, ref offset); PackFloat(headTransform.localRotation.y, sendTransformBuffer, ref offset); PackFloat(headTransform.localRotation.z, sendTransformBuffer, ref offset); PackFloat(headTransform.localRotation.w, sendTransformBuffer, ref offset); Net.SendPacket(m_remoteID, sendTransformBuffer, SendPolicy.Unreliable); } void PackFloat(float f, byte[] buf, ref int offset) { Buffer.BlockCopy(BitConverter.GetBytes(f), 0, buf, offset, 4); offset = offset + 4; } #endregion #region Receive Update public void GetRemoteHeadTransform(Transform headTransform) { bool hasNewTransform = false; Packet packet; while ((packet = Net.ReadPacket()) != null) { if (packet.Size != PACKET_SIZE) { Debug.Log("Invalid packet size: " + packet.Size); continue; } packet.ReadBytes(receiveTransformBuffer); if (receiveTransformBuffer[0] != PACKET_FORMAT) { Debug.Log("Invalid packet type: " + packet.Size); continue; } hasNewTransform = true; } if (hasNewTransform) { receivedPositionPrior = receivedPosition; receivedPosition.x = BitConverter.ToSingle(receiveTransformBuffer, 1); receivedPosition.y = BitConverter.ToSingle(receiveTransformBuffer, 5); receivedPosition.z = BitConverter.ToSingle(receiveTransformBuffer, 9); receivedRotationPrior = receivedRotation; receivedRotation.x = BitConverter.ToSingle(receiveTransformBuffer, 13); receivedRotation.y = BitConverter.ToSingle(receiveTransformBuffer, 17) * -1.0f; receivedRotation.z = BitConverter.ToSingle(receiveTransformBuffer, 21); receivedRotation.w = BitConverter.ToSingle(receiveTransformBuffer, 25) * -1.0f; receivedTime = Time.time; } // since we're receiving updates at a slower rate than we render, // interpolate to make the motion look smoother float completed = Math.Min(Time.time - receivedTime, UPDATE_DELAY) / UPDATE_DELAY; headTransform.localPosition = Vector3.Lerp(receivedPositionPrior, receivedPosition, completed); headTransform.localRotation = Quaternion.Slerp(receivedRotationPrior, receivedRotation, completed); } #endregion } }
/* * 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 Amazon.Runtime; namespace Amazon.S3.Model { /// <summary> /// Returns information about the ListObjects response and response metadata. /// </summary> public class ListObjectsV2Response : AmazonWebServiceResponse { private bool? isTruncated; private List<S3Object> contents = new List<S3Object>(); private string name; private string prefix; private string delimiter; private int? maxKeys; private List<string> commonPrefixes = new List<string>(); private EncodingType encoding; private int? keyCount; private string continuationToken; private string nextContinuationToken; private string startAfter; /// <summary> /// A flag that indicates whether or not Amazon S3 returned all of the results that satisfied /// the search criteria. /// </summary> public bool IsTruncated { get { return this.isTruncated ?? default(bool); } set { this.isTruncated = value; } } // Check to see if IsTruncated property is set internal bool IsSetIsTruncated() { return this.isTruncated.HasValue; } /// <summary> /// Gets and sets the S3Objects property. Metadata about each object returned. /// </summary> public List<S3Object> S3Objects { get { return this.contents; } set { this.contents = value; } } // Check to see if Contents property is set internal bool IsSetContents() { return this.contents.Count > 0; } /// <summary> /// Gets and sets the Name property. The name of the bucket that was listed. /// </summary> public string Name { get { return this.name; } set { this.name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this.name != null; } /// <summary> /// Gets and sets the Prefix property. /// </summary> public string Prefix { get { return this.prefix; } set { this.prefix = value; } } // Check to see if Prefix property is set internal bool IsSetPrefix() { return this.prefix != null; } /// <summary> /// Gets and sets the MaxKeys property. This is max number of object keys returned by the list operation. /// </summary> public int MaxKeys { get { return this.maxKeys ?? default(int); } set { this.maxKeys = value; } } // Check to see if MaxKeys property is set internal bool IsSetMaxKeys() { return this.maxKeys.HasValue; } /// <summary> /// Gets and sets the CommonPrefixes property. /// CommonPrefixes contains all (if there are any) keys between Prefix and the next occurrence /// of the string specified by delimiter /// </summary> public List<string> CommonPrefixes { get { return this.commonPrefixes; } set { this.commonPrefixes = value; } } // Check to see if CommonPrefixes property is set internal bool IsSetCommonPrefixes() { return this.commonPrefixes.Count > 0; } /// <summary> /// Gets and sets the Delimiter property. /// Causes keys that contain the same string between the prefix and the /// first occurrence of the delimiter to be rolled up into a single result /// element in the CommonPrefixes collection. /// </summary> /// <remarks> /// These rolled-up keys are not returned elsewhere in the response. /// </remarks> public string Delimiter { get { return this.delimiter; } set { this.delimiter = value; } } /// <summary> /// Encoding type used by Amazon S3 to encode object keys in the response. /// </summary> public EncodingType Encoding { get { return this.encoding; } set { this.encoding = value; } } // Check to see if DeleteMarker property is set internal bool IsSetEncoding() { return this.encoding != null; } /// <summary> /// KeyCount is the number of keys returned with this request. /// KeyCount will always be less than or equal to MaxKeys field. /// </summary> public int KeyCount { get { return this.keyCount ?? default(int); } set { this.keyCount = value; } } // Check to see if KeyCount property is set internal bool IsSetKeyCount() { return this.keyCount.HasValue; } /// <summary> /// ContinuationToken indicates Amazon S3 that the list is being continued /// on this bucket with a token. /// ContinuationToken is obfuscated and is not a real key /// </summary> public string ContinuationToken { get { return this.continuationToken; } set { this.continuationToken = value; } } // Check to see if ContinuationToken property is set internal bool IsSetContinuationToken() { return this.continuationToken != null; } /// <summary> /// NextContinuationToken is sent when isTruncated is true which means there /// are more keys in the bucket that can be listed. The next ListObjectV2 call /// to Amazon S3 can be continued with this NextContinuationToken. /// NextContinuationToken is obfuscated and is not a real key. /// </summary> public string NextContinuationToken { get { return this.nextContinuationToken; } set { this.nextContinuationToken = value; } } // Check to see if NextContinuationToken property is set internal bool IsSetNextContinuationToken() { return this.nextContinuationToken != null; } /// <summary> /// StartAfter is where you want Amazon S3 to start listing from. /// Amazon S3 starts listing after this specified key. /// StartAfter can be any key in the bucket. /// </summary> public string StartAfter { get { return this.startAfter; } set { this.startAfter = value; } } // Check to see if StartKey property is set internal bool IsSetStartAfter() { return this.startAfter != null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #region Using directives using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// The command returns zero, one or more CimSession objects that represent /// connections with remote computers established from the current PS Session. /// </summary> [Cmdlet(VerbsCommon.Get, "CimSession", DefaultParameterSetName = ComputerNameSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227966")] [OutputType(typeof(CimSession))] public sealed class GetCimSessionCommand : CimBaseCommand { #region constructor /// <summary> /// Constructor. /// </summary> public GetCimSessionCommand() : base(parameters, parameterSets) { DebugHelper.WriteLogEx(); } #endregion #region parameters /// <summary> /// <para> /// The following is the definition of the input parameter "ComputerName". /// Specifies one or more connections by providing their ComputerName(s). The /// Cmdlet then gets CimSession(s) opened with those connections. This parameter /// is an alternative to using CimSession(s) that also identifies the remote /// computer(s). /// </para> /// <para> /// This is the only optional parameter of the Cmdlet. If not provided, the /// Cmdlet returns all CimSession(s) live/active in the runspace. /// </para> /// <para> /// If an instance of CimSession is pipelined to Get-CimSession, the /// ComputerName property of the instance is bound by name with this parameter. /// </para> /// </summary> [Alias(AliasCN, AliasServerName)] [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = ComputerNameSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ComputerName { get { return computername;} set { computername = value; base.SetParameter(value, nameComputerName); } } private string[] computername; /// <summary> /// The following is the definition of the input parameter "Id". /// Specifies one or more numeric Id(s) for which to get CimSession(s). /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = SessionIdSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public UInt32[] Id { get { return id;} set { id = value; base.SetParameter(value, nameId); } } private UInt32[] id; /// <summary> /// The following is the definition of the input parameter "InstanceID". /// Specifies one or Session Instance IDs. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = InstanceIdSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Guid[] InstanceId { get { return instanceid;} set { instanceid = value; base.SetParameter(value, nameInstanceId); } } private Guid[] instanceid; /// <summary> /// The following is the definition of the input parameter "Name". /// Specifies one or more session Name(s) for which to get CimSession(s). The /// argument may contain wildcard characters. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = NameSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Name { get { return name;} set { name = value; base.SetParameter(value, nameName); } } private string[] name; #endregion #region cmdlet processing methods /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { cimGetSession = new CimGetSession(); this.AtBeginProcess = false; } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { base.CheckParameterSet(); cimGetSession.GetCimSession(this); } #endregion #region private members /// <summary> /// <see cref="CimGetSession"/> object used to search CimSession from cache. /// </summary> private CimGetSession cimGetSession; #region const string of parameter names internal const string nameComputerName = "ComputerName"; internal const string nameId = "Id"; internal const string nameInstanceId = "InstanceId"; internal const string nameName = "Name"; #endregion /// <summary> /// Static parameter definition entries. /// </summary> static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>> { { nameComputerName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ComputerNameSet, false), } }, { nameId, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.SessionIdSet, true), } }, { nameInstanceId, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.InstanceIdSet, true), } }, { nameName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.NameSet, true), } }, }; /// <summary> /// Static parameter set entries. /// </summary> static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry> { { CimBaseCommand.ComputerNameSet, new ParameterSetEntry(0, true) }, { CimBaseCommand.SessionIdSet, new ParameterSetEntry(1) }, { CimBaseCommand.InstanceIdSet, new ParameterSetEntry(1) }, { CimBaseCommand.NameSet, new ParameterSetEntry(1) }, }; #endregion } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System.Collections; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Support; using Spring.Objects.Factory.Xml; #endregion namespace Spring.Objects.Factory { /// <summary> /// Unit tests for the ObjectFactoryUtils class. /// </summary> /// <author>Rod Johnson</author> /// <author>Simon White (.NET)</author> /// <author>Rick Evans (.NET)</author> [TestFixture] public sealed class ObjectFactoryUtilsTests { private IConfigurableListableObjectFactory _factory; [SetUp] public void SetUp() { IObjectFactory grandparent = new XmlObjectFactory(new ReadOnlyXmlTestResource("root.xml", GetType())); IObjectFactory parent = new XmlObjectFactory(new ReadOnlyXmlTestResource("middle.xml", GetType()), grandparent); IConfigurableListableObjectFactory child = new XmlObjectFactory(new ReadOnlyXmlTestResource("leaf.xml", GetType()), parent); _factory = child; } /// <summary> /// Check that override doesn't count as two separate objects. /// </summary> [Test] public void CountObjectsIncludingAncestors() { // leaf count... Assert.AreEqual(1, _factory.ObjectDefinitionCount); // count minus duplicate... Assert.AreEqual(6, ObjectFactoryUtils.CountObjectsIncludingAncestors(_factory), "Should count 6 objects, not " + ObjectFactoryUtils.CountObjectsIncludingAncestors(_factory)); } [Test] public void ObjectNamesIncludingAncestors() { var names = ObjectFactoryUtils.ObjectNamesIncludingAncestors(_factory); Assert.AreEqual(6, names.Count); } [Test] public void ObjectNamesForTypeIncludingAncestors() { var names = ObjectFactoryUtils.ObjectNamesForTypeIncludingAncestors(_factory, typeof(ITestObject)); // includes 2 TestObjects from IFactoryObjects (DummyFactory definitions) Assert.AreEqual(4, names.Count); Assert.IsTrue(names.Contains("test")); Assert.IsTrue(names.Contains("test3")); Assert.IsTrue(names.Contains("testFactory1")); Assert.IsTrue(names.Contains("testFactory2")); } [Test] public void ObjectNamesForTypeIncludingAncestorsExcludesObjectsFromParentWhenLocalObjectDefined() { DefaultListableObjectFactory root = new DefaultListableObjectFactory(); root.RegisterObjectDefinition("excludeLocalObject", new RootObjectDefinition(typeof(ArrayList))); DefaultListableObjectFactory child = new DefaultListableObjectFactory(root); child.RegisterObjectDefinition("excludeLocalObject", new RootObjectDefinition(typeof(Hashtable))); var names = ObjectFactoryUtils.ObjectNamesForTypeIncludingAncestors(child, typeof(ArrayList)); // "excludeLocalObject" matches on the parent, but not the local object definition Assert.AreEqual(0, names.Count); names = ObjectFactoryUtils.ObjectNamesForTypeIncludingAncestors(child, typeof(ArrayList), true, true); // "excludeLocalObject" matches on the parent, but not the local object definition Assert.AreEqual(0, names.Count); } [Test] public void CountObjectsIncludingAncestorsWithNonHierarchicalFactory() { StaticListableObjectFactory lof = new StaticListableObjectFactory(); lof.AddObject("t1", new TestObject()); lof.AddObject("t2", new TestObject()); Assert.IsTrue(ObjectFactoryUtils.CountObjectsIncludingAncestors(lof) == 2); } [Test] public void HierarchicalResolutionWithOverride() { object test3 = _factory.GetObject("test3"); object test = _factory.GetObject("test"); object testFactory1 = _factory.GetObject("testFactory1"); IDictionary<string, object> objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(_factory, typeof(ITestObject), true, false); Assert.AreEqual(3, objects.Count); Assert.AreEqual(test3, objects["test3"]); Assert.AreEqual(test, objects["test"]); Assert.AreEqual(testFactory1, objects["testFactory1"]); objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(_factory, typeof(ITestObject), false, false); Assert.AreEqual(2, objects.Count); Assert.AreEqual(test, objects["test"]); Assert.AreEqual(testFactory1, objects["testFactory1"]); objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(_factory, typeof(ITestObject), false, true); Assert.AreEqual(2, objects.Count); Assert.AreEqual(test, objects["test"]); Assert.AreEqual(testFactory1, objects["testFactory1"]); objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(_factory, typeof(ITestObject), true, true); Assert.AreEqual(4, objects.Count); Assert.AreEqual(test3, objects["test3"]); Assert.AreEqual(test, objects["test"]); Assert.AreEqual(testFactory1, objects["testFactory1"]); Assert.IsTrue(objects["testFactory2"] is ITestObject); objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(_factory, typeof(DummyFactory), true, true); Assert.AreEqual(2, objects.Count); Assert.AreEqual(_factory.GetObject("&testFactory1"), objects["&testFactory1"]); Assert.AreEqual(_factory.GetObject("&testFactory2"), objects["&testFactory2"]); objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(_factory, typeof(IFactoryObject), true, true); Assert.AreEqual(2, objects.Count); Assert.AreEqual(_factory.GetObject("&testFactory1"), objects["&testFactory1"]); Assert.AreEqual(_factory.GetObject("&testFactory2"), objects["&testFactory2"]); } [Test] public void ObjectOfTypeIncludingAncestorsWithMoreThanOneObjectOfType() { Assert.Throws<NoSuchObjectDefinitionException>( () => ObjectFactoryUtils.ObjectOfTypeIncludingAncestors(_factory, typeof(ITestObject), true, true), "No unique object of type [Spring.Objects.ITestObject] is defined : Expected single object but found 4"); } [Test] public void ObjectOfTypeIncludingAncestorsExcludesObjectsFromParentWhenLocalObjectDefined() { DefaultListableObjectFactory root = new DefaultListableObjectFactory(); root.RegisterObjectDefinition("excludeLocalObject", new RootObjectDefinition(typeof(ArrayList))); DefaultListableObjectFactory child = new DefaultListableObjectFactory(root); child.RegisterObjectDefinition("excludeLocalObject", new RootObjectDefinition(typeof(Hashtable))); IDictionary<string, object> objectEntries = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(child, typeof(ArrayList), true, true); // "excludeLocalObject" matches on the parent, but not the local object definition Assert.AreEqual(0, objectEntries.Count); } [Test] public void NoObjectsOfTypeIncludingAncestors() { StaticListableObjectFactory lof = new StaticListableObjectFactory(); lof.AddObject("foo", new object()); IDictionary<string, object> objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(lof, typeof(ITestObject), true, false); Assert.IsTrue(objects.Count == 0); } [Test] public void ObjectsOfTypeIncludingAncestorsWithStaticFactory() { StaticListableObjectFactory lof = new StaticListableObjectFactory(); TestObject t1 = new TestObject(); TestObject t2 = new TestObject(); DummyFactory t3 = new DummyFactory(); DummyFactory t4 = new DummyFactory(); t4.IsSingleton = false; lof.AddObject("t1", t1); lof.AddObject("t2", t2); lof.AddObject("t3", t3); t3.AfterPropertiesSet(); // StaticListableObjectFactory does support lifecycle calls. lof.AddObject("t4", t4); t4.AfterPropertiesSet(); // StaticListableObjectFactory does support lifecycle calls. IDictionary<string, object> objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(lof, typeof(ITestObject), true, false); Assert.AreEqual(2, objects.Count); Assert.AreEqual(t1, objects["t1"]); Assert.AreEqual(t2, objects["t2"]); objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(lof, typeof(ITestObject), false, true); Assert.AreEqual(3, objects.Count); Assert.AreEqual(t1, objects["t1"]); Assert.AreEqual(t2, objects["t2"]); Assert.AreEqual(t3.GetObject(), objects["t3"]); objects = ObjectFactoryUtils.ObjectsOfTypeIncludingAncestors(lof, typeof(ITestObject), true, true); Assert.AreEqual(4, objects.Count); Assert.AreEqual(t1, objects["t1"]); Assert.AreEqual(t2, objects["t2"]); Assert.AreEqual(t3.GetObject(), objects["t3"]); Assert.IsTrue(objects["t4"] is TestObject); } [Test] public void IsFactoryDereferenceWithNonFactoryObjectName() { Assert.IsFalse(ObjectFactoryUtils.IsFactoryDereference("roob"), "Name that didn't start with the factory object prefix is being reported " + "(incorrectly) as a factory object dereference."); } [Test] public void IsFactoryDereferenceWithNullName() { Assert.IsFalse(ObjectFactoryUtils.IsFactoryDereference(null), "Null name that (obviously) didn't start with the factory object prefix is being reported " + "(incorrectly) as a factory object dereference."); } [Test] public void IsFactoryDereferenceWithEmptyName() { Assert.IsFalse(ObjectFactoryUtils.IsFactoryDereference(string.Empty), "String.Empty name that (obviously) didn't start with the factory object prefix is being reported " + "(incorrectly) as a factory object dereference."); } [Test] public void IsFactoryDereferenceWithJustTheFactoryObjectPrefixCharacter() { Assert.IsFalse(ObjectFactoryUtils.IsFactoryDereference( ObjectFactoryUtils.FactoryObjectPrefix), "Name that consisted solely of the factory object prefix is being reported " + "(incorrectly) as a factory object dereference."); } [Test] public void IsFactoryDereferenceSunnyDay() { Assert.IsTrue(ObjectFactoryUtils.IsFactoryDereference( ObjectFactoryUtils.FactoryObjectPrefix + "roob"), "Name that did start with the factory object prefix is not being reported " + "(incorrectly) as a factory object dereference."); } } }
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using TribalWars.Browsers.Reporting; using TribalWars.Browsers.Translations; namespace TribalWars.Browsers.Parsers { /// <summary> /// Parses the document of the browser /// </summary> public class HtmlReportParser : IBrowserParser { #region Constants private const RegexOptions regexOptions = RegexOptions.Multiline | RegexOptions.Compiled; #endregion #region Fields private Regex _reportCoreRegex; private Regex _reportEspionageRegex; private Regex _reportRestRegex; #endregion #region Properties /// <summary> /// Gets the pattern for analysing the url /// </summary> public Regex UrlRegex { get { return null; } } /// <summary> /// Gets the pattern for analysing the document /// </summary> public Regex ReportCoreRegex { get { return _reportCoreRegex ?? (_reportCoreRegex = new Regex(GetReportCorePattern(), regexOptions)); } } /// <summary> /// Gets the pattern for analysing the document /// </summary> public Regex ReportEspionageRegex { get { return _reportEspionageRegex ?? (_reportEspionageRegex = new Regex(GetReportEspionagePattern(), regexOptions)); } } /// <summary> /// Gets the pattern for analysing the document /// </summary> public Regex ReportRestRegex { get { return _reportRestRegex ?? (_reportRestRegex = new Regex(GetReportRestPattern(), regexOptions)); } } #endregion #region Public Methods /// <summary> /// Checks if the current page is handled by the /// </summary> /// <param name="url">The browser Uri</param> public bool Handles(string url) { return url.IndexOf("screen=report") > -1; } /// <summary> /// Handles the parsing of the document /// </summary> /// <param name="document">The document Html</param> /// <param name="serverTime">Time the page was generated</param> public bool Handle(string document, DateTime serverTime) { int index = document.IndexOf(string.Format("<th width=\"140\">{0}</th>", TWWords.ReportSubject)); if (index == -1) return false; document = document.Substring(index); var matches = new Dictionary<string, Group>(); if (HandleReportCore(matches, document)) { bool testEspionage = HandleReportEspionage(matches, document); bool testRest = HandleReportRest(matches, document); var options = new ReportOutputOptions(); Report report = ReportParser.ParseHtmlMatch(matches, options); VillageReportCollection.Save(report); return true; } return false; } private bool HandleReportCore(Dictionary<string, Group> matches, string input) { _reportCoreRegex = new Regex(GetReportCorePattern(), regexOptions); Match match = ReportCoreRegex.Match(input); if (match.Success) { matches.Add("date", match.Groups["date"]); matches.Add("luck", match.Groups["luck"]); matches.Add("morale", match.Groups["morale"]); matches.Add("winner", match.Groups["winner"]); matches.Add("you", match.Groups["you"]); matches.Add("attacker", match.Groups["attacker"]); matches.Add("him", match.Groups["him"]); matches.Add("defender", match.Groups["defender"]); matches.Add("atforce", match.Groups["atforce"]); matches.Add("defforce", match.Groups["defforce"]); matches.Add("atloss", match.Groups["atloss"]); matches.Add("defloss", match.Groups["defloss"]); return true; } return false; } private bool HandleReportEspionage(Dictionary<string, Group> matches, string input) { _reportEspionageRegex = new Regex(GetReportEspionagePattern(), regexOptions); Match match = ReportEspionageRegex.Match(input); if (match.Success) { matches.Add("resLeft", match.Groups["resLeft"]); matches.Add("buildings", match.Groups["buildings"]); matches.Add("unitsOutside", match.Groups["unitsOutside"]); return true; } return false; } private bool HandleReportRest(Dictionary<string, Group> matches, string input) { _reportRestRegex = new Regex(GetReportPatternOutside(), regexOptions); Match match = ReportRestRegex.Match(input); if (match.Success) { matches.Add("forcetransit", match.Groups["forcetransit"]); matches.Add("forceSupport", match.Groups["forceSupport"]); } _reportRestRegex = new Regex(GetReportPatternHaul(), regexOptions); match = ReportRestRegex.Match(input); if (match.Success) { matches.Add("res", match.Groups["res"]); matches.Add("haul", match.Groups["haul"]); matches.Add("haulMax", match.Groups["haulMax"]); } _reportRestRegex = new Regex(GetReportPatternRam(), regexOptions); match = ReportRestRegex.Match(input); if (match.Success) { matches.Add("ramBefore", match.Groups["ramBefore"]); matches.Add("ramAfter", match.Groups["ramAfter"]); } _reportRestRegex = new Regex(GetReportPatternCata(), regexOptions); match = ReportRestRegex.Match(input); if (match.Success) { matches.Add("catBuilding", match.Groups["catBuilding"]); matches.Add("catBefore", match.Groups["catBefore"]); matches.Add("catAfter", match.Groups["catAfter"]); } _reportRestRegex = new Regex(GetReportPatternLoyalty(), regexOptions); match = ReportRestRegex.Match(input); if (match.Success) { matches.Add("loyaltyBegin", match.Groups["loyaltyBegin"]); matches.Add("loyaltyEnd", match.Groups["loyaltyEnd"]); } return true; } private string GetReportPatternCata() { var pattern = new StringBuilder(); pattern.Append(string.Format(@"\<tr\>\<th\>{0}:\</th\>\s*", TWWords.ReportCatas)); pattern.Append(string.Format(@"\<td colspan=""2""\>({2} )?(?<catBuilding>\w*) {0}\s?\<b\>(?<catBefore>\d*)\</b\> {1}\s?\<b\>(?<catAfter>\d*)\</b\>\</td\>\</tr\>\s*", TWWords.ReportCatasPre, TWWords.ReportCatasBetween, TWWords.The)); return pattern.ToString(); } private string GetReportPatternLoyalty() { var pattern = new StringBuilder(); pattern.Append(string.Format(@"\<tr\>\<th\>{0}\</th\>\s*", TWWords.ReportLoyalty)); pattern.Append(string.Format(@"\<td colspan=""2""\>{0} \<b\>(?<loyaltyBegin>\d*)\</b\> {1} \<b\>(?<loyaltyEnd>-?\d*)\</b\>\</td\>\</tr\>", TWWords.ReportLoyaltyPre, TWWords.ReportLoyaltyBetween)); return pattern.ToString(); } private string GetReportPatternRam() { var pattern = new StringBuilder(); pattern.Append(string.Format(@"\<tr\>\<th\>{0}:\</th\>\s*", TWWords.ReportRams)); pattern.Append(string.Format(@"\<td colspan=""2""\>{0} \<b\>(?<ramBefore>\d*)\</b\> {1} \<b\>(?<ramAfter>\d*)\</b\>\</td\>\</tr\>\s*", TWWords.ReportRamsPre, TWWords.ReportRamsBetween)); return pattern.ToString(); } private string GetReportPatternHaul() { var pattern = new StringBuilder(); pattern.Append(@"\<table width=""100%"" style=""border: 1px solid #DED3B9""\>\s*"); pattern.Append(string.Format(@"\<tr\>\<th\>{0}:\</th\>\s*\<td width=""220""\>", TWWords.ReportHaul)); pattern.Append(string.Format(@"(?<res>\<img src="".*\.png(\?1)?"" title=""({0}|{1}|{2})"" alt="""" /\>(\d*\<span class=""grey""\>\.\</span\>)?\d*\s*){{0,3}}\</td\>\s*", TWWords.Wood, TWWords.Clay, TWWords.Iron)); pattern.Append(@"\<td\>(?<haul>\d*)/(?<haulMax>\d*)\</td\>\s*\</tr\>\s*"); return pattern.ToString(); } private string GetReportPatternOutside() { var pattern = new StringBuilder(); pattern.Append(string.Format(@"\<h4\>{0}\</h4\>\s*", TWWords.ReportUnitsInTransit)); pattern.Append(@"\<table\>\s*"); pattern.Append(@"\<tr\>(\<th width=""35""\>\<img src="".*\.png(\?1)?"" title="".*"" alt="""" /\>\</th\>)+\</tr\>\s*"); pattern.Append(@"\<tr\>(?<forcetransit>\<td( class=""hidden"")?\>\d*\</td\>)*\s*\</tr\>\s*"); pattern.Append(@"\</table\>\s*"); pattern.Append(@"("); pattern.Append(string.Format(@"\<h4\>{0}\</h4\>\s*", TWWords.ReportUnitsOtherVillages)); pattern.Append(@"\<table\>\s*"); pattern.Append(@"\<tr\>\<th width=""200""\>\</th\>(\<th width=""15""\>\<img src="".*\.png(\?1)?"" title="".*"" alt="""" /\>\</th\>)+\</tr\>\s*"); pattern.Append(string.Format(@"(?<forceSupport>\<tr\>\<td\>\<a href=""/game\.php\?village=\d*&amp;screen=info_village&amp;id=\d*""\>.* \(\d*\|\d*\) {0}\d{{1,2}}\</a\>\</td\>", TWWords.ContinentAbreviation)); pattern.Append(@"(\<td( class=""hidden"")?\>\d*\</td\>)*\</tr\>\s*)*"); pattern.Append(@"\</table\>\s*"); pattern.Append(@")?"); return pattern.ToString(); } #endregion #region Private Methods /// <summary> /// Builds the pattern for matching document input /// </summary> private string GetReportCorePattern() { #region Example //<tr><td>Sent</td><td>Jun 29,2008 16:30</td></tr> //<tr><td colspan="2" valign="top" height="160" style="border: solid 1px black; padding: 4px;"> //<h3>The defender has won</h3> //<h4>Luck (from attacker's point of view)</h4> //<table><tr> // <td><b>-4.7%</b></td> // <td><img src="/graphic/rabe.png" alt="Misfortune" /></td> //<td> //<table style="border: 1px solid black;" cellspacing="0" cellpadding="0"> //<tr> // <td width="40.53732019" height="12"></td> // <td width="9.46267981" style="background-image:url(/graphic/balken_pech.png);"></td> // <td width="2" style="background-color:rgb(0, 0, 0)"></td> // <td width="0" style="background-image:url(/graphic/balken_glueck.png);"></td> // <td width="50"></td> //</tr> //</table> //</td> // <td><img src="/graphic/klee_grau.png" alt="luck" /></td> //</tr> //</table> //<table> //<tr><td><h4>Morale: 62%</h4></td></tr> //</table> //<br /> //<table width="100%" style="border: 1px solid #DED3B9"> //<tr><th width="100">Attacker:</th><th><a href="/game.php?village=99271&amp;screen=info_player&amp;id=1318012">Laoujin</a></th></tr> //<tr><td>Village:</td><td><a href="/game.php?village=99271&amp;screen=info_village&amp;id=86899">iier II (761|360) K37</a></td></tr> //<tr><td colspan="2"> // <table class="vis"> // <tr class="center"> // <td></td> // <td width="35"><img src="/graphic/unit/unit_spear.png" title="Spear fighter" alt="" /></td><td width="35"><img src="/graphic/unit/unit_sword.png" title="Swordsman" alt="" /></td><td width="35"><img src="/graphic/unit/unit_axe.png" title="Axeman" alt="" /></td><td width="35"><img src="/graphic/unit/unit_spy.png" title="Scout" alt="" /></td><td width="35"><img src="/graphic/unit/unit_light.png" title="Light cavalry" alt="" /></td><td width="35"><img src="/graphic/unit/unit_heavy.png" title="Heavy cavalry" alt="" /></td><td width="35"><img src="/graphic/unit/unit_ram.png" title="Ram" alt="" /></td><td width="35"><img src="/graphic/unit/unit_catapult.png" title="Catapult" alt="" /></td><td width="35"><img src="/graphic/unit/unit_snob.png" title="Nobleman" alt="" /></td> // </tr> // <tr class="center"> // <td>Quantity:</td> // <td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td>650</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td> // </tr> // <tr class="center"> // <td>Losses:</td> // <td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td>40</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td> // </tr> // </table> //</td></tr> //</table><br /> //<table width="100%" style="border: 1px solid #DED3B9"> //<tr><th width="100">Defender:</th><th>PrinceHector (deleted)</th></tr> //<tr><td>Village:</td><td><a href="/game.php?village=99271&amp;screen=info_village&amp;id=90425">Jaheira The Harper III (765|350) K37</a></td></tr> //<tr><td colspan="2"> // <table class="vis"> // <tr class="center"> // <td></td> // <td width="35"><img src="/graphic/unit/unit_spear.png" title="Spear fighter" alt="" /></td><td width="35"><img src="/graphic/unit/unit_sword.png" title="Swordsman" alt="" /></td><td width="35"><img src="/graphic/unit/unit_axe.png" title="Axeman" alt="" /></td><td width="35"><img src="/graphic/unit/unit_spy.png" title="Scout" alt="" /></td><td width="35"><img src="/graphic/unit/unit_light.png" title="Light cavalry" alt="" /></td><td width="35"><img src="/graphic/unit/unit_heavy.png" title="Heavy cavalry" alt="" /></td><td width="35"><img src="/graphic/unit/unit_ram.png" title="Ram" alt="" /></td><td width="35"><img src="/graphic/unit/unit_catapult.png" title="Catapult" alt="" /></td><td width="35"><img src="/graphic/unit/unit_snob.png" title="Nobleman" alt="" /></td> // </tr> // <tr class="center"> // <td>Quantity:</td> // <td>7</td><td class="hidden">0</td><td class="hidden">0</td><td>200</td><td>656</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td> // </tr> // <tr class="center"> // <td>Losses:</td> // <td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td> // </tr> // </table> //</td></tr> //</table><br /><br /> #endregion var pattern = new StringBuilder(); // Date, luck, morale, ... pattern.Append(string.Format(@"\<tr\>\<td\>{0}\</td\>\<td\>(?<date>.*)\</td\>\</tr\>", TWWords.ReportSent)); pattern.Append(@"[\s\S]*"); pattern.Append(string.Format(@"\<h3\>{0}\s*(?<winner>({1}|{2})) {3}\</h3\>", TWWords.The, TWWords.ReportAttackerLCase, TWWords.ReportDefenderLCase, TWWords.ReportHasWon)); pattern.Append(@"[\s\S]*"); pattern.Append(@"\s*\<td( style=""padding:0;"")?\>\<b\>(?<luck>-?\d{1,3}(\.\d{1,2})?%)\</b\>\</td\>"); pattern.Append(@"[\s\S]*"); pattern.Append(string.Format(@"\<tr\>\<td\>\<h4\>{0}: (?<morale>\S*%)\</h4\>\</td\>\</tr\>", TWWords.Morale)); pattern.Append(@"[\s\S]*"); // Attacker pattern.Append(@"\<table width=""100%"" style=""border: 1px solid #DED3B9""\>\s*"); pattern.Append(string.Format(@"\<tr\>\<th width=""100""\>{0}:\</th\>\<th\>(\<a href=""/game\.php\?village=\d*&amp;screen=info_player&amp;id=\d*""\>)?(?<attacker>.*)(\</a\>)?\</th\>\</tr\>\s*", TWWords.ReportAttacker)); pattern.Append(string.Format(@"\<tr\>\<td\>{0}:\</td\>\<td\>\<a href=""/game\.php\?village=\d*&amp;screen=info_village&amp;id=\d*""\>(?<you>.*)\</a\>\</td\>\</tr\>\s*", TWWords.Village)); pattern.Append(@"\<tr\>\<td colspan=""2""\>\s*"); pattern.Append(@"\<table class=""vis""\>\s*"); pattern.Append(@"\<tr class=""center""\>\s*"); pattern.Append(@"\<td\>\</td\>\s*"); pattern.Append(@"(\<td width=""35""\>\<img src="".*\.png(\?1)?"" title="".*"" alt="""" /\>\</td\>)+\s*"); pattern.Append(@"\</tr\>\s*"); pattern.Append(@"\<tr class=""center""\>\s*"); pattern.Append(string.Format(@"\<td\>{0}:\</td\>\s*", TWWords.ReportQuantity)); pattern.Append(@"(?<atforce>\<td( class=""hidden"")?\>\d*\</td\>)*\s*\</tr\>\s*"); pattern.Append(@"\<tr class=""center""\>\s*"); pattern.Append(string.Format(@"\<td\>{0}:\</td\>\s*", TWWords.ReportLosses)); pattern.Append(@"(?<atloss>\<td( class=""hidden"")?\>\d*\</td\>)*\s*\</tr\>\s*"); pattern.Append(@"[\s\S]*"); //<tr><td>Village:</td><td><a href="/game.php?village=85946&amp;screen=info_village&amp;id=86973">002 K27 A New Begining (703|284) K27</a></td></tr> //<tr><td colspan="2"> // <p>None of your troops have returned. No information about the strength of your enemy's army could be collected.</p> //</td></tr> //</table><br /><br /> // Defender pattern.Append(string.Format(@"\<tr\>\<th width=""100""\>{0}:\</th\>\<th\>(\<a href=""/game\.php\?village=\d*&amp;screen=info_player&amp;id=\d*""\>)?(?<defender>.*)(\</a\>)?\</th\>\</tr\>\s*", TWWords.ReportDefender)); pattern.Append(string.Format(@"\<tr\>\<td\>{0}:\</td\>\<td\>\<a href=""/game\.php\?village=\d*&amp;screen=info_village&amp;id=\d*""\>(?<him>.*)\</a\>\</td\>\</tr\>\s*", TWWords.Village)); pattern.Append(@"\<tr\>\<td colspan=""2""\>\s*"); pattern.Append(string.Format(@"((\<p\>{0}\</p\>)|(", TWWords.ReportNoDefense.Replace(".", @"\."))); pattern.Append(@"\<table class=""vis""\>\s*"); pattern.Append(@"\<tr class=""center""\>\s*"); pattern.Append(@"\<td\>\</td\>\s*"); pattern.Append(@"(\<td width=""35""\>\<img src="".*\.png(\?1)?"" title="".*"" alt="""" /\>\</td\>)+\s*"); pattern.Append(@"\</tr\>\s*"); pattern.Append(@"\<tr class=""center""\>\s*"); pattern.Append(string.Format(@"\<td\>{0}:\</td\>\s*", TWWords.ReportQuantity)); pattern.Append(@"(?<defforce>\<td( class=""hidden"")?\>\d*\</td\>)*\s*\</tr\>\s*"); pattern.Append(@"\<tr class=""center""\>\s*"); pattern.Append(string.Format(@"\<td\>{0}:\</td\>\s*", TWWords.ReportLosses)); pattern.Append(@"(?<defloss>\<td( class=""hidden"")?\>\d*\</td\>)*\s*\</tr\>\s*"); pattern.Append(@"))"); return pattern.ToString(); } private string GetReportEspionagePattern() { var pattern = new StringBuilder(); #region Example //<h4>Espionage</h4> //<table style="border: 1px solid #DED3B9"> //<tr><th>Resources scouted:</th><td><img src="/graphic/holz.png" title="Wood" alt="" />3<span class="grey">.</span>094 <img src="/graphic/lehm.png" title="Clay" alt="" />7<span class="grey">.</span>776 <img src="/graphic/eisen.png" title="Iron" alt="" />14<span class="grey">.</span>861 </td></tr> // <tr><th>Buildings:</th><td> // Village Headquarters <b>(Level 20)</b><br /> // Barracks <b>(Level 10)</b><br /> // Stable <b>(Level 14)</b><br /> // Workshop <b>(Level 2)</b><br /> // Academy <b>(Level 1)</b><br /> // Smithy <b>(Level 20)</b><br /> // Rally point <b>(Level 1)</b><br /> // Market <b>(Level 10)</b><br /> // Timber camp <b>(Level 25)</b><br /> // Clay pit <b>(Level 25)</b><br /> // Iron mine <b>(Level 25)</b><br /> // Farm <b>(Level 22)</b><br /> // Warehouse <b>(Level 22)</b><br /> // Hiding place <b>(Level 10)</b><br /> // Wall <b>(Level 15)</b><br /> // </td></tr> // <tr><th colspan="2">Units outside of village:</th></tr> // <tr><td colspan="2"> // <table> // <tr><th width="35"><img src="/graphic/unit/unit_spear.png" title="Spear fighter" alt="" /></th><th width="35"><img src="/graphic/unit/unit_sword.png" title="Swordsman" alt="" /></th><th width="35"><img src="/graphic/unit/unit_axe.png" title="Axeman" alt="" /></th><th width="35"><img src="/graphic/unit/unit_spy.png" title="Scout" alt="" /></th><th width="35"><img src="/graphic/unit/unit_light.png" title="Light cavalry" alt="" /></th><th width="35"><img src="/graphic/unit/unit_heavy.png" title="Heavy cavalry" alt="" /></th><th width="35"><img src="/graphic/unit/unit_ram.png" title="Ram" alt="" /></th><th width="35"><img src="/graphic/unit/unit_catapult.png" title="Catapult" alt="" /></th><th width="35"><img src="/graphic/unit/unit_snob.png" title="Nobleman" alt="" /></th></tr> // <tr><td>588</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td><td class="hidden">0</td></tr> // </table> // </td></tr> #endregion // Other stuff pattern.Append(string.Format(@"\<h4\>{0}\</h4\>\s*", TWWords.ReportEspionage)); pattern.Append(@"\<table style=""border: 1px solid #DED3B9""\>\s*"); pattern.Append(string.Format(@"\<tr\>\<th\>{0}:\</th\>\<td\>", TWWords.ReportResourcesScouted)); pattern.Append(string.Format(@"({0}|(?<resLeft>\<img src="".*\.png(\?1)?"" title=""({1}|{2}|{3})"" alt="""" /\>(\d*<span class=""grey""\>\.\</span\>)?\d*\s*){1,3})", TWWords.ReportResourcesScoutedNone, TWWords.Wood, TWWords.Clay, TWWords.Iron)); pattern.Append(@"\</td\>\</tr\>\s*"); pattern.Append(string.Format(@"(\<tr\>\<th\>{0}:\</th\>\<td\>\s*", TWWords.Buildings)); pattern.Append(string.Format(@"(?<buildings>.* \<b\>\({0} \d*\)\</b\>\<br /\>\s*)*", TWWords.BuildingLevel)); pattern.Append(@"\</td\>\</tr\>\s*)?"); pattern.Append(string.Format(@"(\<tr\>\<th colspan=""2""\>{0}:\</th\>\</tr\>\s*", TWWords.ReportUnitsOutside)); pattern.Append(@"\<tr\>\<td colspan=""2""\>\s*"); pattern.Append(@"\<table\>\s*"); pattern.Append(@"\<tr\>(\<th width=""35""\>\<img src="".*\.png(\?1)?"" title="".*"" alt="""" /\>\</th\>)*\</tr\>\s*"); pattern.Append(@"\<tr\>(?<unitsOutside>(\<td( class=""hidden"")?\>\d*\</td\>)*)\</tr\>\s*"); pattern.Append(@"\</table\>)?"); return pattern.ToString(); } private string GetReportRestPattern() { var pattern = new StringBuilder(); pattern.Append(@"("); pattern.Append(string.Format(@"\<h4\>{0}\</h4\>\s*", TWWords.ReportUnitsInTransit)); pattern.Append(@"\<table\>\s*"); pattern.Append(@"\<tr\>(\<th width=""35""\>\<img src="".*\.png(\?1)?"" title="".*"" alt="""" /\>\</th\>)+\</tr\>\s*"); pattern.Append(@"\<tr\>(?<forcetransit>\<td( class=""hidden"")?\>\d*\</td\>)*\s*\</tr\>\s*"); pattern.Append(@"\</table\>\s*"); pattern.Append(@"("); pattern.Append(string.Format(@"\<h4\>{0}\</h4\>\s*", TWWords.ReportUnitsOtherVillages)); pattern.Append(@"\<table\>\s*"); pattern.Append(@"\<tr\>\<th width=""200""\>\</th\>(\<th width=""15""\>\<img src="".*\.png(\?1)?"" title="".*"" alt="""" /\>\</th\>)+\</tr\>\s*"); pattern.Append(string.Format(@"(?<forceSupport>\<tr\>\<td\>\<a href=""/game\.php\?village=\d*&amp;screen=info_village&amp;id=\d*""\>.* \(\d*\|\d*\) {0}\d{{1,2}}\</a\>\</td\>", TWWords.ContinentAbreviation)); pattern.Append(@"(\<td( class=""hidden"")?\>\d*\</td\>)*\</tr\>\s*)*"); pattern.Append(@"\</table\>\s*"); pattern.Append(@")?"); pattern.Append(@")?"); // Haul pattern.Append(@"(\<table width=""100%"" style=""border: 1px solid #DED3B9""\>\s*"); pattern.Append(string.Format(@"\<tr\>\<th\>{0}:\</th\>\s*\<td width=""220""\>", TWWords.ReportHaul)); pattern.Append(string.Format(@"(?<res>\<img src="".*\.png(\?1)?"" title=""({0}|{1}|{2})"" alt="""" /\>(\d*\<span class=""grey""\>\.\</span\>)?\d*\s*){{0,3}}\</td\>\s*)?", TWWords.Wood, TWWords.Clay, TWWords.Iron)); pattern.Append(@"\<td\>(?<haul>\d*)/(?<haulMax>\d*)\</td\>\s*\</tr\>\s*)?"); pattern.Append(string.Format(@"(\<tr\>\<th\>{0}:\</th\>\s*", TWWords.ReportRams)); pattern.Append(string.Format(@"\<td colspan=""2""\>{0} \<b\>(?<ramBefore>\d*)\</b\> {1} \<b\>(?<ramAfter>\d*)\</b\>\</td\>\</tr\>\s*", TWWords.ReportRamsPre, TWWords.ReportRamsBetween)); pattern.Append(string.Format(@"(\<tr\>\<th\>{0}:\</th\>\s*", TWWords.ReportCatas)); pattern.Append(string.Format(@"\<td colspan=""2""\>({2} )?(?<catBuilding>\w*) {0}\s?\<b\>(?<catBefore>\d*)\</b\> {1}\s?\<b\>(?<catAfter>\d*)\</b\>\</td\>\</tr\>\s*)?", TWWords.ReportCatasPre, TWWords.ReportCatasBetween, TWWords.The)); pattern.Append(string.Format(@"(\<tr\>\<th\>{0}\</th\>\s*", TWWords.ReportLoyalty)); pattern.Append(string.Format(@"\<td colspan=""2""\>{0} \<b\>(?<loyaltyBegin>\d*)\</b\> {1} \<b\>(?<loyaltyEnd>-?\d*)\</b\>\</td\>\</tr\>)?", TWWords.ReportLoyaltyPre, TWWords.ReportLoyaltyBetween)); return pattern.ToString(); } #endregion } }
using System; using System.Collections.Generic; #if NETFX_CORE using FileStream = BestHTTP.PlatformSupport.IO.FileStream; using FileMode = BestHTTP.PlatformSupport.IO.FileMode; using Directory = BestHTTP.PlatformSupport.IO.Directory; using File = BestHTTP.PlatformSupport.IO.File; #else using FileStream = System.IO.FileStream; using FileMode = System.IO.FileMode; #endif using BestHTTP.Extensions; namespace BestHTTP { sealed class StreamList : System.IO.Stream { private System.IO.Stream[] Streams; private int CurrentIdx; public StreamList(params System.IO.Stream[] streams) { this.Streams = streams; this.CurrentIdx = 0; } public override bool CanRead { get { if (CurrentIdx >= Streams.Length) return false; return Streams[CurrentIdx].CanRead; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { if (CurrentIdx >= Streams.Length) return false; return Streams[CurrentIdx].CanWrite; } } public override void Flush() { if (CurrentIdx >= Streams.Length) return; // We have to call the flush to all previous streams, as we may advanced the CurrentIdx for (int i = 0; i <= CurrentIdx; ++i) Streams[i].Flush(); } public override long Length { get { if (CurrentIdx >= Streams.Length) return 0; long length = 0; for (int i = 0; i < Streams.Length; ++i) length += Streams[i].Length; return length; } } public override int Read(byte[] buffer, int offset, int count) { if (CurrentIdx >= Streams.Length) return -1; int readCount = Streams[CurrentIdx].Read(buffer, offset, count); while (readCount < count && CurrentIdx++ < Streams.Length) { readCount += Streams[CurrentIdx].Read(buffer, offset + readCount, count - readCount); } return readCount; } public override void Write(byte[] buffer, int offset, int count) { if (CurrentIdx >= Streams.Length) return; Streams[CurrentIdx].Write(buffer, offset, count); } public void Write(string str) { byte[] bytes = str.GetASCIIBytes(); this.Write(bytes, 0, bytes.Length); } protected override void Dispose(bool disposing) { for (int i = 0; i < Streams.Length; ++i) { try { Streams[i].Dispose(); } catch(Exception ex) { HTTPManager.Logger.Exception("StreamList", "Dispose", ex); } } } public override long Position { get { throw new NotImplementedException("Position get"); } set { throw new NotImplementedException("Position set"); } } public override long Seek(long offset, System.IO.SeekOrigin origin) { if (CurrentIdx >= Streams.Length) return 0; return Streams[CurrentIdx].Seek(offset, origin); } public override void SetLength(long value) { throw new NotImplementedException("SetLength"); } } /*public static class AndroidFileHelper { // AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); // AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"); public static Stream GetAPKFileStream(string path) { UnityEngine.AndroidJavaClass up = new UnityEngine.AndroidJavaClass("com.unity3d.player.UnityPlayer"); UnityEngine.AndroidJavaObject cActivity = up.GetStatic<UnityEngine.AndroidJavaObject>("currentActivity"); UnityEngine.AndroidJavaObject assetManager = cActivity.GetStatic<UnityEngine.AndroidJavaObject>("getAssets"); return new AndroidInputStream(assetManager.Call<UnityEngine.AndroidJavaObject>("open", path)); } } public sealed class AndroidInputStream : Stream { private UnityEngine.AndroidJavaObject baseStream; public override bool CanRead { get { throw new NotImplementedException(); } } public override bool CanSeek { get { throw new NotImplementedException(); } } public override bool CanWrite { get { throw new NotImplementedException(); } } public override void Flush() { throw new NotImplementedException(); } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public AndroidInputStream(UnityEngine.AndroidJavaObject inputStream) { this.baseStream = inputStream; } public override int Read(byte[] buffer, int offset, int count) { return this.baseStream.Call<int>("read", buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } }*/ internal sealed class FileConnection : ConnectionBase { public FileConnection(string serverAddress) :base(serverAddress) { } internal override void Abort(HTTPConnectionStates newState) { State = newState; switch (State) { case HTTPConnectionStates.TimedOut: TimedOutStart = DateTime.UtcNow; break; } throw new NotImplementedException(); } protected override void ThreadFunc(object param) { try { // Step 1 : create a stream with header information // Step 2 : create a stream from the file // Step 3 : create a StreamList // Step 4 : create a HTTPResponse object // Step 5 : call the Receive function of the response object using (FileStream fs = new FileStream(this.CurrentRequest.CurrentUri.LocalPath, FileMode.Open)) //using (Stream fs = AndroidFileHelper.GetAPKFileStream(this.CurrentRequest.CurrentUri.LocalPath)) using (StreamList stream = new StreamList(new System.IO.MemoryStream(), fs)) { // This will write to the MemoryStream stream.Write("HTTP/1.1 200 Ok\r\n"); stream.Write("Content-Type: application/octet-stream\r\n"); stream.Write("Content-Length: " + fs.Length.ToString() + "\r\n"); stream.Write("\r\n"); stream.Seek(0, System.IO.SeekOrigin.Begin); base.CurrentRequest.Response = new HTTPResponse(base.CurrentRequest, stream, base.CurrentRequest.UseStreaming, false); if (!CurrentRequest.Response.Receive()) CurrentRequest.Response = null; } } catch(Exception ex) { if (CurrentRequest != null) { // Something gone bad, Response must be null! CurrentRequest.Response = null; switch (State) { case HTTPConnectionStates.AbortRequested: CurrentRequest.State = HTTPRequestStates.Aborted; break; case HTTPConnectionStates.TimedOut: CurrentRequest.State = HTTPRequestStates.TimedOut; break; default: CurrentRequest.Exception = ex; CurrentRequest.State = HTTPRequestStates.Error; break; } } } finally { State = HTTPConnectionStates.Closed; if (CurrentRequest.State == HTTPRequestStates.Processing) { if (CurrentRequest.Response != null) CurrentRequest.State = HTTPRequestStates.Finished; else CurrentRequest.State = HTTPRequestStates.Error; } } } } }
namespace Azure.IoT.TimeSeriesInsights { public partial class AggregateSeries { public AggregateSeries(System.Collections.Generic.IEnumerable<object> timeSeriesId, Azure.IoT.TimeSeriesInsights.DateTimeRange searchSpan, System.TimeSpan interval) { } public Azure.IoT.TimeSeriesInsights.TimeSeriesExpression Filter { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, Azure.IoT.TimeSeriesInsights.TimeSeriesVariable> InlineVariables { get { throw null; } } public System.TimeSpan Interval { get { throw null; } } public System.Collections.Generic.IList<string> ProjectedVariables { get { throw null; } } public Azure.IoT.TimeSeriesInsights.DateTimeRange SearchSpan { get { throw null; } } public System.Collections.Generic.IList<object> TimeSeriesId { get { throw null; } } } public partial class AggregateVariable : Azure.IoT.TimeSeriesInsights.TimeSeriesVariable { public AggregateVariable(Azure.IoT.TimeSeriesInsights.TimeSeriesExpression aggregation) { } public Azure.IoT.TimeSeriesInsights.TimeSeriesExpression Aggregation { get { throw null; } set { } } } public partial class AvailabilityResponse { internal AvailabilityResponse() { } public Azure.IoT.TimeSeriesInsights.EventAvailability Availability { get { throw null; } } } public partial class CategoricalVariable : Azure.IoT.TimeSeriesInsights.TimeSeriesVariable { public CategoricalVariable(Azure.IoT.TimeSeriesInsights.TimeSeriesExpression value, Azure.IoT.TimeSeriesInsights.TimeSeriesDefaultCategory defaultCategory) { } public System.Collections.Generic.IList<Azure.IoT.TimeSeriesInsights.TimeSeriesAggregateCategory> Categories { get { throw null; } } public Azure.IoT.TimeSeriesInsights.TimeSeriesDefaultCategory DefaultCategory { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.InterpolationOperation Interpolation { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.TimeSeriesExpression Value { get { throw null; } set { } } } public partial class DateTimeRange { public DateTimeRange(System.DateTimeOffset from, System.DateTimeOffset to) { } public System.DateTimeOffset From { get { throw null; } set { } } public System.DateTimeOffset To { get { throw null; } set { } } } public partial class EventAvailability { internal EventAvailability() { } public System.Collections.Generic.IReadOnlyDictionary<string, int> Distribution { get { throw null; } } public System.TimeSpan? IntervalSize { get { throw null; } } public Azure.IoT.TimeSeriesInsights.DateTimeRange Range { get { throw null; } } } public partial class EventProperty { public EventProperty() { } public string Name { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.PropertyTypes? Type { get { throw null; } set { } } } public partial class EventSchema { internal EventSchema() { } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.EventProperty> Properties { get { throw null; } } } public partial class GetEvents { public GetEvents(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, Azure.IoT.TimeSeriesInsights.DateTimeRange searchSpan) { } public Azure.IoT.TimeSeriesInsights.TimeSeriesExpression Filter { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.IoT.TimeSeriesInsights.EventProperty> ProjectedProperties { get { throw null; } } public Azure.IoT.TimeSeriesInsights.DateTimeRange SearchSpan { get { throw null; } } public int? Take { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.TimeSeriesId TimeSeriesId { get { throw null; } } } public partial class GetEventSchemaRequest { public GetEventSchemaRequest(Azure.IoT.TimeSeriesInsights.DateTimeRange searchSpan) { } public Azure.IoT.TimeSeriesInsights.DateTimeRange SearchSpan { get { throw null; } } } public partial class GetHierarchiesPage : Azure.IoT.TimeSeriesInsights.PagedResponse { internal GetHierarchiesPage() { } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchy> Hierarchies { get { throw null; } } } public partial class GetInstancesPage : Azure.IoT.TimeSeriesInsights.PagedResponse { internal GetInstancesPage() { } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesInstance> Instances { get { throw null; } } } public partial class GetSeries { public GetSeries(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, Azure.IoT.TimeSeriesInsights.DateTimeRange searchSpan) { } public Azure.IoT.TimeSeriesInsights.TimeSeriesExpression Filter { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, Azure.IoT.TimeSeriesInsights.TimeSeriesVariable> InlineVariables { get { throw null; } } public System.Collections.Generic.IList<string> ProjectedVariables { get { throw null; } } public Azure.IoT.TimeSeriesInsights.DateTimeRange SearchSpan { get { throw null; } } public int? Take { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.TimeSeriesId TimeSeriesId { get { throw null; } } } public partial class GetTypesPage : Azure.IoT.TimeSeriesInsights.PagedResponse { internal GetTypesPage() { } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesType> Types { get { throw null; } } } public partial class HierarchiesBatchRequest { public HierarchiesBatchRequest() { } public Azure.IoT.TimeSeriesInsights.HierarchiesRequestBatchGetDelete Delete { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.HierarchiesRequestBatchGetDelete Get { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchy> Put { get { throw null; } } } public partial class HierarchiesBatchResponse { internal HierarchiesBatchResponse() { } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError> Delete { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchyOperationResult> Get { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchyOperationResult> Put { get { throw null; } } } public partial class HierarchiesClient { protected HierarchiesClient() { } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchyOperationResult[]> CreateOrReplace(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchy> timeSeriesHierarchies, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchyOperationResult[]>> CreateOrReplaceAsync(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchy> timeSeriesHierarchies, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]> DeleteById(System.Collections.Generic.IEnumerable<string> timeSeriesHierarchyIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]>> DeleteByIdAsync(System.Collections.Generic.IEnumerable<string> timeSeriesHierarchyIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]> DeleteByName(System.Collections.Generic.IEnumerable<string> timeSeriesHierarchyNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]>> DeleteByNameAsync(System.Collections.Generic.IEnumerable<string> timeSeriesHierarchyNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchy> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchy> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchyOperationResult[]> GetById(System.Collections.Generic.IEnumerable<string> timeSeriesHierarchyIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchyOperationResult[]>> GetByIdAsync(System.Collections.Generic.IEnumerable<string> timeSeriesHierarchyIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchyOperationResult[]> GetByName(System.Collections.Generic.IEnumerable<string> timeSeriesHierarchyNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchyOperationResult[]>> GetByNameAsync(System.Collections.Generic.IEnumerable<string> timeSeriesHierarchyNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class HierarchiesExpandParameter { public HierarchiesExpandParameter() { } public Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind? Kind { get { throw null; } set { } } } public partial class HierarchiesRequestBatchGetDelete { public HierarchiesRequestBatchGetDelete() { } public System.Collections.Generic.IList<string> HierarchyIds { get { throw null; } } public System.Collections.Generic.IList<string> Names { get { throw null; } } } public partial class HierarchiesSortParameter { public HierarchiesSortParameter() { } public Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy? By { get { throw null; } set { } } } public partial class HierarchyHit { internal HierarchyHit() { } public int? CumulativeInstanceCount { get { throw null; } } public Azure.IoT.TimeSeriesInsights.SearchHierarchyNodesResponse HierarchyNodes { get { throw null; } } public string Name { get { throw null; } } } public partial class InstanceHit { internal InstanceHit() { } public System.Collections.Generic.IReadOnlyList<string> HierarchyIds { get { throw null; } } public Azure.IoT.TimeSeriesInsights.Models.InstanceHitHighlights Highlights { get { throw null; } } public string Name { get { throw null; } } public System.Collections.Generic.IReadOnlyList<object> TimeSeriesId { get { throw null; } } public string TypeId { get { throw null; } } } public partial class InstancesBatchRequest { public InstancesBatchRequest() { } public Azure.IoT.TimeSeriesInsights.InstancesRequestBatchGetOrDelete Delete { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.InstancesRequestBatchGetOrDelete Get { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.IoT.TimeSeriesInsights.TimeSeriesInstance> Put { get { throw null; } } public System.Collections.Generic.IList<Azure.IoT.TimeSeriesInsights.TimeSeriesInstance> Update { get { throw null; } } } public partial class InstancesBatchResponse { internal InstancesBatchResponse() { } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError> Delete { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.InstancesOperationResult> Get { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.InstancesOperationResult> Put { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.InstancesOperationResult> Update { get { throw null; } } } public partial class InstancesClient { protected InstancesClient() { } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]> CreateOrReplace(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesInstance> timeSeriesInstances, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]>> CreateOrReplaceAsync(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesInstance> timeSeriesInstances, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]> Delete(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesId> timeSeriesIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]> Delete(System.Collections.Generic.IEnumerable<string> timeSeriesNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]>> DeleteAsync(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesId> timeSeriesIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]>> DeleteAsync(System.Collections.Generic.IEnumerable<string> timeSeriesNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.InstancesOperationResult[]> Get(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesId> timeSeriesIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.InstancesOperationResult[]> Get(System.Collections.Generic.IEnumerable<string> timeSeriesNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.TimeSeriesInsights.TimeSeriesInstance> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.InstancesOperationResult[]>> GetAsync(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesId> timeSeriesIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.InstancesOperationResult[]>> GetAsync(System.Collections.Generic.IEnumerable<string> timeSeriesNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.TimeSeriesInsights.TimeSeriesInstance> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.SearchSuggestion[]> GetSearchSuggestions(string searchString, int? maxNumberOfSuggestions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.SearchSuggestion[]>> GetSearchSuggestionsAsync(string searchString, int? maxNumberOfSuggestions = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.InstancesOperationResult[]> Replace(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesInstance> timeSeriesInstances, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.InstancesOperationResult[]>> ReplaceAsync(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesInstance> timeSeriesInstances, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class InstancesOperationResult { internal InstancesOperationResult() { } public Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError Error { get { throw null; } } public Azure.IoT.TimeSeriesInsights.TimeSeriesInstance Instance { get { throw null; } } } public partial class InstancesRequestBatchGetOrDelete { public InstancesRequestBatchGetOrDelete() { } public System.Collections.Generic.IList<string> Names { get { throw null; } } public System.Collections.Generic.IList<Azure.IoT.TimeSeriesInsights.TimeSeriesId> TimeSeriesIds { get { throw null; } } } public partial class InstancesSortParameter { public InstancesSortParameter() { } public Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy? By { get { throw null; } set { } } } public partial class InstancesSuggestRequest { public InstancesSuggestRequest(string searchString) { } public string SearchString { get { throw null; } } public int? Take { get { throw null; } set { } } } public partial class InstancesSuggestResponse { internal InstancesSuggestResponse() { } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.SearchSuggestion> Suggestions { get { throw null; } } } public partial class InterpolationOperation { public InterpolationOperation() { } public Azure.IoT.TimeSeriesInsights.Models.InterpolationBoundary Boundary { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.Models.InterpolationKind? Kind { get { throw null; } set { } } } public partial class ModelSettingsClient { protected ModelSettingsClient() { } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesModelSettings> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesModelSettings>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesModelSettings> UpdateDefaultTypeId(string defaultTypeId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesModelSettings>> UpdateDefaultTypeIdAsync(string defaultTypeId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesModelSettings> UpdateName(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesModelSettings>> UpdateNameAsync(string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class ModelSettingsResponse { internal ModelSettingsResponse() { } public Azure.IoT.TimeSeriesInsights.TimeSeriesModelSettings ModelSettings { get { throw null; } } } public partial class NumericVariable : Azure.IoT.TimeSeriesInsights.TimeSeriesVariable { public NumericVariable(Azure.IoT.TimeSeriesInsights.TimeSeriesExpression value, Azure.IoT.TimeSeriesInsights.TimeSeriesExpression aggregation) { } public Azure.IoT.TimeSeriesInsights.TimeSeriesExpression Aggregation { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.InterpolationOperation Interpolation { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.TimeSeriesExpression Value { get { throw null; } set { } } } public partial class PagedResponse { internal PagedResponse() { } public string ContinuationToken { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct PropertyTypes : System.IEquatable<Azure.IoT.TimeSeriesInsights.PropertyTypes> { private readonly object _dummy; private readonly int _dummyPrimitive; public PropertyTypes(string value) { throw null; } public static Azure.IoT.TimeSeriesInsights.PropertyTypes Bool { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.PropertyTypes DateTime { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.PropertyTypes Double { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.PropertyTypes Long { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.PropertyTypes String { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.PropertyTypes TimeSpan { get { throw null; } } public bool Equals(Azure.IoT.TimeSeriesInsights.PropertyTypes other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.TimeSeriesInsights.PropertyTypes left, Azure.IoT.TimeSeriesInsights.PropertyTypes right) { throw null; } public static implicit operator Azure.IoT.TimeSeriesInsights.PropertyTypes (string value) { throw null; } public static bool operator !=(Azure.IoT.TimeSeriesInsights.PropertyTypes left, Azure.IoT.TimeSeriesInsights.PropertyTypes right) { throw null; } public override string ToString() { throw null; } } public partial class PropertyValues : Azure.IoT.TimeSeriesInsights.EventProperty { public PropertyValues() { } public System.Collections.Generic.IList<object> Values { get { throw null; } } } public partial class QueryClient { protected QueryClient() { } public virtual Azure.Pageable<Azure.IoT.TimeSeriesInsights.QueryResultPage> GetEvents(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, System.DateTimeOffset startTime, System.DateTimeOffset endTime, Azure.IoT.TimeSeriesInsights.QueryEventsRequestOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.TimeSeriesInsights.QueryResultPage> GetEvents(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, System.TimeSpan timeSpan, System.DateTimeOffset? endTime = default(System.DateTimeOffset?), Azure.IoT.TimeSeriesInsights.QueryEventsRequestOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.TimeSeriesInsights.QueryResultPage> GetEventsAsync(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, System.DateTimeOffset startTime, System.DateTimeOffset endTime, Azure.IoT.TimeSeriesInsights.QueryEventsRequestOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.TimeSeriesInsights.QueryResultPage> GetEventsAsync(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, System.TimeSpan timeSpan, System.DateTimeOffset? endTime = default(System.DateTimeOffset?), Azure.IoT.TimeSeriesInsights.QueryEventsRequestOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.TimeSeriesInsights.QueryResultPage> GetSeries(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, System.DateTimeOffset startTime, System.DateTimeOffset endTime, Azure.IoT.TimeSeriesInsights.QuerySeriesRequestOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.TimeSeriesInsights.QueryResultPage> GetSeries(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, System.TimeSpan timeSpan, System.DateTimeOffset? endTime = default(System.DateTimeOffset?), Azure.IoT.TimeSeriesInsights.QuerySeriesRequestOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.TimeSeriesInsights.QueryResultPage> GetSeriesAsync(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, System.DateTimeOffset startTime, System.DateTimeOffset endTime, Azure.IoT.TimeSeriesInsights.QuerySeriesRequestOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.TimeSeriesInsights.QueryResultPage> GetSeriesAsync(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, System.TimeSpan timeSpan, System.DateTimeOffset? endTime = default(System.DateTimeOffset?), Azure.IoT.TimeSeriesInsights.QuerySeriesRequestOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class QueryEventsRequestOptions : Azure.IoT.TimeSeriesInsights.QueryRequestOptions { public QueryEventsRequestOptions() { } public System.Collections.Generic.List<Azure.IoT.TimeSeriesInsights.EventProperty> ProjectedProperties { get { throw null; } } } public partial class QueryRequest { public QueryRequest() { } public Azure.IoT.TimeSeriesInsights.AggregateSeries AggregateSeries { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.GetEvents GetEvents { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.GetSeries GetSeries { get { throw null; } set { } } } public abstract partial class QueryRequestOptions { protected QueryRequestOptions() { } public string Filter { get { throw null; } set { } } public int? MaximumNumberOfEvents { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.StoreType StoreType { get { throw null; } set { } } } public partial class QueryResultPage : Azure.IoT.TimeSeriesInsights.PagedResponse { internal QueryResultPage() { } public double? Progress { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.PropertyValues> Properties { get { throw null; } } public System.Collections.Generic.IReadOnlyList<System.DateTimeOffset> Timestamps { get { throw null; } } } public partial class QuerySeriesRequestOptions : Azure.IoT.TimeSeriesInsights.QueryRequestOptions { public QuerySeriesRequestOptions() { } public System.Collections.Generic.IDictionary<string, Azure.IoT.TimeSeriesInsights.TimeSeriesVariable> InlineVariables { get { throw null; } } public System.Collections.Generic.List<string> ProjectedVariables { get { throw null; } } } public partial class SearchHierarchyNodesResponse { internal SearchHierarchyNodesResponse() { } public string ContinuationToken { get { throw null; } } public int? HitCount { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.HierarchyHit> Hits { get { throw null; } } } public partial class SearchInstancesHierarchiesParameters { public SearchInstancesHierarchiesParameters() { } public Azure.IoT.TimeSeriesInsights.HierarchiesExpandParameter Expand { get { throw null; } set { } } public int? PageSize { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.HierarchiesSortParameter Sort { get { throw null; } set { } } } public partial class SearchInstancesParameters { public SearchInstancesParameters() { } public bool? Highlights { get { throw null; } set { } } public int? PageSize { get { throw null; } set { } } public bool? Recursive { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.InstancesSortParameter Sort { get { throw null; } set { } } } public partial class SearchInstancesRequest { public SearchInstancesRequest(string searchString) { } public Azure.IoT.TimeSeriesInsights.SearchInstancesHierarchiesParameters Hierarchies { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.SearchInstancesParameters Instances { get { throw null; } set { } } public System.Collections.Generic.IList<string> Path { get { throw null; } } public string SearchString { get { throw null; } } } public partial class SearchInstancesResponse { internal SearchInstancesResponse() { } public string ContinuationToken { get { throw null; } } public int? HitCount { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.InstanceHit> Hits { get { throw null; } } } public partial class SearchInstancesResponsePage { internal SearchInstancesResponsePage() { } public Azure.IoT.TimeSeriesInsights.SearchHierarchyNodesResponse HierarchyNodes { get { throw null; } } public Azure.IoT.TimeSeriesInsights.SearchInstancesResponse Instances { get { throw null; } } } public partial class SearchSuggestion { internal SearchSuggestion() { } public string HighlightedSearchString { get { throw null; } } public string SearchString { get { throw null; } } } public partial class StoreType { internal StoreType() { } public static Azure.IoT.TimeSeriesInsights.StoreType ColdStore { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.StoreType WarmStore { get { throw null; } } public override string ToString() { throw null; } } public partial class TimeSeriesAggregateCategory { public TimeSeriesAggregateCategory(string label, System.Collections.Generic.IEnumerable<object> values) { } public string Label { get { throw null; } set { } } public System.Collections.Generic.IList<object> Values { get { throw null; } } } public partial class TimeSeriesDefaultCategory { public TimeSeriesDefaultCategory(string label) { } public string Label { get { throw null; } set { } } } public partial class TimeSeriesExpression { public TimeSeriesExpression(string tsx) { } public string Tsx { get { throw null; } set { } } } public partial class TimeSeriesHierarchy { public TimeSeriesHierarchy(string name, Azure.IoT.TimeSeriesInsights.Models.TimeSeriesHierarchySource source) { } public string Id { get { throw null; } set { } } public string Name { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.Models.TimeSeriesHierarchySource Source { get { throw null; } set { } } } public partial class TimeSeriesHierarchyOperationResult { internal TimeSeriesHierarchyOperationResult() { } public Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError Error { get { throw null; } } public Azure.IoT.TimeSeriesInsights.TimeSeriesHierarchy Hierarchy { get { throw null; } } } public partial class TimeSeriesId { public TimeSeriesId(string key1) { } public TimeSeriesId(string key1, string key2) { } public TimeSeriesId(string key1, string key2, string key3) { } public string[] ToArray() { throw null; } public override string ToString() { throw null; } } public partial class TimeSeriesIdProperty { internal TimeSeriesIdProperty() { } public string Name { get { throw null; } } public Azure.IoT.TimeSeriesInsights.Models.TimeSeriesIdPropertyTypes? Type { get { throw null; } } } public partial class TimeSeriesInsightsClient { protected TimeSeriesInsightsClient() { } public TimeSeriesInsightsClient(string environmentFqdn, Azure.Core.TokenCredential credential) { } public TimeSeriesInsightsClient(string environmentFqdn, Azure.Core.TokenCredential credential, Azure.IoT.TimeSeriesInsights.TimeSeriesInsightsClientOptions options) { } public virtual Azure.IoT.TimeSeriesInsights.HierarchiesClient Hierarchies { get { throw null; } } public virtual Azure.IoT.TimeSeriesInsights.InstancesClient Instances { get { throw null; } } public virtual Azure.IoT.TimeSeriesInsights.ModelSettingsClient ModelSettings { get { throw null; } } public virtual Azure.IoT.TimeSeriesInsights.QueryClient Query { get { throw null; } } public virtual Azure.IoT.TimeSeriesInsights.TypesClient Types { get { throw null; } } } public partial class TimeSeriesInsightsClientOptions : Azure.Core.ClientOptions { public TimeSeriesInsightsClientOptions(Azure.IoT.TimeSeriesInsights.TimeSeriesInsightsClientOptions.ServiceVersion version = Azure.IoT.TimeSeriesInsights.TimeSeriesInsightsClientOptions.ServiceVersion.V2020_07_31) { } public Azure.IoT.TimeSeriesInsights.TimeSeriesInsightsClientOptions.ServiceVersion Version { get { throw null; } } public enum ServiceVersion { V2020_07_31 = 1, } } public partial class TimeSeriesInstance { public TimeSeriesInstance(Azure.IoT.TimeSeriesInsights.TimeSeriesId timeSeriesId, string typeId) { } public string Description { get { throw null; } set { } } public System.Collections.Generic.IList<string> HierarchyIds { get { throw null; } } public System.Collections.Generic.IDictionary<string, object> InstanceFields { get { throw null; } } public string Name { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.TimeSeriesId TimeSeriesId { get { throw null; } } public string TypeId { get { throw null; } set { } } } public partial class TimeSeriesModelSettings { internal TimeSeriesModelSettings() { } public string DefaultTypeId { get { throw null; } } public string Name { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesIdProperty> TimeSeriesIdProperties { get { throw null; } } } public partial class TimeSeriesOperationError : System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, object>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<string, object>>, System.Collections.Generic.IReadOnlyDictionary<string, object>, System.Collections.IEnumerable { internal TimeSeriesOperationError() { } public string Code { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationErrorDetails> Details { get { throw null; } } public Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError InnerError { get { throw null; } } public object this[string key] { get { throw null; } } public System.Collections.Generic.IEnumerable<string> Keys { get { throw null; } } public string Message { get { throw null; } } int System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Count { get { throw null; } } public string Target { get { throw null; } } public System.Collections.Generic.IEnumerable<object> Values { get { throw null; } } public bool ContainsKey(string key) { throw null; } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, object>> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(string key, out object value) { throw null; } } public partial class TimeSeriesOperationErrorDetails : System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, object>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<string, object>>, System.Collections.Generic.IReadOnlyDictionary<string, object>, System.Collections.IEnumerable { internal TimeSeriesOperationErrorDetails() { } public string Code { get { throw null; } } public object this[string key] { get { throw null; } } public System.Collections.Generic.IEnumerable<string> Keys { get { throw null; } } public string Message { get { throw null; } } int System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Count { get { throw null; } } public System.Collections.Generic.IEnumerable<object> Values { get { throw null; } } public bool ContainsKey(string key) { throw null; } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, object>> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(string key, out object value) { throw null; } } public partial class TimeSeriesType { public TimeSeriesType(string name, System.Collections.Generic.IDictionary<string, Azure.IoT.TimeSeriesInsights.TimeSeriesVariable> variables) { } public string Description { get { throw null; } set { } } public string Id { get { throw null; } set { } } public string Name { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, Azure.IoT.TimeSeriesInsights.TimeSeriesVariable> Variables { get { throw null; } } } public partial class TimeSeriesTypeOperationResult { internal TimeSeriesTypeOperationResult() { } public Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError Error { get { throw null; } } public Azure.IoT.TimeSeriesInsights.TimeSeriesType TimeSeriesType { get { throw null; } } } public partial class TimeSeriesVariable { public TimeSeriesVariable() { } public Azure.IoT.TimeSeriesInsights.TimeSeriesExpression Filter { get { throw null; } set { } } } public partial class TypesBatchRequest { public TypesBatchRequest() { } public Azure.IoT.TimeSeriesInsights.TypesRequestBatchGetOrDelete Delete { get { throw null; } set { } } public Azure.IoT.TimeSeriesInsights.TypesRequestBatchGetOrDelete Get { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.IoT.TimeSeriesInsights.TimeSeriesType> Put { get { throw null; } } } public partial class TypesBatchResponse { internal TypesBatchResponse() { } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError> Delete { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesTypeOperationResult> Get { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.TimeSeriesInsights.TimeSeriesTypeOperationResult> Put { get { throw null; } } } public partial class TypesClient { protected TypesClient() { } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesTypeOperationResult[]> CreateOrReplace(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesType> timeSeriesTypes, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesTypeOperationResult[]>> CreateOrReplaceAsync(System.Collections.Generic.IEnumerable<Azure.IoT.TimeSeriesInsights.TimeSeriesType> timeSeriesTypes, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]> DeleteById(System.Collections.Generic.IEnumerable<string> timeSeriesTypeIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]>> DeleteByIdAsync(System.Collections.Generic.IEnumerable<string> timeSeriesTypeIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]> DeleteByName(System.Collections.Generic.IEnumerable<string> timeSeriesTypeNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesOperationError[]>> DeleteByNameAsync(System.Collections.Generic.IEnumerable<string> timeSeriesTypeNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesTypeOperationResult[]> GetById(System.Collections.Generic.IEnumerable<string> timeSeriesTypeIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesTypeOperationResult[]>> GetByIdAsync(System.Collections.Generic.IEnumerable<string> timeSeriesTypeIds, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesTypeOperationResult[]> GetByName(System.Collections.Generic.IEnumerable<string> timeSeriesTypeNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.TimeSeriesInsights.TimeSeriesTypeOperationResult[]>> GetByNameAsync(System.Collections.Generic.IEnumerable<string> timeSeriesTypeNames, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.TimeSeriesInsights.TimeSeriesType> GetTypes(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.TimeSeriesInsights.TimeSeriesType> GetTypesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class TypesRequestBatchGetOrDelete { public TypesRequestBatchGetOrDelete() { } public System.Collections.Generic.IList<string> Names { get { throw null; } } public System.Collections.Generic.IList<string> TypeIds { get { throw null; } } } } namespace Azure.IoT.TimeSeriesInsights.Models { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct HierarchiesExpandKind : System.IEquatable<Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind> { private readonly object _dummy; private readonly int _dummyPrimitive; public HierarchiesExpandKind(string value) { throw null; } public static Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind OneLevel { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind UntilChildren { get { throw null; } } public bool Equals(Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind left, Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind right) { throw null; } public static implicit operator Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind (string value) { throw null; } public static bool operator !=(Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind left, Azure.IoT.TimeSeriesInsights.Models.HierarchiesExpandKind right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct HierarchiesSortBy : System.IEquatable<Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy> { private readonly object _dummy; private readonly int _dummyPrimitive; public HierarchiesSortBy(string value) { throw null; } public static Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy CumulativeInstanceCount { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy Name { get { throw null; } } public bool Equals(Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy left, Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy right) { throw null; } public static implicit operator Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy (string value) { throw null; } public static bool operator !=(Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy left, Azure.IoT.TimeSeriesInsights.Models.HierarchiesSortBy right) { throw null; } public override string ToString() { throw null; } } public partial class InstanceHitHighlights { internal InstanceHitHighlights() { } public string Description { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> HierarchyIds { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> HierarchyNames { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> InstanceFieldNames { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> InstanceFieldValues { get { throw null; } } public string Name { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> TimeSeriesId { get { throw null; } } public string TypeName { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct InstancesSortBy : System.IEquatable<Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy> { private readonly object _dummy; private readonly int _dummyPrimitive; public InstancesSortBy(string value) { throw null; } public static Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy DisplayName { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy Rank { get { throw null; } } public bool Equals(Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy left, Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy right) { throw null; } public static implicit operator Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy (string value) { throw null; } public static bool operator !=(Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy left, Azure.IoT.TimeSeriesInsights.Models.InstancesSortBy right) { throw null; } public override string ToString() { throw null; } } public partial class InterpolationBoundary { public InterpolationBoundary() { } public System.TimeSpan? Span { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct InterpolationKind : System.IEquatable<Azure.IoT.TimeSeriesInsights.Models.InterpolationKind> { private readonly object _dummy; private readonly int _dummyPrimitive; public InterpolationKind(string value) { throw null; } public static Azure.IoT.TimeSeriesInsights.Models.InterpolationKind Linear { get { throw null; } } public static Azure.IoT.TimeSeriesInsights.Models.InterpolationKind Step { get { throw null; } } public bool Equals(Azure.IoT.TimeSeriesInsights.Models.InterpolationKind other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.TimeSeriesInsights.Models.InterpolationKind left, Azure.IoT.TimeSeriesInsights.Models.InterpolationKind right) { throw null; } public static implicit operator Azure.IoT.TimeSeriesInsights.Models.InterpolationKind (string value) { throw null; } public static bool operator !=(Azure.IoT.TimeSeriesInsights.Models.InterpolationKind left, Azure.IoT.TimeSeriesInsights.Models.InterpolationKind right) { throw null; } public override string ToString() { throw null; } } public partial class TimeSeriesHierarchySource { public TimeSeriesHierarchySource() { } public System.Collections.Generic.IList<string> InstanceFieldNames { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct TimeSeriesIdPropertyTypes : System.IEquatable<Azure.IoT.TimeSeriesInsights.Models.TimeSeriesIdPropertyTypes> { private readonly object _dummy; private readonly int _dummyPrimitive; public TimeSeriesIdPropertyTypes(string value) { throw null; } public static Azure.IoT.TimeSeriesInsights.Models.TimeSeriesIdPropertyTypes String { get { throw null; } } public bool Equals(Azure.IoT.TimeSeriesInsights.Models.TimeSeriesIdPropertyTypes other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.TimeSeriesInsights.Models.TimeSeriesIdPropertyTypes left, Azure.IoT.TimeSeriesInsights.Models.TimeSeriesIdPropertyTypes right) { throw null; } public static implicit operator Azure.IoT.TimeSeriesInsights.Models.TimeSeriesIdPropertyTypes (string value) { throw null; } public static bool operator !=(Azure.IoT.TimeSeriesInsights.Models.TimeSeriesIdPropertyTypes left, Azure.IoT.TimeSeriesInsights.Models.TimeSeriesIdPropertyTypes right) { throw null; } public override string ToString() { throw null; } } }
namespace android.text.format { [global::MonoJavaBridge.JavaClass()] public partial class Time : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Time() { InitJNI(); } protected Time(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _toString7988; public override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.format.Time._toString7988)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._toString7988)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _clear7989; public virtual void clear(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.text.format.Time._clear7989, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._clear7989, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _format7990; public virtual global::java.lang.String format(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.format.Time._format7990, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._format7990, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _compare7991; public static int compare(android.text.format.Time arg0, android.text.format.Time arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(android.text.format.Time.staticClass, global::android.text.format.Time._compare7991, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _set7992; public virtual void set(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.text.format.Time._set7992, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._set7992, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } internal static global::MonoJavaBridge.MethodId _set7993; public virtual void set(int arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.text.format.Time._set7993, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._set7993, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _set7994; public virtual void set(android.text.format.Time arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.text.format.Time._set7994, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._set7994, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _set7995; public virtual void set(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.text.format.Time._set7995, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._set7995, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _normalize7996; public virtual long normalize(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.text.format.Time._normalize7996, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._normalize7996, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _after7997; public virtual bool after(android.text.format.Time arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.text.format.Time._after7997, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._after7997, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _before7998; public virtual bool before(android.text.format.Time arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.text.format.Time._before7998, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._before7998, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _parse7999; public virtual bool parse(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.text.format.Time._parse7999, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._parse7999, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toMillis8000; public virtual long toMillis(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.text.format.Time._toMillis8000, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._toMillis8000, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getActualMaximum8001; public virtual int getActualMaximum(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.text.format.Time._getActualMaximum8001, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._getActualMaximum8001, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _switchTimezone8002; public virtual void switchTimezone(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.text.format.Time._switchTimezone8002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._switchTimezone8002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _parse33398003; public virtual bool parse3339(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.text.format.Time._parse33398003, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._parse33398003, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getCurrentTimezone8004; public static global::java.lang.String getCurrentTimezone() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.text.format.Time.staticClass, global::android.text.format.Time._getCurrentTimezone8004)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _setToNow8005; public virtual void setToNow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.text.format.Time._setToNow8005); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._setToNow8005); } internal static global::MonoJavaBridge.MethodId _format24458006; public virtual global::java.lang.String format2445() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.format.Time._format24458006)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._format24458006)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getWeekNumber8007; public virtual int getWeekNumber() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.text.format.Time._getWeekNumber8007); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._getWeekNumber8007); } internal static global::MonoJavaBridge.MethodId _format33398008; public virtual global::java.lang.String format3339(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.format.Time._format33398008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._format33398008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _isEpoch8009; public static bool isEpoch(android.text.format.Time arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(android.text.format.Time.staticClass, global::android.text.format.Time._isEpoch8009, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getJulianDay8010; public static int getJulianDay(long arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(android.text.format.Time.staticClass, global::android.text.format.Time._getJulianDay8010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setJulianDay8011; public virtual long setJulianDay(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.text.format.Time._setJulianDay8011, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.text.format.Time.staticClass, global::android.text.format.Time._setJulianDay8011, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _Time8012; public Time(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.format.Time.staticClass, global::android.text.format.Time._Time8012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Time8013; public Time() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.format.Time.staticClass, global::android.text.format.Time._Time8013); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Time8014; public Time(android.text.format.Time arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.format.Time.staticClass, global::android.text.format.Time._Time8014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static global::java.lang.String TIMEZONE_UTC { get { return "UTC"; } } public static int EPOCH_JULIAN_DAY { get { return 2440588; } } internal static global::MonoJavaBridge.FieldId _allDay8015; public bool allDay { get { return default(bool); } set { } } internal static global::MonoJavaBridge.FieldId _second8016; public int second { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _minute8017; public int minute { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _hour8018; public int hour { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _monthDay8019; public int monthDay { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _month8020; public int month { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _year8021; public int year { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _weekDay8022; public int weekDay { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _yearDay8023; public int yearDay { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _isDst8024; public int isDst { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _gmtoff8025; public long gmtoff { get { return default(long); } set { } } internal static global::MonoJavaBridge.FieldId _timezone8026; public global::java.lang.String timezone { get { return default(global::java.lang.String); } set { } } public static int SECOND { get { return 1; } } public static int MINUTE { get { return 2; } } public static int HOUR { get { return 3; } } public static int MONTH_DAY { get { return 4; } } public static int MONTH { get { return 5; } } public static int YEAR { get { return 6; } } public static int WEEK_DAY { get { return 7; } } public static int YEAR_DAY { get { return 8; } } public static int WEEK_NUM { get { return 9; } } public static int SUNDAY { get { return 0; } } public static int MONDAY { get { return 1; } } public static int TUESDAY { get { return 2; } } public static int WEDNESDAY { get { return 3; } } public static int THURSDAY { get { return 4; } } public static int FRIDAY { get { return 5; } } public static int SATURDAY { get { return 6; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.text.format.Time.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/format/Time")); global::android.text.format.Time._toString7988 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "toString", "()Ljava/lang/String;"); global::android.text.format.Time._clear7989 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "clear", "(Ljava/lang/String;)V"); global::android.text.format.Time._format7990 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "format", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.text.format.Time._compare7991 = @__env.GetStaticMethodIDNoThrow(global::android.text.format.Time.staticClass, "compare", "(Landroid/text/format/Time;Landroid/text/format/Time;)I"); global::android.text.format.Time._set7992 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "set", "(IIIIII)V"); global::android.text.format.Time._set7993 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "set", "(III)V"); global::android.text.format.Time._set7994 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "set", "(Landroid/text/format/Time;)V"); global::android.text.format.Time._set7995 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "set", "(J)V"); global::android.text.format.Time._normalize7996 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "normalize", "(Z)J"); global::android.text.format.Time._after7997 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "after", "(Landroid/text/format/Time;)Z"); global::android.text.format.Time._before7998 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "before", "(Landroid/text/format/Time;)Z"); global::android.text.format.Time._parse7999 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "parse", "(Ljava/lang/String;)Z"); global::android.text.format.Time._toMillis8000 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "toMillis", "(Z)J"); global::android.text.format.Time._getActualMaximum8001 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "getActualMaximum", "(I)I"); global::android.text.format.Time._switchTimezone8002 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "switchTimezone", "(Ljava/lang/String;)V"); global::android.text.format.Time._parse33398003 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "parse3339", "(Ljava/lang/String;)Z"); global::android.text.format.Time._getCurrentTimezone8004 = @__env.GetStaticMethodIDNoThrow(global::android.text.format.Time.staticClass, "getCurrentTimezone", "()Ljava/lang/String;"); global::android.text.format.Time._setToNow8005 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "setToNow", "()V"); global::android.text.format.Time._format24458006 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "format2445", "()Ljava/lang/String;"); global::android.text.format.Time._getWeekNumber8007 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "getWeekNumber", "()I"); global::android.text.format.Time._format33398008 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "format3339", "(Z)Ljava/lang/String;"); global::android.text.format.Time._isEpoch8009 = @__env.GetStaticMethodIDNoThrow(global::android.text.format.Time.staticClass, "isEpoch", "(Landroid/text/format/Time;)Z"); global::android.text.format.Time._getJulianDay8010 = @__env.GetStaticMethodIDNoThrow(global::android.text.format.Time.staticClass, "getJulianDay", "(JJ)I"); global::android.text.format.Time._setJulianDay8011 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "setJulianDay", "(I)J"); global::android.text.format.Time._Time8012 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "<init>", "(Ljava/lang/String;)V"); global::android.text.format.Time._Time8013 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "<init>", "()V"); global::android.text.format.Time._Time8014 = @__env.GetMethodIDNoThrow(global::android.text.format.Time.staticClass, "<init>", "(Landroid/text/format/Time;)V"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Primitives; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Models.Trees; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Trees; using Umbraco.Cms.Web.BackOffice.Controllers; using Umbraco.Cms.Web.BackOffice.Extensions; using Umbraco.Cms.Web.Common.Attributes; using Umbraco.Cms.Web.Common.Filters; using Umbraco.Cms.Web.Common.ModelBinders; using Umbraco.Extensions; using static Umbraco.Cms.Core.Constants.Web.Routing; namespace Umbraco.Cms.Web.BackOffice.Trees { /// <summary> /// Used to return tree root nodes /// </summary> [AngularJsonOnlyConfiguration] [PluginController(Constants.Web.Mvc.BackOfficeTreeArea)] public class ApplicationTreeController : UmbracoAuthorizedApiController { private readonly ITreeService _treeService; private readonly ISectionService _sectionService; private readonly ILocalizedTextService _localizedTextService; private readonly IControllerFactory _controllerFactory; private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider; /// <summary> /// Initializes a new instance of the <see cref="ApplicationTreeController"/> class. /// </summary> public ApplicationTreeController( ITreeService treeService, ISectionService sectionService, ILocalizedTextService localizedTextService, IControllerFactory controllerFactory, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) { _treeService = treeService; _sectionService = sectionService; _localizedTextService = localizedTextService; _controllerFactory = controllerFactory; _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; } /// <summary> /// Returns the tree nodes for an application /// </summary> /// <param name="application">The application to load tree for</param> /// <param name="tree">An optional single tree alias, if specified will only load the single tree for the request app</param> /// <param name="queryStrings">The query strings</param> /// <param name="use">Tree use.</param> public async Task<ActionResult<TreeRootNode>> GetApplicationTrees(string application, string tree, [ModelBinder(typeof(HttpQueryStringModelBinder))] FormCollection queryStrings, TreeUse use = TreeUse.Main) { application = application.CleanForXss(); if (string.IsNullOrEmpty(application)) { return NotFound(); } var section = _sectionService.GetByAlias(application); if (section == null) { return NotFound(); } // find all tree definitions that have the current application alias var groupedTrees = _treeService.GetBySectionGrouped(application, use); var allTrees = groupedTrees.Values.SelectMany(x => x).ToList(); if (allTrees.Count == 0) { // if there are no trees defined for this section but the section is defined then we can have a simple // full screen section without trees var name = _localizedTextService.Localize("sections", application); return TreeRootNode.CreateSingleTreeRoot(Constants.System.RootString, null, null, name, TreeNodeCollection.Empty, true); } // handle request for a specific tree / or when there is only one tree if (!tree.IsNullOrWhiteSpace() || allTrees.Count == 1) { var t = tree.IsNullOrWhiteSpace() ? allTrees[0] : allTrees.FirstOrDefault(x => x.TreeAlias == tree); if (t == null) { return NotFound(); } var treeRootNode = await GetTreeRootNode(t, Constants.System.Root, queryStrings); if (treeRootNode != null) { return treeRootNode; } return NotFound(); } // handle requests for all trees // for only 1 group if (groupedTrees.Count == 1) { var nodes = new TreeNodeCollection(); foreach (var t in allTrees) { var nodeResult = await TryGetRootNode(t, queryStrings); if (!(nodeResult.Result is null)) { return nodeResult.Result; } var node = nodeResult.Value; if (node != null) { nodes.Add(node); } } var name = _localizedTextService.Localize("sections", application); if (nodes.Count > 0) { var treeRootNode = TreeRootNode.CreateMultiTreeRoot(nodes); treeRootNode.Name = name; return treeRootNode; } // otherwise it's a section with all empty trees, aka a fullscreen section // todo is this true? what if we just failed to TryGetRootNode on all of them? SD: Yes it's true but we should check the result of TryGetRootNode and throw? return TreeRootNode.CreateSingleTreeRoot(Constants.System.RootString, null, null, name, TreeNodeCollection.Empty, true); } // for many groups var treeRootNodes = new List<TreeRootNode>(); foreach (var (groupName, trees) in groupedTrees) { var nodes = new TreeNodeCollection(); foreach (var t in trees) { var nodeResult = await TryGetRootNode(t, queryStrings); if (nodeResult != null && nodeResult.Result is not null) { return nodeResult.Result; } var node = nodeResult?.Value; if (node != null) { nodes.Add(node); } } if (nodes.Count == 0) { continue; } // no name => third party // use localization key treeHeaders/thirdPartyGroup // todo this is an odd convention var name = groupName.IsNullOrWhiteSpace() ? "thirdPartyGroup" : groupName; var groupRootNode = TreeRootNode.CreateGroupNode(nodes, application); groupRootNode.Name = _localizedTextService.Localize("treeHeaders", name); treeRootNodes.Add(groupRootNode); } return TreeRootNode.CreateGroupedMultiTreeRoot(new TreeNodeCollection(treeRootNodes.OrderBy(x => x.Name))); } /// <summary> /// Tries to get the root node of a tree. /// </summary> /// <remarks> /// <para>Returns null if the root node could not be obtained due to that /// the user isn't authorized to view that tree. In this case since we are /// loading multiple trees we will just return null so that it's not added /// to the list</para> /// </remarks> private async Task<ActionResult<TreeNode>> TryGetRootNode(Tree tree, FormCollection querystring) { if (tree == null) { throw new ArgumentNullException(nameof(tree)); } return await GetRootNode(tree, querystring); } /// <summary> /// Get the tree root node of a tree. /// </summary> private async Task<ActionResult<TreeRootNode>> GetTreeRootNode(Tree tree, int id, FormCollection querystring) { if (tree == null) { throw new ArgumentNullException(nameof(tree)); } var childrenResult = await GetChildren(tree, id, querystring); if (!(childrenResult.Result is null)) { return new ActionResult<TreeRootNode>(childrenResult.Result); } var children = childrenResult.Value; var rootNodeResult = await GetRootNode(tree, querystring); if (!(rootNodeResult.Result is null)) { return rootNodeResult.Result; } var rootNode = rootNodeResult.Value; var sectionRoot = TreeRootNode.CreateSingleTreeRoot( Constants.System.RootString, rootNode.ChildNodesUrl, rootNode.MenuUrl, rootNode.Name, children, tree.IsSingleNodeTree); // assign the route path based on the root node, this means it will route there when the // section is navigated to and no dashboards will be available for this section sectionRoot.RoutePath = rootNode.RoutePath; sectionRoot.Path = rootNode.Path; foreach (var d in rootNode.AdditionalData) { sectionRoot.AdditionalData[d.Key] = d.Value; } return sectionRoot; } /// <summary> /// Gets the root node of a tree. /// </summary> private async Task<ActionResult<TreeNode>> GetRootNode(Tree tree, FormCollection querystring) { if (tree == null) { throw new ArgumentNullException(nameof(tree)); } var result = await GetApiControllerProxy(tree.TreeControllerType, "GetRootNode", querystring); // return null if the user isn't authorized to view that tree if (!((ForbidResult)result.Result is null)) { return null; } var controller = (TreeControllerBase)result.Value; var rootNodeResult = await controller.GetRootNode(querystring); if (!(rootNodeResult.Result is null)) { return rootNodeResult.Result; } var rootNode = rootNodeResult.Value; if (rootNode == null) { throw new InvalidOperationException($"Failed to get root node for tree \"{tree.TreeAlias}\"."); } return rootNode; } /// <summary> /// Get the child nodes of a tree node. /// </summary> private async Task<ActionResult<TreeNodeCollection>> GetChildren(Tree tree, int id, FormCollection querystring) { if (tree == null) { throw new ArgumentNullException(nameof(tree)); } // the method we proxy has an 'id' parameter which is *not* in the querystring, // we need to add it for the proxy to work (else, it does not find the method, // when trying to run auth filters etc). var d = querystring?.ToDictionary(x => x.Key, x => x.Value) ?? new Dictionary<string, StringValues>(); d["id"] = StringValues.Empty; var proxyQuerystring = new FormCollection(d); var controllerResult = await GetApiControllerProxy(tree.TreeControllerType, "GetNodes", proxyQuerystring); if (!(controllerResult.Result is null)) { return new ActionResult<TreeNodeCollection>(controllerResult.Result); } var controller = (TreeControllerBase)controllerResult.Value; return await controller.GetNodes(id.ToInvariantString(), querystring); } /// <summary> /// Gets a proxy to a controller for a specified action. /// </summary> /// <param name="controllerType">The type of the controller.</param> /// <param name="action">The action.</param> /// <param name="querystring">The querystring.</param> /// <returns>An instance of the controller.</returns> /// <remarks> /// <para>Creates an instance of the <paramref name="controllerType"/> and initializes it with a route /// and context etc. so it can execute the specified <paramref name="action"/>. Runs the authorization /// filters for that action, to ensure that the user has permission to execute it.</para> /// </remarks> private async Task<ActionResult<object>> GetApiControllerProxy(Type controllerType, string action, FormCollection querystring) { // note: this is all required in order to execute the auth-filters for the sub request, we // need to "trick" mvc into thinking that it is actually executing the proxied controller. var controllerName = ControllerExtensions.GetControllerName(controllerType); // create proxy route data specifying the action & controller to execute var routeData = new RouteData(new RouteValueDictionary() { [ActionToken] = action, [ControllerToken] = controllerName }); if (!(querystring is null)) { foreach (var (key, value) in querystring) { routeData.Values[key] = value; } } var actionDescriptor = _actionDescriptorCollectionProvider.ActionDescriptors.Items .Cast<ControllerActionDescriptor>() .First(x => x.ControllerName.Equals(controllerName) && x.ActionName == action); var actionContext = new ActionContext(HttpContext, routeData, actionDescriptor); var proxyControllerContext = new ControllerContext(actionContext); var controller = (TreeController)_controllerFactory.CreateController(proxyControllerContext); // TODO: What about other filters? Will they execute? var isAllowed = await controller.ControllerContext.InvokeAuthorizationFiltersForRequest(actionContext); if (!isAllowed) { return Forbid(); } return controller; } } }
using Autofac.Features.Metadata; using Orchard.Environment.Extensions.Models; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace Orchard.UI.Resources { public class ResourceManager : IResourceManager, IUnitOfWorkDependency { private readonly Dictionary<Tuple<string, string>, RequireSettings> _required = new Dictionary<Tuple<string, string>, RequireSettings>(); private readonly List<LinkEntry> _links = new List<LinkEntry>(); private readonly Dictionary<string, MetaEntry> _metas = new Dictionary<string, MetaEntry> { { "generator", new MetaEntry { Content = "Orchard", Name = "generator" } } }; private readonly Dictionary<string, IList<ResourceRequiredContext>> _builtResources = new Dictionary<string, IList<ResourceRequiredContext>>(StringComparer.OrdinalIgnoreCase); private readonly IEnumerable<Meta<IResourceManifestProvider>> _providers; private ResourceManifest _dynamicManifest; private List<string> _headScripts; private List<string> _footScripts; private IEnumerable<IResourceManifest> _manifests; private const string NotIE = "!IE"; private static string ToAppRelativePath(string resourcePath) { if (!string.IsNullOrEmpty(resourcePath) && !Uri.IsWellFormedUriString(resourcePath, UriKind.Absolute)) { resourcePath = VirtualPathUtility.ToAppRelative(resourcePath); } return resourcePath; } private static string FixPath(string resourcePath, string relativeFromPath) { if (!string.IsNullOrEmpty(resourcePath) && !VirtualPathUtility.IsAbsolute(resourcePath) && !Uri.IsWellFormedUriString(resourcePath, UriKind.Absolute)) { // appears to be a relative path (e.g. 'foo.js' or '../foo.js', not "/foo.js" or "http://..") if (string.IsNullOrEmpty(relativeFromPath)) { throw new InvalidOperationException("ResourcePath cannot be relative unless a base relative path is also provided."); } resourcePath = VirtualPathUtility.ToAbsolute(VirtualPathUtility.Combine(relativeFromPath, resourcePath)); } return resourcePath; } private static TagBuilder GetTagBuilder(ResourceDefinition resource, string url) { var tagBuilder = new TagBuilder(resource.TagName); tagBuilder.MergeAttributes(resource.TagBuilder.Attributes); if (!string.IsNullOrEmpty(resource.FilePathAttributeName)) { if (!string.IsNullOrEmpty(url)) { if (VirtualPathUtility.IsAppRelative(url)) { url = VirtualPathUtility.ToAbsolute(url); } tagBuilder.MergeAttribute(resource.FilePathAttributeName, url, true); } } return tagBuilder; } public static void WriteResource(TextWriter writer, ResourceDefinition resource, string url, string condition, Dictionary<string, string> attributes) { if (!string.IsNullOrEmpty(condition)) { if (condition == NotIE) { writer.WriteLine("<!--[if " + condition + "]>-->"); } else { writer.WriteLine("<!--[if " + condition + "]>"); } } var tagBuilder = GetTagBuilder(resource, url); if (attributes != null) { // todo: try null value tagBuilder.MergeAttributes(attributes, true); } writer.WriteLine(tagBuilder.ToString(resource.TagRenderMode)); if (!string.IsNullOrEmpty(condition)) { if (condition == NotIE) { writer.WriteLine("<!--<![endif]-->"); } else { writer.WriteLine("<![endif]-->"); } } } public ResourceManager(IEnumerable<Meta<IResourceManifestProvider>> resourceProviders) { _providers = resourceProviders; } public IEnumerable<IResourceManifest> ResourceProviders { get { if (_manifests == null) { var builder = new ResourceManifestBuilder(); foreach (var provider in _providers) { builder.Feature = provider.Metadata.ContainsKey("Feature") ? (Feature)provider.Metadata["Feature"] : null; provider.Value.BuildManifests(builder); } _manifests = builder.ResourceManifests; } return _manifests; } } public virtual ResourceManifest DynamicResources { get { return _dynamicManifest ?? (_dynamicManifest = new ResourceManifest()); } } public virtual RequireSettings Require(string resourceType, string resourceName) { if (resourceType == null) { throw new ArgumentNullException("resourceType"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } RequireSettings settings; var key = new Tuple<string, string>(resourceType, resourceName); if (!_required.TryGetValue(key, out settings)) { settings = new RequireSettings { Type = resourceType, Name = resourceName }; _required[key] = settings; } _builtResources[resourceType] = null; return settings; } public virtual RequireSettings Include(string resourceType, string resourcePath, string resourceDebugPath) { return Include(resourceType, resourcePath, resourceDebugPath, null); } public virtual RequireSettings Include(string resourceType, string resourcePath, string resourceDebugPath, string relativeFromPath) { if (resourceType == null) { throw new ArgumentNullException("resourceType"); } if (resourcePath == null) { throw new ArgumentNullException("resourcePath"); } // ~/ ==> convert to absolute path (e.g. /orchard/..) if (VirtualPathUtility.IsAppRelative(resourcePath)) { resourcePath = VirtualPathUtility.ToAbsolute(resourcePath); } if (resourceDebugPath != null && VirtualPathUtility.IsAppRelative(resourceDebugPath)) { resourceDebugPath = VirtualPathUtility.ToAbsolute(resourceDebugPath); } resourcePath = FixPath(resourcePath, relativeFromPath); resourceDebugPath = FixPath(resourceDebugPath, relativeFromPath); return Require(resourceType, ToAppRelativePath(resourcePath)).Define(d => d.SetUrl(resourcePath, resourceDebugPath)); } public virtual void RegisterHeadScript(string script) { if (_headScripts == null) { _headScripts = new List<string>(); } _headScripts.Add(script); } public virtual void RegisterFootScript(string script) { if (_footScripts == null) { _footScripts = new List<string>(); } _footScripts.Add(script); } public virtual void NotRequired(string resourceType, string resourceName) { if (resourceType == null) { throw new ArgumentNullException("resourceType"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } var key = new Tuple<string, string>(resourceType, resourceName); _builtResources[resourceType] = null; _required.Remove(key); } public virtual ResourceDefinition FindResource(RequireSettings settings) { return FindResource(settings, true); } private ResourceDefinition FindResource(RequireSettings settings, bool resolveInlineDefinitions) { // find the resource with the given type and name // that has at least the given version number. If multiple, // return the resource with the greatest version number. // If not found and an inlineDefinition is given, define the resource on the fly // using the action. var name = settings.Name ?? ""; var type = settings.Type; var resource = (from p in ResourceProviders from r in p.GetResources(type) where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase) let version = r.Value.Version != null ? new Version(r.Value.Version) : null orderby version descending select r.Value).FirstOrDefault(); if (resource == null && _dynamicManifest != null) { resource = (from r in _dynamicManifest.GetResources(type) where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase) let version = r.Value.Version != null ? new Version(r.Value.Version) : null orderby version descending select r.Value).FirstOrDefault(); } if (resolveInlineDefinitions && resource == null) { // Does not seem to exist, but it's possible it is being // defined by a Define() from a RequireSettings somewhere. if (ResolveInlineDefinitions(settings.Type)) { // if any were defined, now try to find it resource = FindResource(settings, false); } } return resource; } private bool ResolveInlineDefinitions(string resourceType) { bool anyWereDefined = false; foreach (var settings in GetRequiredResources(resourceType).Where(settings => settings.InlineDefinition != null)) { // defining it on the fly var resource = FindResource(settings, false); if (resource == null) { // does not already exist, so define it resource = DynamicResources.DefineResource(resourceType, settings.Name).SetBasePath(settings.BasePath); anyWereDefined = true; } settings.InlineDefinition(resource); settings.InlineDefinition = null; } return anyWereDefined; } public virtual IEnumerable<RequireSettings> GetRequiredResources(string type) { return _required.Where(r => r.Key.Item1 == type).Select(r => r.Value); } public virtual IList<LinkEntry> GetRegisteredLinks() { return _links.AsReadOnly(); } public virtual IList<MetaEntry> GetRegisteredMetas() { return _metas.Values.ToList().AsReadOnly(); } public virtual IList<string> GetRegisteredHeadScripts() { return _headScripts == null ? null : _headScripts.AsReadOnly(); } public virtual IList<string> GetRegisteredFootScripts() { return _footScripts == null ? null : _footScripts.AsReadOnly(); } public virtual IList<ResourceRequiredContext> BuildRequiredResources(string resourceType) { IList<ResourceRequiredContext> requiredResources; if (_builtResources.TryGetValue(resourceType, out requiredResources) && requiredResources != null) { return requiredResources; } var allResources = new OrderedDictionary(); foreach (var settings in GetRequiredResources(resourceType)) { var resource = FindResource(settings); if (resource == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "A '{1}' named '{0}' could not be found.", settings.Name, settings.Type)); } ExpandDependencies(resource, settings, allResources); } requiredResources = (from DictionaryEntry entry in allResources select new ResourceRequiredContext { Resource = (ResourceDefinition)entry.Key, Settings = (RequireSettings)entry.Value }).ToList(); _builtResources[resourceType] = requiredResources; return requiredResources; } protected virtual void ExpandDependencies(ResourceDefinition resource, RequireSettings settings, OrderedDictionary allResources) { if (resource == null) { return; } // Settings is given so they can cascade down into dependencies. For example, if Foo depends on Bar, and Foo's required // location is Head, so too should Bar's location. // forge the effective require settings for this resource // (1) If a require exists for the resource, combine with it. Last settings in gets preference for its specified values. // (2) If no require already exists, form a new settings object based on the given one but with its own type/name. settings = allResources.Contains(resource) ? ((RequireSettings)allResources[resource]).Combine(settings) : new RequireSettings { Type = resource.Type, Name = resource.Name }.Combine(settings); if (resource.Dependencies != null) { var dependencies = from d in resource.Dependencies select FindResource(new RequireSettings { Type = resource.Type, Name = d }); foreach (var dependency in dependencies) { if (dependency == null) { continue; } ExpandDependencies(dependency, settings, allResources); } } allResources[resource] = settings; } public void RegisterLink(LinkEntry link) { _links.Add(link); } public void SetMeta(MetaEntry meta) { if (meta == null) { return; } var index = meta.Name ?? meta.HttpEquiv ?? "charset"; _metas[index] = meta; } public void AppendMeta(MetaEntry meta, string contentSeparator) { if (meta == null) { return; } var index = meta.Name ?? meta.HttpEquiv; if (string.IsNullOrEmpty(index)) { return; } MetaEntry existingMeta; if (_metas.TryGetValue(index, out existingMeta)) { meta = MetaEntry.Combine(existingMeta, meta, contentSeparator); } _metas[index] = meta; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; using Xunit; namespace System.Xml.Tests { public partial class CharCheckingReaderTest : CGenericTestModule { private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator) { CModInfo.CommandLine = "/async"; RunTestCase(testCaseGenerator); } private static void RunTestCase(Func<CTestBase> testCaseGenerator) { var module = new CharCheckingReaderTest(); module.Init(null); module.AddChild(testCaseGenerator()); module.Execute(); Assert.Equal(0, module.FailCount); } private static void RunTest(Func<CTestBase> testCaseGenerator) { RunTestCase(testCaseGenerator); RunTestCaseAsync(testCaseGenerator); } [Fact] [OuterLoop] public static void ErrorConditionReader() { RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void DepthReader() { RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void NamespaceReader() { RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void IsEmptyElementReader() { RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void XmlSpaceReader() { RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void XmlLangReader() { RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void SkipReader() { RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void InvalidXMLReader() { RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadOuterXmlReader() { RunTest(() => new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void AttributeAccessReader() { RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ThisNameReader() { RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void MoveToAttributeReader() { RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void GetAttributeOrdinalReader() { RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void GetAttributeNameReader() { RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ThisOrdinalReader() { RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void MoveToAttributeOrdinalReader() { RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void MoveToFirstAttributeReader() { RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void MoveToNextAttributeReader() { RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void AttributeTestReader() { RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void AttributeXmlDeclarationReader() { RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void XmlnsReader() { RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void XmlnsPrefixReader() { RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadInnerXmlReader() { RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void MoveToContentReader() { RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void IsStartElementReader() { RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadStartElementReader() { RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadEndElementReader() { RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ResolveEntityReader() { RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void HasValueReader() { RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadAttributeValueReader() { RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadReader() { RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void MoveToElementReader() { RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void DisposeReader() { RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void BufferBoundariesReader() { RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void XmlNodeIntegrityTestFileBeforeRead() { RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } }); } [Fact] [OuterLoop] public static void XmlNodeIntegrityTestFileAfterCloseInMiddle() { RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } }); } [Fact] [OuterLoop] public static void XmlNodeIntegrityTestFileAfterClose() { RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } }); } [Fact] [OuterLoop] public static void XmlNodeIntegrityTestFileAfterReadIsFalse() { RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } }); } [Fact] [OuterLoop] public static void ReadSubtreeReader() { RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadToDescendantReader() { RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadToNextSiblingReader() { RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadValueReader() { RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadContentAsBase64Reader() { RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadElementContentAsBase64Reader() { RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadContentAsBinHexReader() { RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadElementContentAsBinHexReader() { RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "CharCheckingReader" } }); } [Fact] [OuterLoop] public static void ReadToFollowingReader() { RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "CharCheckingReader" } }); } } }
using WixSharp; using WixSharp.UI.Forms; namespace WixSharpSetup.Dialogs { partial class ExitDialog { /// <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() { this.imgPanel = new System.Windows.Forms.Panel(); this.description = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.image = new System.Windows.Forms.PictureBox(); this.bottomPanel = new System.Windows.Forms.Panel(); this.viewLog = new System.Windows.Forms.LinkLabel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.back = new System.Windows.Forms.Button(); this.next = new System.Windows.Forms.Button(); this.cancel = new System.Windows.Forms.Button(); this.border1 = new System.Windows.Forms.Panel(); this.textPanel = new System.Windows.Forms.Panel(); this.imgPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.image)).BeginInit(); this.bottomPanel.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.textPanel.SuspendLayout(); this.SuspendLayout(); // // imgPanel // this.imgPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.imgPanel.Controls.Add(this.textPanel); this.imgPanel.Controls.Add(this.image); this.imgPanel.Location = new System.Drawing.Point(0, 0); this.imgPanel.Name = "imgPanel"; this.imgPanel.Size = new System.Drawing.Size(494, 312); this.imgPanel.TabIndex = 8; // // description // this.description.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.description.Location = new System.Drawing.Point(4, 88); this.description.Name = "description"; this.description.Size = new System.Drawing.Size(298, 201); this.description.TabIndex = 7; this.description.Text = "[ExitDialogDescription]"; // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(299, 61); this.label1.TabIndex = 6; this.label1.Text = "[ExitDialogTitle]"; // // image // this.image.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.image.Location = new System.Drawing.Point(0, 0); this.image.Name = "image"; this.image.Size = new System.Drawing.Size(156, 312); this.image.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.image.TabIndex = 4; this.image.TabStop = false; // // bottomPanel // this.bottomPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.bottomPanel.BackColor = System.Drawing.SystemColors.Control; this.bottomPanel.Controls.Add(this.viewLog); this.bottomPanel.Controls.Add(this.tableLayoutPanel1); this.bottomPanel.Controls.Add(this.border1); this.bottomPanel.Location = new System.Drawing.Point(0, 312); this.bottomPanel.Name = "bottomPanel"; this.bottomPanel.Size = new System.Drawing.Size(494, 49); this.bottomPanel.TabIndex = 5; // // viewLog // this.viewLog.Anchor = System.Windows.Forms.AnchorStyles.Left; this.viewLog.AutoSize = true; this.viewLog.Location = new System.Drawing.Point(16, 17); this.viewLog.Name = "viewLog"; this.viewLog.Size = new System.Drawing.Size(54, 13); this.viewLog.TabIndex = 1; this.viewLog.TabStop = true; this.viewLog.Text = "[ViewLog]"; this.viewLog.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.viewLog_LinkClicked); // // tableLayoutPanel1 // this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel1.ColumnCount = 5; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 14F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.back, 1, 0); this.tableLayoutPanel1.Controls.Add(this.next, 2, 0); this.tableLayoutPanel1.Controls.Add(this.cancel, 4, 0); this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 3); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(491, 43); this.tableLayoutPanel1.TabIndex = 7; // // back // this.back.Anchor = System.Windows.Forms.AnchorStyles.Right; this.back.AutoSize = true; this.back.Enabled = false; this.back.Location = new System.Drawing.Point(218, 10); this.back.MinimumSize = new System.Drawing.Size(75, 0); this.back.Name = "back"; this.back.Size = new System.Drawing.Size(77, 23); this.back.TabIndex = 0; this.back.Text = "[WixUIBack]"; this.back.UseVisualStyleBackColor = true; // // next // this.next.Anchor = System.Windows.Forms.AnchorStyles.Right; this.next.AutoSize = true; this.next.Location = new System.Drawing.Point(301, 10); this.next.MinimumSize = new System.Drawing.Size(75, 0); this.next.Name = "next"; this.next.Size = new System.Drawing.Size(81, 23); this.next.TabIndex = 0; this.next.Text = "[WixUIFinish]"; this.next.UseVisualStyleBackColor = true; this.next.Click += new System.EventHandler(this.finish_Click); // // cancel // this.cancel.Anchor = System.Windows.Forms.AnchorStyles.Right; this.cancel.AutoSize = true; this.cancel.Enabled = false; this.cancel.Location = new System.Drawing.Point(402, 10); this.cancel.MinimumSize = new System.Drawing.Size(75, 0); this.cancel.Name = "cancel"; this.cancel.Size = new System.Drawing.Size(86, 23); this.cancel.TabIndex = 0; this.cancel.Text = "[WixUICancel]"; this.cancel.UseVisualStyleBackColor = true; // // border1 // this.border1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.border1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.border1.Location = new System.Drawing.Point(0, 0); this.border1.Name = "border1"; this.border1.Size = new System.Drawing.Size(494, 1); this.border1.TabIndex = 9; // // textPanel // this.textPanel.Controls.Add(this.label1); this.textPanel.Controls.Add(this.description); this.textPanel.Location = new System.Drawing.Point(177, 17); this.textPanel.Name = "textPanel"; this.textPanel.Size = new System.Drawing.Size(305, 289); this.textPanel.TabIndex = 8; // // ExitDialog // this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(494, 361); this.Controls.Add(this.imgPanel); this.Controls.Add(this.bottomPanel); this.Name = "ExitDialog"; this.Text = "[ExitDialog_Title]"; this.Load += new System.EventHandler(this.ExitDialog_Load); this.imgPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.image)).EndInit(); this.bottomPanel.ResumeLayout(false); this.bottomPanel.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.textPanel.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label description; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel bottomPanel; private System.Windows.Forms.PictureBox image; private System.Windows.Forms.LinkLabel viewLog; private System.Windows.Forms.Panel imgPanel; private System.Windows.Forms.Panel border1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Button back; private System.Windows.Forms.Button next; private System.Windows.Forms.Button cancel; private System.Windows.Forms.Panel textPanel; } }
namespace Coop_Listing_Site.Migrations { using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<DAL.CoopContext> { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(DAL.CoopContext context) { UserManager<User> userManager = new UserManager<User>(new UserStore<User>(context)); //Create roles IdentityRole studentrole = new IdentityRole() { Name = "Student" }, coordrole = new IdentityRole() { Name = "Coordinator" }, adminrole = new IdentityRole() { Name = "Admin" }, superAdminRole = new IdentityRole() { Name = "SuperAdmin" }; context.Roles.AddOrUpdate(r => r.Name, studentrole, coordrole, adminrole, superAdminRole); context.SaveChanges(); //Create LaneCC majors Major major = new Major { MajorName = "Computer Simulation and Game Development" }; Major major1 = new Major { MajorName = "Computer Network Operations" }; Major major2 = new Major { MajorName = "Computer Programming" }; Major major3 = new Major { MajorName = "Health Informatics" }; Major major4 = new Major { MajorName = "Retail Management" }; Major major5 = new Major { MajorName = "Business Management" }; Major major6 = new Major { MajorName = "Accounting" }; Major major7 = new Major { MajorName = "Emergency Medical Technician(EMT)" }; Major major8 = new Major { MajorName = "Respiratory Care" }; Major major9 = new Major { MajorName = "Dental Assisting" }; Major major10 = new Major { MajorName = "Dental Hygiene" }; Major major11 = new Major { MajorName = "Medical Office Assistant(MOA)" }; Major major12 = new Major { MajorName = "Respiratory Care Clinical Practice" }; Major major13 = new Major { MajorName = "Physical Therapist Asistant(Clinical Affiliation)" }; Major major14 = new Major { MajorName = "Nursing" }; Major major15 = new Major { MajorName = "Auto Body & Fender" }; Major major16 = new Major { MajorName = "Automotive Technology" }; Major major17 = new Major { MajorName = "Aviation Maintenance" }; Major major18 = new Major { MajorName = "Construction" }; Major major19 = new Major { MajorName = "Diesel Technology" }; Major major20 = new Major { MajorName = "Drafting" }; Major major21 = new Major { MajorName = "Electronics Technology" }; Major major22 = new Major { MajorName = "Energy Management" }; Major major23 = new Major { MajorName = "Flight Technology" }; Major major24 = new Major { MajorName = "Gen Work Experience(180 & 280)" }; Major major25 = new Major { MajorName = "Health Occupations(Pharmacy Technician, Sterile Processing, Vet Assistant)" }; Major major26 = new Major { MajorName = "Occupational Skills" }; Major major27 = new Major { MajorName = "Landscape" }; Major major28 = new Major { MajorName = "Manufacturing Technology" }; Major major29 = new Major { MajorName = "Sustainability Coordinator" }; Major major30 = new Major { MajorName = "Water Conservation Technology" }; Major major31 = new Major { MajorName = "Watershed Science Technology" }; Major major32 = new Major { MajorName = "Welding/ASLCC" }; Major major33 = new Major { MajorName = "Pre-Law" }; Major major34 = new Major { MajorName = "Ethnic Studies" }; Major major35 = new Major { MajorName = "Psychology" }; Major major36 = new Major { MajorName = "Sociology" }; Major major37 = new Major { MajorName = "Service Learning +" }; Major major38 = new Major { MajorName = "Criminal Justice/Academy" }; Major major39 = new Major { MajorName = "Human Services" }; Major major40 = new Major { MajorName = "Geographic Information Science(GIS)" }; Major major41 = new Major { MajorName = "Education(K-12 Teacher Prep)" }; Major major42 = new Major { MajorName = "Career Skills Training" }; Major major43 = new Major { MajorName = "Gen Work Experience(280)" }; Major major44 = new Major { MajorName = "Health Records Technology(HRT)" }; Major major45 = new Major { MajorName = "Aerobics" }; Major major46 = new Major { MajorName = "Athletic Training" }; Major major47 = new Major { MajorName = "Athletics" }; Major major48 = new Major { MajorName = "Coaching" }; Major major49 = new Major { MajorName = "Corrective Fitness" }; Major major50 = new Major { MajorName = "Fitness" }; Major major51 = new Major { MajorName = "Fitness Management" }; Major major52 = new Major { MajorName = "Physical Education" }; Major major53 = new Major { MajorName = "Recreation" }; Major major54 = new Major { MajorName = "Wellness" }; Major major55 = new Major { MajorName = "Political Science" }; Major major56 = new Major { MajorName = "Art & Applied Design" }; Major major57 = new Major { MajorName = "Graphic Design" }; Major major58 = new Major { MajorName = "Journalism" }; Major major59 = new Major { MajorName = "Multimedia Design" }; Major major60 = new Major { MajorName = "Music" }; Major major61 = new Major { MajorName = "Performing Arts" }; Major major62 = new Major { MajorName = "Administration Office Professional" }; Major major63 = new Major { MajorName = "Medical Receptionist" }; Major major64 = new Major { MajorName = "Phlebotomy" }; Major major65 = new Major { MajorName = "Early Childhood Education" }; Major major66 = new Major { MajorName = "Culinary Arts" }; Major major67 = new Major { MajorName = "Hospitality Management" }; //Create LaneCC Departments Department dept = new Department { DepartmentName = "Computer Information Technologies" }; Department dept1 = new Department { DepartmentName = "Business" }; Department dept2 = new Department { DepartmentName = "Health Professions" }; Department dept3 = new Department { DepartmentName = "Advanced Technology" }; Department dept4 = new Department { DepartmentName = "Social Science" }; Department dept5 = new Department { DepartmentName = "Cooperative Education" }; Department dept6 = new Department { DepartmentName = "Media Arts" }; Department dept7 = new Department { DepartmentName = "Child & Family Education" }; Department dept8 = new Department { DepartmentName = "Culinary/Foood Services" }; dept.Majors.Add(major); major.Department = dept; dept.Majors.Add(major1); major1.Department = dept; dept.Majors.Add(major2); major2.Department = dept; dept.Majors.Add(major3); major3.Department = dept; dept1.Majors.Add(major4); major4.Department = dept1; dept1.Majors.Add(major5); major5.Department = dept1; dept1.Majors.Add(major6); major6.Department = dept1; dept2.Majors.Add(major7); major7.Department = dept2; dept2.Majors.Add(major8); major8.Department = dept2; dept2.Majors.Add(major9); major9.Department = dept2; dept2.Majors.Add(major10); major10.Department = dept2; dept2.Majors.Add(major11); major11.Department = dept2; dept2.Majors.Add(major12); major12.Department = dept2; dept2.Majors.Add(major13); major13.Department = dept2; dept2.Majors.Add(major14); major14.Department = dept2; dept3.Majors.Add(major15); major15.Department = dept3; dept3.Majors.Add(major16); major16.Department = dept3; dept3.Majors.Add(major17); major17.Department = dept3; dept3.Majors.Add(major18); major18.Department = dept3; dept3.Majors.Add(major19); major19.Department = dept3; dept3.Majors.Add(major20); major20.Department = dept3; dept3.Majors.Add(major21); major21.Department = dept3; dept3.Majors.Add(major22); major22.Department = dept3; dept3.Majors.Add(major23); major23.Department = dept3; dept3.Majors.Add(major24); major24.Department = dept3; dept3.Majors.Add(major25); major25.Department = dept3; dept3.Majors.Add(major26); major26.Department = dept3; dept3.Majors.Add(major27); major27.Department = dept3; dept3.Majors.Add(major28); major28.Department = dept3; dept3.Majors.Add(major29); major29.Department = dept3; dept3.Majors.Add(major30); major30.Department = dept3; dept3.Majors.Add(major31); major31.Department = dept3; dept3.Majors.Add(major32); major32.Department = dept3; dept3.Majors.Add(major33); major33.Department = dept3; dept4.Majors.Add(major34); major34.Department = dept4; dept4.Majors.Add(major35); major35.Department = dept4; dept4.Majors.Add(major36); major36.Department = dept4; dept4.Majors.Add(major37); major37.Department = dept4; dept4.Majors.Add(major38); major38.Department = dept4; dept4.Majors.Add(major39); major39.Department = dept4; dept4.Majors.Add(major40); major40.Department = dept4; dept4.Majors.Add(major41); major41.Department = dept4; dept5.Majors.Add(major42); major42.Department = dept5; dept5.Majors.Add(major43); major43.Department = dept5; dept5.Majors.Add(major44); major44.Department = dept5; dept5.Majors.Add(major45); major45.Department = dept5; dept5.Majors.Add(major46); major46.Department = dept5; dept5.Majors.Add(major47); major47.Department = dept5; dept5.Majors.Add(major48); major48.Department = dept5; dept5.Majors.Add(major49); major49.Department = dept5; dept5.Majors.Add(major50); major50.Department = dept5; dept5.Majors.Add(major51); major51.Department = dept5; dept5.Majors.Add(major52); major52.Department = dept5; dept5.Majors.Add(major53); major53.Department = dept5; dept5.Majors.Add(major54); major54.Department = dept5; dept5.Majors.Add(major55); major55.Department = dept5; dept6.Majors.Add(major56); major56.Department = dept6; dept6.Majors.Add(major57); major57.Department = dept6; dept6.Majors.Add(major58); major58.Department = dept6; dept6.Majors.Add(major59); major59.Department = dept6; dept6.Majors.Add(major60); major60.Department = dept6; dept6.Majors.Add(major61); major61.Department = dept6; dept2.Majors.Add(major62); major62.Department = dept2; dept2.Majors.Add(major63); major63.Department = dept2; dept2.Majors.Add(major64); major64.Department = dept2; dept7.Majors.Add(major65); major65.Department = dept7; dept8.Majors.Add(major66); major66.Department = dept8; dept8.Majors.Add(major67); major67.Department = dept8; //context.SaveChanges(); // add Users #if DEBUG IdentityResult result1, result2, result3; User user1 = userManager.FindByEmail("test@test.com"); User user2 = userManager.FindByEmail("thinger@test.com"); User user3 = userManager.FindByEmail("testcoord@test.com"); if (user1 == null) { user1 = new User { UserName = "test@test.com", Email = "test@test.com", FirstName = "Test", LastName = "Testman", Enabled = true }; result1 = userManager.Create(user1, "password1"); if (!result1.Succeeded) throw new Exception("Account creation in seed failed"); } if (user2 == null) { user2 = new User { UserName = "thinger@test.com", Email = "thinger@test.com", FirstName = "Jon", LastName = "Doe", Enabled = true }; result2 = userManager.Create(user2, "password1"); if (!result2.Succeeded) throw new Exception("Account creation in seed failed"); } if (user3 == null) { user3 = new User { UserName = "testcoord@test.com", Email = "testcoord@test.com", FirstName = "John", LastName = "Smith", Enabled = true }; result3 = userManager.Create(user3, "password1"); if (!result3.Succeeded) throw new Exception("Account creation in seed failed"); } // save so our new objects have IDs context.SaveChanges(); // add some info StudentInfo sInfo1 = new StudentInfo { LNumber = "L00000001", User = user1, Major = major }; StudentInfo sInfo2 = new StudentInfo { LNumber = "L00000002", User = user2, Major = major }; CoordinatorInfo cInfo1 = new CoordinatorInfo { User = user3 }; cInfo1.Majors.Add(major); cInfo1.Majors.Add(major1); cInfo1.Majors.Add(major2); // Add the student role to them userManager.AddToRole(user1.Id, "Student"); userManager.AddToRole(user2.Id, "Student"); userManager.AddToRoles(user3.Id, "Coordinator", "Admin"); context.Students.Add(sInfo1); context.Students.Add(sInfo2); context.Coordinators.Add(cInfo1); #else var role = context.Roles.FirstOrDefault(r => r.Name == "SuperAdmin"); if (role.Users.Count < 1) { var admin = userManager.FindByEmail("admin@admin.com"); if (admin == null) { admin = new User { UserName = "admin@admin.com", Email = "admin@admin.com", FirstName = "Admin", LastName = "Default", Enabled = true }; var result = userManager.Create(admin, "password1"); if (!result.Succeeded) throw new Exception("Creation of default administrator account failed"); } userManager.AddToRoles(admin.Id, "SuperAdmin", "Admin"); } else { var admin = userManager.FindByEmail("admin@admin.com"); if (!admin.Enabled) { admin.Enabled = true; userManager.Update(admin); } } #endif // test opportunities Opportunity opp1 = new Opportunity { CompanyName = "Oregon Research Institute", ContactName = "Nathen N.", ContactNumber = "(541)484-2123, (541)484-1108", ContactEmail = "nathann@ori.org", Location = "1776 Millrace, Eugene, OR 97403-1983", CompanyWebsite = "http://ori.org", AboutCompany = "Please follow link: http://ori.org/about_ori", AboutDepartment = "This is more about the type of projects we create: http://ori.org/infantnet", CoopPositionTitle = "Web Developer Intern", CoopPositionDuties = @"Oregon Research Institute is seeking students interested in working on web technologies and gaining practical programming experience.Those who have already been introduced to core web technologies will also have the opportunity to learn the full stack from front end responsive design to backend database schematics.The intern will also have opportunity to collaborate with a software development firm.This is an internship with a three or four term commitment and a weekly time commitment will ideally be around 10 hours with compensation at $10 / hr.", Qualifications = @"Suggested skills: Web Design (HTML, CSS, JavaScript), Database Querying, Problem Solving Skills, Curiosity and willingness to learn, Ability to work within a team and take feedback, Attention to detail: Nice skills to have: Android Application Programming experience, Objective C and iOS programming experience, AngularJS, Node JS", Paid = true, Wage = "$10 per hour", Duration = "three to four terms", OpeningsAvailable = 1, TermAvailable = "Fall", Department = dept }; dept.Opportunities.Add(opp1); opp1.Majors.Add(major2); major2.Opportunities.Add(opp1); Opportunity opp2 = new Opportunity { CompanyName = "Get Found", ContactName = "Gerry Meenaghan", ContactNumber = "(541)463-5883", ContactEmail = "meenaghan@lanecc.edu", Location = "319 Goodpasture island rd. Eugene, OR 97401", CompanyWebsite = "http://getfoundeugene.com", AboutCompany = @"Get Found, Eugene, LLC is a small, local web development company based in Eugene.Find out more about what makes it a unique company here: http://getfoundeugene.com", CoopPositionTitle = " Web Development Intern", CoopPositionDuties = @"Website development using HTML5/CSS3, Javascript, JQuery, & PHP; Wordpress, Researching existing templates / layouts and markets for client's websites, Creating web pages aligned with customer order specifications and industry best, practices such as responsive design for mobile devices; search - engine optimization, Occasional and limited office support ranging from answering phones to assisting, technical support staff with hardware / software troubleshooting tasks.", Qualifications = @"2nd-year AAS in Computer Programming student (1st-year / certificate-seeking students considered individually), Specific interest in front - end web coding and design work, Requires high degree of attention to detail; detail - oriented; excellent knowledge of spelling, grammar, punctuation, Successful completion of Web Authoring, JavaScript courses, completion of Academic Writing (WR 121) and Technical Writing(WR 227) highly recommended, Students with skills in advanced web coding / programming technologies such as PHP,preferred", Paid = false, Duration = "11 weeks maximum", OpeningsAvailable = 1, TermAvailable = "Spring", Department = dept }; dept.Opportunities.Add(opp2); opp2.Majors.Add(major2); major2.Opportunities.Add(opp2); Opportunity opp3 = new Opportunity { CompanyName = "A Family For Every Child", ContactName = "Scott Corcoran", ContactNumber = "(541)343-2856", ContactEmail = "scott@afamilyforeverychild.org", Location = "1675 W 11th ave. Eugene, OR 97402", CompanyWebsite = "http://afamilyforeverychild.org", AboutCompany = "AFFEC is agreat company doing wonderful things for children and families.", CoopPositionTitle = "Intern", CoopPositionDuties = "not provided yet", Qualifications = @"Having enough self-confidence to be psychologically stressed during the first few weeks until they understand what is here, Not so headstrong as to think that they have time to change everything, Willing to use their skills to build better interfaces to what we already have.", Paid = false, Duration = "One term", OpeningsAvailable = 1, TermAvailable = "Spring", Department = dept }; dept.Opportunities.Add(opp3); major.Opportunities.Add(opp3); major1.Opportunities.Add(opp3); opp3.Majors.Add(major); opp3.Majors.Add(major1); Opportunity opp4 = new Opportunity { CompanyName = "Lane County Finacial Division", ContactName = "Mike Barnhart", ContactNumber = "(541)682-4199", ContactEmail = "michael.barnhart@co.lane.us", Location = "125 E. 8th Ave. Eugene, OR 97401", CompanyWebsite = "http://lanecounty.org", CoopPositionTitle = "Intern", CoopPositionDuties = @"Auditing the weekly accounts payable vendor checks for accuracy. Agreeing the invoices to the voucher in the computer system, utilizing Excel spreadsheets. Resolving invoice or voucher discrepancies: includes interaction with other departments, Folding, stuffing, and mailing vendor checks. Disbursing checks internally.", Qualifications = @"Must be available to work the following days: Monday, Tuesday, and Thursday", Paid = true, Wage = "$12 per hour", Department = dept1 }; dept1.Opportunities.Add(opp4); foreach (var m in dept1.Majors) { m.Opportunities.Add(opp4); opp4.Majors.Add(m); } Opportunity opp5 = new Opportunity { CompanyName = "Budget Services", ContactName = "University Advancement Human Resources Manager", ContactNumber = "(541)346-3123", ContactEmail = "@uoregon.edu", Location = "1720 E 13th ave. Ste 312 Eugene, OR 97403", CompanyWebsite = "http://@uoregon.edu", AboutCompany = "Budget Services provides central support services for University Advancement of all financial transactions and contracts.", AboutDepartment = @"Budget Services provides central support services for University Advancement of all financial transactions and contracts. These services include accounts payable, accounts receivable, contracts, financial statements and retention and archiving of all financial and contractual documents", CoopPositionTitle = "Assistant", CoopPositionDuties = @"Document intake processing, Financial reporting functions, Review, edit and proof documents (contracts, forms and intranet), Copy, scan and log accounting transactions and other documents, Prepare binders and meeting materials, Data entry, Editing/updating spreadsheets and PDFs, Maintain electronic libraries and back up documentation, Assist with record retention management, Assist with various other projects as assigned", Qualifications = @"High level proficiency with spreadsheet and word processing computer applications, Strong organizational skills, attention to detail, ability to prioritize, and exercise sound independent judgment Experience creating and maintaining computer spreadsheets and databases. Demonstrated independent problem solving skills; ability to maintain confidentiality and professionalism, Ability to work cooperatively and strategically in a team environment with all levels of professionals. Excellent oral and written communication skills and ability to communicate and work effectively with individuals from diverse backgrounds and cultures Commitment to and experience promoting and enhancing diversity and equity", Paid = false, Department = dept1 }; dept1.Opportunities.Add(opp5); foreach (var m in dept1.Majors) { m.Opportunities.Add(opp5); opp4.Majors.Add(m); } context.Opportunities.AddOrUpdate(o => new { o.CompanyName, o.CoopPositionTitle, o.CoopPositionDuties }, opp1, opp2, opp3, opp4, opp5); context.Majors.AddOrUpdate(m => m.MajorName, major, major1, major2, major3, major4, major5, major6, major7, major8, major9, major10, major11, major12, major13, major14, major15, major16, major17, major18, major19, major20, major21, major22, major23, major24, major25, major26, major27, major28, major29, major30, major31, major32, major33, major34, major35, major36, major37, major38, major39, major40, major41, major42, major43, major44, major45, major46, major47, major48, major49, major50, major51, major52, major53, major54, major55, major56, major57, major58, major59, major60, major61, major62, major63, major64, major65, major66, major67); context.Departments.AddOrUpdate(d => d.DepartmentName, dept, dept1, dept2, dept3, dept4, dept5, dept6, dept7, dept8); context.SaveChanges(); #if false var courses = new List<Course>() { //Computer Programming new Course { CourseNumber = "CS133N" }, //0 new Course { CourseNumber = "MTH095" }, //1 new Course { CourseNumber = "CIS195" }, //2 new Course { CourseNumber = "ART288" }, //3 new Course { CourseNumber = "CS233N" }, //4 new Course { CourseNumber = "WR121" }, //5 new Course { CourseNumber = "CG203" }, //6 new Course { CourseNumber = "CS133JS" }, //7 new Course { CourseNumber = "CS125D" }, //8 new Course { CourseNumber = "CS234N" }, //9 new Course { CourseNumber = "CIS244" }, //10 new Course { CourseNumber = "CS295N" }, //11 //Required for Both new Course { CourseNumber = "CIS100" }, //12 //Computer Network Operations new Course { CourseNumber = "CS179" }, //13 new Course { CourseNumber = "CIS140W" } //14 }; courses.ForEach(s => context.Courses.AddOrUpdate(p => p.CourseNumber, s)); var majors = new List<Major>() { //new Major { MajorName = "Computer Programming", Courses = new List<Course>() }, //Initializes the List, can also be placed in the constructor //new Major { MajorName = "Computer Network Operations", Courses = new List<Course>() }, new Major { MajorName = "Computer Simulation and Game Development" }, new Major { MajorName = "Computer Information Systems" } }; majors.ForEach(s => context.Majors.AddOrUpdate(p => p.MajorName, s)); //Programming <--The method below populates the Initialized Courses List... shown above ^^^^^^^^^^^^^^^^^^^ for (int i = 0; i <= 12; i++) { AddOrUpdate_Major_Course(context, majors[0].MajorName, courses[i].CourseNumber); } //Networking for (int k = 12; k <= 14; k++) { AddOrUpdate_Major_Course(context, majors[1].MajorName, courses[k].CourseNumber); } var departments = new List<Department>() { new Department { DepartmentName = "Computer Information Technology", Majors = new List<Major>()} }; departments.ForEach(s => context.Departments.AddOrUpdate(p => p.DepartmentName, s)); //AddOrUpdates the Entity //AddOrUpdate the List in the Entity for (int i = 0; i <= 3; i++) { AddOrUpdate_Dept_Major(context, departments[0].DepartmentName, majors[i].MajorName); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* User Manager Specific Stuff & Open Web Interface for .Net (OWIN) */ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /*{ new CoordinatorInfo { FirstName = "Gerry", LastName = "Meenaghan", LNumber = "L00000000", Email = "meenaghang@lanecc.edu", PhoneNumber = "(541) 463-5883" }; }; var students = new List<StudentInfo>() { new StudentInfo { MajorID = 1, LNumber = "L91234560", FirstName = "Lonnie", LastName = "Teter-Davis", Email = "lonnie@email.com", PhoneNumber = "(541) 123-1111" }, new Student { MajorID = 1, LNumber = "L91234561", FirstName = "Gabe", LastName = "Griffin", Email = "gabe@email.com", PhoneNumber = "(541) 123-2222" }, new Student { MajorID = 1, LNumber = "L91234562",FirstName = "Tony", LastName = "Plueard", Email = "tony@email.com", PhoneNumber = "(541) 123-3333" }, new Student { MajorID = 1, LNumber = "L91234563",FirstName = "Jason", LastName = "Prall", Email = "jason@email.com", PhoneNumber = "(541) 123-4444" }, new Student { MajorID = 1, LNumber = "L91234564",FirstName = "Ben", LastName = "Middleton-Rippberger", Email = "ben@email.com", PhoneNumber = "(541) 123-5555" }, new Student { MajorID = 2, LNumber = "L91234565",FirstName = "Sam", LastName = "Ple", Email = "sample@email.com", PhoneNumber = "(541) 123-6666" }, new Student { MajorID = 3, LNumber = "L91234566",FirstName = "Exam", LastName = "Ple", Email = "example@email.com", PhoneNumber = "(541) 123-7777" }, new Student { MajorID = 4, LNumber = "L91234567",FirstName = "Adam", LastName = "Sandler", Email = "sandlera@lane.edu", PhoneNumber = "(541) 123-8888" }, };*/ var opportunities = new List<Opportunity>() { new Opportunity { CompanyID = 1, OpeningsAvailable = 2, TermAvailable = "Summer" }, new Opportunity { CompanyID = 2, OpeningsAvailable = 1, TermAvailable = "Summer" }, new Opportunity { CompanyID = 3, OpeningsAvailable = 3, TermAvailable = "Winter" }, new Opportunity { CompanyID = 3, OpeningsAvailable = 1, TermAvailable = "Spring" } }; } //helper method used like the AddOrUpdate method... this inhibits the migration from duplicating entries void AddOrUpdate_Major_Course(DAL.CoopContext context, string majorName, string courseNumber) { var major = context.Majors.SingleOrDefault(m => m.MajorName == majorName); //var course = major.Courses.SingleOrDefault(c => c.CourseNumber == courseNumber); //if (course == null) // major.Courses.Add(context.Courses.Single(c => c.CourseNumber == courseNumber)); } void AddOrUpdate_Dept_Major(DAL.CoopContext context, string deptName, string majorName) { var dept = context.Departments.SingleOrDefault(d => d.DepartmentName == deptName); var major = dept.Majors.SingleOrDefault(m => m.MajorName == majorName); if (major == null) dept.Majors.Add(context.Majors.Single(m => m.MajorName == majorName)); #endif } } }
using System; using BTCPayServer.Data; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; namespace BTCPayServer.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20170913143004_Init")] public partial class Init : Migration { protected override void Up(MigrationBuilder migrationBuilder) { int? maxLength = this.IsMySql(migrationBuilder.ActiveProvider) ? (int?)255 : null; migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false, maxLength: maxLength), 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: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false, maxLength: maxLength), 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: "Stores", columns: table => new { Id = table.Column<string>(nullable: false, maxLength: maxLength), DerivationStrategy = table.Column<string>(nullable: true), SpeedPolicy = table.Column<int>(nullable: false), StoreCertificate = table.Column<byte[]>(nullable: true), StoreName = table.Column<string>(nullable: true), StoreWebsite = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Stores", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false, maxLength: maxLength) }, 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("Sqlite:Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false, maxLength: maxLength) }, 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, maxLength: 255), ProviderKey = table.Column<string>(nullable: false, maxLength: 255), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false, maxLength: maxLength) }, 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, maxLength: maxLength), RoleId = table.Column<string>(nullable: false, maxLength: maxLength) }, 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.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false, maxLength: maxLength), LoginProvider = table.Column<string>(nullable: false, maxLength: 64), Name = table.Column<string>(nullable: false, maxLength: 64), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Invoices", columns: table => new { Id = table.Column<string>(nullable: false, maxLength: maxLength), Blob = table.Column<byte[]>(nullable: true), Created = table.Column<DateTimeOffset>(nullable: false), CustomerEmail = table.Column<string>(nullable: true), ExceptionStatus = table.Column<string>(nullable: true), ItemCode = table.Column<string>(nullable: true), OrderId = table.Column<string>(nullable: true), Status = table.Column<string>(nullable: true), StoreDataId = table.Column<string>(nullable: true, maxLength: maxLength) }, constraints: table => { table.PrimaryKey("PK_Invoices", x => x.Id); table.ForeignKey( name: "FK_Invoices_Stores_StoreDataId", column: x => x.StoreDataId, principalTable: "Stores", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "UserStore", columns: table => new { ApplicationUserId = table.Column<string>(nullable: false, maxLength: maxLength), StoreDataId = table.Column<string>(nullable: false, maxLength: maxLength), Role = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_UserStore", x => new { x.ApplicationUserId, x.StoreDataId }); table.ForeignKey( name: "FK_UserStore_AspNetUsers_ApplicationUserId", column: x => x.ApplicationUserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_UserStore_Stores_StoreDataId", column: x => x.StoreDataId, principalTable: "Stores", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Payments", columns: table => new { Id = table.Column<string>(nullable: false, maxLength: maxLength), Blob = table.Column<byte[]>(nullable: true), InvoiceDataId = table.Column<string>(nullable: true, maxLength: maxLength) }, constraints: table => { table.PrimaryKey("PK_Payments", x => x.Id); table.ForeignKey( name: "FK_Payments_Invoices_InvoiceDataId", column: x => x.InvoiceDataId, principalTable: "Invoices", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "RefundAddresses", columns: table => new { Id = table.Column<string>(nullable: false, maxLength: maxLength), Blob = table.Column<byte[]>(nullable: true), InvoiceDataId = table.Column<string>(nullable: true, maxLength: maxLength) }, constraints: table => { table.PrimaryKey("PK_RefundAddresses", x => x.Id); table.ForeignKey( name: "FK_RefundAddresses_Invoices_InvoiceDataId", column: x => x.InvoiceDataId, principalTable: "Invoices", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true); 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: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true); migrationBuilder.CreateIndex( name: "IX_Invoices_StoreDataId", table: "Invoices", column: "StoreDataId"); migrationBuilder.CreateIndex( name: "IX_Payments_InvoiceDataId", table: "Payments", column: "InvoiceDataId"); migrationBuilder.CreateIndex( name: "IX_RefundAddresses_InvoiceDataId", table: "RefundAddresses", column: "InvoiceDataId"); migrationBuilder.CreateIndex( name: "IX_UserStore_StoreDataId", table: "UserStore", column: "StoreDataId"); } 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: "Payments"); migrationBuilder.DropTable( name: "RefundAddresses"); migrationBuilder.DropTable( name: "UserStore"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "Invoices"); migrationBuilder.DropTable( name: "AspNetUsers"); migrationBuilder.DropTable( name: "Stores"); } } }
//----------------------------------------------------------------------- // <copyright file="ARScreen.cs" company="Google"> // // Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System.Collections; using UnityEngine; using Tango; /// <summary> /// ARScreen takes the YUV image from the API, resize the image plane and passes /// the YUV data and vertices data to the YUV2RGB shader to produce a properly /// sized RGBA image. /// /// Please note that all the YUV to RGB conversion is done through the YUV2RGB /// shader, no computation is in this class, this class only passes the data to /// shader. /// </summary> public class ARScreen : MonoBehaviour { public Camera m_renderCamera; public Material m_screenMaterial; // Values for debug display. [HideInInspector] public TangoEnums.TangoPoseStatusType m_status; [HideInInspector] public int m_frameCount; private TangoApplication m_tangoApplication; private YUVTexture m_textures; // Matrix for Tango coordinate frame to Unity coordinate frame conversion. // Start of service frame with respect to Unity world frame. private Matrix4x4 m_uwTss; // Unity camera frame with respect to color camera frame. private Matrix4x4 m_cTuc; // Device frame with respect to IMU frame. private Matrix4x4 m_imuTd; // Color camera frame with respect to IMU frame. private Matrix4x4 m_imuTc; // Unity camera frame with respect to IMU frame, this is composed by // Matrix4x4.Inverse(m_imuTd) * m_imuTc * m_cTuc; // We pre-compute this matrix to save some computation in update(). private Matrix4x4 m_dTuc; /// <summary> /// Initialize the AR Screen. /// </summary> private void Start() { // Constant matrix converting start of service frame to Unity world frame. m_uwTss = new Matrix4x4(); m_uwTss.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_uwTss.SetColumn(1, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); m_uwTss.SetColumn(2, new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); m_uwTss.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); // Constant matrix converting Unity world frame frame to device frame. m_cTuc.SetColumn(0, new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_cTuc.SetColumn(1, new Vector4(0.0f, -1.0f, 0.0f, 0.0f)); m_cTuc.SetColumn(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); m_cTuc.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); m_tangoApplication = FindObjectOfType<TangoApplication>(); if (m_tangoApplication != null) { if (AndroidHelper.IsTangoCorePresent()) { // Request Tango permissions m_tangoApplication.RegisterPermissionsCallback(_OnTangoApplicationPermissionsEvent); m_tangoApplication.RequestNecessaryPermissionsAndConnect(); m_tangoApplication.Register(this); } else { // If no Tango Core is present let's tell the user to install it. Debug.Log("Tango Core is outdated."); } } else { Debug.Log("No Tango Manager found in scene."); } if (m_tangoApplication != null) { m_textures = m_tangoApplication.GetVideoOverlayTextureYUV(); // Pass YUV textures to shader for process. m_screenMaterial.SetTexture("_YTex", m_textures.m_videoOverlayTextureY); m_screenMaterial.SetTexture("_UTex", m_textures.m_videoOverlayTextureCb); m_screenMaterial.SetTexture("_VTex", m_textures.m_videoOverlayTextureCr); } m_tangoApplication.Register(this); } /// <summary> /// Unity update function, we update our texture from here. /// </summary> private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { if (m_tangoApplication != null) { m_tangoApplication.Shutdown(); } // This is a temporary fix for a lifecycle issue where calling // Application.Quit() here, and restarting the application immediately, // results in a hard crash. AndroidHelper.AndroidQuit(); } double timestamp = VideoOverlayProvider.RenderLatestFrame(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR); _UpdateTransformation(timestamp); GL.InvalidateState(); } /// <summary> /// This callback function is called after user appoved or declined the permission to use Motion Tracking. /// </summary> /// <param name="permissionsGranted">If the permissions were granted.</param> private void _OnTangoApplicationPermissionsEvent(bool permissionsGranted) { if (permissionsGranted) { m_tangoApplication.InitApplication(); m_tangoApplication.InitProviders(string.Empty); m_tangoApplication.ConnectToService(); // Ask ARScreen to query the camera intrinsics from Tango Service. _SetCameraIntrinsics(); _SetCameraExtrinsics(); } else { AndroidHelper.ShowAndroidToastMessage("Motion Tracking Permissions Needed", true); } } /// <summary> /// Update the camera gameobject's transformation to the pose that on current timestamp. /// </summary> /// <param name="timestamp">Time to update the camera to.</param> private void _UpdateTransformation(double timestamp) { TangoPoseData pose = new TangoPoseData(); TangoCoordinateFramePair pair; pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; PoseProvider.GetPoseAtTime(pose, timestamp, pair); m_status = pose.status_code; if (pose.status_code == TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID) { Vector3 m_tangoPosition = new Vector3((float)pose.translation[0], (float)pose.translation[1], (float)pose.translation[2]); Quaternion m_tangoRotation = new Quaternion((float)pose.orientation[0], (float)pose.orientation[1], (float)pose.orientation[2], (float)pose.orientation[3]); Matrix4x4 ssTd = Matrix4x4.TRS(m_tangoPosition, m_tangoRotation, Vector3.one); // Here we are getting the pose of Unity camera frame with respect to Unity world. // This is the transformation of our current pose within the Unity coordinate frame. Matrix4x4 uwTuc = m_uwTss * ssTd * m_dTuc; // Extract new local position m_renderCamera.transform.position = uwTuc.GetColumn(3); // Extract new local rotation m_renderCamera.transform.rotation = Quaternion.LookRotation(uwTuc.GetColumn(2), uwTuc.GetColumn(1)); m_frameCount++; } else { m_frameCount = 0; } } /// <summary> /// Set the screen (video overlay image plane) size and vertices. The image plane is not /// applying any project matrix or view matrix. So it's drawing space is the normalized /// screen space, that is [-1.0f, 1.0f] for both width and height. /// </summary> /// <param name="normalizedOffsetX">Horizontal padding to add to the left and right edges.</param> /// <param name="normalizedOffsetY">Vertical padding to add to top and bottom edges.</param> private void _SetScreenVertices(float normalizedOffsetX, float normalizedOffsetY) { MeshFilter meshFilter = GetComponent<MeshFilter>(); Mesh mesh = meshFilter.mesh; mesh.Clear(); // Set the vertices base on the offset, note that the offset is used to compensate // the ratio differences between the camera image and device screen. Vector3[] verts = new Vector3[4]; verts[0] = new Vector3(-1.0f - normalizedOffsetX, -1.0f - normalizedOffsetY, 1.0f); verts[1] = new Vector3(-1.0f - normalizedOffsetX, 1.0f + normalizedOffsetY, 1.0f); verts[2] = new Vector3(1.0f + normalizedOffsetX, 1.0f + normalizedOffsetY, 1.0f); verts[3] = new Vector3(1.0f + normalizedOffsetX, -1.0f - normalizedOffsetY, 1.0f); // Set indices. int[] indices = new int[6]; indices[0] = 0; indices[1] = 2; indices[2] = 3; indices[3] = 1; indices[4] = 2; indices[5] = 0; // Set UVs. Vector2[] uvs = new Vector2[4]; uvs[0] = new Vector2(0, 0); uvs[1] = new Vector2(0, 1f); uvs[2] = new Vector2(1f, 1f); uvs[3] = new Vector2(1f, 0); mesh.Clear(); mesh.vertices = verts; mesh.triangles = indices; mesh.uv = uvs; meshFilter.mesh = mesh; mesh.RecalculateNormals(); } /// <summary> /// The function is for querying the camera extrinsic, for example: the transformation between /// IMU and device frame. These extrinsics is used to transform the pose from the color camera frame /// to the device frame. Because the extrinsic is being queried using the GetPoseAtTime() /// with a desired frame pair, it can only be queried after the ConnectToService() is called. /// /// The device with respect to IMU frame is not directly queryable from API, so we use the IMU /// frame as a temporary value to get the device frame with respect to IMU frame. /// </summary> private void _SetCameraExtrinsics() { double timestamp = 0.0; TangoCoordinateFramePair pair; TangoPoseData poseData = new TangoPoseData(); // Getting the transformation of device frame with respect to IMU frame. pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_IMU; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; PoseProvider.GetPoseAtTime(poseData, timestamp, pair); Vector3 position = new Vector3((float)poseData.translation[0], (float)poseData.translation[1], (float)poseData.translation[2]); Quaternion quat = new Quaternion((float)poseData.orientation[0], (float)poseData.orientation[1], (float)poseData.orientation[2], (float)poseData.orientation[3]); m_imuTd = Matrix4x4.TRS(position, quat, new Vector3(1.0f, 1.0f, 1.0f)); // Getting the transformation of IMU frame with respect to color camera frame. pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_IMU; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_CAMERA_COLOR; PoseProvider.GetPoseAtTime(poseData, timestamp, pair); position = new Vector3((float)poseData.translation[0], (float)poseData.translation[1], (float)poseData.translation[2]); quat = new Quaternion((float)poseData.orientation[0], (float)poseData.orientation[1], (float)poseData.orientation[2], (float)poseData.orientation[3]); m_imuTc = Matrix4x4.TRS(position, quat, new Vector3(1.0f, 1.0f, 1.0f)); m_dTuc = Matrix4x4.Inverse(m_imuTd) * m_imuTc * m_cTuc; } /// <summary> /// Set up the size of ARScreen based on camera intrinsics. /// </summary> private void _SetCameraIntrinsics() { TangoCameraIntrinsics intrinsics = new TangoCameraIntrinsics(); VideoOverlayProvider.GetIntrinsics(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, intrinsics); float verticalFOV = 2.0f * Mathf.Rad2Deg * Mathf.Atan((intrinsics.height * 0.5f) / (float)intrinsics.fy); if (!float.IsNaN(verticalFOV)) { m_renderCamera.fieldOfView = verticalFOV; // Here we are scaling the image plane to make sure the image plane's ratio is set as the // color camera image ratio. // If we don't do this, because we are drawing the texture fullscreen, the image plane will // be set to the screen's ratio. float widthRatio = (float)Screen.width / (float)intrinsics.width; float heightRatio = (float)Screen.height / (float)intrinsics.height; if (widthRatio >= heightRatio) { float normalizedOffset = ((widthRatio / heightRatio) - 1.0f) / 2.0f; _SetScreenVertices(0, normalizedOffset); } else { float normalizedOffset = ((heightRatio / widthRatio) - 1.0f) / 2.0f; _SetScreenVertices(normalizedOffset, 0); } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; #if SILVERLIGHT using System.Core; #endif #if CLR2 namespace Microsoft.Scripting.Ast { #else namespace System.Linq.Expressions { #endif /// <summary> /// Represents a control expression that handles multiple selections by passing control to a <see cref="SwitchCase"/>. /// </summary> #if !SILVERLIGHT [DebuggerTypeProxy(typeof(Expression.SwitchExpressionProxy))] #endif public sealed class SwitchExpression : Expression { private readonly Type _type; private readonly Expression _switchValue; private readonly ReadOnlyCollection<SwitchCase> _cases; private readonly Expression _defaultBody; private readonly MethodInfo _comparison; internal SwitchExpression(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, ReadOnlyCollection<SwitchCase> cases) { _type = type; _switchValue = switchValue; _defaultBody = defaultBody; _comparison = comparison; _cases = cases; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _type; } } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Switch; } } /// <summary> /// Gets the test for the switch. /// </summary> public Expression SwitchValue { get { return _switchValue; } } /// <summary> /// Gets the collection of <see cref="SwitchCase"/> objects for the switch. /// </summary> public ReadOnlyCollection<SwitchCase> Cases { get { return _cases; } } /// <summary> /// Gets the test for the switch. /// </summary> public Expression DefaultBody { get { return _defaultBody; } } /// <summary> /// Gets the equality comparison method, if any. /// </summary> public MethodInfo Comparison { get { return _comparison; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitSwitch(this); } internal bool IsLifted { get { if (_switchValue.Type.IsNullableType()) { return (_comparison == null) || !TypeUtils.AreEquivalent(_switchValue.Type, _comparison.GetParametersCached()[0].ParameterType.GetNonRefType()); } return false; } } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="switchValue">The <see cref="SwitchValue" /> property of the result.</param> /// <param name="cases">The <see cref="Cases" /> property of the result.</param> /// <param name="defaultBody">The <see cref="DefaultBody" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public SwitchExpression Update(Expression switchValue, IEnumerable<SwitchCase> cases, Expression defaultBody) { if (switchValue == SwitchValue && cases == Cases && defaultBody == DefaultBody) { return this; } return Expression.Switch(Type, switchValue, defaultBody, Comparison, cases); } } public partial class Expression { /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Expression switchValue, params SwitchCase[] cases) { return Switch(switchValue, null, null, (IEnumerable<SwitchCase>)cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, params SwitchCase[] cases) { return Switch(switchValue, defaultBody, null, (IEnumerable<SwitchCase>)cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="comparison">The equality comparison method to use.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, MethodInfo comparison, params SwitchCase[] cases) { return Switch(switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>)cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="type">The result type of the switch.</param> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="comparison">The equality comparison method to use.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, params SwitchCase[] cases) { return Switch(type, switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>)cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="comparison">The equality comparison method to use.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Expression switchValue, Expression defaultBody, MethodInfo comparison, IEnumerable<SwitchCase> cases) { return Switch(null, switchValue, defaultBody, comparison, cases); } /// <summary> /// Creates a <see cref="SwitchExpression"/>. /// </summary> /// <param name="type">The result type of the switch.</param> /// <param name="switchValue">The value to be tested against each case.</param> /// <param name="defaultBody">The result of the switch if no cases are matched.</param> /// <param name="comparison">The equality comparison method to use.</param> /// <param name="cases">The valid cases for this switch.</param> /// <returns>The created <see cref="SwitchExpression"/>.</returns> public static SwitchExpression Switch(Type type, Expression switchValue, Expression defaultBody, MethodInfo comparison, IEnumerable<SwitchCase> cases) { RequiresCanRead(switchValue, "switchValue"); if (switchValue.Type == typeof(void)) throw Error.ArgumentCannotBeOfTypeVoid(); var caseList = cases.ToReadOnly(); ContractUtils.RequiresNotEmpty(caseList, "cases"); ContractUtils.RequiresNotNullItems(caseList, "cases"); // Type of the result. Either provided, or it is type of the branches. Type resultType = type ?? caseList[0].Body.Type; bool customType = type != null; if (comparison != null) { var pms = comparison.GetParametersCached(); if (pms.Length != 2) { throw Error.IncorrectNumberOfMethodCallArguments(comparison); } // Validate that the switch value's type matches the comparison method's // left hand side parameter type. var leftParam = pms[0]; bool liftedCall = false; if (!ParameterIsAssignable(leftParam, switchValue.Type)) { liftedCall = ParameterIsAssignable(leftParam, switchValue.Type.GetNonNullableType()); if (!liftedCall) { throw Error.SwitchValueTypeDoesNotMatchComparisonMethodParameter(switchValue.Type, leftParam.ParameterType); } } var rightParam = pms[1]; foreach (var c in caseList) { ContractUtils.RequiresNotNull(c, "cases"); ValidateSwitchCaseType(c.Body, customType, resultType, "cases"); for (int i = 0; i < c.TestValues.Count; i++) { // When a comparison method is provided, test values can have different type but have to // be reference assignable to the right hand side parameter of the method. Type rightOperandType = c.TestValues[i].Type; if (liftedCall) { if (!rightOperandType.IsNullableType()) { throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType); } rightOperandType = rightOperandType.GetNonNullableType(); } if (!ParameterIsAssignable(rightParam, rightOperandType)) { throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType); } } } } else { // When comparison method is not present, all the test values must have // the same type. Use the first test value's type as the baseline. var firstTestValue = caseList[0].TestValues[0]; foreach (var c in caseList) { ContractUtils.RequiresNotNull(c, "cases"); ValidateSwitchCaseType(c.Body, customType, resultType, "cases"); // When no comparison method is provided, require all test values to have the same type. for (int i = 0; i < c.TestValues.Count; i++) { if (!TypeUtils.AreEquivalent(firstTestValue.Type, c.TestValues[i].Type)) { throw new ArgumentException(Strings.AllTestValuesMustHaveSameType, "cases"); } } } // Now we need to validate that switchValue.Type and testValueType // make sense in an Equal node. Fortunately, Equal throws a // reasonable error, so just call it. var equal = Equal(switchValue, firstTestValue, false, comparison); // Get the comparison function from equals node. comparison = equal.Method; } if (defaultBody == null) { if (resultType != typeof(void)) throw Error.DefaultBodyMustBeSupplied(); } else { ValidateSwitchCaseType(defaultBody, customType, resultType, "defaultBody"); } // if we have a non-boolean userdefined equals, we don't want it. if (comparison != null && comparison.ReturnType != typeof(bool)) { throw Error.EqualityMustReturnBoolean(comparison); } return new SwitchExpression(resultType, switchValue, defaultBody, comparison, caseList); } /// <summary> /// If custom type is provided, all branches must be reference assignable to the result type. /// If no custom type is provided, all branches must have the same type - resultType. /// </summary> private static void ValidateSwitchCaseType(Expression @case, bool customType, Type resultType, string parameterName) { if (customType) { if (resultType != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(resultType, @case.Type)) { throw new ArgumentException(Strings.ArgumentTypesMustMatch, parameterName); } } } else { if (!TypeUtils.AreEquivalent(resultType, @case.Type)) { throw new ArgumentException(Strings.AllCaseBodiesMustHaveSameType, parameterName); } } } } }
// // 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 System.IO; using System.Linq; namespace Encog.Parse { /// <summary> /// PeekableInputStream: This class allows a stream to be /// read like normal. However, the ability to peek is added. /// The calling method can peek as far as is needed. This is /// used by the ParseHTML class. /// </summary> public class PeekableInputStream : Stream { /// <summary> /// The underlying stream. /// </summary> private readonly Stream _stream; /// <summary> /// Bytes that have been peeked at. /// </summary> private byte[] _peekBytes; /// <summary> /// How many bytes have been peeked at. /// </summary> private int _peekLength; /// <summary> /// Construct a peekable input stream based on the specified stream. /// </summary> /// <param name="stream">The underlying stream.</param> public PeekableInputStream(Stream stream) { _stream = stream; _peekBytes = new byte[10]; _peekLength = 0; } /// <summary> /// Specifies that the stream can read. /// </summary> public override bool CanRead { get { return true; } } /// <summary> /// Specifies that the stream cannot write. /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Specifies that the stream cannot seek. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Specifies that the stream cannot determine its length. /// </summary> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// Specifies that the stream cannot determine its position. /// </summary> public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } /// <summary> /// Not supported. /// </summary> public override void Flush() { // writing is not supported, so nothing to do here } /// <summary> /// Not supported. /// </summary> /// <param name="v">The length.</param> public override void SetLength(long v) { throw new NotSupportedException(); } /// <summary> /// Not supported. /// </summary> /// <param name="offset"></param> /// <param name="origin"></param> /// <returns></returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Read bytes from the stream. /// </summary> /// <param name="buffer">The buffer to read the bytes into.</param> /// <param name="offset">The offset to begin storing the bytes at.</param> /// <param name="count">How many bytes to read.</param> /// <returns>The number of bytes read.</returns> public override int Read(byte[] buffer, int offset, int count) { if (_peekLength == 0) { return _stream.Read(buffer, offset, count); } for (int i = 0; i < count; i++) { buffer[offset + i] = Pop(); } return count; } /// <summary> /// Not supported. /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } /// <summary> /// Read a single byte. /// </summary> /// <returns>The byte read, or -1 for end of stream.</returns> public int Read() { var b = new byte[1]; int count = Read(b, 0, 1); if (count < 1) return -1; return b[0]; } /// <summary> /// Peek ahead the specified depth. /// </summary> /// <param name="depth">How far to peek ahead.</param> /// <returns>The byte read.</returns> public int Peek(int depth) { // does the size of the peek buffer need to be extended? if (_peekBytes.Length <= depth) { var temp = new byte[depth + 10]; for (int i = 0; i < _peekBytes.Length; i++) { temp[i] = _peekBytes[i]; } _peekBytes = temp; } // does more data need to be read? if (depth >= _peekLength) { int offset = _peekLength; int length = (depth - _peekLength) + 1; int lengthRead = _stream.Read(_peekBytes, offset, length); if (lengthRead < 1) { return -1; } _peekLength = depth + 1; } return _peekBytes[depth]; } private byte Pop() { byte result = _peekBytes[0]; _peekLength--; for (int i = 0; i < _peekLength; i++) { _peekBytes[i] = _peekBytes[i + 1]; } return result; } /// <summary> /// Peek at the next character from the stream. /// </summary> /// <returns>The next character.</returns> public int Peek() { return Peek(0); } /// <summary> /// Peek ahead and see if the specified string is present. /// </summary> /// <param name="str">The string we are looking for.</param> /// <returns>True if the string was found.</returns> public bool Peek(String str) { return !str.Where((t, i) => Peek(i) != t).Any(); } /// <summary> /// Skip the specified number of bytes. /// </summary> /// <param name="count">The number of bytes to skip.</param> /// <returns>The actual number of bytes skipped.</returns> public long Skip(long count) { long count2 = count; while (count2 > 0) { Read(); count2--; } return count; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Routing.Visibility; namespace Microsoft.Msagl.Routing.Rectilinear.Nudging { /// <summary> /// sets the order of connector paths on the edges /// </summary> internal class CombinatorialNudger { const int NotOrdered = int.MaxValue; //A new visibility graph is needed; the DAG of AxisEdges. readonly VisibilityGraph pathVisibilityGraph = new VisibilityGraph(); internal VisibilityGraph PathVisibilityGraph { get { return pathVisibilityGraph; } } readonly Dictionary<AxisEdge, List<PathEdge>> axisEdgesToPathOrders = new Dictionary<AxisEdge, List<PathEdge>>(); internal CombinatorialNudger(IEnumerable<Path> paths) { OriginalPaths = paths; } IEnumerable<Path> OriginalPaths { get; set; } internal Dictionary<AxisEdge, List<PathEdge>> GetOrder() { FillTheVisibilityGraphByWalkingThePaths(); InitPathOrder(); OrderPaths(); return axisEdgesToPathOrders; } void FillTheVisibilityGraphByWalkingThePaths() { foreach (var path in OriginalPaths) FillTheVisibilityGraphByWalkingPath(path); } void FillTheVisibilityGraphByWalkingPath(Path path){ var pathEdgesEnum = CreatePathEdgesFromPoints(path.PathPoints, path.Width).GetEnumerator(); if (pathEdgesEnum.MoveNext()) path.SetFirstEdge(pathEdgesEnum.Current); while(pathEdgesEnum.MoveNext()) path.AddEdge(pathEdgesEnum.Current); } IEnumerable<PathEdge> CreatePathEdgesFromPoints(IEnumerable<Point> pathPoints, double width) { var p0 = pathPoints.First(); foreach (var p1 in pathPoints.Skip(1)) { yield return CreatePathEdge(p0, p1, width); p0 = p1; } } PathEdge CreatePathEdge(Point p0, Point p1, double width){ var dir = CompassVector.DirectionsFromPointToPoint(p0, p1); switch (dir){ case Directions.East: case Directions.North: return new PathEdge(GetAxisEdge(p0, p1), width); case Directions.South: case Directions.West: return new PathEdge(GetAxisEdge(p1,p0), width){Reversed = true}; default: throw new InvalidOperationException( #if TEST_MSAGL "Not a rectilinear path" #endif ); } } AxisEdge GetAxisEdge(Point p0, Point p1){ return PathVisibilityGraph.AddEdge(p0, p1, ((m, n) => new AxisEdge(m, n))) as AxisEdge; } void InitPathOrder() { foreach (var axisEdge in PathVisibilityGraph.Edges.Select(a => (AxisEdge) a)) axisEdgesToPathOrders[axisEdge] = new List<PathEdge>(); foreach (var pathEdge in OriginalPaths.SelectMany(path => path.PathEdges)) axisEdgesToPathOrders[pathEdge.AxisEdge].Add(pathEdge); } void OrderPaths() { foreach (var axisEdge in WalkGraphEdgesInTopologicalOrderIfPossible(PathVisibilityGraph)) OrderPathEdgesSharingEdge(axisEdge); } void OrderPathEdgesSharingEdge(AxisEdge edge) { var pathOrder = PathOrderOfVisEdge(edge); pathOrder.Sort(new Comparison<PathEdge>(CompareTwoPathEdges)); var i = 0; //fill the index foreach (var pathEdge in pathOrder) pathEdge.Index = i++; // if (pathOrder.PathEdges.Count > 1) // Nudger.ShowOrderedPaths(null,pathOrder.PathEdges.Select(e => e.Path), edge.SourcePoint, edge.TargetPoint); } static int CompareTwoPathEdges(PathEdge x, PathEdge y) { if (x == y) return 0; Debug.Assert(x.AxisEdge == y.AxisEdge); //Nudger.ShowOrderedPaths(null, new[] { x.Path, y.Path }, x.AxisEdge.SourcePoint, x.AxisEdge.TargetPoint); int r = CompareInDirectionStartingFromAxisEdge(x, y, x.AxisEdge, x.AxisEdge.Direction); return r!=0 ? r : -CompareInDirectionStartingFromAxisEdge(x, y, x.AxisEdge, CompassVector.OppositeDir(x.AxisEdge.Direction)); } /// <summary> /// /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="axisEdge">axisEdge together with the axisEdgeIsReversed parameter define direction of the movement over the paths</param> /// <param name="direction"></param> /// <returns></returns> static int CompareInDirectionStartingFromAxisEdge(PathEdge x, PathEdge y, AxisEdge axisEdge, Directions direction){ while (true) { x = GetNextPathEdgeInDirection(x, axisEdge, direction); if (x == null) return 0; y = GetNextPathEdgeInDirection(y, axisEdge, direction); if (y == null) return 0; if (x.AxisEdge == y.AxisEdge) { direction = FindContinuedDirection(axisEdge, direction, x.AxisEdge); axisEdge = x.AxisEdge; int r = GetExistingOrder(x, y); if (r == NotOrdered) continue; return direction == axisEdge.Direction ? r : -r; } //there is a fork var forkVertex = direction == axisEdge.Direction ? axisEdge.Target : axisEdge.Source; var xFork = OtherVertex(x.AxisEdge, forkVertex); var yFork = OtherVertex(y.AxisEdge, forkVertex); var projection = ProjectionForCompare(axisEdge, direction != axisEdge.Direction); return projection(xFork.Point).CompareTo(projection(yFork.Point)); } } static Directions FindContinuedDirection(AxisEdge edge, Directions direction, AxisEdge nextAxisEdge) { if (edge.Direction == direction) return nextAxisEdge.Source == edge.Target ? nextAxisEdge.Direction : CompassVector.OppositeDir(nextAxisEdge.Direction); return nextAxisEdge.Source == edge.Source ? nextAxisEdge.Direction : CompassVector.OppositeDir(nextAxisEdge.Direction); } static VisibilityVertex OtherVertex(VisibilityEdge axisEdge, VisibilityVertex v) { return axisEdge.Source==v?axisEdge.Target:axisEdge.Source; } static PointProjection ProjectionForCompare(AxisEdge axisEdge, bool isReversed) { if (axisEdge.Direction == Directions.North) return isReversed ? (p => -p.X) : (PointProjection)(p => p.X); return isReversed ? (p => p.Y) : (PointProjection)(p => -p.Y); } static PathEdge GetNextPathEdgeInDirection(PathEdge e, AxisEdge axisEdge, Directions direction) { Debug.Assert(e.AxisEdge==axisEdge); return axisEdge.Direction == direction ? (e.Reversed ? e.Prev : e.Next) : (e.Reversed ? e.Next : e.Prev); } static int GetExistingOrder(PathEdge x, PathEdge y ) { int xi = x.Index; if (xi == -1) return NotOrdered; int yi = y.Index; Debug.Assert(yi!=-1); return xi.CompareTo(yi); } internal List<PathEdge> PathOrderOfVisEdge(AxisEdge axisEdge) { return axisEdgesToPathOrders[axisEdge]; } static void InitQueueOfSources(Queue<VisibilityVertex> queue, IDictionary<VisibilityVertex, int> dictionary, VisibilityGraph graph) { foreach (var v in graph.Vertices()) { int inDegree = v.InEdges.Count; dictionary[v] = inDegree; if (inDegree == 0) queue.Enqueue(v); } Debug.Assert(queue.Count > 0); } static internal IEnumerable<AxisEdge> WalkGraphEdgesInTopologicalOrderIfPossible(VisibilityGraph visibilityGraph){ //Here the visibility graph is always a DAG since the edges point only to North and East // where possible var sourcesQueue = new Queue<VisibilityVertex>(); var inDegreeLeftUnprocessed = new Dictionary<VisibilityVertex, int>(); InitQueueOfSources(sourcesQueue, inDegreeLeftUnprocessed, visibilityGraph); while (sourcesQueue.Count > 0){ var visVertex = sourcesQueue.Dequeue(); foreach (var edge in visVertex.OutEdges){ var incomingEdges = inDegreeLeftUnprocessed[edge.Target]--; if(incomingEdges == 1)//it is already zero in the dictionary; all incoming edges have been processed sourcesQueue.Enqueue(edge.Target); yield return (AxisEdge)edge; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter; using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite { public partial class MultipleChannelExtendedTest : SMB2TestBase { #region Test Case [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.MultipleChannel)] [TestCategory(TestCategories.Positive)] [Description("Operate file via multi-channel with lock operation on different channels.")] public void MultipleChannel_LockUnlockOnDiffChannel() { MultipleChannelTestWithLock(false); } [TestMethod] [TestCategory(TestCategories.Smb30)] [TestCategory(TestCategories.MultipleChannel)] [TestCategory(TestCategories.Positive)] [Description("Operate file via multi-channel with lock operation on same channel.")] public void MultipleChannel_LockUnlockOnSameChannel() { MultipleChannelTestWithLock(true); } #endregion #region Common Methods /// <summary> /// Establish alternative channel and lock/unlock byte range of a file from same or different channel client /// </summary> /// <param name="lockUnlockOnSameChannel">Set this parameter to true if the unlock operation is taken from the same channel client</param> private void MultipleChannelTestWithLock(bool lockUnlockOnSameChannel) { uint treeId; FILEID fileId; #region Check Applicability TestConfig.CheckDialect(DialectRevision.Smb30); TestConfig.CheckCapabilities(NEGOTIATE_Response_Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL); #endregion BaseTestSite.Log.Add( LogEntryKind.TestStep, "Establish main channel with client {0} and server {1}.", clientIps[0].ToString(), serverIps[0].ToString()); EstablishMainChannel( TestConfig.RequestDialects, serverIps[0], clientIps[0], out treeId); #region CREATE to open file for WRITE and LOCK BaseTestSite.Log.Add( LogEntryKind.TestStep, "Main channel: CREATE file."); Smb2CreateContextResponse[] serverCreateContexts; status = mainChannelClient.Create( treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileId, out serverCreateContexts); #endregion #region WRITE content to file BaseTestSite.Log.Add( LogEntryKind.TestStep, "Main channel: WRITE content to file."); status = mainChannelClient.Write(treeId, fileId, contentWrite); #endregion #region Request byte lock range //Construct LOCK_ELEMENT LOCK_ELEMENT[] locks = new LOCK_ELEMENT[1]; uint lockSequence = 0; locks[0].Offset = 0; locks[0].Length = (ulong)TestConfig.WriteBufferLengthInKb * 1024; locks[0].Flags = LOCK_ELEMENT_Flags_Values.LOCKFLAG_SHARED_LOCK; BaseTestSite.Log.Add( LogEntryKind.TestStep, "Main channel client starts to lock a byte range for file \"{0}\" with parameters offset:{1}, length:{2}, flags: {3})", fileName, locks[0].Offset, locks[0].Length, locks[0].Flags.ToString()); status = mainChannelClient.Lock(treeId, lockSequence++, fileId, locks); #endregion #region WRITE content within the locking range BaseTestSite.Log.Add( LogEntryKind.TestStep, "Main channel: attempts to write content within the locking range."); status = mainChannelClient.Write( treeId, fileId, contentWrite, checker: (header, response) => { BaseTestSite.Assert.AreNotEqual( Smb2Status.STATUS_SUCCESS, header.Status, "Write should not success when shared lock is taken"); BaseTestSite.CaptureRequirementIfAreEqual( Smb2Status.STATUS_FILE_LOCK_CONFLICT, header.Status, RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Id, RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Description); }); #endregion BaseTestSite.Log.Add( LogEntryKind.TestStep, "Establish alternative channel with client {0} and server {1}.", clientIps[1].ToString(), serverIps[1].ToString()); EstablishAlternativeChannel( TestConfig.RequestDialects, serverIps[1], clientIps[1], treeId); #region READ/WRITE from alternative channel within the locking range Random random = new Random(); uint offset = (uint)random.Next(0, TestConfig.WriteBufferLengthInKb * 1024 - 1); uint length = (uint)random.Next(0, (int)(TestConfig.WriteBufferLengthInKb * 1024 - offset)); BaseTestSite.Log.Add( LogEntryKind.Debug, "Alternative channel: attempts to randomly read the locking range with offset: {0} and length: {1}", offset, length); status = alternativeChannelClient.Read(treeId, fileId, offset, length, out contentRead); BaseTestSite.Log.Add( LogEntryKind.TestStep, "Alternative channel: attempts to write content to the locking range"); status = alternativeChannelClient.Write( treeId, fileId, contentWrite, checker: (header, response) => { BaseTestSite.Assert.AreNotEqual( Smb2Status.STATUS_SUCCESS, header.Status, "All opens MUST NOT be allowed to write within the range when SMB2_LOCKFLAG_SHARED_LOCK set"); BaseTestSite.CaptureRequirementIfAreEqual( Smb2Status.STATUS_FILE_LOCK_CONFLICT, header.Status, RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Id, RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Description); }); #endregion BaseTestSite.Log.Add( LogEntryKind.TestStep, "Read and write the locking range from Client3 when the file is locked"); ValidateByteLockRangeFromAnotherClient(true); locks[0].Flags = LOCK_ELEMENT_Flags_Values.LOCKFLAG_UNLOCK; if (lockUnlockOnSameChannel) { BaseTestSite.Log.Add( LogEntryKind.TestStep, "From main channel client unlock the range"); status = mainChannelClient.Lock(treeId, lockSequence++, fileId, locks); } else { BaseTestSite.Log.Add( LogEntryKind.TestStep, "From alternative channel client unlock the range"); status = alternativeChannelClient.Lock(treeId, lockSequence++, fileId, locks); } BaseTestSite.Log.Add( LogEntryKind.TestStep, "Read and write the locking range from Client3 when the file is unlocked"); ValidateByteLockRangeFromAnotherClient(false); ClientTearDown(mainChannelClient, treeId, fileId); } /// <summary> /// Read and write the file within the locking byte range when lock or unlock is taken /// </summary> /// <param name="isLocked">Set true to indicate that access the file when lock operation is taken</param> private void ValidateByteLockRangeFromAnotherClient(bool isLocked) { Smb2FunctionalClient client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite); client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite); client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress); status = client.Negotiate( TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled, capabilityValue: Capabilities_Values.GLOBAL_CAP_DFS | Capabilities_Values.GLOBAL_CAP_DIRECTORY_LEASING | Capabilities_Values.GLOBAL_CAP_LARGE_MTU | Capabilities_Values.GLOBAL_CAP_LEASING | Capabilities_Values.GLOBAL_CAP_MULTI_CHANNEL | Capabilities_Values.GLOBAL_CAP_PERSISTENT_HANDLES); status = client.SessionSetup( TestConfig.DefaultSecurityPackage, TestConfig.SutComputerName, TestConfig.AccountCredential, TestConfig.UseServerGssToken); uint treeId; status = client.TreeConnect(uncSharePath, out treeId); Smb2CreateContextResponse[] serverCreateContexts; FILEID fileId; status = client.Create( treeId, fileName, CreateOptions_Values.FILE_NON_DIRECTORY_FILE, out fileId, out serverCreateContexts); string data; Random random = new Random(); uint offset = (uint)random.Next(0, TestConfig.WriteBufferLengthInKb * 1024 - 1); uint length = (uint)random.Next(0, (int)(TestConfig.WriteBufferLengthInKb * 1024 - offset)); status = client.Read(treeId, fileId, offset, length, out data); status = client.Write(treeId, fileId, contentWrite, checker: (header, response) => { }); if (isLocked) { BaseTestSite.Assert.AreNotEqual( Smb2Status.STATUS_SUCCESS, status, "Write content to locked range of file from different client is not expected to success"); BaseTestSite.CaptureRequirementIfAreEqual( Smb2Status.STATUS_FILE_LOCK_CONFLICT, status, RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Id, RequirementCategory.STATUS_FILE_LOCK_CONFLICT.Description); } else { BaseTestSite.Assert.AreEqual( Smb2Status.STATUS_SUCCESS, status, "Write content in file failed with error code=" + Smb2Status.GetStatusCode(status)); } } #endregion } }
using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Linq; namespace Orleans.Runtime { internal class ThreadTrackingStatistic { public ITimeInterval ExecutingCpuCycleTime; public ITimeInterval ExecutingWallClockTime; public ITimeInterval ProcessingCpuCycleTime; public ITimeInterval ProcessingWallClockTime; public ulong NumRequests; public string Name; private static readonly StageAnalysis globalStageAnalyzer = new StageAnalysis(); private const string CONTEXT_SWTICH_COUNTER_NAME = "Context Switches/sec"; public static bool ClientConnected = false; private bool firstStart; private static readonly List<FloatValueStatistic> allExecutingCpuCycleTime = new List<FloatValueStatistic>(); private static readonly List<FloatValueStatistic> allExecutingWallClockTime = new List<FloatValueStatistic>(); private static readonly List<FloatValueStatistic> allProcessingCpuCycleTime = new List<FloatValueStatistic>(); private static readonly List<FloatValueStatistic> allProcessingWallClockTime = new List<FloatValueStatistic>(); private static readonly List<FloatValueStatistic> allNumProcessedRequests = new List<FloatValueStatistic>(); private static FloatValueStatistic totalExecutingCpuCycleTime; private static FloatValueStatistic totalExecutingWallClockTime; private static FloatValueStatistic totalProcessingCpuCycleTime; private static FloatValueStatistic totalProcessingWallClockTime; private static FloatValueStatistic totalNumProcessedRequests; /// <summary> /// Keep track of thread statistics, mainly timing, can be created outside the thread to be tracked. /// </summary> /// <param name="threadName">Name used for logging the collected stastistics</param> /// <param name="storage"></param> public ThreadTrackingStatistic(string threadName) { ExecutingCpuCycleTime = new TimeIntervalThreadCycleCounterBased(); ExecutingWallClockTime = TimeIntervalFactory.CreateTimeInterval(true); ProcessingCpuCycleTime = new TimeIntervalThreadCycleCounterBased(); ProcessingWallClockTime = TimeIntervalFactory.CreateTimeInterval(true); NumRequests = 0; firstStart = true; Name = threadName; CounterStorage storage = StatisticsCollector.ReportDetailedThreadTimeTrackingStats ? CounterStorage.LogOnly : CounterStorage.DontStore; CounterStorage aggrCountersStorage = CounterStorage.LogOnly; // 4 direct counters allExecutingCpuCycleTime.Add( FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.THREADS_EXECUTION_TIME_TOTAL_CPU_CYCLES, threadName), () => (float)ExecutingCpuCycleTime.Elapsed.TotalMilliseconds, storage)); allExecutingWallClockTime.Add( FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.THREADS_EXECUTION_TIME_TOTAL_WALL_CLOCK, threadName), () => (float)ExecutingWallClockTime.Elapsed.TotalMilliseconds, storage)); allProcessingCpuCycleTime.Add( FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.THREADS_PROCESSING_TIME_TOTAL_CPU_CYCLES, threadName), () => (float)ProcessingCpuCycleTime.Elapsed.TotalMilliseconds, storage)); allProcessingWallClockTime.Add( FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.THREADS_PROCESSING_TIME_TOTAL_WALL_CLOCK, threadName), () => (float)ProcessingWallClockTime.Elapsed.TotalMilliseconds, storage)); // numRequests allNumProcessedRequests.Add( FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.THREADS_PROCESSED_REQUESTS_PER_THREAD, threadName), () => (float)NumRequests, storage)); // aggregate stats if (totalExecutingCpuCycleTime == null) { totalExecutingCpuCycleTime = FloatValueStatistic.FindOrCreate( new StatisticName(StatisticNames.THREADS_EXECUTION_TIME_AVERAGE_CPU_CYCLES, "AllThreads"), () => CalculateTotalAverage(allExecutingCpuCycleTime, totalNumProcessedRequests), aggrCountersStorage); } if (totalExecutingWallClockTime == null) { totalExecutingWallClockTime = FloatValueStatistic.FindOrCreate( new StatisticName(StatisticNames.THREADS_EXECUTION_TIME_AVERAGE_WALL_CLOCK, "AllThreads"), () => CalculateTotalAverage(allExecutingWallClockTime, totalNumProcessedRequests), aggrCountersStorage); } if (totalProcessingCpuCycleTime == null) { totalProcessingCpuCycleTime = FloatValueStatistic.FindOrCreate( new StatisticName(StatisticNames.THREADS_PROCESSING_TIME_AVERAGE_CPU_CYCLES, "AllThreads"), () => CalculateTotalAverage(allProcessingCpuCycleTime, totalNumProcessedRequests), aggrCountersStorage); } if (totalProcessingWallClockTime == null) { totalProcessingWallClockTime = FloatValueStatistic.FindOrCreate( new StatisticName(StatisticNames.THREADS_PROCESSING_TIME_AVERAGE_WALL_CLOCK, "AllThreads"), () => CalculateTotalAverage(allProcessingWallClockTime, totalNumProcessedRequests), aggrCountersStorage); } if (totalNumProcessedRequests == null) { totalNumProcessedRequests = FloatValueStatistic.FindOrCreate( new StatisticName(StatisticNames.THREADS_PROCESSED_REQUESTS_PER_THREAD, "AllThreads"), () => (float)allNumProcessedRequests.Select(cs => cs.GetCurrentValue()).Sum(), aggrCountersStorage); } if (StatisticsCollector.PerformStageAnalysis) globalStageAnalyzer.AddTracking(this); } private float CalculateTotalAverage(List<FloatValueStatistic> allthreasCounters, FloatValueStatistic allNumRequestsCounter) { float allThreads = allthreasCounters.Select(cs => cs.GetCurrentValue()).Sum(); float numRequests = allNumRequestsCounter.GetCurrentValue(); if (numRequests > 0) return allThreads / numRequests; return 0; } public static void FirstClientConnectedStartTracking() { ClientConnected = true; } /// <summary> /// Call once when the thread is started, must be called from the thread being tracked /// </summary> public void OnStartExecution() { // Only once a client has connected do we start tracking statistics if (ClientConnected) { ExecutingCpuCycleTime.Start(); ExecutingWallClockTime.Start(); } } /// <summary> /// Call once when the thread is stopped, must be called from the thread being tracked /// </summary> public void OnStopExecution() { // Only once a client has connected do we start tracking statistics if (ClientConnected) { ExecutingCpuCycleTime.Stop(); ExecutingWallClockTime.Stop(); } } /// <summary> /// Call once before processing a request, must be called from the thread being tracked /// </summary> public void OnStartProcessing() { // Only once a client has connected do we start tracking statistics if (!ClientConnected) return; // As this function is called constantly, we perform two additional tasks in this function which require calls from the thread being tracked (the constructor is not called from the tracked thread) if (firstStart) { // If this is the first function call where client has connected, we ensure execution timers are started and context switches are tracked firstStart = false; if (StatisticsCollector.CollectContextSwitchesStats) { TrackContextSwitches(); } OnStartExecution(); } else { // Must toggle this counter as its "Elapsed" value contains the value when it was last stopped, this is a limitation of our techniques for CPU tracking of threads ExecutingCpuCycleTime.Stop(); ExecutingCpuCycleTime.Start(); } ProcessingCpuCycleTime.Start(); ProcessingWallClockTime.Start(); } /// <summary> /// Call once after processing multiple requests as a batch or a single request, must be called from the thread being tracked /// </summary> /// <param name="num">Number of processed requests</param> public void OnStopProcessing() { // Only once a client has connected do we start tracking statistics if (ClientConnected) { ProcessingCpuCycleTime.Stop(); ProcessingWallClockTime.Stop(); } } /// <summary> /// Call once to just increment the stastistic of processed requests /// </summary> /// <param name="num">Number of processed requests</param> public void IncrementNumberOfProcessed(int num = 1) { // Only once a client has connected do we start tracking statistics if (ClientConnected) { if (num > 0) { NumRequests += (ulong)num; } } } private void TrackContextSwitches() { PerformanceCounterCategory allThreadsWithPerformanceCounters = new PerformanceCounterCategory("Thread"); PerformanceCounter[] performanceCountersForThisThread = null; // Iterate over all "Thread" category performance counters on system (includes numerous processes) foreach (string threadName in allThreadsWithPerformanceCounters.GetInstanceNames()) { // Obtain those performance counters for the OrleansHost if (threadName.Contains("OrleansHost") && threadName.EndsWith("/" + Thread.CurrentThread.ManagedThreadId)) { performanceCountersForThisThread = allThreadsWithPerformanceCounters.GetCounters(threadName); break; } } // In the case that the performance was not obtained correctly (this condition is null), we simply will not have stats for context switches if (performanceCountersForThisThread == null) return; // Look at all performance counters for this thread foreach (PerformanceCounter performanceCounter in performanceCountersForThisThread) { // Find performance counter for context switches if (performanceCounter.CounterName == CONTEXT_SWTICH_COUNTER_NAME) { // Use raw value for logging, should show total context switches FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.THREADS_CONTEXT_SWITCHES, Name), () => (float)performanceCounter.RawValue, CounterStorage.LogOnly); } } } } }
using Foundation; using System; using UIKit; using System.Collections.Generic; namespace tvText { /// <summary> /// Controlls the Collection View that will be used to display the results of the user's /// search input. This controller both provides the data for the Collection, but responds /// to the user's input. /// </summary> /// <remarks> /// See our Working with Collection View documentation for more information: /// https://developer.xamarin.com/guides/ios/tvos/user-interface/collection-views/ /// </remarks> public partial class SearchResultsViewController : UICollectionViewController , IUISearchResultsUpdating { #region Constants /// <summary> /// The cell identifier as entered in the Storyboard. /// </summary> public const string CellID = "ImageCell"; #endregion #region Private Variables /// <summary> /// The backing store for the filter string. /// </summary> private string _searchFilter = ""; #endregion #region Computed Properties /// <summary> /// Gets or sets all pictures that the user can search for. /// </summary> /// <value>A collection of <c>PictureInformation</c> objects.</value> public List<PictureInformation> AllPictures { get; set;} /// <summary> /// Gets or sets the pictures that match the user's search term either by /// title of keywords. /// </summary> /// <value>A collection of <c>PictureInformation</c> objects.</value> public List<PictureInformation> FoundPictures { get; set; } /// <summary> /// Gets or sets the search filter enter by the user to limit the /// list of returned pictures. /// </summary> /// <value>A <c>string</c> containing the filter parameters.</value> public string SearchFilter { get { return _searchFilter; } set { _searchFilter = value.ToLower(); FindPictures (); CollectionView?.ReloadData (); } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:tvText.SearchResultsViewController"/> class. /// </summary> /// <param name="handle">Handle.</param> public SearchResultsViewController (IntPtr handle) : base (handle) { // Initialize this.AllPictures = new List<PictureInformation> (); this.FoundPictures = new List<PictureInformation> (); PopulatePictures (); FindPictures (); } #endregion #region Private Methods /// <summary> /// Populates the collection of available pictures. /// </summary> private void PopulatePictures () { // Clear list AllPictures.Clear (); // Add images AllPictures.Add (new PictureInformation ("Antipasta Platter","Antipasta","cheese,grapes,tomato,coffee,meat,plate")); AllPictures.Add (new PictureInformation ("Cheese Plate", "CheesePlate", "cheese,plate,bread")); AllPictures.Add (new PictureInformation ("Coffee House", "CoffeeHouse", "coffee,people,menu,restaurant,cafe")); AllPictures.Add (new PictureInformation ("Computer and Expresso", "ComputerExpresso", "computer,coffee,expresso,phone,notebook")); AllPictures.Add (new PictureInformation ("Hamburger", "Hamburger", "meat,bread,cheese,tomato,pickle,lettus")); AllPictures.Add (new PictureInformation ("Lasagna Dinner", "Lasagna", "salad,bread,plate,lasagna,pasta")); AllPictures.Add (new PictureInformation ("Expresso Meeting", "PeopleExpresso", "people,bag,phone,expresso,coffee,table,tablet,notebook")); AllPictures.Add (new PictureInformation ("Soup and Sandwich", "SoupAndSandwich", "soup,sandwich,bread,meat,plate,tomato,lettus,egg")); AllPictures.Add (new PictureInformation ("Morning Coffee", "TabletCoffee", "tablet,person,man,coffee,magazine,table")); AllPictures.Add (new PictureInformation ("Evening Coffee", "TabletMagCoffee", "tablet,magazine,coffee,table")); } /// <summary> /// Populates the <c>FoundPictures</c> collection with any picture (from the <c>AllPictures</c> collection) that /// matches the <c>SearchFilter</c> by either the title or keywords. /// </summary> private void FindPictures () { // Clear list FoundPictures.Clear (); // Scan each picture for a match foreach (PictureInformation picture in AllPictures) { if (SearchFilter == "") { // If no search term, everything matches FoundPictures.Add (picture); } else if (picture.Title.Contains (SearchFilter) || picture.Keywords.Contains (SearchFilter)) { // If the search term is in the title or keywords, we've found a match FoundPictures.Add (picture); } } } #endregion #region Override Methods /// <summary> /// Returns the number of section in the Collection View /// </summary> /// <returns>The of sections.</returns> /// <param name="collectionView">Collection view.</param> public override nint NumberOfSections (UICollectionView collectionView) { // Only one section in this collection return 1; } /// <summary> /// Gets the number of found pictures matching the <c>SearchFilter</c>. /// </summary> /// <returns>The items count.</returns> /// <param name="collectionView">Collection view.</param> /// <param name="section">Section.</param> public override nint GetItemsCount (UICollectionView collectionView, nint section) { // Return the number of matching pictures return FoundPictures.Count; } /// <summary> /// Gets a new <c>SearchResultViewCell</c> for the given row in the Collection View. /// </summary> /// <returns>A <c>SearchResultViewCell</c>.</returns> /// <param name="collectionView">Collection view.</param> /// <param name="indexPath">Index path.</param> public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { // Get a new cell and return it var cell = collectionView.DequeueReusableCell (CellID, indexPath); return (UICollectionViewCell)cell; } /// <summary> /// Called before a Collection View Cell is displayed to allow it to be initialized. /// </summary> /// <param name="collectionView">Collection view.</param> /// <param name="cell">Cell.</param> /// <param name="indexPath">Index path.</param> public override void WillDisplayCell (UICollectionView collectionView, UICollectionViewCell cell, NSIndexPath indexPath) { // Grab the cell var currentCell = cell as SearchResultViewCell; if (currentCell == null) throw new Exception ("Expected to display a `SearchResultViewCell`."); // Display the current picture info in the cell var item = FoundPictures [indexPath.Row]; currentCell.PictureInfo = item; } /// <summary> /// Respond to an item being selected (clicked on) in the Collection View. /// </summary> /// <param name="collectionView">Collection view.</param> /// <param name="indexPath">Index path.</param> public override void ItemSelected (UICollectionView collectionView, NSIndexPath indexPath) { // If this Search Controller was presented as a modal view, close // it before continuing // DismissViewController (true, null); // Grab the picture being selected and report it var picture = FoundPictures [indexPath.Row]; Console.WriteLine ("Selected: {0}", picture.Title); } /// <summary> /// Updates the search results for search controller. /// </summary> /// <param name="searchController">Search controller.</param> public void UpdateSearchResultsForSearchController (UISearchController searchController) { // Save the search filter and update the Collection View SearchFilter = searchController.SearchBar.Text ?? string.Empty; } /// <summary> /// Called when the focus shifts from one Collection View Cell to another. /// </summary> /// <param name="context">Context.</param> /// <param name="coordinator">Coordinator.</param> /// <remarks>We are using this method to highligh the currently In-Focus picture.</remarks> public override void DidUpdateFocus (UIFocusUpdateContext context, UIFocusAnimationCoordinator coordinator) { var previousItem = context.PreviouslyFocusedView as SearchResultViewCell; if (previousItem != null) { UIView.Animate (0.2, () => { previousItem.TextColor = UIColor.LightGray; }); } var nextItem = context.NextFocusedView as SearchResultViewCell; if (nextItem != null) { UIView.Animate (0.2, () => { nextItem.TextColor = UIColor.Black; }); } } #endregion } }
using Lucene.Net.Diagnostics; using System; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ArrayUtil = Lucene.Net.Util.ArrayUtil; using ByteBlockPool = Lucene.Net.Util.ByteBlockPool; using BytesRef = Lucene.Net.Util.BytesRef; using BytesRefHash = Lucene.Net.Util.BytesRefHash; using IndexReader = Lucene.Net.Index.IndexReader; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using TermsEnum = Lucene.Net.Index.TermsEnum; using TermState = Lucene.Net.Index.TermState; /// <summary> /// A rewrite method that tries to pick the best /// constant-score rewrite method based on term and /// document counts from the query. If both the number of /// terms and documents is small enough, then /// <see cref="MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE"/> is used. /// Otherwise, <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is /// used. /// </summary> // LUCENENET specific: made this class public. In Lucene there was a derived class // with the same name that was nested within MultiTermQuery, but in .NET it is // more intuitive if our classes are not nested. public class ConstantScoreAutoRewrite : TermCollectingRewrite<BooleanQuery> { /// <summary> /// Defaults derived from rough tests with a 20.0 million /// doc Wikipedia index. With more than 350 terms in the /// query, the filter method is fastest: /// </summary> public static int DEFAULT_TERM_COUNT_CUTOFF = 350; /// <summary> /// If the query will hit more than 1 in 1000 of the docs /// in the index (0.1%), the filter method is fastest: /// </summary> public static double DEFAULT_DOC_COUNT_PERCENT = 0.1; private int termCountCutoff = DEFAULT_TERM_COUNT_CUTOFF; private double docCountPercent = DEFAULT_DOC_COUNT_PERCENT; /// <summary> /// If the number of terms in this query is equal to or /// larger than this setting then /// <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is used. /// </summary> public virtual int TermCountCutoff { get => termCountCutoff; set => termCountCutoff = value; } /// <summary> /// If the number of documents to be visited in the /// postings exceeds this specified percentage of the /// <see cref="Index.IndexReader.MaxDoc"/> for the index, then /// <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is used. /// Value may be 0.0 to 100.0. /// </summary> public virtual double DocCountPercent { get => docCountPercent; set => docCountPercent = value; } protected override BooleanQuery GetTopLevelQuery() { return new BooleanQuery(true); } protected override void AddClause(BooleanQuery topLevel, Term term, int docFreq, float boost, TermContext states) //ignored { topLevel.Add(new TermQuery(term, states), Occur.SHOULD); } public override Query Rewrite(IndexReader reader, MultiTermQuery query) { // Get the enum and start visiting terms. If we // exhaust the enum before hitting either of the // cutoffs, we use ConstantBooleanQueryRewrite; else, // ConstantFilterRewrite: int docCountCutoff = (int)((docCountPercent / 100.0) * reader.MaxDoc); int termCountLimit = Math.Min(BooleanQuery.MaxClauseCount, termCountCutoff); CutOffTermCollector col = new CutOffTermCollector(docCountCutoff, termCountLimit); CollectTerms(reader, query, col); int size = col.pendingTerms.Count; if (col.hasCutOff) { return MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE.Rewrite(reader, query); } else { BooleanQuery bq = GetTopLevelQuery(); if (size > 0) { BytesRefHash pendingTerms = col.pendingTerms; int[] sort = pendingTerms.Sort(col.termsEnum.Comparer); for (int i = 0; i < size; i++) { int pos = sort[i]; // docFreq is not used for constant score here, we pass 1 // to explicitely set a fake value, so it's not calculated AddClause(bq, new Term(query.m_field, pendingTerms.Get(pos, new BytesRef())), 1, 1.0f, col.array.termState[pos]); } } // Strip scores Query result = new ConstantScoreQuery(bq); result.Boost = query.Boost; return result; } } internal sealed class CutOffTermCollector : TermCollector { internal CutOffTermCollector(int docCountCutoff, int termCountLimit) { pendingTerms = new BytesRefHash(new ByteBlockPool(new ByteBlockPool.DirectAllocator()), 16, array); this.docCountCutoff = docCountCutoff; this.termCountLimit = termCountLimit; } public override void SetNextEnum(TermsEnum termsEnum) { this.termsEnum = termsEnum; } public override bool Collect(BytesRef bytes) { int pos = pendingTerms.Add(bytes); docVisitCount += termsEnum.DocFreq; if (pendingTerms.Count >= termCountLimit || docVisitCount >= docCountCutoff) { hasCutOff = true; return false; } TermState termState = termsEnum.GetTermState(); if (Debugging.AssertsEnabled) Debugging.Assert(termState != null); if (pos < 0) { pos = (-pos) - 1; array.termState[pos].Register(termState, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); } else { array.termState[pos] = new TermContext(m_topReaderContext, termState, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); } return true; } internal int docVisitCount = 0; internal bool hasCutOff = false; internal TermsEnum termsEnum; internal readonly int docCountCutoff, termCountLimit; internal readonly TermStateByteStart array = new TermStateByteStart(16); internal BytesRefHash pendingTerms; } public override int GetHashCode() { const int prime = 1279; return (int)(prime * termCountCutoff + J2N.BitConversion.DoubleToInt64Bits(docCountPercent)); } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj is null) { return false; } if (this.GetType() != obj.GetType()) { return false; } ConstantScoreAutoRewrite other = (ConstantScoreAutoRewrite)obj; if (other.termCountCutoff != termCountCutoff) { return false; } if (J2N.BitConversion.DoubleToInt64Bits(other.docCountPercent) != J2N.BitConversion.DoubleToInt64Bits(docCountPercent)) { return false; } return true; } /// <summary> /// Special implementation of <see cref="BytesRefHash.BytesStartArray"/> that keeps parallel arrays for <see cref="TermContext"/> </summary> internal sealed class TermStateByteStart : BytesRefHash.DirectBytesStartArray { internal TermContext[] termState; public TermStateByteStart(int initSize) : base(initSize) { } public override int[] Init() { int[] ord = base.Init(); termState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; if (Debugging.AssertsEnabled) Debugging.Assert(termState.Length >= ord.Length); return ord; } public override int[] Grow() { int[] ord = base.Grow(); if (termState.Length < ord.Length) { TermContext[] tmpTermState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(termState, 0, tmpTermState, 0, termState.Length); termState = tmpTermState; } if (Debugging.AssertsEnabled) Debugging.Assert(termState.Length >= ord.Length); return ord; } public override int[] Clear() { termState = null; return base.Clear(); } } } }
//Copyright (c) Service Stack LLC. All Rights Reserved. //License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt using System; using System.Globalization; using System.IO; using System.Text; using ServiceStack.Text.Common; namespace ServiceStack.Text.Json { public class JsonTypeSerializer : ITypeSerializer { public static ITypeSerializer Instance = new JsonTypeSerializer(); public bool IncludeNullValues { get { return JsConfig.IncludeNullValues; } } public string TypeAttrInObject { get { return JsConfig.JsonTypeAttrInObject; } } internal static string GetTypeAttrInObject(string typeAttr) { return string.Format("{{\"{0}\":", typeAttr); } public static readonly bool[] WhiteSpaceFlags = new bool[' ' + 1]; static JsonTypeSerializer() { foreach (var c in JsonUtils.WhiteSpaceChars) { WhiteSpaceFlags[c] = true; } } public WriteObjectDelegate GetWriteFn<T>() { return JsonWriter<T>.WriteFn(); } public WriteObjectDelegate GetWriteFn(Type type) { return JsonWriter.GetWriteFn(type); } public TypeInfo GetTypeInfo(Type type) { return JsonWriter.GetTypeInfo(type); } /// <summary> /// Shortcut escape when we're sure value doesn't contain any escaped chars /// </summary> /// <param name="writer"></param> /// <param name="value"></param> public void WriteRawString(TextWriter writer, string value) { writer.Write(JsWriter.QuoteChar); writer.Write(value); writer.Write(JsWriter.QuoteChar); } public void WritePropertyName(TextWriter writer, string value) { if (JsState.WritingKeyCount > 0) { writer.Write(JsWriter.EscapedQuoteString); writer.Write(value); writer.Write(JsWriter.EscapedQuoteString); } else { WriteRawString(writer, value); } } public void WriteString(TextWriter writer, string value) { JsonUtils.WriteString(writer, value); } public void WriteBuiltIn(TextWriter writer, object value) { if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar); WriteRawString(writer, value.ToString()); if (JsState.WritingKeyCount > 0 && !JsState.IsWritingValue) writer.Write(JsonUtils.QuoteChar); } public void WriteObjectString(TextWriter writer, object value) { JsonUtils.WriteString(writer, value != null ? value.ToString() : null); } public void WriteFormattableObjectString(TextWriter writer, object value) { var formattable = value as IFormattable; JsonUtils.WriteString(writer, formattable != null ? formattable.ToString(null, CultureInfo.InvariantCulture) : null); } public void WriteException(TextWriter writer, object value) { WriteString(writer, ((Exception)value).Message); } public void WriteDateTime(TextWriter writer, object oDateTime) { var dateTime = (DateTime)oDateTime; switch (JsConfig.DateHandler) { case DateHandler.UnixTime: writer.Write(dateTime.ToUnixTime()); return; case DateHandler.UnixTimeMs: writer.Write(dateTime.ToUnixTimeMs()); return; } writer.Write(JsWriter.QuoteString); DateTimeSerializer.WriteWcfJsonDate(writer, dateTime); writer.Write(JsWriter.QuoteString); } public void WriteNullableDateTime(TextWriter writer, object dateTime) { if (dateTime == null) writer.Write(JsonUtils.Null); else WriteDateTime(writer, dateTime); } public void WriteDateTimeOffset(TextWriter writer, object oDateTimeOffset) { writer.Write(JsWriter.QuoteString); DateTimeSerializer.WriteWcfJsonDateTimeOffset(writer, (DateTimeOffset)oDateTimeOffset); writer.Write(JsWriter.QuoteString); } public void WriteNullableDateTimeOffset(TextWriter writer, object dateTimeOffset) { if (dateTimeOffset == null) writer.Write(JsonUtils.Null); else WriteDateTimeOffset(writer, dateTimeOffset); } public void WriteTimeSpan(TextWriter writer, object oTimeSpan) { var stringValue = JsConfig.TimeSpanHandler == TimeSpanHandler.StandardFormat ? oTimeSpan.ToString() : DateTimeSerializer.ToXsdTimeSpanString((TimeSpan)oTimeSpan); WriteRawString(writer, stringValue); } public void WriteNullableTimeSpan(TextWriter writer, object oTimeSpan) { if (oTimeSpan == null) return; WriteTimeSpan(writer, ((TimeSpan?)oTimeSpan).Value); } public void WriteGuid(TextWriter writer, object oValue) { WriteRawString(writer, ((Guid)oValue).ToString("N")); } public void WriteNullableGuid(TextWriter writer, object oValue) { if (oValue == null) return; WriteRawString(writer, ((Guid)oValue).ToString("N")); } public void WriteBytes(TextWriter writer, object oByteValue) { if (oByteValue == null) return; WriteRawString(writer, Convert.ToBase64String((byte[])oByteValue)); } public void WriteChar(TextWriter writer, object charValue) { if (charValue == null) writer.Write(JsonUtils.Null); else WriteString(writer, ((char)charValue).ToString()); } public void WriteByte(TextWriter writer, object byteValue) { if (byteValue == null) writer.Write(JsonUtils.Null); else writer.Write((byte)byteValue); } public void WriteInt16(TextWriter writer, object intValue) { if (intValue == null) writer.Write(JsonUtils.Null); else writer.Write((short)intValue); } public void WriteUInt16(TextWriter writer, object intValue) { if (intValue == null) writer.Write(JsonUtils.Null); else writer.Write((ushort)intValue); } public void WriteInt32(TextWriter writer, object intValue) { if (intValue == null) writer.Write(JsonUtils.Null); else writer.Write((int)intValue); } public void WriteUInt32(TextWriter writer, object uintValue) { if (uintValue == null) writer.Write(JsonUtils.Null); else writer.Write((uint)uintValue); } public void WriteInt64(TextWriter writer, object integerValue) { if (integerValue == null) writer.Write(JsonUtils.Null); else writer.Write((long)integerValue); } public void WriteUInt64(TextWriter writer, object ulongValue) { if (ulongValue == null) { writer.Write(JsonUtils.Null); } else writer.Write((ulong)ulongValue); } public void WriteBool(TextWriter writer, object boolValue) { if (boolValue == null) writer.Write(JsonUtils.Null); else writer.Write(((bool)boolValue) ? JsonUtils.True : JsonUtils.False); } public void WriteFloat(TextWriter writer, object floatValue) { if (floatValue == null) writer.Write(JsonUtils.Null); else { var floatVal = (float)floatValue; if (Equals(floatVal, float.MaxValue) || Equals(floatVal, float.MinValue)) writer.Write(floatVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(floatVal.ToString(CultureInfo.InvariantCulture)); } } public void WriteDouble(TextWriter writer, object doubleValue) { if (doubleValue == null) writer.Write(JsonUtils.Null); else { var doubleVal = (double)doubleValue; if (Equals(doubleVal, double.MaxValue) || Equals(doubleVal, double.MinValue)) writer.Write(doubleVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(doubleVal.ToString(CultureInfo.InvariantCulture)); } } public void WriteDecimal(TextWriter writer, object decimalValue) { if (decimalValue == null) writer.Write(JsonUtils.Null); else writer.Write(((decimal)decimalValue).ToString(CultureInfo.InvariantCulture)); } public void WriteEnum(TextWriter writer, object enumValue) { if (enumValue == null) return; if (GetTypeInfo(enumValue.GetType()).IsNumeric) JsWriter.WriteEnumFlags(writer, enumValue); else WriteRawString(writer, enumValue.ToString()); } public void WriteEnumFlags(TextWriter writer, object enumFlagValue) { JsWriter.WriteEnumFlags(writer, enumFlagValue); } public void WriteLinqBinary(TextWriter writer, object linqBinaryValue) { #if !(__IOS__ || SL5 || XBOX || ANDROID || PCL) WriteRawString(writer, Convert.ToBase64String(((System.Data.Linq.Binary)linqBinaryValue).ToArray())); #endif } public ParseStringDelegate GetParseFn<T>() { return JsonReader.Instance.GetParseFn<T>(); } public ParseStringDelegate GetParseFn(Type type) { return JsonReader.GetParseFn(type); } public string ParseRawString(string value) { return value; } public string ParseString(string value) { return string.IsNullOrEmpty(value) ? value : ParseRawString(value); } public static bool IsEmptyMap(string value, int i = 1) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline if (value.Length == i) return true; return value[i++] == JsWriter.MapEndChar; } internal static string ParseString(string json, ref int index) { var jsonLength = json.Length; if (json[index] != JsonUtils.QuoteChar) throw new Exception("Invalid unquoted string starting with: " + json.SafeSubstring(50)); var startIndex = ++index; do { char c = json[index]; if (c == JsonUtils.QuoteChar) break; if (c != JsonUtils.EscapeChar) continue; c = json[index++]; if (c == 'u') { index += 4; } } while (index++ < jsonLength); index++; return json.Substring(startIndex, Math.Min(index, jsonLength) - startIndex - 1); } public string UnescapeString(string value) { var i = 0; return UnEscapeJsonString(value, ref i); } public string UnescapeSafeString(string value) { if (string.IsNullOrEmpty(value)) return value; return value[0] == JsonUtils.QuoteChar && value[value.Length - 1] == JsonUtils.QuoteChar ? value.Substring(1, value.Length - 2) : value; //if (value[0] != JsonUtils.QuoteChar) // throw new Exception("Invalid unquoted string starting with: " + value.SafeSubstring(50)); //return value.Substring(1, value.Length - 2); } static readonly char[] IsSafeJsonChars = new[] { JsonUtils.QuoteChar, JsonUtils.EscapeChar }; internal static string ParseJsonString(string json, ref int index) { for (; index < json.Length; index++) { var ch = json[index]; if (ch >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[ch]) break; } //Whitespace inline return UnEscapeJsonString(json, ref index); } private static string UnEscapeJsonString(string json, ref int index) { if (string.IsNullOrEmpty(json)) return json; var jsonLength = json.Length; var firstChar = json[index]; if (firstChar == JsonUtils.QuoteChar) { index++; //MicroOp: See if we can short-circuit evaluation (to avoid StringBuilder) var strEndPos = json.IndexOfAny(IsSafeJsonChars, index); if (strEndPos == -1) return json.Substring(index, jsonLength - index); if (json[strEndPos] == JsonUtils.QuoteChar) { var potentialValue = json.Substring(index, strEndPos - index); index = strEndPos + 1; return potentialValue; } } return Unescape(json); } public static string Unescape(string input) { var length = input.Length; int start = 0; int count = 0; StringBuilder output = new StringBuilder(length); for ( ; count < length; ) { if (input[count] == JsonUtils.QuoteChar) { if (start != count) { output.Append(input, start, count - start); } count++; start = count; continue; } if (input[count] == JsonUtils.EscapeChar) { if (start != count) { output.Append(input, start, count - start); } start = count; count++; if (count >= length) continue; //we will always be parsing an escaped char here var c = input[count]; switch (c) { case 'a': output.Append('\a'); count++; break; case 'b': output.Append('\b'); count++; break; case 'f': output.Append('\f'); count++; break; case 'n': output.Append('\n'); count++; break; case 'r': output.Append('\r'); count++; break; case 'v': output.Append('\v'); count++; break; case 't': output.Append('\t'); count++; break; case 'u': if (count + 4 < length) { var unicodeString = input.Substring(count+1, 4); var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber); output.Append(JsonTypeSerializer.ConvertFromUtf32((int) unicodeIntVal)); count += 5; } else { output.Append(c); } break; case 'x': if (count + 4 < length) { var unicodeString = input.Substring(count+1, 4); var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber); output.Append(JsonTypeSerializer.ConvertFromUtf32((int) unicodeIntVal)); count += 5; } else if (count + 2 < length) { var unicodeString = input.Substring(count+1, 2); var unicodeIntVal = UInt32.Parse(unicodeString, NumberStyles.HexNumber); output.Append(JsonTypeSerializer.ConvertFromUtf32((int) unicodeIntVal)); count += 3; } else { output.Append(input, start, count - start); } break; default: output.Append(c); count++; break; } start = count; } else { count++; } } output.Append(input, start, length - start); return output.ToString(); } /// <summary> /// Given a character as utf32, returns the equivalent string provided that the character /// is legal json. /// </summary> /// <param name="utf32"></param> /// <returns></returns> public static string ConvertFromUtf32(int utf32) { if (utf32 < 0 || utf32 > 0x10FFFF) throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF."); if (utf32 < 0x10000) return new string((char)utf32, 1); utf32 -= 0x10000; return new string(new[] {(char) ((utf32 >> 10) + 0xD800), (char) (utf32 % 0x0400 + 0xDC00)}); } public string EatTypeValue(string value, ref int i) { return EatValue(value, ref i); } public bool EatMapStartChar(string value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline return value[i++] == JsWriter.MapStartChar; } public string EatMapKey(string value, ref int i) { var valueLength = value.Length; for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline var tokenStartPos = i; var valueChar = value[i]; switch (valueChar) { //If we are at the end, return. case JsWriter.ItemSeperator: case JsWriter.MapEndChar: return null; //Is Within Quotes, i.e. "..." case JsWriter.QuoteChar: return ParseString(value, ref i); } //Is Value while (++i < valueLength) { valueChar = value[i]; if (valueChar == JsWriter.ItemSeperator //If it doesn't have quotes it's either a keyword or number so also has a ws boundary || (valueChar < WhiteSpaceFlags.Length && WhiteSpaceFlags[valueChar]) ) { break; } } return value.Substring(tokenStartPos, i - tokenStartPos); } public bool EatMapKeySeperator(string value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline if (value.Length == i) return false; return value[i++] == JsWriter.MapKeySeperator; } public bool EatItemSeperatorOrMapEndChar(string value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline if (i == value.Length) return false; var success = value[i] == JsWriter.ItemSeperator || value[i] == JsWriter.MapEndChar; i++; if (success) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline } return success; } public void EatWhitespace(string value, ref int i) { for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline } public string EatValue(string value, ref int i) { var valueLength = value.Length; if (i == valueLength) return null; for (; i < value.Length; i++) { var c = value[i]; if (c >= WhiteSpaceFlags.Length || !WhiteSpaceFlags[c]) break; } //Whitespace inline if (i == valueLength) return null; var tokenStartPos = i; var valueChar = value[i]; var withinQuotes = false; var endsToEat = 1; switch (valueChar) { //If we are at the end, return. case JsWriter.ItemSeperator: case JsWriter.MapEndChar: return null; //Is Within Quotes, i.e. "..." case JsWriter.QuoteChar: return ParseString(value, ref i); //Is Type/Map, i.e. {...} case JsWriter.MapStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsonUtils.EscapeChar) { i++; continue; } if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.MapStartChar) endsToEat++; if (valueChar == JsWriter.MapEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); //Is List, i.e. [...] case JsWriter.ListStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsonUtils.EscapeChar) { i++; continue; } if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.ListStartChar) endsToEat++; if (valueChar == JsWriter.ListEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); } //Is Value while (++i < valueLength) { valueChar = value[i]; if (valueChar == JsWriter.ItemSeperator || valueChar == JsWriter.MapEndChar //If it doesn't have quotes it's either a keyword or number so also has a ws boundary || (valueChar < WhiteSpaceFlags.Length && WhiteSpaceFlags[valueChar]) ) { break; } } var strValue = value.Substring(tokenStartPos, i - tokenStartPos); return strValue == JsonUtils.Null ? null : strValue; } } }
// // System.Data.SqlTypes.SqlDecimal // // Author: // Tim Coleman <tim@timcoleman.com> // Ville Palo <vi64pa@koti.soon.fi> // // (C) Copyright 2002 Tim Coleman // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Mono.Data.Tds.Protocol; using System; using System.Text; using System.Globalization; namespace System.Data.SqlTypes { public struct SqlDecimal : INullable, IComparable { #region Fields int[] value; byte precision; byte scale; bool positive; private bool notNull; // borrowed from System.Decimal const int SCALE_SHIFT = 16; const int SIGN_SHIFT = 31; const int RESERVED_SS32_BITS = 0x7F00FFFF; const ulong LIT_GUINT64_HIGHBIT = 0x8000000000000000; const ulong LIT_GUINT32_HIGHBIT = 0x80000000; const byte DECIMAL_MAX_INTFACTORS = 9; static uint [] constantsDecadeInt32Factors = new uint [10] { 1u, 10u, 100u, 1000u, 10000u, 100000u, 1000000u, 10000000u, 100000000u, 1000000000u }; public static readonly byte MaxPrecision = 38; public static readonly byte MaxScale = 38; // This should be 99999999999999999999999999999999999999 public static readonly SqlDecimal MaxValue = new SqlDecimal (MaxPrecision, (byte)0, true, (int)-1, 160047679, 1518781562, 1262177448); // This should be -99999999999999999999999999999999999999 public static readonly SqlDecimal MinValue = new SqlDecimal (MaxPrecision, (byte)0, false, -1, 160047679, 1518781562, 1262177448); public static readonly SqlDecimal Null; #endregion #region Constructors public SqlDecimal (decimal value) { int[] binData = Decimal.GetBits (value); this.precision = MaxPrecision; // this value seems unclear this.scale = (byte)(((uint)binData [3]) >> SCALE_SHIFT); if (this.scale > MaxScale || ((uint)binData [3] & RESERVED_SS32_BITS) != 0) throw new ArgumentException(Locale.GetText ("Invalid scale")); this.value = new int[4]; this.value[0] = binData[0]; this.value[1] = binData[1]; this.value[2] = binData[2]; this.value[3] = 0; if (value >= 0) positive = true; else positive = false; notNull = true; precision = GetPrecision (value); } public SqlDecimal (double value) : this ((decimal)value) { SqlDecimal n = this; int digits = 17 - precision; if (digits > 0) n = AdjustScale (this, digits, false); else n = Round (this, 17); this.notNull = n.notNull; this.positive = n.positive; this.precision = n.precision; this.scale = n.scale; this.value = n.value; } public SqlDecimal (int value) : this ((decimal)value) { } public SqlDecimal (long value) : this ((decimal)value) { } public SqlDecimal (byte bPrecision, byte bScale, bool fPositive, int[] bits) : this (bPrecision, bScale, fPositive, bits[0], bits[1], bits[2], bits[3]) { } public SqlDecimal (byte bPrecision, byte bScale, bool fPositive, int data1, int data2, int data3, int data4) { this.precision = bPrecision; this.scale = bScale; this.positive = fPositive; this.value = new int[4]; this.value[0] = data1; this.value[1] = data2; this.value[2] = data3; this.value[3] = data4; notNull = true; if (precision < scale) throw new SqlTypeException (Locale.GetText ("Invalid presicion/scale combination.")); if (precision > 38) throw new SqlTypeException (Locale.GetText ("Invalid precision/scale combination.")); if (this.ToDouble () > (Math.Pow (10, 38) - 1) || this.ToDouble () < -(Math.Pow (10, 38))) throw new SqlTypeException ("Can't convert to SqlDecimal, Out of range "); } #endregion #region Properties public byte[] BinData { get { byte [] b = new byte [value.Length * 4]; int j = 0; for (int i = 0; i < value.Length; i++) { b [j++] = (byte)(0xff & value [i]); b [j++] = (byte)(0xff & value [i] >> 8); b [j++] = (byte)(0xff & value [i] >> 16); b [j++] = (byte)(0xff & value [i] >> 24); } return b; } } public int[] Data { get { if (this.IsNull) throw new SqlNullValueException (); // Data should always return clone, not to be modified int [] ret = new int [4]; ret [0] = value [0]; ret [1] = value [1]; ret [2] = value [2]; ret [3] = value [3]; return ret; } } public bool IsNull { get { return !notNull; } } public bool IsPositive { get { return positive; } } public byte Precision { get { return precision; } } public byte Scale { get { return scale; } } public decimal Value { get { if (this.IsNull) throw new SqlNullValueException (); if (this.value[3] > 0) throw new OverflowException (); return new decimal (value[0], value[1], value[2], !positive, scale); } } #endregion #region Methods public static SqlDecimal Abs (SqlDecimal n) { if (!n.notNull) return n; return new SqlDecimal (n.Precision, n.Scale, true, n.Data); } public static SqlDecimal Add (SqlDecimal x, SqlDecimal y) { return (x + y); } public static SqlDecimal AdjustScale (SqlDecimal n, int digits, bool fRound) { byte prec = n.Precision; if (n.IsNull) throw new SqlNullValueException (); int [] data; byte newScale; if (digits == 0) return n; else if (digits > 0) { prec = (byte)(prec + digits); decimal d = n.Value; if (digits > 0) for (int i = 0; i < digits; i++) d *= 10; data = Decimal.GetBits (d); data [3] = 0; newScale = (byte) (n.scale + digits); } else { if (fRound) n = Round (n, digits + n.scale); else n = Round (Truncate (n, digits + n.scale), digits + n.scale); data = n.Data; newScale = n.scale; } return new SqlDecimal (prec, newScale, n.positive, data); } public static SqlDecimal Ceiling (SqlDecimal n) { if (!n.notNull) return n; return AdjustScale (n, -(n.Scale), true); } public int CompareTo (object value) { if (value == null) return 1; else if (!(value is SqlDecimal)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SqlTypes.SqlDecimal")); else if (((SqlDecimal)value).IsNull) return 1; else return this.Value.CompareTo (((SqlDecimal)value).Value); } public static SqlDecimal ConvertToPrecScale (SqlDecimal n, int precision, int scale) { // return new SqlDecimal ((byte)precision, (byte)scale, n.IsPositive, n.Data); // FIXME: precision return AdjustScale (n, scale - n.scale, true); } public static SqlDecimal Divide (SqlDecimal x, SqlDecimal y) { return (x / y); } public override bool Equals (object value) { if (!(value is SqlDecimal)) return false; else if (this.IsNull && ((SqlDecimal)value).IsNull) return true; else if (((SqlDecimal)value).IsNull) return false; else return (bool) (this == (SqlDecimal)value); } public static SqlBoolean Equals (SqlDecimal x, SqlDecimal y) { return (x == y); } public static SqlDecimal Floor (SqlDecimal n) { return AdjustScale (n, -(n.Scale), false); } internal static SqlDecimal FromTdsBigDecimal (TdsBigDecimal x) { if (x == null) return Null; else return new SqlDecimal (x.Precision, x.Scale, !x.IsNegative, x.Data); } public override int GetHashCode () { int result = 10; result = 91 * result + this.Data[0]; result = 91 * result + this.Data[1]; result = 91 * result + this.Data[2]; result = 91 * result + this.Data[3]; result = 91 * result + (int)this.Scale; result = 91 * result + (int)this.Precision; return result; } public static SqlBoolean GreaterThan (SqlDecimal x, SqlDecimal y) { return (x > y); } public static SqlBoolean GreaterThanOrEqual (SqlDecimal x, SqlDecimal y) { return (x >= y); } public static SqlBoolean LessThan (SqlDecimal x, SqlDecimal y) { return (x < y); } public static SqlBoolean LessThanOrEqual (SqlDecimal x, SqlDecimal y) { return (x <= y); } public static SqlDecimal Multiply (SqlDecimal x, SqlDecimal y) { return (x * y); } public static SqlBoolean NotEquals (SqlDecimal x, SqlDecimal y) { return (x != y); } public static SqlDecimal Parse (string s) { if (s == null) throw new ArgumentNullException (Locale.GetText ("string s")); else return new SqlDecimal (Decimal.Parse (s)); } public static SqlDecimal Power (SqlDecimal n, double exp) { if (n.IsNull) return SqlDecimal.Null; return new SqlDecimal (Math.Pow (n.ToDouble (), exp)); } public static SqlDecimal Round (SqlDecimal n, int position) { if (n.IsNull) throw new SqlNullValueException (); decimal d = n.Value; d = Decimal.Round (d, position); return new SqlDecimal (d); } public static SqlInt32 Sign (SqlDecimal n) { SqlInt32 result = 0; if (n >= new SqlDecimal (0)) result = 1; else result = -1; return result; } public static SqlDecimal Subtract (SqlDecimal x, SqlDecimal y) { return (x - y); } private byte GetPrecision (decimal value) { string str = value.ToString (); byte result = 0; foreach (char c in str) { if (c >= '0' && c <= '9') result++; } return result; } public double ToDouble () { // FIXME: This is wrong way to do this double d = (uint)this.Data [0]; d += ((uint)this.Data [1]) * Math.Pow (2, 32); d += ((uint)this.Data [2]) * Math.Pow (2, 64); d += ((uint)this.Data [3]) * Math.Pow (2, 96); d = d / Math.Pow (10, scale); return d; } public SqlBoolean ToSqlBoolean () { return ((SqlBoolean)this); } public SqlByte ToSqlByte () { return ((SqlByte)this); } public SqlDouble ToSqlDouble () { return ((SqlDouble)this); } public SqlInt16 ToSqlInt16 () { return ((SqlInt16)this); } public SqlInt32 ToSqlInt32 () { return ((SqlInt32)this); } public SqlInt64 ToSqlInt64 () { return ((SqlInt64)this); } public SqlMoney ToSqlMoney () { return ((SqlMoney)this); } public SqlSingle ToSqlSingle () { return ((SqlSingle)this); } public SqlString ToSqlString () { return ((SqlString)this); } public override string ToString () { if (this.IsNull) return "Null"; // convert int [4] --> ulong [2] ulong lo = (uint)this.Data [0]; lo += (ulong)((ulong)this.Data [1] << 32); ulong hi = (uint)this.Data [2]; hi += (ulong)((ulong)this.Data [3] << 32); uint rest = 0; String result = ""; StringBuilder Result = new StringBuilder (); for (int i = 0; lo != 0 || hi != 0; i++) { Div128By32 (ref hi, ref lo, 10, ref rest); Result.Insert (0, rest.ToString ()); } while (Result.Length < this.Precision) Result.Append ("0"); while (Result.Length > this.Precision) Result.Remove (Result.Length - 1, 1); if (this.Scale > 0) Result.Insert (Result.Length - this.Scale, "."); if (!positive) Result.Insert (0, '-'); return Result.ToString (); } // From decimal.c private static int Div128By32(ref ulong hi, ref ulong lo, uint divider) { uint t = 0; return Div128By32 (ref hi, ref lo, divider, ref t); } // From decimal.c private static int Div128By32(ref ulong hi, ref ulong lo, uint divider, ref uint rest) { ulong a = 0; ulong b = 0; ulong c = 0; a = (uint)(hi >> 32); b = a / divider; a -= b * divider; a <<= 32; a |= (uint)hi; c = a / divider; a -= c * divider; a <<= 32; hi = b << 32 | (uint)c; a |= (uint)(lo >> 32); b = a / divider; a -= b * divider; a <<= 32; a |= (uint)lo; c = a / divider; a -= c * divider; lo = b << 32 | (uint)c; rest = (uint)a; a <<= 1; return (a > divider || (a == divider && (c & 1) == 1)) ? 1 : 0; } [MonoTODO("Find out what is the right way to set scale and precision")] private static SqlDecimal DecimalDiv (SqlDecimal x, SqlDecimal y) { ulong lo = 0; ulong hi = 0; int sc = 0; // scale int texp = 0; int rc = 0; byte prec = 0; // precision bool positive = ! (x.positive ^ y.positive); prec = x.Precision >= y.Precision ? x.Precision : y.Precision; DecimalDivSub (ref x, ref y, ref lo, ref hi, ref texp); sc = x.Scale - y.Scale; Rescale128 (ref lo, ref hi, ref sc, texp, 0, 38, 1); uint r = 0; while (prec < sc) { Div128By32(ref hi, ref lo, 10, ref r); sc--; } if (r >= 5) lo++; while ((((double)hi) * Math.Pow(2,64) + lo) - Math.Pow (10, prec) > 0) prec++; while ((prec + sc) > MaxScale) { Div128By32(ref hi, ref lo, 10, ref r); sc--; if (r >= 5) lo++; } int resultLo = (int)lo; int resultMi = (int)(lo >> 32); int resultMi2 = (int)(hi); int resultHi = (int)(hi >> 32); return new SqlDecimal (prec, (byte)sc, positive, resultLo, resultMi, resultMi2, resultHi); } // From decimal.c private static void Rescale128 (ref ulong clo, ref ulong chi, ref int scale, int texp, int minScale, int maxScale, int roundFlag) { uint factor = 0; uint overhang = 0; int sc = 0; int i = 0; int rc = 0; int roundBit = 0; sc = scale; if (texp > 0) { // reduce exp while (texp > 0 && sc <= maxScale) { overhang = (uint)(chi >> 64); while (texp > 0 && (((clo & 1) == 0) || overhang > 0)) { if (--texp == 0) roundBit = (int)(clo & 1); RShift128 (ref clo, ref chi); overhang = (uint)(chi >> 32); } if (texp > DECIMAL_MAX_INTFACTORS) i = DECIMAL_MAX_INTFACTORS; else i = texp; if (sc + i > maxScale) i = maxScale - sc; if (i == 0) break; texp -= i; sc += i; // 10^i/2^i=5^i factor = constantsDecadeInt32Factors [i] >> i; // System.Console.WriteLine ("***"); Mult128By32 (ref clo, ref chi, factor, 0); // System.Console.WriteLine ((((double)chi) * Math.Pow (2,64) + clo)); } while (texp > 0) { if (--texp == 0) roundBit = (int)(clo & 1); RShift128 (ref clo, ref chi); } } while (sc > maxScale) { i = scale - maxScale; if (i > DECIMAL_MAX_INTFACTORS) i = DECIMAL_MAX_INTFACTORS; sc -= i; roundBit = Div128By32 (ref clo, ref chi, constantsDecadeInt32Factors[i]); } while (sc < minScale) { if (roundFlag == 0) roundBit = 0; i = minScale - sc; if (i > DECIMAL_MAX_INTFACTORS) i = DECIMAL_MAX_INTFACTORS; sc += i; Mult128By32 (ref clo, ref chi, constantsDecadeInt32Factors[i], roundBit); roundBit = 0; } scale = sc; Normalize128 (ref clo, ref chi, ref sc, roundFlag, roundBit); } // From decimal.c private static void Normalize128(ref ulong clo, ref ulong chi, ref int scale, int roundFlag, int roundBit) { int sc = scale; int deltaScale; scale = sc; if ((roundFlag != 0) && (roundBit != 0)) RoundUp128 (ref clo, ref chi); } // From decimal.c private static void RoundUp128(ref ulong lo, ref ulong hi) { if ((++lo) == 0) ++hi; } // From decimal.c private static void DecimalDivSub (ref SqlDecimal x, ref SqlDecimal y, ref ulong clo, ref ulong chi, ref int exp) { ulong xlo, xmi, xhi; ulong tlo = 0; ulong tmi = 0; ulong thi = 0;; uint ylo = 0; uint ymi = 0; uint ymi2 = 0; uint yhi = 0; int ashift = 0; int bshift = 0; int extraBit = 0; xhi = (ulong)((ulong)x.Data [3] << 32) | (ulong)x.Data [2]; xmi = (ulong)((ulong)x.Data [1] << 32) | (ulong)x.Data [0]; xlo = (uint)0; ylo = (uint)y.Data [0]; ymi = (uint)y.Data [1]; ymi2 = (uint)y.Data [2]; yhi = (uint)y.Data [3]; if (ylo == 0 && ymi == 0 && ymi2 == 0 && yhi == 0) throw new DivideByZeroException (); if (xmi == 0 && xhi == 0) { clo = chi = 0; return; } // enlarge dividend to get maximal precision for (ashift = 0; (xhi & LIT_GUINT64_HIGHBIT) == 0; ++ashift) LShift128 (ref xmi, ref xhi); // ensure that divisor is at least 2^95 for (bshift = 0; (yhi & LIT_GUINT32_HIGHBIT) == 0; ++bshift) LShift128 (ref ylo, ref ymi, ref ymi2, ref yhi); thi = ((ulong)yhi) << 32 | (ulong)ymi2; tmi = ((ulong)ymi) << 32 | (ulong)ylo; tlo = 0; if (xhi > thi || (xhi == thi && xmi >=tmi)) { Sub192(xlo, xmi, xhi, tlo, tmi, thi, ref xlo, ref xmi, ref xhi); extraBit = 1; } else { extraBit = 0; } Div192By128To128 (xlo, xmi, xhi, ylo, ymi, ymi2, yhi, ref clo, ref chi); exp = 128 + ashift - bshift; if (extraBit != 0) { RShift128 (ref clo, ref chi); chi += LIT_GUINT64_HIGHBIT; exp--; } // try loss free right shift while (exp > 0 && (clo & 1) == 0) { RShift128 (ref clo, ref chi); exp--; } } // From decimal.c private static void RShift192(ref ulong lo, ref ulong mi, ref ulong hi) { lo >>= 1; if ((mi & 1) != 0) lo |= LIT_GUINT64_HIGHBIT; mi >>= 1; if ((hi & 1) != 0) mi |= LIT_GUINT64_HIGHBIT; hi >>= 1; } // From decimal.c private static void RShift128(ref ulong lo, ref ulong hi) { lo >>=1; if ((hi & 1) != 0) lo |= LIT_GUINT64_HIGHBIT; hi >>= 1; } // From decimal.c private static void LShift128(ref ulong lo, ref ulong hi) { hi <<= 1; if ((lo & LIT_GUINT64_HIGHBIT) != 0) hi++; lo <<= 1; } // From decimal.c private static void LShift128(ref uint lo, ref uint mi, ref uint mi2, ref uint hi) { hi <<= 1; if ((mi2 & LIT_GUINT32_HIGHBIT) != 0) hi++; mi2 <<= 1; if ((mi & LIT_GUINT32_HIGHBIT) != 0) mi2++; mi <<= 1; if ((lo & LIT_GUINT32_HIGHBIT) != 0) mi++; lo <<= 1; } // From decimal.c private static void Div192By128To128 (ulong xlo, ulong xmi, ulong xhi, uint ylo, uint ymi, uint ymi2, uint yhi, ref ulong clo, ref ulong chi) { ulong rlo, rmi, rhi; // remainders uint h, c; rlo = xlo; rmi = xmi; rhi = xhi; h = Div192By128To32WithRest (ref rlo, ref rmi, ref rhi, ylo, ymi, ymi2, yhi); // mid 32 bit rhi = (rhi << 32) | (rmi >> 32); rmi = (rmi << 32) | (rlo >> 32); rlo <<= 32; chi = (((ulong)h) << 32) | Div192By128To32WithRest ( ref rlo, ref rmi, ref rhi, ylo, ymi, ymi2, yhi); // low 32 bit rhi = (rhi << 32) | (rmi >> 32); rmi = (rmi << 32) | (rlo >> 32); rlo <<= 32; h = Div192By128To32WithRest (ref rlo, ref rmi, ref rhi, ylo, ymi, ymi2, yhi); // estimate lowest 32 bit (two last bits may be wrong) if (rhi >= yhi) c = 0xFFFFFFFF; else { rhi <<= 32; c = (uint)(rhi / yhi); } clo = (((ulong)h) << 32) | c; } // From decimal.c private static uint Div192By128To32WithRest(ref ulong xlo, ref ulong xmi, ref ulong xhi, uint ylo, uint ymi, uint ymi2, uint yhi) { ulong rlo, rmi, rhi; // remainder ulong tlo = 0; ulong thi = 0; uint c; rlo = xlo; rmi = xmi; rhi = xhi; if (rhi >= (((ulong)yhi << 32))) c = 0xFFFFFFFF; else c = (uint) (rhi / yhi); Mult128By32To128 (ylo, ymi, ymi2, yhi, c, ref tlo, ref thi); Sub192 (rlo, rmi, rhi, 0, tlo, thi, ref rlo, ref rmi, ref rhi); while (((long)rhi) < 0) { c--; Add192 (rlo, rmi, rhi, 0, (((ulong)ymi) << 32) | ylo, yhi | ymi2, ref rlo, ref rmi, ref rhi); } xlo = rlo; xmi = rmi; xhi = rhi; return c; } // From decimal.c private static void Mult192By32 (ref ulong clo, ref ulong cmi, ref ulong chi, ulong factor, int roundBit) { ulong a = 0; uint h0 = 0; uint h1 = 0; uint h2 = 0; a = ((ulong)(uint)clo) * factor; if (roundBit != 0) a += factor / 2; h0 = (uint)a; a >>= 32; a += (clo >> 32) * factor; h1 = (uint)a; clo = ((ulong)h1) << 32 | h0; a >>= 32; a += ((ulong)(uint)cmi) * factor; h0 = (uint)a; a >>= 32; a += (cmi >> 32) * factor; h1 = (uint)a; cmi = ((ulong)h1) << 32 | h0; a >>= 32; a += ((ulong)(uint)chi) * factor; h0 = (uint)a; a >>= 32; a += (chi >> 32) * factor; h1 = (uint)a; chi = ((ulong)h1) << 32 | h0; } // From decimal.c private static void Mult128By32 (ref ulong clo, ref ulong chi, uint factor, int roundBit) { ulong a = 0; uint h0 = 0; uint h1 = 0; uint h2 = 0; a = ((ulong)(uint)clo) * factor; if (roundBit != 0) a += factor / 2; h0 = (uint)a; a >>= 32; a += (clo >> 32) * factor; h1 = (uint)a; clo = ((ulong)h1) << 32 | h0; a >>= 32; a += ((ulong)(uint)chi) * factor; h0 = (uint)a; a >>= 32; a += (chi >> 32) * factor; h1 = (uint)a; chi = ((ulong)h1) << 32 | h0; } // From decimal.c private static void Mult128By32To128(uint xlo, uint xmi, uint xmi2, uint xhi, uint factor, ref ulong clo, ref ulong chi) { ulong a; uint h0, h1, h2; a = ((ulong)xlo) * factor; h0 = (uint)a; a >>= 32; a += ((ulong)xmi) * factor; h1 = (uint)a; a >>= 32; a += ((ulong)xmi2) * factor; h2 = (uint)a; a >>= 32; a += ((ulong)xhi) * factor; clo = ((ulong)h1) << 32 | h0; chi = a | h2; } // From decimal.c private static void Add192 (ulong xlo, ulong xmi, ulong xhi, ulong ylo, ulong ymi, ulong yhi, ref ulong clo, ref ulong cmi, ref ulong chi) { xlo += ylo; if (xlo < ylo) { xmi++; if (xmi == 0) xhi++; } xmi += ymi; if (xmi < ymi) xmi++; xhi += yhi; clo = xlo; cmi = xmi; chi = xhi; } // From decimal.c private static void Sub192 (ulong xlo, ulong xmi, ulong xhi, ulong ylo, ulong ymi, ulong yhi, ref ulong lo, ref ulong mi, ref ulong hi) { ulong clo = 0; ulong cmi = 0; ulong chi = 0; clo = xlo - ylo; cmi = xmi - ymi; chi = xhi - yhi; if (xlo < ylo) { if (cmi == 0) chi--; cmi--; } if (xmi < ymi) chi--; lo = clo; mi = cmi; hi = chi; } public static SqlDecimal Truncate (SqlDecimal n, int position) { int diff = n.scale - position; if (diff == 0) return n; int [] data = n.Data; decimal d = new decimal (data [0], data [1], data [2], !n.positive, 0); decimal x = 10; for (int i = 0; i < diff; i++, x *= 10) d = d - d % x; data = Decimal.GetBits (d); data [3] = 0; return new SqlDecimal (n.precision, n.scale, n.positive, data); } public static SqlDecimal operator + (SqlDecimal x, SqlDecimal y) { // if one of them is negative, perform subtraction if (x.IsPositive && !y.IsPositive) return x - y; if (y.IsPositive && !x.IsPositive) return y - x; // adjust the scale to the larger of the two beforehand if (x.scale > y.scale) y = SqlDecimal.AdjustScale (y, x.scale - y.scale, true); // FIXME: should be false (fix it after AdjustScale(,,false) is fixed) else if (y.scale > x.scale) x = SqlDecimal.AdjustScale (x, y.scale - x.scale, true); // FIXME: should be false (fix it after AdjustScale(,,false) is fixed) // set the precision to the greater of the two byte resultPrecision; if (x.Precision > y.Precision) resultPrecision = x.Precision; else resultPrecision = y.Precision; int[] xData = x.Data; int[] yData = y.Data; int[] resultBits = new int[4]; ulong res; ulong carry = 0; // add one at a time, and carry the results over to the next for (int i = 0; i < 4; i +=1) { carry = 0; res = (ulong)(xData[i]) + (ulong)(yData[i]) + carry; if (res > Int32.MaxValue) { carry = res - Int32.MaxValue; res = Int32.MaxValue; } resultBits [i] = (int)res; } // if we have carry left, then throw an exception if (carry > 0) throw new OverflowException (); else return new SqlDecimal (resultPrecision, x.Scale, x.IsPositive, resultBits); } public static SqlDecimal operator / (SqlDecimal x, SqlDecimal y) { // return new SqlDecimal (x.Value / y.Value); return DecimalDiv (x, y); } public static SqlBoolean operator == (SqlDecimal x, SqlDecimal y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Scale > y.Scale) y = SqlDecimal.AdjustScale(y, x.Scale - y.Scale, false); else if (y.Scale > x.Scale) x = SqlDecimal.AdjustScale(y, y.Scale - x.Scale, false); for (int i = 0; i < 4; i += 1) { if (x.Data[i] != y.Data[i]) return new SqlBoolean (false); } return new SqlBoolean (true); } public static SqlBoolean operator > (SqlDecimal x, SqlDecimal y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Scale > y.Scale) y = SqlDecimal.AdjustScale(y, x.Scale - y.Scale, false); else if (y.Scale > x.Scale) x = SqlDecimal.AdjustScale(x, y.Scale - x.Scale, false); for (int i = 3; i >= 0; i--) { if (x.Data[i] == 0 && y.Data[i] == 0) continue; else return new SqlBoolean (x.Data[i] > y.Data[i]); } return new SqlBoolean (false); } public static SqlBoolean operator >= (SqlDecimal x, SqlDecimal y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Scale > y.Scale) y = SqlDecimal.AdjustScale(y, x.Scale - y.Scale, true); else if (y.Scale > x.Scale) x = SqlDecimal.AdjustScale(x, y.Scale - x.Scale, true); for (int i = 3; i >= 0; i -= 1) { if (x.Data[i] == 0 && y.Data[i] == 0) continue; else return new SqlBoolean (x.Data[i] >= y.Data[i]); } return new SqlBoolean (true); } public static SqlBoolean operator != (SqlDecimal x, SqlDecimal y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Scale > y.Scale) x = SqlDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SqlDecimal.AdjustScale(y, x.Scale - y.Scale, true); for (int i = 0; i < 4; i += 1) { if (x.Data[i] != y.Data[i]) return new SqlBoolean (true); } return new SqlBoolean (false); } public static SqlBoolean operator < (SqlDecimal x, SqlDecimal y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Scale > y.Scale) y = SqlDecimal.AdjustScale(y, x.Scale - y.Scale, true); else if (y.Scale > x.Scale) x = SqlDecimal.AdjustScale(x, y.Scale - x.Scale, true); for (int i = 3; i >= 0; i -= 1) { if (x.Data[i] == 0 && y.Data[i] == 0) continue; return new SqlBoolean (x.Data[i] < y.Data[i]); } return new SqlBoolean (false); } public static SqlBoolean operator <= (SqlDecimal x, SqlDecimal y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; if (x.Scale > y.Scale) y = SqlDecimal.AdjustScale(y, x.Scale - y.Scale, true); else if (y.Scale > x.Scale) x = SqlDecimal.AdjustScale(x, y.Scale - x.Scale, true); for (int i = 3; i >= 0; i -= 1) { if (x.Data[i] == 0 && y.Data[i] == 0) continue; else return new SqlBoolean (x.Data[i] <= y.Data[i]); } return new SqlBoolean (true); } public static SqlDecimal operator * (SqlDecimal x, SqlDecimal y) { // adjust the scale to the smaller of the two beforehand if (x.Scale > y.Scale) x = SqlDecimal.AdjustScale(x, y.Scale - x.Scale, true); else if (y.Scale > x.Scale) y = SqlDecimal.AdjustScale(y, x.Scale - y.Scale, true); // set the precision to the greater of the two byte resultPrecision; if (x.Precision > y.Precision) resultPrecision = x.Precision; else resultPrecision = y.Precision; int[] xData = x.Data; int[] yData = y.Data; int[] resultBits = new int[4]; ulong res; ulong carry = 0; // multiply one at a time, and carry the results over to the next for (int i = 0; i < 4; i +=1) { carry = 0; res = (ulong)(xData[i]) * (ulong)(yData[i]) + carry; if (res > Int32.MaxValue) { carry = res - Int32.MaxValue; res = Int32.MaxValue; } resultBits [i] = (int)res; } // if we have carry left, then throw an exception if (carry > 0) throw new OverflowException (); else return new SqlDecimal (resultPrecision, x.Scale, (x.IsPositive == y.IsPositive), resultBits); } public static SqlDecimal operator - (SqlDecimal x, SqlDecimal y) { if (x.IsPositive && !y.IsPositive) return x + y; if (!x.IsPositive && y.IsPositive) return -(x + y); if (!x.IsPositive && !y.IsPositive) return y - x; // otherwise, x is positive and y is positive bool resultPositive = (bool)(x > y); int[] yData = y.Data; for (int i = 0; i < 4; i += 1) yData[i] = -yData[i]; SqlDecimal yInverse = new SqlDecimal (y.Precision, y.Scale, y.IsPositive, yData); if (resultPositive) return x + yInverse; else return -(x + yInverse); } public static SqlDecimal operator - (SqlDecimal n) { return new SqlDecimal (n.Precision, n.Scale, !n.IsPositive, n.Data); } public static explicit operator SqlDecimal (SqlBoolean x) { if (x.IsNull) return Null; else return new SqlDecimal ((decimal)x.ByteValue); } public static explicit operator Decimal (SqlDecimal n) { return n.Value; } public static explicit operator SqlDecimal (SqlDouble x) { checked { if (x.IsNull) return Null; else return new SqlDecimal ((double)x.Value); } } public static explicit operator SqlDecimal (SqlSingle x) { checked { if (x.IsNull) return Null; else return new SqlDecimal ((double)x.Value); } } public static explicit operator SqlDecimal (SqlString x) { checked { return Parse (x.Value); } } public static implicit operator SqlDecimal (decimal x) { return new SqlDecimal (x); } public static implicit operator SqlDecimal (SqlByte x) { if (x.IsNull) return Null; else return new SqlDecimal ((decimal)x.Value); } public static implicit operator SqlDecimal (SqlInt16 x) { if (x.IsNull) return Null; else return new SqlDecimal ((decimal)x.Value); } public static implicit operator SqlDecimal (SqlInt32 x) { if (x.IsNull) return Null; else return new SqlDecimal ((decimal)x.Value); } public static implicit operator SqlDecimal (SqlInt64 x) { if (x.IsNull) return Null; else return new SqlDecimal ((decimal)x.Value); } public static implicit operator SqlDecimal (SqlMoney x) { if (x.IsNull) return Null; else return new SqlDecimal ((decimal)x.Value); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftRightLogicalInt3232() { var test = new SimpleUnaryOpTest__ShiftRightLogicalInt3232(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalInt3232 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector256<Int32> _clsVar; private Vector256<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static SimpleUnaryOpTest__ShiftRightLogicalInt3232() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftRightLogicalInt3232() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ShiftRightLogical( Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<Int32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ShiftRightLogical( _clsVar, 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Int32>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftRightLogicalInt3232(); var result = Avx2.ShiftRightLogical(test._fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.ShiftRightLogical(_fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { if (0 != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<Int32>(Vector256<Int32><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mime; using System.Text; using CommandLine; using CommandLine.Text; using log4net; using subdown.Providers.OpenSubtitles; namespace subdown { /// <summary> /// Specifies how the DownloadDirectory should be resolved /// </summary> public enum SubtitleDownloadType { /// <summary> /// The DownloadDirectory is relative to each video file searched /// </summary> RelativeToFile, /// <summary> /// The DownloadDirectory is relative to the SearchDirectory /// </summary> RelativeToDirectory, /// <summary> /// The DownloadDirectory is static /// </summary> Static } public class SubtitleDownloaderOptions { [OptionArray('f', "files", DefaultValue = new string[] { }, HelpText = "Filenames", Required = false)] public string[] Filenames { get; set; } [Option('s', "searchDirectory", DefaultValue = "", HelpText = "Directory to search for files")] public string SearchDirectory { get; set; } [Option('t', "downloadType", DefaultValue = SubtitleDownloadType.RelativeToDirectory, HelpText = "Specifies how the DownloadDirectory should be resolved. Values: {RelativeToFile, RelativeToDirectory, Static}")] public SubtitleDownloadType DownloadType { get; set; } [Option('d', "donwloadDir", DefaultValue = "subs", HelpText = "Directory to download subtitles")] public string DownloadDirectory { get; set; } [Option('l', "language", DefaultValue = "eng", HelpText = "Subtitle language. Defaults to \"eng\"")] public string Language { get; set; } [Option("listFiles", DefaultValue = false, HelpText = "Just show the list of files")] public bool List { get; set; } /// <summary> /// The name of the Subtitle provider that will be used. Defaults to "osp", OpenSubtitleProvider. /// </summary> [Option('p', "provider", DefaultValue = "osp", HelpText = "The name of the Subtitle Provider")] public string SubtitleProviderName { get; set; } /// <summary> /// The maximum number of subtitles downloaded for a file. This includes the files already found at the specified subtitle download location /// </summary> [Option("subsPerFile", DefaultValue = 3, HelpText = "The maximum number of subtitles per file")] public int MaximumSubtitlesPerFile { get; set; } /// <summary> /// Subtitle downloads can sometimes be grouped together to increase performance. When this is possible, how may should be downloaded together ? /// </summary> [Option("chunkSize", DefaultValue = 10, HelpText = "Subtitles can be downloaded in bulk. Specify how many should be grouped together.")] public int DownloadChunkSize { get; set; } /// <summary> /// It's only common sense to wait a little, usually /// </summary> [Option("waitBetweenChunks", DefaultValue = 200, HelpText = "Milliseconds to wait between chunk downloads.")] public int TimeToWaitBetweenChunks { set; get; } [Option("waitBetweenSubtitles", DefaultValue = 200, HelpText = "Milliseconds to wait between subtitle downloads.")] public int TimeToWaitBetweenSubtitles { get; set; } /// <summary> /// Subtitles can be obtained via APIs or direct downloads. This option specifies how a subtitle provider implementation should obtain the subtitles /// </summary> [Option("forceDirectDownload", DefaultValue = false, HelpText = "Subtitles can be obtained via APIs or direct downloads. This option specifies how a subtitle provider implementation should obtain the subtitles.")] public bool ForceDirectDownload { get; set; } /// <summary> /// Strictly for debugging purposes /// </summary> [Option('e', "enable", DefaultValue = true, HelpText = "Strictly for debugging purposes, this flag needs to be enabled for the options to be valid")] public bool Enable { get; set; } [Option('r', "recursiveSearch", DefaultValue = false, HelpText = "Search for video files recursively.")] public bool Recurse { get; set; } private static readonly ILog Log = LogManager.GetLogger(typeof(SubtitleDownloaderOptions)); public bool Validate() { bool isValid = Enable; if (Filenames != null && Filenames.Length > 0 && Filenames.Any(filename => !File.Exists(filename))) { isValid = false; } if (!String.IsNullOrWhiteSpace(SearchDirectory) && Directory.Exists(SearchDirectory) == false) { isValid = false; } if (!isValid) { Log.Warn("subdown options could not be validated"); Log.Warn("subdown options: " + this); } return isValid; } [HelpOption] public string GetUsage() { var help = new HelpText { Heading = new HeadingInfo("subdown", "1.0"), Copyright = new CopyrightInfo("Dan", DateTime.Now.Year), AdditionalNewLineAfterOption = true, AddDashesToOption = true, MaximumDisplayWidth = 80 }; help.AddPreOptionsLine("Usage: subdown"); help.AddOptions(this); return help; } public override string ToString() { var sb = new StringBuilder(); if (Filenames != null && Filenames.Length > 0) { sb.AppendLine("filenames: " + Filenames.Aggregate("", (e, i) => e + i + " ")); } if (!String.IsNullOrWhiteSpace(SearchDirectory)) { sb.AppendLine("search directory: " + SearchDirectory); } if (!String.IsNullOrWhiteSpace(DownloadDirectory)) { sb.AppendLine("download directory: " + DownloadDirectory); } if (!String.IsNullOrWhiteSpace(Language)) { sb.AppendLine("language: " + Language); } if (!String.IsNullOrWhiteSpace(SubtitleProviderName)) { sb.AppendLine("provider: " + SubtitleProviderName); } sb.AppendLine(String.Format("DownloadChunkSize {0}", DownloadChunkSize)); sb.AppendLine(String.Format("DownloadType {0}", DownloadType)); sb.AppendLine(String.Format("Enable: {0}", Enable)); sb.AppendLine(String.Format("ForceDirectDownload: {0}", ForceDirectDownload)); sb.AppendLine(String.Format("MaximumSubtitlesPerFile: {0}", MaximumSubtitlesPerFile)); sb.AppendLine(String.Format("SubtitleProviderName: {0}", SubtitleProviderName)); sb.AppendLine(String.Format("TimeToWaitBetweenChunks: {0}", TimeToWaitBetweenChunks)); sb.AppendLine(String.Format("TimeToWaitBetweenSubtitles: {0}", TimeToWaitBetweenSubtitles)); return sb.ToString(); } private static SubtitleDownloaderOptions _default; public static SubtitleDownloaderOptions Default { get { if (_default == null) { _default = new SubtitleDownloaderOptions { DownloadChunkSize = 10, DownloadDirectory = "subs", DownloadType = SubtitleDownloadType.RelativeToDirectory, Filenames = new[] { "" }, ForceDirectDownload = false, Language = "eng", MaximumSubtitlesPerFile = 3, SearchDirectory = "", SubtitleProviderName = "osp", TimeToWaitBetweenChunks = 200, TimeToWaitBetweenSubtitles = 200 }; } return _default; } } public readonly string[] VideoExtensions = SubtitleDownloader.VideoFileExtensions; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Extensions; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Video; using osu.Framework.Lists; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Framework.Threading; using osu.Game.Beatmaps.Formats; using osu.Game.Database; using osu.Game.IO; using osu.Game.IO.Archives; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Rulesets; using osu.Game.Rulesets.Objects.Types; namespace osu.Game.Beatmaps { /// <summary> /// Handles the storage and retrieval of Beatmaps/WorkingBeatmaps. /// </summary> public partial class BeatmapManager : DownloadableArchiveModelManager<BeatmapSetInfo, BeatmapSetFileInfo> { /// <summary> /// Fired when a single difficulty has been hidden. /// </summary> public event Action<BeatmapInfo> BeatmapHidden; /// <summary> /// Fired when a single difficulty has been restored. /// </summary> public event Action<BeatmapInfo> BeatmapRestored; /// <summary> /// A default representation of a WorkingBeatmap to use when no beatmap is available. /// </summary> public readonly WorkingBeatmap DefaultBeatmap; public override string[] HandledExtensions => new[] { ".osz" }; protected override string[] HashableFileTypes => new[] { ".osu" }; protected override string ImportFromStablePath => "Songs"; private readonly RulesetStore rulesets; private readonly BeatmapStore beatmaps; private readonly AudioManager audioManager; private readonly GameHost host; private readonly BeatmapUpdateQueue updateQueue; public BeatmapManager(Storage storage, IDatabaseContextFactory contextFactory, RulesetStore rulesets, IAPIProvider api, AudioManager audioManager, GameHost host = null, WorkingBeatmap defaultBeatmap = null) : base(storage, contextFactory, api, new BeatmapStore(contextFactory), host) { this.rulesets = rulesets; this.audioManager = audioManager; this.host = host; DefaultBeatmap = defaultBeatmap; beatmaps = (BeatmapStore)ModelStore; beatmaps.BeatmapHidden += b => BeatmapHidden?.Invoke(b); beatmaps.BeatmapRestored += b => BeatmapRestored?.Invoke(b); updateQueue = new BeatmapUpdateQueue(api); } protected override ArchiveDownloadRequest<BeatmapSetInfo> CreateDownloadRequest(BeatmapSetInfo set, bool minimiseDownloadSize) => new DownloadBeatmapSetRequest(set, minimiseDownloadSize); protected override bool ShouldDeleteArchive(string path) => Path.GetExtension(path)?.ToLowerInvariant() == ".osz"; protected override Task Populate(BeatmapSetInfo beatmapSet, ArchiveReader archive, CancellationToken cancellationToken = default) { if (archive != null) beatmapSet.Beatmaps = createBeatmapDifficulties(beatmapSet.Files); foreach (BeatmapInfo b in beatmapSet.Beatmaps) { // remove metadata from difficulties where it matches the set if (beatmapSet.Metadata.Equals(b.Metadata)) b.Metadata = null; b.BeatmapSet = beatmapSet; } validateOnlineIds(beatmapSet); return updateQueue.UpdateAsync(beatmapSet, cancellationToken); } protected override void PreImport(BeatmapSetInfo beatmapSet) { if (beatmapSet.Beatmaps.Any(b => b.BaseDifficulty == null)) throw new InvalidOperationException($"Cannot import {nameof(BeatmapInfo)} with null {nameof(BeatmapInfo.BaseDifficulty)}."); // check if a set already exists with the same online id, delete if it does. if (beatmapSet.OnlineBeatmapSetID != null) { var existingOnlineId = beatmaps.ConsumableItems.FirstOrDefault(b => b.OnlineBeatmapSetID == beatmapSet.OnlineBeatmapSetID); if (existingOnlineId != null) { Delete(existingOnlineId); beatmaps.PurgeDeletable(s => s.ID == existingOnlineId.ID); LogForModel(beatmapSet, $"Found existing beatmap set with same OnlineBeatmapSetID ({beatmapSet.OnlineBeatmapSetID}). It has been purged."); } } } private void validateOnlineIds(BeatmapSetInfo beatmapSet) { var beatmapIds = beatmapSet.Beatmaps.Where(b => b.OnlineBeatmapID.HasValue).Select(b => b.OnlineBeatmapID).ToList(); // ensure all IDs are unique if (beatmapIds.GroupBy(b => b).Any(g => g.Count() > 1)) { resetIds(); return; } // find any existing beatmaps in the database that have matching online ids var existingBeatmaps = QueryBeatmaps(b => beatmapIds.Contains(b.OnlineBeatmapID)).ToList(); if (existingBeatmaps.Count > 0) { // reset the import ids (to force a re-fetch) *unless* they match the candidate CheckForExisting set. // we can ignore the case where the new ids are contained by the CheckForExisting set as it will either be used (import skipped) or deleted. var existing = CheckForExisting(beatmapSet); if (existing == null || existingBeatmaps.Any(b => !existing.Beatmaps.Contains(b))) resetIds(); } void resetIds() => beatmapSet.Beatmaps.ForEach(b => b.OnlineBeatmapID = null); } protected override bool CheckLocalAvailability(BeatmapSetInfo model, IQueryable<BeatmapSetInfo> items) => items.Any(b => b.OnlineBeatmapSetID == model.OnlineBeatmapSetID); /// <summary> /// Delete a beatmap difficulty. /// </summary> /// <param name="beatmap">The beatmap difficulty to hide.</param> public void Hide(BeatmapInfo beatmap) => beatmaps.Hide(beatmap); /// <summary> /// Restore a beatmap difficulty. /// </summary> /// <param name="beatmap">The beatmap difficulty to restore.</param> public void Restore(BeatmapInfo beatmap) => beatmaps.Restore(beatmap); private readonly WeakList<WorkingBeatmap> workingCache = new WeakList<WorkingBeatmap>(); /// <summary> /// Retrieve a <see cref="WorkingBeatmap"/> instance for the provided <see cref="BeatmapInfo"/> /// </summary> /// <param name="beatmapInfo">The beatmap to lookup.</param> /// <param name="previous">The currently loaded <see cref="WorkingBeatmap"/>. Allows for optimisation where elements are shared with the new beatmap. May be returned if beatmapInfo requested matches</param> /// <returns>A <see cref="WorkingBeatmap"/> instance correlating to the provided <see cref="BeatmapInfo"/>.</returns> public WorkingBeatmap GetWorkingBeatmap(BeatmapInfo beatmapInfo, WorkingBeatmap previous = null) { if (beatmapInfo?.ID > 0 && previous != null && previous.BeatmapInfo?.ID == beatmapInfo.ID) return previous; if (beatmapInfo?.BeatmapSet == null || beatmapInfo == DefaultBeatmap?.BeatmapInfo) return DefaultBeatmap; lock (workingCache) { var working = workingCache.FirstOrDefault(w => w.BeatmapInfo?.ID == beatmapInfo.ID); if (working == null) { if (beatmapInfo.Metadata == null) beatmapInfo.Metadata = beatmapInfo.BeatmapSet.Metadata; workingCache.Add(working = new BeatmapManagerWorkingBeatmap(Files.Store, new LargeTextureStore(host?.CreateTextureLoaderStore(Files.Store)), beatmapInfo, audioManager)); } previous?.TransferTo(working); return working; } } /// <summary> /// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>The first result for the provided query, or null if no results were found.</returns> public BeatmapSetInfo QueryBeatmapSet(Expression<Func<BeatmapSetInfo, bool>> query) => beatmaps.ConsumableItems.AsNoTracking().FirstOrDefault(query); protected override bool CanUndelete(BeatmapSetInfo existing, BeatmapSetInfo import) { if (!base.CanUndelete(existing, import)) return false; var existingIds = existing.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i); var importIds = import.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i); // force re-import if we are not in a sane state. return existing.OnlineBeatmapSetID == import.OnlineBeatmapSetID && existingIds.SequenceEqual(importIds); } /// <summary> /// Returns a list of all usable <see cref="BeatmapSetInfo"/>s. /// </summary> /// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns> public List<BeatmapSetInfo> GetAllUsableBeatmapSets() => GetAllUsableBeatmapSetsEnumerable().ToList(); /// <summary> /// Returns a list of all usable <see cref="BeatmapSetInfo"/>s. /// </summary> /// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns> public IQueryable<BeatmapSetInfo> GetAllUsableBeatmapSetsEnumerable() => beatmaps.ConsumableItems.Where(s => !s.DeletePending && !s.Protected); /// <summary> /// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>Results from the provided query.</returns> public IEnumerable<BeatmapSetInfo> QueryBeatmapSets(Expression<Func<BeatmapSetInfo, bool>> query) => beatmaps.ConsumableItems.AsNoTracking().Where(query); /// <summary> /// Perform a lookup query on available <see cref="BeatmapInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>The first result for the provided query, or null if no results were found.</returns> public BeatmapInfo QueryBeatmap(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().FirstOrDefault(query); /// <summary> /// Perform a lookup query on available <see cref="BeatmapInfo"/>s. /// </summary> /// <param name="query">The query.</param> /// <returns>Results from the provided query.</returns> public IQueryable<BeatmapInfo> QueryBeatmaps(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().Where(query); protected override string HumanisedModelName => "beatmap"; protected override BeatmapSetInfo CreateModel(ArchiveReader reader) { // let's make sure there are actually .osu files to import. string mapName = reader.Filenames.FirstOrDefault(f => f.EndsWith(".osu")); if (string.IsNullOrEmpty(mapName)) { Logger.Log($"No beatmap files found in the beatmap archive ({reader.Name}).", LoggingTarget.Database); return null; } Beatmap beatmap; using (var stream = new LineBufferedReader(reader.GetStream(mapName))) beatmap = Decoder.GetDecoder<Beatmap>(stream).Decode(stream); return new BeatmapSetInfo { OnlineBeatmapSetID = beatmap.BeatmapInfo.BeatmapSet?.OnlineBeatmapSetID, Beatmaps = new List<BeatmapInfo>(), Metadata = beatmap.Metadata, DateAdded = DateTimeOffset.UtcNow }; } /// <summary> /// Create all required <see cref="BeatmapInfo"/>s for the provided archive. /// </summary> private List<BeatmapInfo> createBeatmapDifficulties(List<BeatmapSetFileInfo> files) { var beatmapInfos = new List<BeatmapInfo>(); foreach (var file in files.Where(f => f.Filename.EndsWith(".osu"))) { using (var raw = Files.Store.GetStream(file.FileInfo.StoragePath)) using (var ms = new MemoryStream()) //we need a memory stream so we can seek using (var sr = new LineBufferedReader(ms)) { raw.CopyTo(ms); ms.Position = 0; var decoder = Decoder.GetDecoder<Beatmap>(sr); IBeatmap beatmap = decoder.Decode(sr); beatmap.BeatmapInfo.Path = file.Filename; beatmap.BeatmapInfo.Hash = ms.ComputeSHA2Hash(); beatmap.BeatmapInfo.MD5Hash = ms.ComputeMD5Hash(); var ruleset = rulesets.GetRuleset(beatmap.BeatmapInfo.RulesetID); beatmap.BeatmapInfo.Ruleset = ruleset; // TODO: this should be done in a better place once we actually need to dynamically update it. beatmap.BeatmapInfo.StarDifficulty = ruleset?.CreateInstance().CreateDifficultyCalculator(new DummyConversionBeatmap(beatmap)).Calculate().StarRating ?? 0; beatmap.BeatmapInfo.Length = calculateLength(beatmap); beatmap.BeatmapInfo.BPM = beatmap.ControlPointInfo.BPMMode; beatmapInfos.Add(beatmap.BeatmapInfo); } } return beatmapInfos; } private double calculateLength(IBeatmap b) { if (!b.HitObjects.Any()) return 0; var lastObject = b.HitObjects.Last(); double endTime = (lastObject as IHasEndTime)?.EndTime ?? lastObject.StartTime; double startTime = b.HitObjects.First().StartTime; return endTime - startTime; } /// <summary> /// A dummy WorkingBeatmap for the purpose of retrieving a beatmap for star difficulty calculation. /// </summary> private class DummyConversionBeatmap : WorkingBeatmap { private readonly IBeatmap beatmap; public DummyConversionBeatmap(IBeatmap beatmap) : base(beatmap.BeatmapInfo, null) { this.beatmap = beatmap; } protected override IBeatmap GetBeatmap() => beatmap; protected override Texture GetBackground() => null; protected override VideoSprite GetVideo() => null; protected override Track GetTrack() => null; } private class BeatmapUpdateQueue { private readonly IAPIProvider api; private const int update_queue_request_concurrency = 4; private readonly ThreadedTaskScheduler updateScheduler = new ThreadedTaskScheduler(update_queue_request_concurrency, nameof(BeatmapUpdateQueue)); public BeatmapUpdateQueue(IAPIProvider api) { this.api = api; } public Task UpdateAsync(BeatmapSetInfo beatmapSet, CancellationToken cancellationToken) { if (api?.State != APIState.Online) return Task.CompletedTask; LogForModel(beatmapSet, "Performing online lookups..."); return Task.WhenAll(beatmapSet.Beatmaps.Select(b => UpdateAsync(beatmapSet, b, cancellationToken)).ToArray()); } // todo: expose this when we need to do individual difficulty lookups. protected Task UpdateAsync(BeatmapSetInfo beatmapSet, BeatmapInfo beatmap, CancellationToken cancellationToken) => Task.Factory.StartNew(() => update(beatmapSet, beatmap), cancellationToken, TaskCreationOptions.HideScheduler, updateScheduler); private void update(BeatmapSetInfo set, BeatmapInfo beatmap) { if (api?.State != APIState.Online) return; var req = new GetBeatmapRequest(beatmap); req.Success += res => { LogForModel(set, $"Online retrieval mapped {beatmap} to {res.OnlineBeatmapSetID} / {res.OnlineBeatmapID}."); beatmap.Status = res.Status; beatmap.BeatmapSet.Status = res.BeatmapSet.Status; beatmap.BeatmapSet.OnlineBeatmapSetID = res.OnlineBeatmapSetID; beatmap.OnlineBeatmapID = res.OnlineBeatmapID; }; req.Failure += e => { LogForModel(set, $"Online retrieval failed for {beatmap} ({e.Message})"); }; // intentionally blocking to limit web request concurrency req.Perform(api); } } } }
using Signum.Engine.Translation; using Signum.React.Filters; using Signum.Utilities; using Signum.Utilities.DataStructures; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using System.ComponentModel.DataAnnotations; using Signum.Engine.Basics; using Signum.Entities.Translation; using Signum.Entities; using Signum.Engine.Maps; using Signum.Utilities.Reflection; using Signum.React.Files; using System.IO; using Signum.Engine.Mailing; namespace Signum.React.Translation { [ValidateModelFilter] public class TranslatedInstanceController : ControllerBase { [HttpGet("api/translatedInstance")] public List<TranslatedTypeSummaryTS> Status() { return TranslatedInstanceLogic.TranslationInstancesStatus().Select(a => new TranslatedTypeSummaryTS(a)).ToList(); } [HttpGet("api/translatedInstance/view/{type}")] public TranslatedInstanceViewTypeTS View(string type, string? culture, string filter) { Type t = TypeLogic.GetType(type); var c = culture == null ? null : CultureInfo.GetCultureInfo(culture); var master = TranslatedInstanceLogic.FromEntities(t); var support = TranslatedInstanceLogic.TranslationsForType(t, culture: c); var all = string.IsNullOrEmpty(filter); var cultures = TranslationLogic.CurrentCultureInfos(TranslatedInstanceLogic.DefaultCulture); Func<LocalizedInstanceKey, bool> filtered = li => { if (all) return true; if (li.RowId.ToString() == filter || li.Instance.Id.ToString() == filter || li.Instance.Key() == filter) return true; if (li.Route.PropertyString().Contains(filter, StringComparison.InvariantCultureIgnoreCase)) return true; if (master.GetOrThrow(li)?.Contains(filter, StringComparison.InvariantCultureIgnoreCase) == true) return true; if (cultures.Any(ci => (support.TryGetC(ci)?.TryGetC(li)?.TranslatedText ?? "").Contains(filter, StringComparison.InvariantCultureIgnoreCase))) return true; return false; }; var sd = new StringDistance(); var supportByInstance = (from kvpCult in support from kvpLocIns in kvpCult.Value where master.ContainsKey(kvpLocIns.Key) where filtered(kvpLocIns.Key) let newText = master.TryGet(kvpLocIns.Key, null) group (lockIns: kvpLocIns.Key, translatedInstance: kvpLocIns.Value, culture: kvpCult.Key, newText: newText) by kvpLocIns.Key.Instance into gInstance select KeyValuePair.Create(gInstance.Key, gInstance.AgGroupToDictionary(a => a.lockIns.RouteAndRowId(), gr => gr.ToDictionary(a => a.culture.Name, a => new TranslatedPairViewTS { OriginalText = a.translatedInstance.OriginalText, Diff = a.translatedInstance.OriginalText.Equals(a.newText) ? null : sd.DiffText(a.translatedInstance.OriginalText, a.newText), TranslatedText = a.translatedInstance.TranslatedText }) ))).ToDictionary(); return new TranslatedInstanceViewTypeTS { TypeName = type, Routes = TranslatedInstanceLogic.TranslateableRoutes.GetOrThrow(t).ToDictionary(a => a.Key.PropertyString(), a => a.Value), MasterCulture = TranslatedInstanceLogic.DefaultCulture.Name, Instances = master.Where(kvp => filtered(kvp.Key)).GroupBy(a => a.Key.Instance).Select(gr => new TranslatedInstanceViewTS { Lite = gr.Key, Master = gr.ToDictionary( a => a.Key.RouteAndRowId(), a => a.Value! ), Translations = supportByInstance.TryGetC(gr.Key) ?? new Dictionary<string, Dictionary<string, TranslatedPairViewTS>>() }).ToList() }; } [HttpGet("api/translatedInstance/sync/{type}")] public TypeInstancesChangesTS Sync(string type, string culture) { Type t = TypeLogic.GetType(type); var deletedTranslations = TranslatedInstanceLogic.CleanTranslations(t); var c = CultureInfo.GetCultureInfo(culture); int totalInstances; var changes = TranslatedInstanceSynchronizer.GetTypeInstanceChangesTranslated(TranslationServer.Translators, t, c, out totalInstances); var sd = new StringDistance(); return new TypeInstancesChangesTS { MasterCulture = TranslatedInstanceLogic.DefaultCulture.Name, Routes = TranslatedInstanceLogic.TranslateableRoutes.GetOrThrow(t).ToDictionary(a => a.Key.PropertyString(), a => a.Value), TotalInstances = totalInstances, TypeName = t.Name, Instances = changes.Instances.Select(a => new InstanceChangesTS { Instance = a.Instance, RouteConflicts = a.RouteConflicts.ToDictionaryEx( ipr => ipr.Key.RouteRowId(), ipr => new PropertyChangeTS { Support = ipr.Value.ToDictionaryEx(c => c.Key.Name, c => new PropertyRouteConflictTS { Original = c.Value.Original, OldOriginal = c.Value.OldOriginal, OldTranslation = c.Value.OldTranslation, Diff = c.Value.OldOriginal == null || c.Value.Original == null || c.Value.OldOriginal.Equals(c.Value.Original) ? null : sd.DiffText(c.Value.OldOriginal, c.Value.Original), AutomaticTranslations = c.Value.AutomaticTranslations.ToArray(), }) } ) }).ToList(), DeletedTranslations = deletedTranslations, }; } [HttpPost("api/translatedInstance/save/{type}")] public void Save([Required, FromBody] List<TranslationRecordTS> body, string type, string? culture) { Type t = TypeLogic.GetType(type); CultureInfo? c = culture == null ? null : CultureInfo.GetCultureInfo(culture); var records = GetTranslationRecords(body, t); TranslatedInstanceLogic.SaveRecords(records, t, c); } private List<TranslationRecord> GetTranslationRecords(List<TranslationRecordTS> records, Type type) { var propertyRoute = TranslatedInstanceLogic.TranslateableRoutes.GetOrThrow(type).Keys .ToDictionaryEx(pr => pr.PropertyString(), pr => { var mlistPr = pr.GetMListItemsRoute(); var mlistPkType = mlistPr == null ? null : ((FieldMList)Schema.Current.Field(mlistPr.Parent!)).TableMList.PrimaryKey.Type; return (pr, mlistPkType); }); var list = (from rec in records let c = CultureInfo.GetCultureInfo(rec.Culture) let prInfo = propertyRoute.GetOrThrow(rec.PropertyRoute) select new TranslationRecord { Culture = c, Key = new LocalizedInstanceKey( prInfo.pr, rec.Lite, prInfo.mlistPkType == null ? (PrimaryKey?)null : new PrimaryKey((IComparable)ReflectionTools.Parse(rec.RowId!, prInfo.mlistPkType)!) ), OriginalText = rec.OriginalText, TranslatedText = rec.TranslatedText, }).ToList(); return list; } [HttpGet("api/translatedInstance/viewFile/{type}")] public FileStreamResult ViewFile(string type, string culture) { Type t = TypeLogic.GetType(type); var c = CultureInfo.GetCultureInfo(culture); var file = TranslatedInstanceLogic.ExportExcelFile(t, c); return FilesController.GetFileStreamResult(file); } [HttpGet("api/translatedInstance/syncFile/{type}")] public FileStreamResult SyncFile(string type, string culture) { Type t = TypeLogic.GetType(type); var c = CultureInfo.GetCultureInfo(culture); var file = TranslatedInstanceLogic.ExportExcelFileSync(t, c); return FilesController.GetFileStreamResult(file); } [HttpPost("api/translatedInstance/uploadFile")] public void UploadFile([Required, FromBody] FileUpload file) { TranslatedInstanceLogic.ImportExcelFile(new MemoryStream(file.content), file.fileName); } } public class TranslationRecordTS { public string Culture; public string PropertyRoute; public string? RowId; public Lite<Entity> Lite; public string OriginalText; public string TranslatedText; } public class TypeInstancesChangesTS { public string TypeName; public string MasterCulture; public int TotalInstances; public List<InstanceChangesTS> Instances; public Dictionary<string, TranslateableRouteType> Routes { get; internal set; } public int DeletedTranslations; } public class InstanceChangesTS { public Lite<Entity> Instance; public Dictionary<string, PropertyChangeTS> RouteConflicts; } public class PropertyChangeTS { public string? TranslatedText; public Dictionary<string, PropertyRouteConflictTS> Support; } public class PropertyRouteConflictTS { public string? OldOriginal; public string? OldTranslation; public string Original; public AutomaticTranslation[]? AutomaticTranslations; public List<StringDistance.DiffPair<List<StringDistance.DiffPair<string>>>>? Diff { get; set; } } public class FileUpload { public string fileName; public byte[] content; } public class TranslatedInstanceViewTypeTS { public string TypeName; public string MasterCulture; public Dictionary<string, TranslateableRouteType> Routes; public List<TranslatedInstanceViewTS> Instances; } public class TranslatedInstanceViewTS { public Lite<Entity> Lite; public Dictionary<string, string> Master; public Dictionary<string, Dictionary<string, TranslatedPairViewTS>> Translations; } public class TranslatedPairViewTS { public string OriginalText { get; set; } public string TranslatedText { get; set; } public List<StringDistance.DiffPair<List<StringDistance.DiffPair<string>>>>? Diff { get; set; } } public class TranslatedTypeSummaryTS { public string Type { get; } public bool IsDefaultCulture { get; } public string Culture { get; } public TranslatedSummaryState? State { get; } public TranslatedTypeSummaryTS(TranslatedTypeSummary ts) { this.IsDefaultCulture = ts.CultureInfo.Name == TranslatedInstanceLogic.DefaultCulture.Name; this.Type = TypeLogic.GetCleanName(ts.Type); this.Culture = ts.CultureInfo.Name; this.State = ts.State; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; namespace System { public class RandomDataGenerator { private Random _rand = new Random(); private int? _seed = null; public int? Seed { get { return _seed; } set { if (!_seed.HasValue && value.HasValue) { _seed = value; _rand = new Random(value.Value); } } } // returns a byte array of random data public void GetBytes(int newSeed, byte[] buffer) { Seed = newSeed; GetBytes(buffer); } public void GetBytes(byte[] buffer) { _rand.NextBytes(buffer); } // returns a non-negative Int64 between 0 and Int64.MaxValue public long GetInt64(int newSeed) { Seed = newSeed; return GetInt64(); } public long GetInt64() { byte[] buffer = new byte[8]; GetBytes(buffer); long result = BitConverter.ToInt64(buffer, 0); return result != long.MinValue ? Math.Abs(result) : long.MaxValue; } // returns a non-negative Int32 between 0 and Int32.MaxValue public int GetInt32(int new_seed) { Seed = new_seed; return GetInt32(); } public int GetInt32() { return _rand.Next(); } // returns a non-negative Int16 between 0 and Int16.MaxValue public short GetInt16(int new_seed) { Seed = new_seed; return GetInt16(); } public short GetInt16() { return (short)_rand.Next(1 + short.MaxValue); } // returns a non-negative Byte between 0 and Byte.MaxValue public byte GetByte(int new_seed) { Seed = new_seed; return GetByte(); } public byte GetByte() { return (byte)_rand.Next(1 + byte.MaxValue); } // returns a non-negative Double between 0.0 and 1.0 public double GetDouble(int new_seed) { Seed = new_seed; return GetDouble(); } public double GetDouble() { return _rand.NextDouble(); } // returns a non-negative Single between 0.0 and 1.0 public float GetSingle(int newSeed) { Seed = newSeed; return GetSingle(); } public float GetSingle() { return (float)_rand.NextDouble(); } // returns a valid char that is a letter public char GetCharLetter(int newSeed) { Seed = newSeed; return GetCharLetter(); } public char GetCharLetter() { return GetCharLetter(allowSurrogate: true); } // returns a valid char that is a letter // if allowsurrogate is true then surrogates are valid return values public char GetCharLetter(int newSeed, bool allowSurrogate) { Seed = newSeed; return GetCharLetter(allowSurrogate); } public char GetCharLetter(bool allowSurrogate) { return GetCharLetter(allowSurrogate, allowNoWeight: true); } // returns a valid char that is a letter // if allowsurrogate is true then surrogates are valid return values // if allownoweight is true, then no-weight characters are valid return values public char GetCharLetter(int newSeed, bool allowSurrogate, bool allowNoWeight) { Seed = newSeed; return GetCharLetter(allowSurrogate, allowNoWeight); } public char GetCharLetter(bool allowSurrogate, bool allowNoWeight) { short iVal; char c = 'a'; int counter; bool loopCondition = true; // attempt to randomly find a letter counter = 100; do { counter--; iVal = GetInt16(); if (false == allowNoWeight) { throw new NotSupportedException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES"); } c = Convert.ToChar(iVal); loopCondition = allowSurrogate ? (!char.IsLetter(c)) : (!char.IsLetter(c) || char.IsSurrogate(c)); } while (loopCondition && 0 < counter); if (!char.IsLetter(c)) { // we tried and failed to get a letter // Grab an ASCII letter c = Convert.ToChar(GetInt16() % 26 + 'A'); } return c; } // returns a valid char that is a number public char GetCharNumber(int newSeed) { Seed = newSeed; return GetCharNumber(); } public char GetCharNumber() { return GetCharNumber(true); } // returns a valid char that is a number // if allownoweight is true, then no-weight characters are valid return values public char GetCharNumber(int newSeed, bool allowNoWeight) { Seed = newSeed; return GetCharNumber(allowNoWeight); } public char GetCharNumber(bool allowNoWeight) { char c = '0'; int counter; short iVal; bool loopCondition = true; // attempt to randomly find a number counter = 100; do { counter--; iVal = GetInt16(); if (false == allowNoWeight) { throw new InvalidOperationException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES"); } c = Convert.ToChar(iVal); loopCondition = !char.IsNumber(c); } while (loopCondition && 0 < counter); if (!char.IsNumber(c)) { // we tried and failed to get a letter // Grab an ASCII number c = Convert.ToChar(GetInt16() % 10 + '0'); } return c; } // returns a valid char public char GetChar(int newSeed) { Seed = newSeed; return GetChar(); } public char GetChar() { return GetChar(allowSurrogate: true); } // returns a valid char // if allowsurrogate is true then surrogates are valid return values public char GetChar(int newSeed, bool allowSurrogate) { Seed = newSeed; return GetChar(allowSurrogate); } public char GetChar(bool allowSurrogate) { return GetChar(allowSurrogate, allowNoWeight: true); } // returns a valid char // if allowsurrogate is true then surrogates are valid return values // if allownoweight characters then noweight characters are valid return values public char GetChar(int newSeed, bool allowSurrogate, bool allowNoWeight) { Seed = newSeed; return GetChar(allowSurrogate, allowNoWeight); } public char GetChar(bool allowSurrogate, bool allowNoWeight) { short iVal = GetInt16(); char c = (char)(iVal); if (!char.IsLetter(c)) { // we tried and failed to get a letter // Just grab an ASCII letter c = (char)(GetInt16() % 26 + 'A'); } return c; } // returns a string. If "validPath" is set, only valid path characters // will be included public string GetString(int newSeed, bool validPath, int minLength, int maxLength) { Seed = newSeed; return GetString(validPath, minLength, maxLength); } public string GetString(bool validPath, int minLength, int maxLength) { return GetString(validPath, true, true, minLength, maxLength); } public string GetString(int newSeed, bool validPath, bool allowNulls, int minLength, int maxLength) { Seed = newSeed; return GetString(validPath, allowNulls, minLength, maxLength); } public string GetString(bool validPath, bool allowNulls, int minLength, int maxLength) { return GetString(validPath, allowNulls, true, minLength, maxLength); } public string GetString(int newSeed, bool validPath, bool allowNulls, bool allowNoWeight, int minLength, int maxLength) { Seed = newSeed; return GetString(validPath, allowNulls, allowNoWeight, minLength, maxLength); } public string GetString(bool validPath, bool allowNulls, bool allowNoWeight, int minLength, int maxLength) { StringBuilder sVal = new StringBuilder(); char c; int length; if (0 == minLength && 0 == maxLength) return string.Empty; if (minLength > maxLength) return null; length = minLength; if (minLength != maxLength) { length = (GetInt32() % (maxLength - minLength)) + minLength; } for (int i = 0; length > i; i++) { if (validPath) { if (0 == (GetByte() % 2)) { c = GetCharLetter(true, allowNoWeight); } else { c = GetCharNumber(allowNoWeight); } } else if (!allowNulls) { do { c = GetChar(true, allowNoWeight); } while (c == '\u0000'); } else { c = GetChar(true, allowNoWeight); } sVal.Append(c); } string s = sVal.ToString(); return s; } public string[] GetStrings(int newSeed, bool validPath, int minLength, int maxLength) { Seed = newSeed; return GetStrings(validPath, minLength, maxLength); } public string[] GetStrings(bool validPath, int minLength, int maxLength) { string validString; const char c_LATIN_A = '\u0100'; const char c_LOWER_A = 'a'; const char c_UPPER_A = 'A'; const char c_ZERO_WEIGHT = '\uFEFF'; const char c_DOUBLE_WIDE_A = '\uFF21'; const string c_SURROGATE_UPPER = "\uD801\uDC00"; const string c_SURROGATE_LOWER = "\uD801\uDC28"; const char c_LOWER_SIGMA1 = (char)0x03C2; const char c_LOWER_SIGMA2 = (char)0x03C3; const char c_UPPER_SIGMA = (char)0x03A3; const char c_SPACE = ' '; if (2 >= minLength && 2 >= maxLength || minLength > maxLength) return null; validString = GetString(validPath, minLength - 1, maxLength - 1); string[] retStrings = new string[12]; retStrings[0] = GetString(validPath, minLength, maxLength); retStrings[1] = validString + c_LATIN_A; retStrings[2] = validString + c_LOWER_A; retStrings[3] = validString + c_UPPER_A; retStrings[4] = validString + c_ZERO_WEIGHT; retStrings[5] = validString + c_DOUBLE_WIDE_A; retStrings[6] = GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_UPPER; retStrings[7] = GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_LOWER; retStrings[8] = validString + c_LOWER_SIGMA1; retStrings[9] = validString + c_LOWER_SIGMA2; retStrings[10] = validString + c_UPPER_SIGMA; retStrings[11] = validString + c_SPACE; return retStrings; } public DateTime GetDateTime(int newSeed) => new DateTime(GetInt64(newSeed) % (DateTime.MaxValue.Ticks + 1)); public static void VerifyRandomDistribution(byte[] random) { // Better tests for randomness are available. For now just use a simple // check that compares the number of 0s and 1s in the bits. VerifyNeutralParity(random); } private static void VerifyNeutralParity(byte[] random) { int zeroCount = 0, oneCount = 0; for (int i = 0; i < random.Length; i++) { for (int j = 0; j < 8; j++) { if (((random[i] >> j) & 1) == 1) { oneCount++; } else { zeroCount++; } } } // Over the long run there should be about as many 1s as 0s. // This isn't a guarantee, just a statistical observation. // Allow a 7% tolerance band before considering it to have gotten out of hand. double bitDifference = Math.Abs(zeroCount - oneCount) / (double)(zeroCount + oneCount); const double AllowedTolerance = 0.07; if (bitDifference > AllowedTolerance) { throw new InvalidOperationException("Expected bitDifference < " + AllowedTolerance + ", got " + bitDifference + "."); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; namespace FluentSharp.CoreLib { public static class Crypto_ExtensionMethods { //Random numbers public static Random _random = new Random((int)DateTime.Now.Ticks); public static int random(this int maxValue) { return _random.Next(maxValue); } public static string randomString(this int size) { // inspired from the accepted answer from http://stackoverflow.com/questions/1122483/c-random-string-generator var stringBuilder = new StringBuilder(); for (int i = 0; i < size; i++) { var intValue = Convert.ToInt32(Math.Floor(93 * _random.NextDouble() + 33)); // gets a ASCII value from 33 till 126 var ch = Convert.ToChar(intValue); stringBuilder.Append(ch); } return stringBuilder.ToString(); } public static string randomChars(this int size) { var stringBuilder = new StringBuilder(); for (int i = 0; i < size; i++) { var next = (byte) 255.random(); stringBuilder.Append(next.@char()); } return stringBuilder.ToString(); } public static byte[] randomBytes(this int size) { var bytes = new List<Byte>(); for (int i = 0; i < size; i++) bytes.Add((byte) 255.random()); return bytes.toArray(); } public static string randomNumbers(this int size) { var stringBuilder = new StringBuilder(); for (int i = 0; i < size; i++) { var intValue = Convert.ToInt32(Math.Floor(10 * _random.NextDouble() + 48)); // gets a ASCII value from 33 till 126 var ch = Convert.ToChar(intValue); stringBuilder.Append(ch); } return stringBuilder.ToString(); } public static string randomLetters(this int size) { var stringBuilder = new StringBuilder(); for (int i = 0; i < size; i++) { var intValue = Convert.ToInt32(Math.Floor(26 * _random.NextDouble() + 65)); // gets a ASCII value from 33 till 126 if (1000.random().isEven()) // if it is an even number intValue += 32; // make it lower case var ch = Convert.ToChar(intValue); stringBuilder.Append(ch); } return stringBuilder.ToString(); } // MD5 String public static string md5Hash(this string stringToHash) { if (stringToHash.isNull()) return ""; var md5 = MD5.Create(); var data = md5.ComputeHash(stringToHash.asciiBytes()); return data.hexString(); } //AES //based on code sample from: http://msdn.microsoft.com/en-us/library/system.security.cryptography.aes(v=vs.100).aspx public static byte[] encrypt_AES(this string plainText, string key, string iv) { return plainText.encrypt_AES(key.hexStringToByteArray(), iv.hexStringToByteArray()); } public static byte[] encrypt_AES(this string plainText, byte[] Key, byte[] IV) { // Check arguments. if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException("plainText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("Key"); // Declare the streams used // to encrypt to an in memory // array of bytes. MemoryStream msEncrypt = null; CryptoStream csEncrypt = null; StreamWriter swEncrypt = null; // Declare the Aes object // used to encrypt the data. Aes aesAlg = null; // Declare the bytes used to hold the // encrypted data. //byte[] encrypted = null; try { // Create an Aes object // with the specified key and IV. aesAlg = Aes.Create(); aesAlg.Key = Key; aesAlg.IV = IV; // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. msEncrypt = new MemoryStream(); csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); swEncrypt = new StreamWriter(csEncrypt); //Write all data to the stream. swEncrypt.Write(plainText); } finally { // Clean things up. // Close the streams. if (swEncrypt != null) swEncrypt.Close(); if (csEncrypt != null) csEncrypt.Close(); if (msEncrypt != null) msEncrypt.Close(); // Clear the Aes object. if (aesAlg != null) aesAlg.Clear(); } // Return the encrypted bytes from the memory stream. return msEncrypt.ToArray(); } public static string decrypt_AES(this byte[] cipherText, string key, string iv) { return cipherText.decrypt_AES(key.hexStringToByteArray(), iv.hexStringToByteArray()); } public static string decrypt_AES(this byte[] cipherText, byte[] Key, byte[] IV) { // Check arguments. if (cipherText == null || cipherText.Length <= 0) throw new ArgumentNullException("cipherText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("Key"); // TDeclare the streams used // to decrypt to an in memory // array of bytes. MemoryStream msDecrypt = null; CryptoStream csDecrypt = null; StreamReader srDecrypt = null; // Declare the Aes object // used to decrypt the data. Aes aesAlg = null; // Declare the string used to hold // the decrypted text. string plaintext = null; try { // Create an Aes object // with the specified key and IV. aesAlg = Aes.Create(); aesAlg.Key = Key; aesAlg.IV = IV; // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. msDecrypt = new MemoryStream(cipherText); csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); srDecrypt = new StreamReader(csDecrypt); // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } finally { // Clean things up. // Close the streams. if (srDecrypt != null) srDecrypt.Close(); if (csDecrypt != null) csDecrypt.Close(); if (msDecrypt != null) msDecrypt.Close(); // Clear the Aes object. if (aesAlg != null) aesAlg.Clear(); } return plaintext; } } }
using System; using System.Collections.Generic; using System.Data; using System.Runtime.CompilerServices; using System.Web; using System.Web.Caching; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Events; using umbraco.DataLayer; namespace umbraco.BusinessLogic { /// <summary> /// Represents a umbraco Usertype /// </summary> public class UserType { /// <summary> /// Creates a new empty instance of a UserType /// </summary> public UserType() { } /// <summary> /// Creates a new instance of a UserType and attempts to /// load it's values from the database cache. /// </summary> /// <remarks> /// If the UserType is not found in the existing ID list, then this object /// will remain an empty object /// </remarks> /// <param name="id">The UserType id to find</param> public UserType(int id) { this.LoadByPrimaryKey(id); } /// <summary> /// Initializes a new instance of the <see cref="UserType"/> class. /// </summary> /// <param name="id">The user type id.</param> /// <param name="name">The name.</param> public UserType(int id, string name) { _id = id; _name = name; } /// <summary> /// Creates a new instance of UserType with all parameters /// </summary> /// <param name="id"></param> /// <param name="name"></param> /// <param name="defaultPermissions"></param> /// <param name="alias"></param> public UserType(int id, string name, string defaultPermissions, string alias) { _name = name; _id = id; _defaultPermissions = defaultPermissions; _alias = alias; } private int _id; private string _name; private string _defaultPermissions; private string _alias; /// <summary> /// The cache storage for all user types /// </summary> private static List<UserType> UserTypes { get { return ApplicationContext.Current.ApplicationCache.GetCacheItem( CacheKeys.UserTypeCacheKey, () => { var tmp = new List<UserType>(); using (var dr = SqlHelper.ExecuteReader("select id, userTypeName, userTypeAlias, userTypeDefaultPermissions from umbracoUserType")) { while (dr.Read()) { tmp.Add(new UserType( dr.GetShort("id"), dr.GetString("userTypeName"), dr.GetString("userTypeDefaultPermissions"), dr.GetString("userTypeAlias"))); } } return tmp; }); } } private static ISqlHelper SqlHelper { get { return Application.SqlHelper; } } #region Public Properties /// <summary> /// Gets or sets the user type alias. /// </summary> public string Alias { get { return _alias; } set { _alias = value; } } /// <summary> /// Gets the name of the user type. /// </summary> public string Name { get { return _name; } set { _name = value; } } /// <summary> /// Gets the id the user type /// </summary> public int Id { get { return _id; } } /// <summary> /// Gets the default permissions of the user type /// </summary> public string DefaultPermissions { get { return _defaultPermissions; } set { _defaultPermissions = value; } } /// <summary> /// Returns an array of UserTypes /// </summary> [Obsolete("Use the GetAll method instead")] public static UserType[] getAll { get { return GetAllUserTypes().ToArray(); } } #endregion /// <summary> /// Saves this instance. /// </summary> public void Save() { //ensure that this object has an ID specified (it exists in the database) if (_id <= 0) throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method"); SqlHelper.ExecuteNonQuery(@" update umbracoUserType set userTypeAlias=@alias,userTypeName=@name,userTypeDefaultPermissions=@permissions where id=@id", SqlHelper.CreateParameter("@alias", _alias), SqlHelper.CreateParameter("@name", _name), SqlHelper.CreateParameter("@permissions", _defaultPermissions), SqlHelper.CreateParameter("@id", _id) ); //raise event OnUpdated(this, new EventArgs()); } /// <summary> /// Deletes this instance. /// </summary> public void Delete() { //ensure that this object has an ID specified (it exists in the database) if (_id <= 0) throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method"); SqlHelper.ExecuteNonQuery(@"delete from umbracoUserType where id=@id", SqlHelper.CreateParameter("@id", _id)); //raise event OnDeleted(this, new EventArgs()); } /// <summary> /// Load the data for the current UserType by it's id /// </summary> /// <param name="id"></param> /// <returns>Returns true if the UserType id was found /// and the data was loaded, false if it wasn't</returns> public bool LoadByPrimaryKey(int id) { var userType = GetUserType(id); if (userType == null) return false; _id = userType.Id; _alias = userType.Alias; _defaultPermissions = userType.DefaultPermissions; _name = userType.Name; return true; } /// <summary> /// Creates a new user type /// </summary> /// <param name="name"></param> /// <param name="defaultPermissions"></param> /// <param name="alias"></param> [MethodImpl(MethodImplOptions.Synchronized)] public static UserType MakeNew(string name, string defaultPermissions, string alias) { //ensure that the current alias does not exist //get the id for the new user type var existing = UserTypes.Find(ut => (ut.Alias == alias)); if (existing != null) throw new Exception("The UserType alias specified already exists"); SqlHelper.ExecuteNonQuery(@" insert into umbracoUserType (userTypeAlias,userTypeName,userTypeDefaultPermissions) values (@alias,@name,@permissions)", SqlHelper.CreateParameter("@alias", alias), SqlHelper.CreateParameter("@name", name), SqlHelper.CreateParameter("@permissions", defaultPermissions)); //get it's id var newId = SqlHelper.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoUserType WHERE userTypeAlias=@alias", SqlHelper.CreateParameter("@alias", alias)); //load the instance and return it using (var dr = SqlHelper.ExecuteReader( "select id, userTypeName, userTypeAlias, userTypeDefaultPermissions from umbracoUserType where id=@id", SqlHelper.CreateParameter("@id", newId))) { if (dr.Read()) { var ut = new UserType( dr.GetShort("id"), dr.GetString("userTypeName"), dr.GetString("userTypeDefaultPermissions"), dr.GetString("userTypeAlias")); //raise event OnNew(ut, new EventArgs()); return ut; } throw new InvalidOperationException("Could not read the new User Type with id of " + newId); } } /// <summary> /// Gets the user type with the specied ID /// </summary> /// <param name="id">The id.</param> /// <returns></returns> public static UserType GetUserType(int id) { return UserTypes.Find(ut => (ut.Id == id)); } /// <summary> /// Returns all UserType's /// </summary> /// <returns></returns> public static List<UserType> GetAllUserTypes() { return UserTypes; } internal static event TypedEventHandler<UserType, EventArgs> New; private static void OnNew(UserType userType, EventArgs args) { if (New != null) { New(userType, args); } } internal static event TypedEventHandler<UserType, EventArgs> Deleted; private static void OnDeleted(UserType userType, EventArgs args) { if (Deleted != null) { Deleted(userType, args); } } internal static event TypedEventHandler<UserType, EventArgs> Updated; private static void OnUpdated(UserType userType, EventArgs args) { if (Updated != null) { Updated(userType, args); } } } }
// 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.Drawing.Imaging { /// <summary> /// Defines a 5 x 5 matrix that contains the homogeneous coordinates for the RGBA space. /// </summary> [StructLayout(LayoutKind.Sequential)] public sealed class ColorMatrix { private float _matrix00; private float _matrix01; private float _matrix02; private float _matrix03; private float _matrix04; private float _matrix10; private float _matrix11; private float _matrix12; private float _matrix13; private float _matrix14; private float _matrix20; private float _matrix21; private float _matrix22; private float _matrix23; private float _matrix24; private float _matrix30; private float _matrix31; private float _matrix32; private float _matrix33; private float _matrix34; private float _matrix40; private float _matrix41; private float _matrix42; private float _matrix43; private float _matrix44; /// <summary> /// Initializes a new instance of the <see cref='ColorMatrix'/> class. /// </summary> public ColorMatrix() { /* * Setup identity matrix by default */ _matrix00 = 1.0f; //matrix01 = 0.0f; //matrix02 = 0.0f; //matrix03 = 0.0f; //matrix04 = 0.0f; //matrix10 = 0.0f; _matrix11 = 1.0f; //matrix12 = 0.0f; //matrix13 = 0.0f; //matrix14 = 0.0f; //matrix20 = 0.0f; //matrix21 = 0.0f; _matrix22 = 1.0f; // matrix23 = 0.0f; // matrix24 = 0.0f; // matrix30 = 0.0f; //matrix31 = 0.0f; // matrix32 = 0.0f; _matrix33 = 1.0f; // matrix34 = 0.0f; // matrix40 = 0.0f; // matrix41 = 0.0f; // matrix42 = 0.0f; // matrix43 = 0.0f; _matrix44 = 1.0f; } /// <summary> /// Represents the element at the 0th row and 0th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix00 { get { return _matrix00; } set { _matrix00 = value; } } /// <summary> /// Represents the element at the 0th row and 1st column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix01 { get { return _matrix01; } set { _matrix01 = value; } } /// <summary> /// Represents the element at the 0th row and 2nd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix02 { get { return _matrix02; } set { _matrix02 = value; } } /// <summary> /// Represents the element at the 0th row and 3rd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix03 { get { return _matrix03; } set { _matrix03 = value; } } /// <summary> /// Represents the element at the 0th row and 4th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix04 { get { return _matrix04; } set { _matrix04 = value; } } /// <summary> /// Represents the element at the 1st row and 0th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix10 { get { return _matrix10; } set { _matrix10 = value; } } /// <summary> /// Represents the element at the 1st row and 1st column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix11 { get { return _matrix11; } set { _matrix11 = value; } } /// <summary> /// Represents the element at the 1st row and 2nd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix12 { get { return _matrix12; } set { _matrix12 = value; } } /// <summary> /// Represents the element at the 1st row and 3rd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix13 { get { return _matrix13; } set { _matrix13 = value; } } /// <summary> /// Represents the element at the 1st row and 4th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix14 { get { return _matrix14; } set { _matrix14 = value; } } /// <summary> /// Represents the element at the 2nd row and 0th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix20 { get { return _matrix20; } set { _matrix20 = value; } } /// <summary> /// Represents the element at the 2nd row and 1st column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix21 { get { return _matrix21; } set { _matrix21 = value; } } /// <summary> /// Represents the element at the 2nd row and 2nd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix22 { get { return _matrix22; } set { _matrix22 = value; } } /// <summary> /// Represents the element at the 2nd row and 3rd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix23 { get { return _matrix23; } set { _matrix23 = value; } } /// <summary> /// Represents the element at the 2nd row and 4th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix24 { get { return _matrix24; } set { _matrix24 = value; } } /// <summary> /// Represents the element at the 3rd row and 0th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix30 { get { return _matrix30; } set { _matrix30 = value; } } /// <summary> /// Represents the element at the 3rd row and 1st column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix31 { get { return _matrix31; } set { _matrix31 = value; } } /// <summary> /// Represents the element at the 3rd row and 2nd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix32 { get { return _matrix32; } set { _matrix32 = value; } } /// <summary> /// Represents the element at the 3rd row and 3rd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix33 { get { return _matrix33; } set { _matrix33 = value; } } /// <summary> /// Represents the element at the 3rd row and 4th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix34 { get { return _matrix34; } set { _matrix34 = value; } } /// <summary> /// Represents the element at the 4th row and 0th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix40 { get { return _matrix40; } set { _matrix40 = value; } } /// <summary> /// Represents the element at the 4th row and 1st column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix41 { get { return _matrix41; } set { _matrix41 = value; } } /// <summary> /// Represents the element at the 4th row and 2nd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix42 { get { return _matrix42; } set { _matrix42 = value; } } /// <summary> /// Represents the element at the 4th row and 3rd column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix43 { get { return _matrix43; } set { _matrix43 = value; } } /// <summary> /// Represents the element at the 4th row and 4th column of this <see cref='ColorMatrix'/>. /// </summary> public float Matrix44 { get { return _matrix44; } set { _matrix44 = value; } } /// <summary> /// Initializes a new instance of the <see cref='ColorMatrix'/> class with the elements in the specified matrix. /// </summary> [CLSCompliant(false)] public ColorMatrix(float[][] newColorMatrix) { SetMatrix(newColorMatrix); } internal void SetMatrix(float[][] newColorMatrix) { _matrix00 = newColorMatrix[0][0]; _matrix01 = newColorMatrix[0][1]; _matrix02 = newColorMatrix[0][2]; _matrix03 = newColorMatrix[0][3]; _matrix04 = newColorMatrix[0][4]; _matrix10 = newColorMatrix[1][0]; _matrix11 = newColorMatrix[1][1]; _matrix12 = newColorMatrix[1][2]; _matrix13 = newColorMatrix[1][3]; _matrix14 = newColorMatrix[1][4]; _matrix20 = newColorMatrix[2][0]; _matrix21 = newColorMatrix[2][1]; _matrix22 = newColorMatrix[2][2]; _matrix23 = newColorMatrix[2][3]; _matrix24 = newColorMatrix[2][4]; _matrix30 = newColorMatrix[3][0]; _matrix31 = newColorMatrix[3][1]; _matrix32 = newColorMatrix[3][2]; _matrix33 = newColorMatrix[3][3]; _matrix34 = newColorMatrix[3][4]; _matrix40 = newColorMatrix[4][0]; _matrix41 = newColorMatrix[4][1]; _matrix42 = newColorMatrix[4][2]; _matrix43 = newColorMatrix[4][3]; _matrix44 = newColorMatrix[4][4]; } internal float[][] GetMatrix() { float[][] returnMatrix = new float[5][]; for (int i = 0; i < 5; i++) returnMatrix[i] = new float[5]; returnMatrix[0][0] = _matrix00; returnMatrix[0][1] = _matrix01; returnMatrix[0][2] = _matrix02; returnMatrix[0][3] = _matrix03; returnMatrix[0][4] = _matrix04; returnMatrix[1][0] = _matrix10; returnMatrix[1][1] = _matrix11; returnMatrix[1][2] = _matrix12; returnMatrix[1][3] = _matrix13; returnMatrix[1][4] = _matrix14; returnMatrix[2][0] = _matrix20; returnMatrix[2][1] = _matrix21; returnMatrix[2][2] = _matrix22; returnMatrix[2][3] = _matrix23; returnMatrix[2][4] = _matrix24; returnMatrix[3][0] = _matrix30; returnMatrix[3][1] = _matrix31; returnMatrix[3][2] = _matrix32; returnMatrix[3][3] = _matrix33; returnMatrix[3][4] = _matrix34; returnMatrix[4][0] = _matrix40; returnMatrix[4][1] = _matrix41; returnMatrix[4][2] = _matrix42; returnMatrix[4][3] = _matrix43; returnMatrix[4][4] = _matrix44; return returnMatrix; } /// <summary> /// Gets or sets the value of the specified element of this <see cref='ColorMatrix'/>. /// </summary> public float this[int row, int column] { get { return GetMatrix()[row][column]; } set { float[][] tempMatrix = GetMatrix(); tempMatrix[row][column] = value; SetMatrix(tempMatrix); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Binary.Metadata; using Apache.Ignite.Core.Impl.Binary.Structure; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Binary writer implementation. /// </summary> internal class BinaryWriter : IBinaryWriter, IBinaryRawWriter { /** Marshaller. */ private readonly Marshaller _marsh; /** Stream. */ private readonly IBinaryStream _stream; /** Builder (used only during build). */ private BinaryObjectBuilder _builder; /** Handles. */ private BinaryHandleDictionary<object, long> _hnds; /** Metadatas collected during this write session. */ private IDictionary<int, BinaryType> _metas; /** Current stack frame. */ private Frame _frame; /** Whether we are currently detaching an object: detachment root when true, null otherwise. */ private object _detaching; /** Whether we are directly within peer loading object holder. */ private bool _isInWrapper; /** Schema holder. */ private readonly BinaryObjectSchemaHolder _schema = BinaryObjectSchemaHolder.Current; /// <summary> /// Gets the marshaller. /// </summary> internal Marshaller Marshaller { get { return _marsh; } } /// <summary> /// Invoked when binary object writing finishes. /// </summary> internal event Action<BinaryObjectHeader, object> OnObjectWritten; /// <summary> /// Write named boolean value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Boolean value.</param> public void WriteBoolean(string fieldName, bool val) { WriteFieldId(fieldName, BinaryTypeId.Bool); WriteBooleanField(val); } /// <summary> /// Writes the boolean field. /// </summary> /// <param name="val">if set to <c>true</c> [value].</param> internal void WriteBooleanField(bool val) { _stream.WriteByte(BinaryTypeId.Bool); _stream.WriteBool(val); } /// <summary> /// Write boolean value. /// </summary> /// <param name="val">Boolean value.</param> public void WriteBoolean(bool val) { _stream.WriteBool(val); } /// <summary> /// Write named boolean array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Boolean array.</param> public void WriteBooleanArray(string fieldName, bool[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayBool); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayBool); BinaryUtils.WriteBooleanArray(val, _stream); } } /// <summary> /// Write boolean array. /// </summary> /// <param name="val">Boolean array.</param> public void WriteBooleanArray(bool[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayBool); BinaryUtils.WriteBooleanArray(val, _stream); } } /// <summary> /// Write named byte value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Byte value.</param> public void WriteByte(string fieldName, byte val) { WriteFieldId(fieldName, BinaryTypeId.Byte); WriteByteField(val); } /// <summary> /// Write byte field value. /// </summary> /// <param name="val">Byte value.</param> internal void WriteByteField(byte val) { _stream.WriteByte(BinaryTypeId.Byte); _stream.WriteByte(val); } /// <summary> /// Write byte value. /// </summary> /// <param name="val">Byte value.</param> public void WriteByte(byte val) { _stream.WriteByte(val); } /// <summary> /// Write named byte array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Byte array.</param> public void WriteByteArray(string fieldName, byte[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayByte); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayByte); BinaryUtils.WriteByteArray(val, _stream); } } /// <summary> /// Write byte array. /// </summary> /// <param name="val">Byte array.</param> public void WriteByteArray(byte[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayByte); BinaryUtils.WriteByteArray(val, _stream); } } /// <summary> /// Write named short value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Short value.</param> public void WriteShort(string fieldName, short val) { WriteFieldId(fieldName, BinaryTypeId.Short); WriteShortField(val); } /// <summary> /// Write short field value. /// </summary> /// <param name="val">Short value.</param> internal void WriteShortField(short val) { _stream.WriteByte(BinaryTypeId.Short); _stream.WriteShort(val); } /// <summary> /// Write short value. /// </summary> /// <param name="val">Short value.</param> public void WriteShort(short val) { _stream.WriteShort(val); } /// <summary> /// Write named short array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Short array.</param> public void WriteShortArray(string fieldName, short[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayShort); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayShort); BinaryUtils.WriteShortArray(val, _stream); } } /// <summary> /// Write short array. /// </summary> /// <param name="val">Short array.</param> public void WriteShortArray(short[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayShort); BinaryUtils.WriteShortArray(val, _stream); } } /// <summary> /// Write named char value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Char value.</param> public void WriteChar(string fieldName, char val) { WriteFieldId(fieldName, BinaryTypeId.Char); WriteCharField(val); } /// <summary> /// Write char field value. /// </summary> /// <param name="val">Char value.</param> internal void WriteCharField(char val) { _stream.WriteByte(BinaryTypeId.Char); _stream.WriteChar(val); } /// <summary> /// Write char value. /// </summary> /// <param name="val">Char value.</param> public void WriteChar(char val) { _stream.WriteChar(val); } /// <summary> /// Write named char array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Char array.</param> public void WriteCharArray(string fieldName, char[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayChar); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayChar); BinaryUtils.WriteCharArray(val, _stream); } } /// <summary> /// Write char array. /// </summary> /// <param name="val">Char array.</param> public void WriteCharArray(char[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayChar); BinaryUtils.WriteCharArray(val, _stream); } } /// <summary> /// Write named int value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Int value.</param> public void WriteInt(string fieldName, int val) { WriteFieldId(fieldName, BinaryTypeId.Int); WriteIntField(val); } /// <summary> /// Writes the int field. /// </summary> /// <param name="val">The value.</param> internal void WriteIntField(int val) { _stream.WriteByte(BinaryTypeId.Int); _stream.WriteInt(val); } /// <summary> /// Write int value. /// </summary> /// <param name="val">Int value.</param> public void WriteInt(int val) { _stream.WriteInt(val); } /// <summary> /// Write named int array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Int array.</param> public void WriteIntArray(string fieldName, int[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayInt); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayInt); BinaryUtils.WriteIntArray(val, _stream); } } /// <summary> /// Write int array. /// </summary> /// <param name="val">Int array.</param> public void WriteIntArray(int[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayInt); BinaryUtils.WriteIntArray(val, _stream); } } /// <summary> /// Write named long value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Long value.</param> public void WriteLong(string fieldName, long val) { WriteFieldId(fieldName, BinaryTypeId.Long); WriteLongField(val); } /// <summary> /// Writes the long field. /// </summary> /// <param name="val">The value.</param> internal void WriteLongField(long val) { _stream.WriteByte(BinaryTypeId.Long); _stream.WriteLong(val); } /// <summary> /// Write long value. /// </summary> /// <param name="val">Long value.</param> public void WriteLong(long val) { _stream.WriteLong(val); } /// <summary> /// Write named long array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Long array.</param> public void WriteLongArray(string fieldName, long[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayLong); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayLong); BinaryUtils.WriteLongArray(val, _stream); } } /// <summary> /// Write long array. /// </summary> /// <param name="val">Long array.</param> public void WriteLongArray(long[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayLong); BinaryUtils.WriteLongArray(val, _stream); } } /// <summary> /// Write named float value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Float value.</param> public void WriteFloat(string fieldName, float val) { WriteFieldId(fieldName, BinaryTypeId.Float); WriteFloatField(val); } /// <summary> /// Writes the float field. /// </summary> /// <param name="val">The value.</param> internal void WriteFloatField(float val) { _stream.WriteByte(BinaryTypeId.Float); _stream.WriteFloat(val); } /// <summary> /// Write float value. /// </summary> /// <param name="val">Float value.</param> public void WriteFloat(float val) { _stream.WriteFloat(val); } /// <summary> /// Write named float array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Float array.</param> public void WriteFloatArray(string fieldName, float[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayFloat); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayFloat); BinaryUtils.WriteFloatArray(val, _stream); } } /// <summary> /// Write float array. /// </summary> /// <param name="val">Float array.</param> public void WriteFloatArray(float[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayFloat); BinaryUtils.WriteFloatArray(val, _stream); } } /// <summary> /// Write named double value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Double value.</param> public void WriteDouble(string fieldName, double val) { WriteFieldId(fieldName, BinaryTypeId.Double); WriteDoubleField(val); } /// <summary> /// Writes the double field. /// </summary> /// <param name="val">The value.</param> internal void WriteDoubleField(double val) { _stream.WriteByte(BinaryTypeId.Double); _stream.WriteDouble(val); } /// <summary> /// Write double value. /// </summary> /// <param name="val">Double value.</param> public void WriteDouble(double val) { _stream.WriteDouble(val); } /// <summary> /// Write named double array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Double array.</param> public void WriteDoubleArray(string fieldName, double[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayDouble); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayDouble); BinaryUtils.WriteDoubleArray(val, _stream); } } /// <summary> /// Write double array. /// </summary> /// <param name="val">Double array.</param> public void WriteDoubleArray(double[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayDouble); BinaryUtils.WriteDoubleArray(val, _stream); } } /// <summary> /// Write named decimal value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Decimal value.</param> public void WriteDecimal(string fieldName, decimal? val) { WriteFieldId(fieldName, BinaryTypeId.Decimal); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.Decimal); BinaryUtils.WriteDecimal(val.Value, _stream); } } /// <summary> /// Write decimal value. /// </summary> /// <param name="val">Decimal value.</param> public void WriteDecimal(decimal? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.Decimal); BinaryUtils.WriteDecimal(val.Value, _stream); } } /// <summary> /// Write named decimal array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Decimal array.</param> public void WriteDecimalArray(string fieldName, decimal?[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayDecimal); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayDecimal); BinaryUtils.WriteDecimalArray(val, _stream); } } /// <summary> /// Write decimal array. /// </summary> /// <param name="val">Decimal array.</param> public void WriteDecimalArray(decimal?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayDecimal); BinaryUtils.WriteDecimalArray(val, _stream); } } /// <summary> /// Write named date value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Date value.</param> public void WriteTimestamp(string fieldName, DateTime? val) { WriteFieldId(fieldName, BinaryTypeId.Timestamp); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.Timestamp); BinaryUtils.WriteTimestamp(val.Value, _stream, _marsh.TimestampConverter); } } /// <summary> /// Write date value. /// </summary> /// <param name="val">Date value.</param> public void WriteTimestamp(DateTime? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.Timestamp); BinaryUtils.WriteTimestamp(val.Value, _stream, _marsh.TimestampConverter); } } /// <summary> /// Write named date array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Date array.</param> public void WriteTimestampArray(string fieldName, DateTime?[] val) { WriteFieldId(fieldName, BinaryTypeId.Timestamp); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayTimestamp); BinaryUtils.WriteTimestampArray(val, _stream, _marsh.TimestampConverter); } } /// <summary> /// Write date array. /// </summary> /// <param name="val">Date array.</param> public void WriteTimestampArray(DateTime?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayTimestamp); BinaryUtils.WriteTimestampArray(val, _stream, _marsh.TimestampConverter); } } /// <summary> /// Write named string value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">String value.</param> public void WriteString(string fieldName, string val) { WriteFieldId(fieldName, BinaryTypeId.String); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.String); BinaryUtils.WriteString(val, _stream); } } /// <summary> /// Write string value. /// </summary> /// <param name="val">String value.</param> public void WriteString(string val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.String); BinaryUtils.WriteString(val, _stream); } } /// <summary> /// Write named string array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">String array.</param> public void WriteStringArray(string fieldName, string[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayString); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayString); BinaryUtils.WriteStringArray(val, _stream); } } /// <summary> /// Write string array. /// </summary> /// <param name="val">String array.</param> public void WriteStringArray(string[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayString); BinaryUtils.WriteStringArray(val, _stream); } } /// <summary> /// Write named GUID value. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">GUID value.</param> public void WriteGuid(string fieldName, Guid? val) { WriteFieldId(fieldName, BinaryTypeId.Guid); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.Guid); BinaryUtils.WriteGuid(val.Value, _stream); } } /// <summary> /// Write GUID value. /// </summary> /// <param name="val">GUID value.</param> public void WriteGuid(Guid? val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.Guid); BinaryUtils.WriteGuid(val.Value, _stream); } } /// <summary> /// Write named GUID array. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">GUID array.</param> public void WriteGuidArray(string fieldName, Guid?[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayGuid); if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayGuid); BinaryUtils.WriteGuidArray(val, _stream); } } /// <summary> /// Write GUID array. /// </summary> /// <param name="val">GUID array.</param> public void WriteGuidArray(Guid?[] val) { if (val == null) WriteNullRawField(); else { _stream.WriteByte(BinaryTypeId.ArrayGuid); BinaryUtils.WriteGuidArray(val, _stream); } } /// <summary> /// Write named enum value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Enum value.</param> public void WriteEnum<T>(string fieldName, T val) { WriteFieldId(fieldName, BinaryTypeId.Enum); WriteEnum(val); } /// <summary> /// Write enum value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Enum value.</param> public void WriteEnum<T>(T val) { // ReSharper disable once CompareNonConstrainedGenericWithNull if (val == null) WriteNullField(); else { // Unwrap nullable. var valType = val.GetType(); var type = Nullable.GetUnderlyingType(valType) ?? valType; if (!type.IsEnum) { throw new BinaryObjectException("Type is not an enum: " + type); } var handler = BinarySystemHandlers.GetWriteHandler(type, _marsh.ForceTimestamp); if (handler != null) { // All enums except long/ulong. handler.Write(this, val); } else { throw new BinaryObjectException(string.Format("Enum '{0}' has unsupported underlying type '{1}'. " + "Use WriteObject instead of WriteEnum.", type, Enum.GetUnderlyingType(type))); } } } /// <summary> /// Write enum value. /// </summary> /// <param name="val">Enum value.</param> /// <param name="type">Enum type.</param> internal void WriteEnum(int val, Type type) { var desc = _marsh.GetDescriptor(type); WriteEnum(val, desc.TypeId); var binaryTypeHolder = Marshaller.GetCachedBinaryTypeHolder(desc.TypeId); if (binaryTypeHolder == null || !binaryTypeHolder.IsSaved) { // Save enum fields only once - they can't change locally at runtime. var metaHnd = _marsh.GetBinaryTypeHandler(desc); var binaryFields = metaHnd.OnObjectWriteFinished(); SaveMetadata(desc, binaryFields); } } /// <summary> /// Write enum value. /// </summary> /// <param name="val">Enum value.</param> /// <param name="typeId">Enum type id.</param> private void WriteEnum(int val, int typeId) { _stream.WriteByte(BinaryTypeId.Enum); _stream.WriteInt(typeId); _stream.WriteInt(val); } /// <summary> /// Write named enum array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Enum array.</param> public void WriteEnumArray<T>(string fieldName, T[] val) { WriteFieldId(fieldName, BinaryTypeId.ArrayEnum); WriteEnumArray(val); } /// <summary> /// Write enum array. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Enum array.</param> public void WriteEnumArray<T>(T[] val) { WriteEnumArrayInternal(val, null); } /// <summary> /// Writes the enum array. /// </summary> /// <param name="val">The value.</param> /// <param name="elementTypeId">The element type id.</param> public void WriteEnumArrayInternal(Array val, int? elementTypeId) { if (val == null) WriteNullField(); else { _stream.WriteByte(BinaryTypeId.ArrayEnum); BinaryUtils.WriteArray(val, this, elementTypeId); } } /// <summary> /// Write named object value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Object value.</param> public void WriteObject<T>(string fieldName, T val) { WriteFieldId(fieldName, BinaryTypeId.Object); // ReSharper disable once CompareNonConstrainedGenericWithNull if (val == null) WriteNullField(); else Write(val); } /// <summary> /// Write object value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="val">Object value.</param> public void WriteObject<T>(T val) { Write(val); } /// <summary> /// Write named object array. /// </summary> /// <typeparam name="T">Element type.</typeparam> /// <param name="fieldName">Field name.</param> /// <param name="val">Object array.</param> public void WriteArray<T>(string fieldName, T[] val) { WriteFieldId(fieldName, BinaryTypeId.Array); WriteArray(val); } /// <summary> /// Write object array. /// </summary> /// <typeparam name="T">Element type.</typeparam> /// <param name="val">Object array.</param> public void WriteArray<T>(T[] val) { WriteArrayInternal(val); } /// <summary> /// Write object array. /// </summary> /// <param name="val">Object array.</param> public void WriteArrayInternal(Array val) { if (val == null) WriteNullRawField(); else { if (WriteHandle(_stream.Position, val)) return; _stream.WriteByte(BinaryTypeId.Array); BinaryUtils.WriteArray(val, this); } } /// <summary> /// Write named collection. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Collection.</param> public void WriteCollection(string fieldName, ICollection val) { WriteFieldId(fieldName, BinaryTypeId.Collection); WriteCollection(val); } /// <summary> /// Write collection. /// </summary> /// <param name="val">Collection.</param> public void WriteCollection(ICollection val) { if (val == null) WriteNullField(); else { if (WriteHandle(_stream.Position, val)) return; WriteByte(BinaryTypeId.Collection); BinaryUtils.WriteCollection(val, this); } } /// <summary> /// Write named dictionary. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Dictionary.</param> public void WriteDictionary(string fieldName, IDictionary val) { WriteFieldId(fieldName, BinaryTypeId.Dictionary); WriteDictionary(val); } /// <summary> /// Write dictionary. /// </summary> /// <param name="val">Dictionary.</param> public void WriteDictionary(IDictionary val) { if (val == null) WriteNullField(); else { if (WriteHandle(_stream.Position, val)) return; WriteByte(BinaryTypeId.Dictionary); BinaryUtils.WriteDictionary(val, this); } } /// <summary> /// Write NULL field. /// </summary> private void WriteNullField() { _stream.WriteByte(BinaryUtils.HdrNull); } /// <summary> /// Write NULL raw field. /// </summary> private void WriteNullRawField() { _stream.WriteByte(BinaryUtils.HdrNull); } /// <summary> /// Get raw writer. /// </summary> /// <returns> /// Raw writer. /// </returns> public IBinaryRawWriter GetRawWriter() { if (_frame.RawPos == 0) _frame.RawPos = _stream.Position; return this; } /// <summary> /// Set new builder. /// </summary> /// <param name="builder">Builder.</param> /// <returns>Previous builder.</returns> internal BinaryObjectBuilder SetBuilder(BinaryObjectBuilder builder) { BinaryObjectBuilder ret = _builder; _builder = builder; return ret; } /// <summary> /// Constructor. /// </summary> /// <param name="marsh">Marshaller.</param> /// <param name="stream">Stream.</param> internal BinaryWriter(Marshaller marsh, IBinaryStream stream) { _marsh = marsh; _stream = stream; } /// <summary> /// Write object. /// </summary> /// <param name="obj">Object.</param> public void Write<T>(T obj) { // Handle special case for null. // ReSharper disable once CompareNonConstrainedGenericWithNull if (obj == null) { _stream.WriteByte(BinaryUtils.HdrNull); return; } // We use GetType() of a real object instead of typeof(T) to take advantage of // automatic Nullable'1 unwrapping. Type type = obj.GetType(); // Handle common case when primitive is written. if (type.IsPrimitive) { WritePrimitive(obj, type); return; } // Handle special case for builder. if (WriteBuilderSpecials(obj)) return; // Are we dealing with a well-known type? var handler = BinarySystemHandlers.GetWriteHandler(type, _marsh.ForceTimestamp); if (handler != null) { if (handler.SupportsHandles && WriteHandle(_stream.Position, obj)) return; handler.Write(this, obj); return; } // Wrap objects as required. if (WrapperFunc != null && type != WrapperFunc.Method.ReturnType) { if (_isInWrapper) { _isInWrapper = false; } else { _isInWrapper = true; Write(WrapperFunc(obj)); return; } } // Suppose that we faced normal object and perform descriptor lookup. var desc = _marsh.GetDescriptor(type); // Writing normal object. var pos = _stream.Position; // Dealing with handles. if (desc.Serializer.SupportsHandles && WriteHandle(pos, obj)) return; // Skip header length as not everything is known now _stream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current); // Write type name for unregistered types if (!desc.IsRegistered) { WriteString(Marshaller.GetTypeName(type)); } var headerSize = _stream.Position - pos; // Preserve old frame. var oldFrame = _frame; // Push new frame. _frame.RawPos = 0; _frame.Pos = pos; _frame.Struct = new BinaryStructureTracker(desc, desc.WriterTypeStructure); _frame.HasCustomTypeData = false; var schemaIdx = _schema.PushSchema(); try { // Write object fields. desc.Serializer.WriteBinary(obj, this); var dataEnd = _stream.Position; // Write schema var schemaOffset = dataEnd - pos; int schemaId; var flags = desc.UserType ? BinaryObjectHeader.Flag.UserType : BinaryObjectHeader.Flag.None; if (_frame.HasCustomTypeData) flags |= BinaryObjectHeader.Flag.CustomDotNetType; if (Marshaller.CompactFooter && desc.UserType) flags |= BinaryObjectHeader.Flag.CompactFooter; var hasSchema = _schema.WriteSchema(_stream, schemaIdx, out schemaId, ref flags); if (hasSchema) { flags |= BinaryObjectHeader.Flag.HasSchema; // Calculate and write header. if (_frame.RawPos > 0) _stream.WriteInt(_frame.RawPos - pos); // raw offset is in the last 4 bytes // Update schema in type descriptor if (desc.Schema.Get(schemaId) == null) desc.Schema.Add(schemaId, _schema.GetSchema(schemaIdx)); } else schemaOffset = headerSize; if (_frame.RawPos > 0) flags |= BinaryObjectHeader.Flag.HasRaw; var len = _stream.Position - pos; var hashCode = BinaryArrayEqualityComparer.GetHashCode(Stream, pos + BinaryObjectHeader.Size, dataEnd - pos - BinaryObjectHeader.Size); var header = new BinaryObjectHeader(desc.IsRegistered ? desc.TypeId : BinaryTypeId.Unregistered, hashCode, len, schemaId, schemaOffset, flags); BinaryObjectHeader.Write(header, _stream, pos); if (OnObjectWritten != null) { OnObjectWritten(header, obj); } Stream.Seek(pos + len, SeekOrigin.Begin); // Seek to the end } finally { _schema.PopSchema(schemaIdx); } // Apply structure updates if any. _frame.Struct.UpdateWriterStructure(this); // Restore old frame. _frame = oldFrame; } /// <summary> /// Marks current object with a custom type data flag. /// </summary> public void SetCustomTypeDataFlag(bool hasCustomTypeData) { _frame.HasCustomTypeData = hasCustomTypeData; } /// <summary> /// Write primitive type. /// </summary> /// <param name="val">Object.</param> /// <param name="type">Type.</param> private unsafe void WritePrimitive<T>(T val, Type type) { // .NET defines 14 primitive types. // Types check sequence is designed to minimize comparisons for the most frequent types. if (type == typeof(int)) WriteIntField(TypeCaster<int>.Cast(val)); else if (type == typeof(long)) WriteLongField(TypeCaster<long>.Cast(val)); else if (type == typeof(bool)) WriteBooleanField(TypeCaster<bool>.Cast(val)); else if (type == typeof(byte)) WriteByteField(TypeCaster<byte>.Cast(val)); else if (type == typeof(short)) WriteShortField(TypeCaster<short>.Cast(val)); else if (type == typeof(char)) WriteCharField(TypeCaster<char>.Cast(val)); else if (type == typeof(float)) WriteFloatField(TypeCaster<float>.Cast(val)); else if (type == typeof(double)) WriteDoubleField(TypeCaster<double>.Cast(val)); else if (type == typeof(sbyte)) { var val0 = TypeCaster<sbyte>.Cast(val); WriteByteField(*(byte*)&val0); } else if (type == typeof(ushort)) { var val0 = TypeCaster<ushort>.Cast(val); WriteShortField(*(short*) &val0); } else if (type == typeof(uint)) { var val0 = TypeCaster<uint>.Cast(val); WriteIntField(*(int*)&val0); } else if (type == typeof(ulong)) { var val0 = TypeCaster<ulong>.Cast(val); WriteLongField(*(long*)&val0); } else if (type == typeof(IntPtr)) { var val0 = TypeCaster<IntPtr>.Cast(val).ToInt64(); WriteLongField(val0); } else if (type == typeof(UIntPtr)) { var val0 = TypeCaster<UIntPtr>.Cast(val).ToUInt64(); WriteLongField(*(long*)&val0); } else throw BinaryUtils.GetUnsupportedTypeException(type, val); } /// <summary> /// Try writing object as special builder type. /// </summary> /// <param name="obj">Object.</param> /// <returns>True if object was written, false otherwise.</returns> private bool WriteBuilderSpecials<T>(T obj) { if (_builder != null) { // Special case for binary object during build. BinaryObject portObj = obj as BinaryObject; if (portObj != null) { if (!WriteHandle(_stream.Position, portObj)) _builder.ProcessBinary(_stream, portObj); return true; } // Special case for binary enum during build. BinaryEnum binEnum = obj as BinaryEnum; if (binEnum != null) { WriteEnum(binEnum.EnumValue, binEnum.TypeId); return true; } // Special case for builder during build. BinaryObjectBuilder portBuilder = obj as BinaryObjectBuilder; if (portBuilder != null) { if (!WriteHandle(_stream.Position, portBuilder)) _builder.ProcessBuilder(_stream, portBuilder); return true; } } return false; } /// <summary> /// Add handle to handles map. /// </summary> /// <param name="pos">Position in stream.</param> /// <param name="obj">Object.</param> /// <returns><c>true</c> if object was written as handle.</returns> private bool WriteHandle(long pos, object obj) { if (_hnds == null) { // Cache absolute handle position. _hnds = new BinaryHandleDictionary<object, long>(obj, pos, ReferenceEqualityComparer<object>.Instance); return false; } long hndPos; if (!_hnds.TryGetValue(obj, out hndPos)) { // Cache absolute handle position. _hnds.Add(obj, pos); return false; } _stream.WriteByte(BinaryUtils.HdrHnd); // Handle is written as difference between position before header and handle position. _stream.WriteInt((int)(pos - hndPos)); return true; } /// <summary> /// Perform action with detached semantics. /// </summary> /// <param name="o">Object to write.</param> /// <param name="parentCollection"> /// Hack for collections. When the root object for the current writer is a known collection type /// (<see cref="BinaryTypeId.Array"/>, <see cref="BinaryTypeId.Collection"/>, /// <see cref="BinaryTypeId.Dictionary"/>), we want to detach every element of that collection, because /// Java side handles every element as a separate BinaryObject - they can't share handles. /// </param> internal void WriteObjectDetached<T>(T o, object parentCollection = null) { if (_detaching != parentCollection) { Write(o); } else { var oldDetaching = _detaching; _detaching = _detaching ?? o; var oldHnds = _hnds; _hnds = null; try { Write(o); } finally { _detaching = oldDetaching; if (oldHnds != null) { // Merge newly recorded handles with old ones and restore old on the stack. // Otherwise we can use current handles right away. if (_hnds != null) oldHnds.Merge(_hnds); _hnds = oldHnds; } } } } /// <summary> /// Gets or sets a function to wrap all serializer objects. /// </summary> internal Func<object, object> WrapperFunc { get; set; } /// <summary> /// Stream. /// </summary> internal IBinaryStream Stream { get { return _stream; } } /// <summary> /// Gets collected metadatas. /// </summary> /// <returns>Collected metadatas (if any).</returns> internal ICollection<BinaryType> GetBinaryTypes() { return _metas == null ? null : _metas.Values; } /// <summary> /// Write field ID. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="fieldTypeId">Field type ID.</param> private void WriteFieldId(string fieldName, byte fieldTypeId) { if (_frame.RawPos != 0) throw new BinaryObjectException("Cannot write named fields after raw data is written."); var fieldId = _frame.Struct.GetFieldId(fieldName, fieldTypeId); _schema.PushField(fieldId, _stream.Position - _frame.Pos); } /// <summary> /// Saves metadata for this session. /// </summary> /// <param name="desc">The descriptor.</param> /// <param name="fields">Fields metadata.</param> internal void SaveMetadata(IBinaryTypeDescriptor desc, IDictionary<string, BinaryField> fields) { Debug.Assert(desc != null); if (!desc.UserType && (fields == null || fields.Count == 0)) { // System types with no fields (most of them) do not need to be sent. // AffinityKey is an example of system type with metadata. return; } if (_metas == null) { _metas = new Dictionary<int, BinaryType>(1) { {desc.TypeId, new BinaryType(desc, _marsh, fields)} }; } else { BinaryType meta; if (_metas.TryGetValue(desc.TypeId, out meta)) meta.UpdateFields(fields); else _metas[desc.TypeId] = new BinaryType(desc, _marsh, fields); } } /// <summary> /// Stores current writer stack frame. /// </summary> private struct Frame { /** Current object start position. */ public int Pos; /** Current raw position. */ public int RawPos; /** Current type structure tracker. */ public BinaryStructureTracker Struct; /** Custom type data. */ public bool HasCustomTypeData; } } }
// Copyright 2017, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.Iam.V1; using Google.Cloud.PubSub.V1; 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.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.PubSub.V1.Snippets { public class GeneratedSubscriberClientSnippets { public async Task CreateSubscriptionAsync() { // Snippet: CreateSubscriptionAsync(SubscriptionName,TopicName,PushConfig,int?,CallSettings) // Additional: CreateSubscriptionAsync(SubscriptionName,TopicName,PushConfig,int?,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SubscriptionName name = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); TopicName topic = new TopicName("[PROJECT]", "[TOPIC]"); PushConfig pushConfig = new PushConfig(); int ackDeadlineSeconds = 0; // Make the request Subscription response = await subscriberClient.CreateSubscriptionAsync(name, topic, pushConfig, ackDeadlineSeconds); // End snippet } public void CreateSubscription() { // Snippet: CreateSubscription(SubscriptionName,TopicName,PushConfig,int?,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SubscriptionName name = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); TopicName topic = new TopicName("[PROJECT]", "[TOPIC]"); PushConfig pushConfig = new PushConfig(); int ackDeadlineSeconds = 0; // Make the request Subscription response = subscriberClient.CreateSubscription(name, topic, pushConfig, ackDeadlineSeconds); // End snippet } public async Task CreateSubscriptionAsync_RequestObject() { // Snippet: CreateSubscriptionAsync(Subscription,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) Subscription request = new Subscription { SubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), TopicAsTopicNameOneof = TopicNameOneof.From(new TopicName("[PROJECT]", "[TOPIC]")), }; // Make the request Subscription response = await subscriberClient.CreateSubscriptionAsync(request); // End snippet } public void CreateSubscription_RequestObject() { // Snippet: CreateSubscription(Subscription,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) Subscription request = new Subscription { SubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), TopicAsTopicNameOneof = TopicNameOneof.From(new TopicName("[PROJECT]", "[TOPIC]")), }; // Make the request Subscription response = subscriberClient.CreateSubscription(request); // End snippet } public async Task GetSubscriptionAsync() { // Snippet: GetSubscriptionAsync(SubscriptionName,CallSettings) // Additional: GetSubscriptionAsync(SubscriptionName,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request Subscription response = await subscriberClient.GetSubscriptionAsync(subscription); // End snippet } public void GetSubscription() { // Snippet: GetSubscription(SubscriptionName,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request Subscription response = subscriberClient.GetSubscription(subscription); // End snippet } public async Task GetSubscriptionAsync_RequestObject() { // Snippet: GetSubscriptionAsync(GetSubscriptionRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) GetSubscriptionRequest request = new GetSubscriptionRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request Subscription response = await subscriberClient.GetSubscriptionAsync(request); // End snippet } public void GetSubscription_RequestObject() { // Snippet: GetSubscription(GetSubscriptionRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) GetSubscriptionRequest request = new GetSubscriptionRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request Subscription response = subscriberClient.GetSubscription(request); // End snippet } public async Task UpdateSubscriptionAsync_RequestObject() { // Snippet: UpdateSubscriptionAsync(UpdateSubscriptionRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) UpdateSubscriptionRequest request = new UpdateSubscriptionRequest { Subscription = new Subscription(), UpdateMask = new FieldMask(), }; // Make the request Subscription response = await subscriberClient.UpdateSubscriptionAsync(request); // End snippet } public void UpdateSubscription_RequestObject() { // Snippet: UpdateSubscription(UpdateSubscriptionRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) UpdateSubscriptionRequest request = new UpdateSubscriptionRequest { Subscription = new Subscription(), UpdateMask = new FieldMask(), }; // Make the request Subscription response = subscriberClient.UpdateSubscription(request); // End snippet } public async Task ListSubscriptionsAsync() { // Snippet: ListSubscriptionsAsync(ProjectName,string,int?,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) ProjectName project = new ProjectName("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListSubscriptionsResponse, Subscription> response = subscriberClient.ListSubscriptionsAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Subscription item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSubscriptionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Subscription item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Subscription> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Subscription item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } public void ListSubscriptions() { // Snippet: ListSubscriptions(ProjectName,string,int?,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) ProjectName project = new ProjectName("[PROJECT]"); // Make the request PagedEnumerable<ListSubscriptionsResponse, Subscription> response = subscriberClient.ListSubscriptions(project); // Iterate over all response items, lazily performing RPCs as required foreach (Subscription item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSubscriptionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Subscription item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Subscription> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Subscription item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } public async Task ListSubscriptionsAsync_RequestObject() { // Snippet: ListSubscriptionsAsync(ListSubscriptionsRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) ListSubscriptionsRequest request = new ListSubscriptionsRequest { ProjectAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListSubscriptionsResponse, Subscription> response = subscriberClient.ListSubscriptionsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Subscription item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSubscriptionsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Subscription item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Subscription> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Subscription item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } public void ListSubscriptions_RequestObject() { // Snippet: ListSubscriptions(ListSubscriptionsRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) ListSubscriptionsRequest request = new ListSubscriptionsRequest { ProjectAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedEnumerable<ListSubscriptionsResponse, Subscription> response = subscriberClient.ListSubscriptions(request); // Iterate over all response items, lazily performing RPCs as required foreach (Subscription item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSubscriptionsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Subscription item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Subscription> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Subscription item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } public async Task DeleteSubscriptionAsync() { // Snippet: DeleteSubscriptionAsync(SubscriptionName,CallSettings) // Additional: DeleteSubscriptionAsync(SubscriptionName,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request await subscriberClient.DeleteSubscriptionAsync(subscription); // End snippet } public void DeleteSubscription() { // Snippet: DeleteSubscription(SubscriptionName,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request subscriberClient.DeleteSubscription(subscription); // End snippet } public async Task DeleteSubscriptionAsync_RequestObject() { // Snippet: DeleteSubscriptionAsync(DeleteSubscriptionRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) DeleteSubscriptionRequest request = new DeleteSubscriptionRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request await subscriberClient.DeleteSubscriptionAsync(request); // End snippet } public void DeleteSubscription_RequestObject() { // Snippet: DeleteSubscription(DeleteSubscriptionRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) DeleteSubscriptionRequest request = new DeleteSubscriptionRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request subscriberClient.DeleteSubscription(request); // End snippet } public async Task ModifyAckDeadlineAsync() { // Snippet: ModifyAckDeadlineAsync(SubscriptionName,IEnumerable<string>,int,CallSettings) // Additional: ModifyAckDeadlineAsync(SubscriptionName,IEnumerable<string>,int,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); IEnumerable<string> ackIds = new List<string>(); int ackDeadlineSeconds = 0; // Make the request await subscriberClient.ModifyAckDeadlineAsync(subscription, ackIds, ackDeadlineSeconds); // End snippet } public void ModifyAckDeadline() { // Snippet: ModifyAckDeadline(SubscriptionName,IEnumerable<string>,int,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); IEnumerable<string> ackIds = new List<string>(); int ackDeadlineSeconds = 0; // Make the request subscriberClient.ModifyAckDeadline(subscription, ackIds, ackDeadlineSeconds); // End snippet } public async Task ModifyAckDeadlineAsync_RequestObject() { // Snippet: ModifyAckDeadlineAsync(ModifyAckDeadlineRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), AckIds = { }, AckDeadlineSeconds = 0, }; // Make the request await subscriberClient.ModifyAckDeadlineAsync(request); // End snippet } public void ModifyAckDeadline_RequestObject() { // Snippet: ModifyAckDeadline(ModifyAckDeadlineRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) ModifyAckDeadlineRequest request = new ModifyAckDeadlineRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), AckIds = { }, AckDeadlineSeconds = 0, }; // Make the request subscriberClient.ModifyAckDeadline(request); // End snippet } public async Task AcknowledgeAsync() { // Snippet: AcknowledgeAsync(SubscriptionName,IEnumerable<string>,CallSettings) // Additional: AcknowledgeAsync(SubscriptionName,IEnumerable<string>,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); IEnumerable<string> ackIds = new List<string>(); // Make the request await subscriberClient.AcknowledgeAsync(subscription, ackIds); // End snippet } public void Acknowledge() { // Snippet: Acknowledge(SubscriptionName,IEnumerable<string>,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); IEnumerable<string> ackIds = new List<string>(); // Make the request subscriberClient.Acknowledge(subscription, ackIds); // End snippet } public async Task AcknowledgeAsync_RequestObject() { // Snippet: AcknowledgeAsync(AcknowledgeRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) AcknowledgeRequest request = new AcknowledgeRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), AckIds = { }, }; // Make the request await subscriberClient.AcknowledgeAsync(request); // End snippet } public void Acknowledge_RequestObject() { // Snippet: Acknowledge(AcknowledgeRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) AcknowledgeRequest request = new AcknowledgeRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), AckIds = { }, }; // Make the request subscriberClient.Acknowledge(request); // End snippet } public async Task PullAsync() { // Snippet: PullAsync(SubscriptionName,bool?,int,CallSettings) // Additional: PullAsync(SubscriptionName,bool?,int,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); bool returnImmediately = false; int maxMessages = 0; // Make the request PullResponse response = await subscriberClient.PullAsync(subscription, returnImmediately, maxMessages); // End snippet } public void Pull() { // Snippet: Pull(SubscriptionName,bool?,int,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); bool returnImmediately = false; int maxMessages = 0; // Make the request PullResponse response = subscriberClient.Pull(subscription, returnImmediately, maxMessages); // End snippet } public async Task PullAsync_RequestObject() { // Snippet: PullAsync(PullRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) PullRequest request = new PullRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), MaxMessages = 0, }; // Make the request PullResponse response = await subscriberClient.PullAsync(request); // End snippet } public void Pull_RequestObject() { // Snippet: Pull(PullRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) PullRequest request = new PullRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), MaxMessages = 0, }; // Make the request PullResponse response = subscriberClient.Pull(request); // End snippet } public async Task StreamingPull() { // Snippet: StreamingPull(CallSettings,BidirectionalStreamingSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize streaming call, retrieving the stream object SubscriberClient.StreamingPullStream duplexStream = subscriberClient.StreamingPull(); // Sending requests and retrieving responses can be arbitrarily interleaved. // Exact sequence will depend on client/server behavior. // Create task to do something with responses from server Task.Run(async () => { IAsyncEnumerator<StreamingPullResponse> responseStream = duplexStream.ResponseStream; while (await responseStream.MoveNext()) { StreamingPullResponse response = responseStream.Current; // Do something with streamed response } // The response stream has completed }); // Send requests to the server bool done = false; while (!done) { // Initialize a request StreamingPullRequest request = new StreamingPullRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), StreamAckDeadlineSeconds = 0, }; // Stream a request to the server await duplexStream.WriteAsync(request); // Set "done" to true when sending requests is complete } // Complete writing requests to the stream await duplexStream.WriteCompleteAsync(); // End snippet } public async Task ModifyPushConfigAsync() { // Snippet: ModifyPushConfigAsync(SubscriptionName,PushConfig,CallSettings) // Additional: ModifyPushConfigAsync(SubscriptionName,PushConfig,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); PushConfig pushConfig = new PushConfig(); // Make the request await subscriberClient.ModifyPushConfigAsync(subscription, pushConfig); // End snippet } public void ModifyPushConfig() { // Snippet: ModifyPushConfig(SubscriptionName,PushConfig,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); PushConfig pushConfig = new PushConfig(); // Make the request subscriberClient.ModifyPushConfig(subscription, pushConfig); // End snippet } public async Task ModifyPushConfigAsync_RequestObject() { // Snippet: ModifyPushConfigAsync(ModifyPushConfigRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) ModifyPushConfigRequest request = new ModifyPushConfigRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), PushConfig = new PushConfig(), }; // Make the request await subscriberClient.ModifyPushConfigAsync(request); // End snippet } public void ModifyPushConfig_RequestObject() { // Snippet: ModifyPushConfig(ModifyPushConfigRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) ModifyPushConfigRequest request = new ModifyPushConfigRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), PushConfig = new PushConfig(), }; // Make the request subscriberClient.ModifyPushConfig(request); // End snippet } public async Task ListSnapshotsAsync() { // Snippet: ListSnapshotsAsync(ProjectName,string,int?,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) ProjectName project = new ProjectName("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListSnapshotsResponse, Snapshot> response = subscriberClient.ListSnapshotsAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Snapshot item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSnapshotsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Snapshot item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Snapshot> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Snapshot item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } public void ListSnapshots() { // Snippet: ListSnapshots(ProjectName,string,int?,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) ProjectName project = new ProjectName("[PROJECT]"); // Make the request PagedEnumerable<ListSnapshotsResponse, Snapshot> response = subscriberClient.ListSnapshots(project); // Iterate over all response items, lazily performing RPCs as required foreach (Snapshot item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSnapshotsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Snapshot item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Snapshot> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Snapshot item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } public async Task ListSnapshotsAsync_RequestObject() { // Snippet: ListSnapshotsAsync(ListSnapshotsRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) ListSnapshotsRequest request = new ListSnapshotsRequest { ProjectAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListSnapshotsResponse, Snapshot> response = subscriberClient.ListSnapshotsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Snapshot item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSnapshotsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Snapshot item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Snapshot> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Snapshot item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } public void ListSnapshots_RequestObject() { // Snippet: ListSnapshots(ListSnapshotsRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) ListSnapshotsRequest request = new ListSnapshotsRequest { ProjectAsProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedEnumerable<ListSnapshotsResponse, Snapshot> response = subscriberClient.ListSnapshots(request); // Iterate over all response items, lazily performing RPCs as required foreach (Snapshot item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSnapshotsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Snapshot item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Snapshot> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Snapshot item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } public async Task CreateSnapshotAsync() { // Snippet: CreateSnapshotAsync(SnapshotName,SubscriptionName,CallSettings) // Additional: CreateSnapshotAsync(SnapshotName,SubscriptionName,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SnapshotName name = new SnapshotName("[PROJECT]", "[SNAPSHOT]"); SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request Snapshot response = await subscriberClient.CreateSnapshotAsync(name, subscription); // End snippet } public void CreateSnapshot() { // Snippet: CreateSnapshot(SnapshotName,SubscriptionName,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SnapshotName name = new SnapshotName("[PROJECT]", "[SNAPSHOT]"); SubscriptionName subscription = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); // Make the request Snapshot response = subscriberClient.CreateSnapshot(name, subscription); // End snippet } public async Task CreateSnapshotAsync_RequestObject() { // Snippet: CreateSnapshotAsync(CreateSnapshotRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) CreateSnapshotRequest request = new CreateSnapshotRequest { SnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"), SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request Snapshot response = await subscriberClient.CreateSnapshotAsync(request); // End snippet } public void CreateSnapshot_RequestObject() { // Snippet: CreateSnapshot(CreateSnapshotRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) CreateSnapshotRequest request = new CreateSnapshotRequest { SnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"), SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request Snapshot response = subscriberClient.CreateSnapshot(request); // End snippet } public async Task DeleteSnapshotAsync() { // Snippet: DeleteSnapshotAsync(SnapshotName,CallSettings) // Additional: DeleteSnapshotAsync(SnapshotName,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SnapshotName snapshot = new SnapshotName("[PROJECT]", "[SNAPSHOT]"); // Make the request await subscriberClient.DeleteSnapshotAsync(snapshot); // End snippet } public void DeleteSnapshot() { // Snippet: DeleteSnapshot(SnapshotName,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SnapshotName snapshot = new SnapshotName("[PROJECT]", "[SNAPSHOT]"); // Make the request subscriberClient.DeleteSnapshot(snapshot); // End snippet } public async Task DeleteSnapshotAsync_RequestObject() { // Snippet: DeleteSnapshotAsync(DeleteSnapshotRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) DeleteSnapshotRequest request = new DeleteSnapshotRequest { SnapshotAsSnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"), }; // Make the request await subscriberClient.DeleteSnapshotAsync(request); // End snippet } public void DeleteSnapshot_RequestObject() { // Snippet: DeleteSnapshot(DeleteSnapshotRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) DeleteSnapshotRequest request = new DeleteSnapshotRequest { SnapshotAsSnapshotName = new SnapshotName("[PROJECT]", "[SNAPSHOT]"), }; // Make the request subscriberClient.DeleteSnapshot(request); // End snippet } public async Task SeekAsync_RequestObject() { // Snippet: SeekAsync(SeekRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SeekRequest request = new SeekRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request SeekResponse response = await subscriberClient.SeekAsync(request); // End snippet } public void Seek_RequestObject() { // Snippet: Seek(SeekRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SeekRequest request = new SeekRequest { SubscriptionAsSubscriptionName = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"), }; // Make the request SeekResponse response = subscriberClient.Seek(request); // End snippet } public async Task SetIamPolicyAsync() { // Snippet: SetIamPolicyAsync(string,Policy,CallSettings) // Additional: SetIamPolicyAsync(string,Policy,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); Policy policy = new Policy(); // Make the request Policy response = await subscriberClient.SetIamPolicyAsync(formattedResource, policy); // End snippet } public void SetIamPolicy() { // Snippet: SetIamPolicy(string,Policy,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); Policy policy = new Policy(); // Make the request Policy response = subscriberClient.SetIamPolicy(formattedResource, policy); // End snippet } public async Task SetIamPolicyAsync_RequestObject() { // Snippet: SetIamPolicyAsync(SetIamPolicyRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), Policy = new Policy(), }; // Make the request Policy response = await subscriberClient.SetIamPolicyAsync(request); // End snippet } public void SetIamPolicy_RequestObject() { // Snippet: SetIamPolicy(SetIamPolicyRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), Policy = new Policy(), }; // Make the request Policy response = subscriberClient.SetIamPolicy(request); // End snippet } public async Task GetIamPolicyAsync() { // Snippet: GetIamPolicyAsync(string,CallSettings) // Additional: GetIamPolicyAsync(string,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); // Make the request Policy response = await subscriberClient.GetIamPolicyAsync(formattedResource); // End snippet } public void GetIamPolicy() { // Snippet: GetIamPolicy(string,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); // Make the request Policy response = subscriberClient.GetIamPolicy(formattedResource); // End snippet } public async Task GetIamPolicyAsync_RequestObject() { // Snippet: GetIamPolicyAsync(GetIamPolicyRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), }; // Make the request Policy response = await subscriberClient.GetIamPolicyAsync(request); // End snippet } public void GetIamPolicy_RequestObject() { // Snippet: GetIamPolicy(GetIamPolicyRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), }; // Make the request Policy response = subscriberClient.GetIamPolicy(request); // End snippet } public async Task TestIamPermissionsAsync() { // Snippet: TestIamPermissionsAsync(string,IEnumerable<string>,CallSettings) // Additional: TestIamPermissionsAsync(string,IEnumerable<string>,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); IEnumerable<string> permissions = new List<string>(); // Make the request TestIamPermissionsResponse response = await subscriberClient.TestIamPermissionsAsync(formattedResource, permissions); // End snippet } public void TestIamPermissions() { // Snippet: TestIamPermissions(string,IEnumerable<string>,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) string formattedResource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(); IEnumerable<string> permissions = new List<string>(); // Make the request TestIamPermissionsResponse response = subscriberClient.TestIamPermissions(formattedResource, permissions); // End snippet } public async Task TestIamPermissionsAsync_RequestObject() { // Snippet: TestIamPermissionsAsync(TestIamPermissionsRequest,CallSettings) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), Permissions = { }, }; // Make the request TestIamPermissionsResponse response = await subscriberClient.TestIamPermissionsAsync(request); // End snippet } public void TestIamPermissions_RequestObject() { // Snippet: TestIamPermissions(TestIamPermissionsRequest,CallSettings) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { Resource = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]").ToString(), Permissions = { }, }; // Make the request TestIamPermissionsResponse response = subscriberClient.TestIamPermissions(request); // End snippet } } }
using BulletSharp.Math; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace BspDemo { public struct BspBrush { public int FirstSide { get; set; } public int NumSides { get; set; } public int ShaderNum { get; set; } } public struct BspBrushSide { public int PlaneNum { get; set; } public int ShaderNum { get; set; } } [DebuggerDisplay("ClassName: {ClassName}")] public class BspEntity { public string ClassName { get; set; } public Vector3 Origin { get; set; } public Dictionary<string, string> KeyValues { get; set; } public BspEntity() { KeyValues = new Dictionary<string, string>(); } } public struct BspLeaf { public int Cluster; public int Area; public Vector3 Min; public Vector3 Max; public int FirstLeafFace; public int NumLeafFaces; public int FirstLeafBrush; public int NumLeafBrushes; } [DebuggerDisplay("Offset: {Offset}, Length: {Length}")] public struct BspLump { public int Offset; public int Length; } public struct BspPlane { public Vector3 Normal; public float Distance; } [Flags] public enum ContentFlags { Solid = 1, AreaPortal = 0x8000, MonsterClip = 0x20000, Detail = 0x8000000 } public class BspShader { public string Shader; public int SurfaceFlags; public ContentFlags ContentFlags; } public enum IBspLumpType { Entities = 0, Shaders, Planes, Nodes, Leaves, LeafFaces, LeafBrushes, Models, Brushes, BrushSides, Vertices, MeshIndices, Faces, Lightmaps, LightVols, VisData } public enum VBspLumpType { Entities = 0, Planes, Texdata, Vertexes, Visibility, Nodes, Texinfo, Faces, Lighting, Occlusion, Leafs, Unused1, Edges, Surfedges, Models, Worldlights, LeafFaces, LeafBrushes, Brushes, BrushSides, Area, AreaPortals, Portals, Clusters, PortalVerts, ClusterPortals, Dispinfo, OriginalFaces, Unused2, PhysCollide, VertNormals, VertNormalIndices, DispLightmapAlphas, DispVerts, DispLightmapSamplePos, GameLump, LeafWaterData, Primitives, PrimVerts, PrimIndices, Pakfile, ClipPortalVerts, Cubemaps, TexdataStringData, TexdataStringTable, Overlays, LeafMinDistToWater, FaceMacroTextureInfo, DispTris, PhysCollideSurface, Unused3, Unused4, Unused5, LightingHDR, WorldlightsHDR, LeaflightHDR1, LeaflightHDR2 } public class BspLoader { public BspBrush[] Brushes { get; set; } public BspBrushSide[] BrushSides { get; set; } public List<BspEntity> Entities { get; set; } public BspLeaf[] Leaves { get; set; } public int[] LeafBrushes { get; set; } public BspPlane[] Planes { get; set; } public List<BspShader> Shaders { get; set; } public bool IsVbsp { get; private set; } public bool LoadBspFile(string filename) { return LoadBspFile(new FileStream(filename, FileMode.Open, FileAccess.Read)); } public bool LoadBspFile(Stream buffer) { BinaryReader reader = new BinaryReader(buffer); // read header string id = Encoding.ASCII.GetString(reader.ReadBytes(4), 0, 4); int version = reader.ReadInt32(); if (id != "IBSP" && id != "VBSP") return false; int nHeaderLumps; if (id == "IBSP") { if (version != 0x2E) { return false; } nHeaderLumps = 17; } else// if (id == "VBSP") { if (version != 0x14) { return false; } nHeaderLumps = 64; IsVbsp = true; } BspLump[] lumps = new BspLump[nHeaderLumps]; for (int i = 0; i < lumps.Length; i++) { lumps[i].Offset = reader.ReadInt32(); lumps[i].Length = reader.ReadInt32(); if (IsVbsp) { reader.ReadInt32(); // lump format version reader.ReadInt32(); // lump ident code } } // read brushes int lumpHeaderOffset = IsVbsp ? (int)VBspLumpType.Brushes : (int)IBspLumpType.Brushes; buffer.Position = lumps[lumpHeaderOffset].Offset; int length = lumps[lumpHeaderOffset].Length / Marshal.SizeOf(typeof(BspBrush)); Brushes = new BspBrush[length]; for (int i = 0; i < length; i++) { Brushes[i].FirstSide = reader.ReadInt32(); Brushes[i].NumSides = reader.ReadInt32(); Brushes[i].ShaderNum = reader.ReadInt32(); } // read brush sides lumpHeaderOffset = IsVbsp ? (int)VBspLumpType.BrushSides : (int)IBspLumpType.BrushSides; buffer.Position = lumps[lumpHeaderOffset].Offset; length = lumps[lumpHeaderOffset].Length / Marshal.SizeOf(typeof(BspBrushSide)); BrushSides = new BspBrushSide[length]; for (int i = 0; i < length; i++) { if (IsVbsp) { BrushSides[i].PlaneNum = reader.ReadUInt16(); reader.ReadInt16(); // texinfo BrushSides[i].ShaderNum = reader.ReadInt16(); reader.ReadInt16(); // bevel } else { BrushSides[i].PlaneNum = reader.ReadInt32(); BrushSides[i].ShaderNum = reader.ReadInt32(); } } // read entities Entities = new List<BspEntity>(); buffer.Position = lumps[(int)IBspLumpType.Entities].Offset; length = lumps[(int)IBspLumpType.Entities].Length; byte[] entityBytes = new byte[length]; reader.Read(entityBytes, 0, length); string entityString = Encoding.ASCII.GetString(entityBytes); string[] entityStrings = entityString.Split('\n'); BspEntity bspEntity = null; foreach (string entity in entityStrings) { switch (entity) { case "\0": continue; case "{": bspEntity = new BspEntity(); break; case "}": Entities.Add(bspEntity); break; default: string[] keyValue = entity.Trim('\"').Split(new[] { "\" \"" }, 2, 0); switch (keyValue[0]) { case "classname": bspEntity.ClassName = keyValue[1]; break; case "origin": string[] originStrings = keyValue[1].Split(' '); bspEntity.Origin = new Vector3( float.Parse(originStrings[0], CultureInfo.InvariantCulture), float.Parse(originStrings[1], CultureInfo.InvariantCulture), float.Parse(originStrings[2], CultureInfo.InvariantCulture)); break; default: if (!bspEntity.KeyValues.ContainsKey(keyValue[0])) { if (keyValue.Length == 1) { bspEntity.KeyValues.Add(keyValue[0], ""); } else { bspEntity.KeyValues.Add(keyValue[0], keyValue[1]); } } break; } break; } } // read leaves lumpHeaderOffset = IsVbsp ? (int)VBspLumpType.Leafs : (int)IBspLumpType.Leaves; buffer.Position = lumps[lumpHeaderOffset].Offset; length = lumps[lumpHeaderOffset].Length; length /= IsVbsp ? 32 : Marshal.SizeOf(typeof(BspLeaf)); Leaves = new BspLeaf[length]; for (int i = 0; i < length; i++) { if (IsVbsp) { reader.ReadInt32(); // contents Leaves[i].Cluster = reader.ReadInt16(); Leaves[i].Area = reader.ReadInt16(); //Swap Y and Z; invert Z Leaves[i].Min.X = reader.ReadInt16(); Leaves[i].Min.Z = -reader.ReadInt16(); Leaves[i].Min.Y = reader.ReadInt16(); //Swap Y and Z; invert Z Leaves[i].Max.X = reader.ReadInt16(); Leaves[i].Max.Z = -reader.ReadInt16(); Leaves[i].Max.Y = reader.ReadInt16(); Leaves[i].FirstLeafFace = reader.ReadUInt16(); Leaves[i].NumLeafFaces = reader.ReadUInt16(); Leaves[i].FirstLeafBrush = reader.ReadUInt16(); Leaves[i].NumLeafBrushes = reader.ReadUInt16(); reader.ReadInt16(); // leafWaterDataID //reader.ReadInt16(); // ambientLighting //reader.ReadSByte(); // ambientLighting reader.ReadInt16(); // padding } else { Leaves[i].Cluster = reader.ReadInt32(); Leaves[i].Area = reader.ReadInt32(); //Swap Y and Z; invert Z Leaves[i].Min.X = reader.ReadInt32(); Leaves[i].Min.Z = -reader.ReadInt32(); Leaves[i].Min.Y = reader.ReadInt32(); //Swap Y and Z; invert Z Leaves[i].Max.X = reader.ReadInt32(); Leaves[i].Max.Z = -reader.ReadInt32(); Leaves[i].Max.Y = reader.ReadInt32(); Leaves[i].FirstLeafFace = reader.ReadInt32(); Leaves[i].NumLeafFaces = reader.ReadInt32(); Leaves[i].FirstLeafBrush = reader.ReadInt32(); Leaves[i].NumLeafBrushes = reader.ReadInt32(); } } // read leaf brushes lumpHeaderOffset = IsVbsp ? (int)VBspLumpType.LeafBrushes : (int)IBspLumpType.LeafBrushes; buffer.Position = lumps[lumpHeaderOffset].Offset; length = lumps[lumpHeaderOffset].Length; length /= IsVbsp ? sizeof(short) : sizeof(int); LeafBrushes = new int[length]; for (int i = 0; i < length; i++) { if (IsVbsp) { LeafBrushes[i] = reader.ReadInt16(); } else { LeafBrushes[i] = reader.ReadInt32(); } } // read planes lumpHeaderOffset = IsVbsp ? (int)VBspLumpType.Planes : (int)IBspLumpType.Planes; buffer.Position = lumps[lumpHeaderOffset].Offset; length = lumps[lumpHeaderOffset].Length; length /= IsVbsp ? (Marshal.SizeOf(typeof(BspPlane)) + sizeof(int)) : Marshal.SizeOf(typeof(BspPlane)); Planes = new BspPlane[length]; for (int i = 0; i < length; i++) { Planes[i].Normal.X = reader.ReadSingle(); Planes[i].Normal.Y = reader.ReadSingle(); Planes[i].Normal.Z = reader.ReadSingle(); Planes[i].Distance = reader.ReadSingle(); if (IsVbsp) { reader.ReadInt32(); // type } } if (!IsVbsp) { // read shaders Shaders = new List<BspShader>(); buffer.Position = lumps[(int)IBspLumpType.Shaders].Offset; length = lumps[(int)IBspLumpType.Shaders].Length / (64 + 2 * sizeof(int)); byte[] shaderBytes = new byte[64]; for (int i = 0; i < length; i++) { BspShader shader = new BspShader(); reader.Read(shaderBytes, 0, 64); shader.Shader = Encoding.ASCII.GetString(shaderBytes, 0, Array.IndexOf(shaderBytes, (byte)0)); shader.SurfaceFlags = reader.ReadInt32(); shader.ContentFlags = (ContentFlags)reader.ReadInt32(); Shaders.Add(shader); } } return true; } public bool FindVectorByName(string name, ref Vector3 outVector) { foreach (BspEntity entity in Entities) { if (entity.ClassName == name) { outVector = entity.Origin; return true; } } return false; } } }
#region Namespaces using Epi.Windows.Enter; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; #endregion namespace Epi.Windows.Enter.Dialogs { public partial class AutoSearchResults : Epi.Windows.Dialogs.DialogBase { private int currentRow = -1; private DataTable dataTable = null; private new EnterMainForm mainForm; #region Constructors /// <summary> /// The default constructor for the Auto Search Results dialog /// </summary> public AutoSearchResults() { InitializeComponent(); } /// <summary> /// Constructor for AutoSearch Results dialog /// </summary> /// <param name="view">The current view</param> /// <param name="mainForm">Enter module's main form</param> /// <param name="data">Data table containing auto search results</param> public AutoSearchResults(View view, EnterMainForm mainForm, DataTable data, bool showContinueNewMessage = false) : base(mainForm) { #region Input Validation if (view == null) { { throw new ArgumentNullException("view"); } } #endregion Input Validation InitializeComponent(); //this.view = view; this.mainForm = mainForm; // set DataGridView properties this.dataGrid1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; this.dataGrid1.AllowUserToAddRows = false; this.dataGrid1.AllowUserToDeleteRows = false; this.dataGrid1.AllowUserToOrderColumns = false; this.dataGrid1.AllowUserToResizeRows = false; this.dataGrid1.AllowUserToResizeColumns = true; this.dataGrid1.AllowDrop = false; this.dataGrid1.MultiSelect = false; // add event handlers this.dataGrid1.KeyDown += new KeyEventHandler(OnKeyDown); this.btnOK.KeyDown += new KeyEventHandler(OnKeyDown); this.btnCancel.KeyDown += new KeyEventHandler(OnKeyDown); this.KeyDown += new KeyEventHandler(OnKeyDown); base.KeyDown += new KeyEventHandler(OnKeyDown); this.dataGrid1.SelectionChanged += new EventHandler(dataGrid1_SelectionChanged); this.lblOKInstructions.Visible = !showContinueNewMessage; this.lblCancelInstructions.Visible = !showContinueNewMessage; this.lblContinueNewMessage.Visible = showContinueNewMessage; this.btnCancel.Visible = !showContinueNewMessage; if (showContinueNewMessage) { btnOK.Location = new Point(230, 270); } this.lblContinueNew2.Visible = showContinueNewMessage; DisplayResults(data); } #endregion #region Private Methods /// <summary> /// Display auto search results /// </summary> public void DisplayResults(DataTable data) { dataTable = new DataTable(); dataTable = data; dataGrid1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells; float TotalFillWeight = 0.0f; dataGrid1.DataSource = dataTable; for (int i = 0; i < dataTable.Columns.Count && TotalFillWeight< 65436; i++) { TotalFillWeight += 100; //hide the "Unique Key" and "RecStatus" columns if (dataGrid1.Columns[i].Name.Equals("UniqueKey", StringComparison.OrdinalIgnoreCase) || dataGrid1.Columns[i].Name.Equals("RecStatus", StringComparison.OrdinalIgnoreCase)) { dataGrid1.Columns[i].Visible = false; } } if (this.dataTable.Rows.Count > 0) { GetCurrentRecord(); } } #endregion #region Private Event Handlers /// <summary> /// Handles the Click event of the Cancel button /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void btnCancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } /// <summary> /// Handles the Click event of the OK button /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void btnOK_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; } private void GetCurrentRecord() { if (dataGrid1.Rows.Count > 0) { if (dataGrid1.CurrentRow == null) { dataGrid1.CurrentCell = dataGrid1.Rows[0].Cells[0]; } currentRow = dataGrid1.CurrentRow.Index; string record = dataGrid1.CurrentRow.Cells["UniqueKey"].Value.ToString(); mainForm.RecordId = record; } else { } } /// <summary> /// Handles the Double Click event of the datagrid /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void dataGrid1_DoubleClick(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; } /// <summary> /// Handles the SelectionChanged event for the DataGridView control /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">EventArgs value</param> private void dataGrid1_SelectionChanged(object sender, EventArgs e) { if (dataGrid1.SelectedRows.Count > 0) { GetCurrentRecord(); btnOK.Enabled = true; } else { btnOK.Enabled = false; } } /// <summary> /// Handles the KeyDown event for all controls to capture Esc and Enter keys /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">KeyEventArgs value</param> private void OnKeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Escape: this.DialogResult = DialogResult.Cancel; break; case Keys.Enter: e.SuppressKeyPress = true; this.DialogResult = DialogResult.OK; break; } } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Collections.Generic; using NPOI; using System.IO; using NPOI.HSSF.Record.Crypto; using NPOI.Util; using NPOI.HSSF.Record.Chart; using NPOI.POIFS.Crypt; /** * A stream based way to get at complete records, with * as low a memory footprint as possible. * This handles Reading from a RecordInputStream, turning * the data into full records, processing continue records * etc. * Most users should use {@link HSSFEventFactory} / * {@link HSSFListener} and have new records pushed to * them, but this does allow for a "pull" style of coding. */ public class RecordFactoryInputStream { /** * Keeps track of the sizes of the Initial records up to and including {@link FilePassRecord} * Needed for protected files because each byte is encrypted with respect to its absolute * position from the start of the stream. */ private class StreamEncryptionInfo { private int _InitialRecordsSize; private FilePassRecord _filePassRec; private Record _lastRecord; private bool _hasBOFRecord; public StreamEncryptionInfo(RecordInputStream rs, List<Record> outputRecs) { Record rec; rs.NextRecord(); int recSize = 4 + rs.Remaining; rec = RecordFactory.CreateSingleRecord(rs); outputRecs.Add(rec); FilePassRecord fpr = null; if (rec is BOFRecord) { _hasBOFRecord = true; // Fetch the next record, and see if it indicates whether // the document is encrypted or not if (rs.HasNextRecord) { rs.NextRecord(); rec = RecordFactory.CreateSingleRecord(rs); recSize += rec.RecordSize; outputRecs.Add(rec); // Encrypted is normally BOF then FILEPASS // May sometimes be BOF, WRITEPROTECT, FILEPASS if (rec is WriteProtectRecord && rs.HasNextRecord) { rs.NextRecord(); rec = RecordFactory.CreateSingleRecord(rs); recSize += rec.RecordSize; outputRecs.Add(rec); } // If it's a FILEPASS, track it specifically but // don't include it in the main stream if (rec is FilePassRecord) { fpr = (FilePassRecord)rec; outputRecs.RemoveAt(outputRecs.Count - 1); // TODO - add fpr not Added to outPutRecs rec = outputRecs[0]; } else { // workbook not encrypted (typical case) if (rec is EOFRecord) { // A workbook stream is never empty, so crash instead // of trying to keep track of nesting level throw new InvalidOperationException("Nothing between BOF and EOF"); } } } } else { // Invalid in a normal workbook stream. // However, some test cases work on sub-sections of // the workbook stream that do not begin with BOF _hasBOFRecord = false; } _InitialRecordsSize = recSize; _filePassRec = fpr; _lastRecord = rec; } public RecordInputStream CreateDecryptingStream(Stream original) { FilePassRecord fpr = _filePassRec; String userPassword = Biff8EncryptionKey.CurrentUserPassword; if (userPassword == null) { userPassword = Decryptor.DEFAULT_PASSWORD; } //return new RecordInputStream(original, key, _InitialRecordsSize); throw new NotImplementedException("Implement it based on poi 4.2 in the future"); } public bool HasEncryption { get { return _filePassRec != null; } } /** * @return last record scanned while looking for encryption info. * This will typically be the first or second record Read. Possibly <code>null</code> * if stream was empty */ public Record LastRecord { get { return _lastRecord; } } /** * <c>false</c> in some test cases */ public bool HasBOFRecord { get { return _hasBOFRecord; } } } private RecordInputStream _recStream; private bool _shouldIncludeContinueRecords; /** * Temporarily stores a group of {@link Record}s, for future return by {@link #nextRecord()}. * This is used at the start of the workbook stream, and also when the most recently read * underlying record is a {@link MulRKRecord} */ private Record[] _unreadRecordBuffer; /** * used to help iterating over the unread records */ private int _unreadRecordIndex = -1; /** * The most recent record that we gave to the user */ private Record _lastRecord = null; /** * The most recent DrawingRecord seen */ private DrawingRecord _lastDrawingRecord = new DrawingRecord(); private int _bofDepth; private bool _lastRecordWasEOFLevelZero; /** * @param shouldIncludeContinueRecords caller can pass <c>false</c> if loose * {@link ContinueRecord}s should be skipped (this is sometimes useful in event based * processing). */ public RecordFactoryInputStream(Stream in1, bool shouldIncludeContinueRecords) { RecordInputStream rs = new RecordInputStream(in1); List<Record> records = new List<Record>(); StreamEncryptionInfo sei = new StreamEncryptionInfo(rs, records); if (sei.HasEncryption) { rs = sei.CreateDecryptingStream(in1); } else { // typical case - non-encrypted stream } if (records.Count != 0) { _unreadRecordBuffer = new Record[records.Count]; _unreadRecordBuffer = records.ToArray(); _unreadRecordIndex = 0; } _recStream = rs; _shouldIncludeContinueRecords = shouldIncludeContinueRecords; _lastRecord = sei.LastRecord; /* * How to recognise end of stream? * In the best case, the underlying input stream (in) ends just after the last EOF record * Usually however, the stream is pAdded with an arbitrary byte count. Excel and most apps * reliably use zeros for pAdding and if this were always the case, this code could just * skip all the (zero sized) records with sid==0. However, bug 46987 Shows a file with * non-zero pAdding that is read OK by Excel (Excel also fixes the pAdding). * * So to properly detect the workbook end of stream, this code has to identify the last * EOF record. This is not so easy because the worbook bof+eof pair do not bracket the * whole stream. The worksheets follow the workbook, but it is not easy to tell how many * sheet sub-streams should be present. Hence we are looking for an EOF record that is not * immediately followed by a BOF record. One extra complication is that bof+eof sub- * streams can be nested within worksheet streams and it's not clear in these cases what * record might follow any EOF record. So we also need to keep track of the bof/eof * nesting level. */ _bofDepth = sei.HasBOFRecord ? 1 : 0; _lastRecordWasEOFLevelZero = false; } /** * Returns the next (complete) record from the * stream, or null if there are no more. */ public Record NextRecord() { Record r; r = GetNextUnreadRecord(); if (r != null) { // found an unread record return r; } while (true) { if (!_recStream.HasNextRecord) { // recStream is exhausted; return null; } // step underlying RecordInputStream to the next record _recStream.NextRecord(); if (_lastRecordWasEOFLevelZero) { // Potential place for ending the workbook stream // Check that the next record is not BOFRecord(0x0809) // Normally the input stream Contains only zero pAdding after the last EOFRecord, // but bug 46987 and 48068 suggests that the padding may be garbage. // This code relies on the pAdding bytes not starting with BOFRecord.sid if (_recStream.Sid != BOFRecord.sid) { return null; } // else - another sheet substream starting here } r = ReadNextRecord(); if (r == null) { // some record types may get skipped (e.g. DBCellRecord and ContinueRecord) continue; } return r; } } /** * @return the next {@link Record} from the multiple record group as expanded from * a recently read {@link MulRKRecord}. <code>null</code> if not present. */ private Record GetNextUnreadRecord() { if (_unreadRecordBuffer != null) { int ix = _unreadRecordIndex; if (ix < _unreadRecordBuffer.Length) { Record result = _unreadRecordBuffer[ix]; _unreadRecordIndex = ix + 1; return result; } _unreadRecordIndex = -1; _unreadRecordBuffer = null; } return null; } /** * @return the next available record, or <code>null</code> if * this pass didn't return a record that's * suitable for returning (eg was a continue record). */ private Record ReadNextRecord() { Record record = RecordFactory.CreateSingleRecord(_recStream); _lastRecordWasEOFLevelZero = false; if (record is BOFRecord) { _bofDepth++; return record; } if (record is EOFRecord) { _bofDepth--; if (_bofDepth < 1) { _lastRecordWasEOFLevelZero = true; } return record; } if (record is DBCellRecord) { // Not needed by POI. Regenerated from scratch by POI when spreadsheet is written return null; } if (record is RKRecord) { return RecordFactory.ConvertToNumberRecord((RKRecord)record); } if (record is MulRKRecord) { Record[] records = RecordFactory.ConvertRKRecords((MulRKRecord)record); _unreadRecordBuffer = records; _unreadRecordIndex = 1; return records[0]; } if (record.Sid == DrawingGroupRecord.sid && _lastRecord is DrawingGroupRecord) { DrawingGroupRecord lastDGRecord = (DrawingGroupRecord)_lastRecord; lastDGRecord.Join((AbstractEscherHolderRecord)record); return null; } if (record.Sid == ContinueRecord.sid) { ContinueRecord contRec = (ContinueRecord)record; if (_lastRecord is ObjRecord || _lastRecord is TextObjectRecord) { // Drawing records have a very strange continue behaviour. //There can actually be OBJ records mixed between the continues. _lastDrawingRecord.ProcessContinueRecord(contRec.Data); //we must remember the position of the continue record. //in the serialization procedure the original structure of records must be preserved if (_shouldIncludeContinueRecords) { return record; } return null; } if (_lastRecord is DrawingGroupRecord) { ((DrawingGroupRecord)_lastRecord).ProcessContinueRecord(contRec.Data); return null; } if (_lastRecord is DrawingRecord) { //((DrawingRecord)_lastRecord).ProcessContinueRecord(contRec.Data); return contRec; } if (_lastRecord is CrtMlFrtRecord) { return record; } if (_lastRecord is UnknownRecord) { //Gracefully handle records that we don't know about, //that happen to be continued return record; } if (_lastRecord is EOFRecord) { // This is really odd, but excel still sometimes // outPuts a file like this all the same return record; } //if (_lastRecord is StringRecord) //{ // ((StringRecord)_lastRecord).ProcessContinueRecord(contRec.Data); // return null; //} throw new RecordFormatException("Unhandled Continue Record"); } _lastRecord = record; if (record is DrawingRecord) { _lastDrawingRecord = (DrawingRecord)record; } return record; } } }
// 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.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.IO { public partial class FileStream : Stream { internal const int DefaultBufferSize = 4096; private const FileShare DefaultShare = FileShare.Read; private const bool DefaultUseAsync = false; private const bool DefaultIsAsync = false; private FileStreamBase _innerStream; internal FileStream(FileStreamBase innerStream) { if (innerStream == null) { throw new ArgumentNullException(nameof(innerStream)); } this._innerStream = innerStream; } public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access) : this(handle, access, DefaultBufferSize) { } public FileStream(string path, System.IO.FileMode mode) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), DefaultShare, DefaultBufferSize, DefaultUseAsync) { } public FileStream(string path, System.IO.FileMode mode, FileAccess access) : this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultUseAsync) { } public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, DefaultBufferSize, DefaultUseAsync) { } public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, DefaultUseAsync) { } public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) : this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None) { } public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { Init(path, mode, access, share, bufferSize, options); } private void Init(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; String badArg = null; if (mode < FileMode.CreateNew || mode > FileMode.Append) badArg = "mode"; else if (access < FileAccess.Read || access > FileAccess.ReadWrite) badArg = "access"; else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete)) badArg = "share"; if (badArg != null) throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum); // NOTE: any change to FileOptions enum needs to be matched here in the error validation if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0) throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); // Write access validation if ((access & FileAccess.Write) == 0) { if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append) { // No write access, mode and access disagree but flag access since mode comes first throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access)); } } string fullPath = Path.GetFullPath(path); ValidatePath(fullPath, "path"); if ((access & FileAccess.Read) != 0 && mode == FileMode.Append) throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access)); this._innerStream = FileSystem.Current.Open(fullPath, mode, access, share, bufferSize, options, this); } static partial void ValidatePath(string fullPath, string paramName); // InternalOpen, InternalCreate, and InternalAppend: // Factory methods for FileStream used by File, FileInfo, and ReadLinesIterator // Specifies default access and sharing options for FileStreams created by those classes internal static FileStream InternalOpen(String path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultUseAsync) { return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync); } internal static FileStream InternalCreate(String path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultUseAsync) { return new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize, useAsync); } internal static FileStream InternalAppend(String path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultUseAsync) { return new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read, bufferSize, useAsync); } #region FileStream members public virtual bool IsAsync { get { return this._innerStream.IsAsync; } } public string Name { get { return this._innerStream.Name; } } public virtual Microsoft.Win32.SafeHandles.SafeFileHandle SafeFileHandle { get { return this._innerStream.SafeFileHandle; } } public virtual void Flush(bool flushToDisk) { this._innerStream.Flush(flushToDisk); } #endregion #region Stream members #region Properties public override bool CanRead { get { return _innerStream.CanRead; } } public override bool CanSeek { get { return _innerStream.CanSeek; } } public override bool CanWrite { get { return _innerStream.CanWrite; } } public override long Length { get { return _innerStream.Length; } } public override long Position { get { return _innerStream.Position; } set { _innerStream.Position = value; } } public override int ReadTimeout { get { return _innerStream.ReadTimeout; } set { _innerStream.ReadTimeout = value; } } public override bool CanTimeout { get { return _innerStream.CanTimeout; } } public override int WriteTimeout { get { return _innerStream.WriteTimeout; } set { _innerStream.WriteTimeout = value; } } #endregion Properties #region Methods public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { return _innerStream.CopyToAsync(destination, bufferSize, cancellationToken); } protected override void Dispose(bool disposing) { if (_innerStream != null) { // called even during finalization _innerStream.DisposeInternal(disposing); } base.Dispose(disposing); } public override void Flush() { _innerStream.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (this.GetType() != typeof(FileStream)) return base.FlushAsync(cancellationToken); return _innerStream.FlushAsync(cancellationToken); } public override int Read(byte[] buffer, int offset, int count) { return _innerStream.Read(buffer, offset, count); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() or ReadAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/ReadAsync) when we are not sure. if (this.GetType() != typeof(FileStream)) return base.ReadAsync(buffer, offset, count, cancellationToken); return _innerStream.ReadAsync(buffer, offset, count, cancellationToken); } public override int ReadByte() { return _innerStream.ReadByte(); } public override long Seek(long offset, SeekOrigin origin) { return _innerStream.Seek(offset, origin); } public override void SetLength(long value) { _innerStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { _innerStream.Write(buffer, offset, count); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() or WriteAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write/WriteAsync) when we are not sure. if (this.GetType() != typeof(FileStream)) return base.WriteAsync(buffer, offset, count, cancellationToken); return _innerStream.WriteAsync(buffer, offset, count, cancellationToken); } public override void WriteByte(byte value) { _innerStream.WriteByte(value); } #endregion Methods #endregion Stream members [Security.SecuritySafeCritical] ~FileStream() { // Preserved for compatibility since FileStream has defined a // finalizer in past releases and derived classes may depend // on Dispose(false) call. Dispose(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Internal.TypeSystem { /// <summary> /// Represents the fundamental base type of all types within the type system. /// </summary> public abstract partial class TypeDesc : TypeSystemEntity { public static readonly TypeDesc[] EmptyTypes = new TypeDesc[0]; /// Inherited types are required to override, and should use the algorithms /// in TypeHashingAlgorithms in their implementation. public abstract override int GetHashCode(); public override bool Equals(Object o) { // Its only valid to compare two TypeDescs in the same context Debug.Assert(o == null || !(o is TypeDesc) || Object.ReferenceEquals(((TypeDesc)o).Context, this.Context)); return Object.ReferenceEquals(this, o); } #if DEBUG public static bool operator ==(TypeDesc left, TypeDesc right) { // Its only valid to compare two TypeDescs in the same context Debug.Assert(Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null) || Object.ReferenceEquals(left.Context, right.Context)); return Object.ReferenceEquals(left, right); } public static bool operator !=(TypeDesc left, TypeDesc right) { // Its only valid to compare two TypeDescs in the same context Debug.Assert(Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null) || Object.ReferenceEquals(left.Context, right.Context)); return !Object.ReferenceEquals(left, right); } #endif // The most frequently used type properties are cached here to avoid excesive virtual calls private TypeFlags _typeFlags; /// <summary> /// Gets the generic instantiation information of this type. /// For generic definitions, retrieves the generic parameters of the type. /// For generic instantiation, retrieves the generic arguments of the type. /// </summary> public virtual Instantiation Instantiation { get { return Instantiation.Empty; } } /// <summary> /// Gets a value indicating whether this type has a generic instantiation. /// This will be true for generic type instantiations and generic definitions. /// </summary> public bool HasInstantiation { get { return this.Instantiation.Length != 0; } } internal void SetWellKnownType(WellKnownType wellKnownType) { TypeFlags flags; switch (wellKnownType) { case WellKnownType.Void: case WellKnownType.Boolean: case WellKnownType.Char: case WellKnownType.SByte: case WellKnownType.Byte: case WellKnownType.Int16: case WellKnownType.UInt16: case WellKnownType.Int32: case WellKnownType.UInt32: case WellKnownType.Int64: case WellKnownType.UInt64: case WellKnownType.IntPtr: case WellKnownType.UIntPtr: case WellKnownType.Single: case WellKnownType.Double: flags = (TypeFlags)wellKnownType; break; case WellKnownType.ValueType: case WellKnownType.Enum: flags = TypeFlags.Class; break; case WellKnownType.Nullable: flags = TypeFlags.Nullable; break; case WellKnownType.Object: case WellKnownType.String: case WellKnownType.Array: case WellKnownType.MulticastDelegate: case WellKnownType.Exception: flags = TypeFlags.Class; break; case WellKnownType.RuntimeTypeHandle: case WellKnownType.RuntimeMethodHandle: case WellKnownType.RuntimeFieldHandle: flags = TypeFlags.ValueType; break; default: throw new ArgumentException(); } _typeFlags = flags; } protected abstract TypeFlags ComputeTypeFlags(TypeFlags mask); [MethodImpl(MethodImplOptions.NoInlining)] private TypeFlags InitializeTypeFlags(TypeFlags mask) { TypeFlags flags = ComputeTypeFlags(mask); if ((flags & mask) == 0) flags = Context.ComputeTypeFlags(this, flags, mask); Debug.Assert((flags & mask) != 0); _typeFlags |= flags; return flags & mask; } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected internal TypeFlags GetTypeFlags(TypeFlags mask) { TypeFlags flags = _typeFlags & mask; if (flags != 0) return flags; return InitializeTypeFlags(mask); } /// <summary> /// Retrieves the category of the type. This is one of the possible values of /// <see cref="TypeFlags"/> less than <see cref="TypeFlags.CategoryMask"/>. /// </summary> public TypeFlags Category { get { return GetTypeFlags(TypeFlags.CategoryMask); } } /// <summary> /// Gets a value indicating whether this type is an interface type. /// </summary> public bool IsInterface { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.Interface; } } /// <summary> /// Gets a value indicating whether this type is a value type (not a reference type). /// </summary> public bool IsValueType { get { return GetTypeFlags(TypeFlags.CategoryMask) < TypeFlags.Class; } } /// <summary> /// Gets a value indicating whether this is one of the primitive types (boolean, char, void, /// a floating point, or an integer type). /// </summary> public bool IsPrimitive { get { return GetTypeFlags(TypeFlags.CategoryMask) < TypeFlags.ValueType; } } /// <summary> /// Gets a value indicating whether this is an enum type. /// Access <see cref="UnderlyingType"/> to retrieve the underlying integral type. /// </summary> public bool IsEnum { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.Enum; } } /// <summary> /// Gets a value indicating whether this is a delegate type. /// </summary> public bool IsDelegate { get { var baseType = this.BaseType; return (baseType != null) ? baseType.IsWellKnownType(WellKnownType.MulticastDelegate) : false; } } /// <summary> /// Gets a value indicating whether this is System.Void type. /// </summary> public bool IsVoid { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.Void; } } /// <summary> /// Gets a value indicating whether this is System.String type. /// </summary> public bool IsString { get { return this.IsWellKnownType(WellKnownType.String); } } /// <summary> /// Gets a value indicating whether this is System.Object type. /// </summary> public bool IsObject { get { return this.IsWellKnownType(WellKnownType.Object); } } /// <summary> /// Gets a value indicating whether this is a generic definition, or /// an instance of System.Nullable`1. /// </summary> public bool IsNullable { get { return this.GetTypeDefinition().IsWellKnownType(WellKnownType.Nullable); } } /// <summary> /// Gets a value indicating whether this is an array type (<see cref="ArrayType"/>). /// Note this will return true for both multidimensional array types and vector types. /// Use <see cref="IsSzArray"/> to check for vector types. /// </summary> public bool IsArray { get { return this.GetType() == typeof(ArrayType); } } /// <summary> /// Gets a value indicating whether this is a vector type. A vector is a single-dimensional /// array with a zero lower bound. To check for arrays in general, use <see cref="IsArray"/>. /// </summary> public bool IsSzArray { get { return this.IsArray && ((ArrayType)this).IsSzArray; } } /// <summary> /// Gets a value indicating whether this is a non-vector array type. /// To check for arrays in general, use <see cref="IsArray"/>. /// </summary> public bool IsMdArray { get { return this.IsArray && ((ArrayType)this).IsMdArray; } } /// <summary> /// Gets a value indicating whether this is a managed pointer type (<see cref="ByRefType"/>). /// </summary> public bool IsByRef { get { return this.GetType() == typeof(ByRefType); } } /// <summary> /// Gets a value indicating whether this is an unmanaged pointer type (<see cref="PointerType"/>). /// </summary> public bool IsPointer { get { return this.GetType() == typeof(PointerType); } } /// <summary> /// Gets a value indicating whether this is an unmanaged function pointer type (<see cref="FunctionPointerType"/>). /// </summary> public bool IsFunctionPointer { get { return this.GetType() == typeof(FunctionPointerType); } } /// <summary> /// Gets a value indicating whether this is a <see cref="SignatureTypeVariable"/> or <see cref="SignatureMethodVariable"/>. /// </summary> public bool IsSignatureVariable { get { return this.GetType() == typeof(SignatureTypeVariable) || this.GetType() == typeof(SignatureMethodVariable); } } /// <summary> /// Gets a value indicating whether this is a generic parameter (<see cref="GenericParameterDesc"/>). /// </summary> public bool IsGenericParameter { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.GenericParameter; } } /// <summary> /// Gets a value indicating whether this is a pointer, byref, array, or szarray type, /// and can be used as a ParameterizedType. /// </summary> public bool IsParameterizedType { get { TypeFlags flags = GetTypeFlags(TypeFlags.CategoryMask); Debug.Assert((flags >= TypeFlags.Array && flags <= TypeFlags.Pointer) == (this is ParameterizedType)); return (flags >= TypeFlags.Array && flags <= TypeFlags.Pointer); } } /// <summary> /// Gets a value indicating whether this is a class, an interface, a value type, or a /// generic instance of one of them. /// </summary> public bool IsDefType { get { Debug.Assert(GetTypeFlags(TypeFlags.CategoryMask) <= TypeFlags.Interface == this is DefType); return GetTypeFlags(TypeFlags.CategoryMask) <= TypeFlags.Interface; } } /// <summary> /// Gets a value indicating whether locations of this type refer to an object on the GC heap. /// </summary> public bool IsGCPointer { get { TypeFlags category = GetTypeFlags(TypeFlags.CategoryMask); return category == TypeFlags.Class || category == TypeFlags.Array || category == TypeFlags.SzArray || category == TypeFlags.Interface; } } public bool ContainsGenericVariables { get { return (GetTypeFlags(TypeFlags.ContainsGenericVariables | TypeFlags.ContainsGenericVariablesComputed) & TypeFlags.ContainsGenericVariables) != 0; } } /// <summary> /// Gets the type from which this type derives from, or null if there's no such type. /// </summary> public virtual DefType BaseType { get { return null; } } /// <summary> /// Gets a value indicating whether this type has a base type. /// </summary> public bool HasBaseType { get { return BaseType != null; } } /// <summary> /// If this is an enum type, gets the underlying integral type of the enum type. /// For all other types, returns 'this'. /// </summary> public virtual TypeDesc UnderlyingType { get { if (!this.IsEnum) return this; // TODO: Cache the result? foreach (var field in this.GetFields()) { if (!field.IsStatic) return field.FieldType; } throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, this); } } /// <summary> /// Gets a value indicating whether this type has a class constructor method. /// Use <see cref="GetStaticConstructor"/> to retrieve it. /// </summary> public bool HasStaticConstructor { get { return (GetTypeFlags(TypeFlags.HasStaticConstructor | TypeFlags.HasStaticConstructorComputed) & TypeFlags.HasStaticConstructor) != 0; } } /// <summary> /// Gets all methods on this type defined within the type's metadata. /// This will not include methods injected by the type system context. /// </summary> public virtual IEnumerable<MethodDesc> GetMethods() { return MethodDesc.EmptyMethods; } /// <summary> /// Gets a named method on the type. This method only looks at methods defined /// in type's metadata. The <paramref name="signature"/> parameter can be null. /// If signature is not specified and there are multiple matches, the first one /// is returned. Returns null if method not found. /// </summary> // TODO: Substitutions, generics, modopts, ... public virtual MethodDesc GetMethod(string name, MethodSignature signature) { foreach (var method in GetMethods()) { if (method.Name == name) { if (signature == null || signature.Equals(method.Signature)) return method; } } return null; } /// <summary> /// Retrieves the class constructor method of this type. /// </summary> /// <returns></returns> public virtual MethodDesc GetStaticConstructor() { return null; } /// <summary> /// Retrieves the public parameterless constructor method of the type, or null if there isn't one /// or the type is abstract. /// </summary> public virtual MethodDesc GetDefaultConstructor() { return null; } /// <summary> /// Gets all fields on the type as defined in the metadata. /// </summary> public virtual IEnumerable<FieldDesc> GetFields() { return FieldDesc.EmptyFields; } /// <summary> /// Gets a named field on the type. Returns null if the field wasn't found. /// </summary> // TODO: Substitutions, generics, modopts, ... // TODO: field signature public virtual FieldDesc GetField(string name) { foreach (var field in GetFields()) { if (field.Name == name) return field; } return null; } public virtual TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation) { return this; } /// <summary> /// Gets the definition of the type. If this is a generic type instance, /// this method strips the instantiation (E.g C&lt;int&gt; -> C&lt;T&gt;) /// </summary> public virtual TypeDesc GetTypeDefinition() { return this; } /// <summary> /// Gets a value indicating whether this is a type definition. Returns false /// if this is an instantiated generic type. /// </summary> public bool IsTypeDefinition { get { return GetTypeDefinition() == this; } } /// <summary> /// Determine if two types share the same type definition /// </summary> public bool HasSameTypeDefinition(TypeDesc otherType) { return GetTypeDefinition() == otherType.GetTypeDefinition(); } /// <summary> /// Gets a value indicating whether this type has a finalizer method. /// Use <see cref="GetFinalizer"/> to retrieve the method. /// </summary> public virtual bool HasFinalizer { get { return false; } } /// <summary> /// Gets the finalizer method (an override of the System.Object::Finalize method) /// if this type has one. Returns null if the type doesn't define one. /// </summary> public virtual MethodDesc GetFinalizer() { return null; } /// <summary> /// Gets a value indicating whether this type has generic variance (the definition of the type /// has a generic parameter that is co- or contravariant). /// </summary> public bool HasVariance { get { return (GetTypeFlags(TypeFlags.HasGenericVariance | TypeFlags.HasGenericVarianceComputed) & TypeFlags.HasGenericVariance) != 0; } } /// <summary> /// Gets a value indicating whether this type is an uninstantiated definition of a generic type. /// </summary> public bool IsGenericDefinition { get { return HasInstantiation && IsTypeDefinition; } } } }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright 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 Facebook.Unity.Editor { using System; using System.Collections; using System.Collections.Generic; using Facebook.Unity.Canvas; using Facebook.Unity.Editor.Dialogs; using Facebook.Unity.Mobile; using UnityEngine; internal class EditorFacebook : FacebookBase, IMobileFacebookImplementation, ICanvasFacebookImplementation { private const string WarningMessage = "You are using the facebook SDK in the Unity Editor. " + "Behavior may not be the same as when used on iOS, Android, or Web."; private const string AccessTokenKey = "com.facebook.unity.editor.accesstoken"; public EditorFacebook() : base(new CallbackManager()) { } public override bool LimitEventUsage { get; set; } public ShareDialogMode ShareDialogMode { get; set; } public override string SDKName { get { return "FBUnityEditorSDK"; } } public override string SDKVersion { get { return Facebook.Unity.FacebookSdkVersion.Build; } } private IFacebookCallbackHandler EditorGameObject { get { return ComponentFactory.GetComponent<EditorFacebookGameObject>(); } } public override void Init( HideUnityDelegate hideUnityDelegate, InitDelegate onInitComplete) { // Warn that editor behavior will not match supported platforms FacebookLogger.Warn(WarningMessage); base.Init( hideUnityDelegate, onInitComplete); this.EditorGameObject.OnInitComplete(string.Empty); } public override void LogInWithReadPermissions( IEnumerable<string> permissions, FacebookDelegate<ILoginResult> callback) { // For the editor don't worry about the difference between // LogInWithReadPermissions and LogInWithPublishPermissions this.LogInWithPublishPermissions(permissions, callback); } public override void LogInWithPublishPermissions( IEnumerable<string> permissions, FacebookDelegate<ILoginResult> callback) { var dialog = ComponentFactory.GetComponent<MockLoginDialog>(); dialog.Callback = this.EditorGameObject.OnLoginComplete; dialog.CallbackID = this.CallbackManager.AddFacebookDelegate(callback); } public override void AppRequest( string message, OGActionType? actionType, string objectId, IEnumerable<string> to, IEnumerable<object> filters, IEnumerable<string> excludeIds, int? maxRecipients, string data, string title, FacebookDelegate<IAppRequestResult> callback) { this.ShowEmptyMockDialog(this.OnAppRequestsComplete, callback, "Mock App Request"); } public override void ShareLink( Uri contentURL, string contentTitle, string contentDescription, Uri photoURL, FacebookDelegate<IShareResult> callback) { this.ShowMockShareDialog("ShareLink", callback); } public override void FeedShare( string toId, Uri link, string linkName, string linkCaption, string linkDescription, Uri picture, string mediaSource, FacebookDelegate<IShareResult> callback) { this.ShowMockShareDialog("FeedShare", callback); } public override void GameGroupCreate( string name, string description, string privacy, FacebookDelegate<IGroupCreateResult> callback) { this.ShowEmptyMockDialog(this.OnGroupCreateComplete, callback, "Mock Group Create"); } public override void GameGroupJoin( string id, FacebookDelegate<IGroupJoinResult> callback) { this.ShowEmptyMockDialog(this.OnGroupJoinComplete, callback, "Mock Group Join"); } public override void ActivateApp(string appId) { FacebookLogger.Info("This only needs to be called for iOS or Android."); } public override void GetAppLink(FacebookDelegate<IAppLinkResult> callback) { var result = new Dictionary<string, object>(); result[Constants.UrlKey] = "mockurl://testing.url"; result[Constants.CallbackIdKey] = this.CallbackManager.AddFacebookDelegate(callback); this.OnGetAppLinkComplete(MiniJSON.Json.Serialize(result)); } public override void AppEventsLogEvent( string logEvent, float? valueToSum, Dictionary<string, object> parameters) { FacebookLogger.Log("Pew! Pretending to send this off. Doesn't actually work in the editor"); } public override void AppEventsLogPurchase( float logPurchase, string currency, Dictionary<string, object> parameters) { FacebookLogger.Log("Pew! Pretending to send this off. Doesn't actually work in the editor"); } public void AppInvite( Uri appLinkUrl, Uri previewImageUrl, FacebookDelegate<IAppInviteResult> callback) { this.ShowEmptyMockDialog(this.OnAppInviteComplete, callback, "Mock App Invite"); } public void FetchDeferredAppLink( FacebookDelegate<IAppLinkResult> callback) { var result = new Dictionary<string, object>(); result[Constants.UrlKey] = "mockurl://testing.url"; result[Constants.RefKey] = "mock ref"; result[Constants.ExtrasKey] = new Dictionary<string, object>() { { "mock extra key", "mock extra value" } }; result[Constants.TargetUrlKey] = "mocktargeturl://mocktarget.url"; result[Constants.CallbackIdKey] = this.CallbackManager.AddFacebookDelegate(callback); this.OnFetchDeferredAppLinkComplete(MiniJSON.Json.Serialize(result)); } public void Pay( string product, string action, int quantity, int? quantityMin, int? quantityMax, string requestId, string pricepointId, string testCurrency, FacebookDelegate<IPayResult> callback) { this.ShowEmptyMockDialog(this.OnPayComplete, callback, "Mock Pay Dialog"); } public void RefreshCurrentAccessToken( FacebookDelegate<IAccessTokenRefreshResult> callback) { if (callback == null) { return; } var result = new Dictionary<string, object>() { { Constants.CallbackIdKey, this.CallbackManager.AddFacebookDelegate(callback) } }; if (AccessToken.CurrentAccessToken == null) { result[Constants.ErrorKey] = "No current access token"; } else { var accessTokenDic = (IDictionary<string, object>)MiniJSON.Json.Deserialize( AccessToken.CurrentAccessToken.ToJson()); result.AddAllKVPFrom(accessTokenDic); } this.OnRefreshCurrentAccessTokenComplete(result.ToJson()); } public override void OnAppRequestsComplete(string message) { var result = new AppRequestResult(message); CallbackManager.OnFacebookResponse(result); } public override void OnGetAppLinkComplete(string message) { var result = new AppLinkResult(message); CallbackManager.OnFacebookResponse(result); } public override void OnGroupCreateComplete(string message) { var result = new GroupCreateResult(message); CallbackManager.OnFacebookResponse(result); } public override void OnGroupJoinComplete(string message) { var result = new GroupJoinResult(message); CallbackManager.OnFacebookResponse(result); } public override void OnLoginComplete(string message) { var result = new LoginResult(message); this.OnAuthResponse(result); } public override void OnShareLinkComplete(string message) { var result = new ShareResult(message); CallbackManager.OnFacebookResponse(result); } public void OnAppInviteComplete(string message) { var result = new AppInviteResult(message); CallbackManager.OnFacebookResponse(result); } public void OnFetchDeferredAppLinkComplete(string message) { var result = new AppLinkResult(message); CallbackManager.OnFacebookResponse(result); } public void OnPayComplete(string message) { var result = new PayResult(message); CallbackManager.OnFacebookResponse(result); } public void OnRefreshCurrentAccessTokenComplete(string message) { var result = new AccessTokenRefreshResult(message); CallbackManager.OnFacebookResponse(result); } #region Canvas Dummy Methods public void OnFacebookAuthResponseChange(string message) { throw new NotSupportedException(); } public void OnUrlResponse(string message) { throw new NotSupportedException(); } #endregion private void ShowEmptyMockDialog<T>( EditorFacebookMockDialog.OnComplete callback, FacebookDelegate<T> userCallback, string title) where T : IResult { var dialog = ComponentFactory.GetComponent<EmptyMockDialog>(); dialog.Callback = callback; dialog.CallbackID = this.CallbackManager.AddFacebookDelegate(userCallback); dialog.EmptyDialogTitle = title; } private void ShowMockShareDialog( string subTitle, FacebookDelegate<IShareResult> userCallback) { var dialog = ComponentFactory.GetComponent<MockShareDialog>(); dialog.SubTitle = subTitle; dialog.Callback = this.EditorGameObject.OnShareLinkComplete; dialog.CallbackID = this.CallbackManager.AddFacebookDelegate(userCallback); } } }
// 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. // Don't entity encode high chars (160 to 256) #define ENTITY_ENCODE_HIGH_ASCII_CHARS using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Text; namespace System.Net { public static class WebUtility { // some consts copied from Char / CharUnicodeInfo since we don't have friend access to those types private const char HIGH_SURROGATE_START = '\uD800'; private const char LOW_SURROGATE_START = '\uDC00'; private const char LOW_SURROGATE_END = '\uDFFF'; private const int UNICODE_PLANE00_END = 0x00FFFF; private const int UNICODE_PLANE01_START = 0x10000; private const int UNICODE_PLANE16_END = 0x10FFFF; private const int UnicodeReplacementChar = '\uFFFD'; private const int MaxInt32Digits = 10; #region HtmlEncode / HtmlDecode methods [return: NotNullIfNotNull("value")] public static string? HtmlEncode(string? value) { if (string.IsNullOrEmpty(value)) { return value; } ReadOnlySpan<char> valueSpan = value.AsSpan(); // Don't create ValueStringBuilder if we don't have anything to encode int index = IndexOfHtmlEncodingChars(valueSpan); if (index == -1) { return value; } // For small inputs we allocate on the stack. In most cases a buffer three // times larger the original string should be sufficient as usually not all // characters need to be encoded. // For larger string we rent the input string's length plus a fixed // conservative amount of chars from the ArrayPool. Span<char> buffer = value.Length < 80 ? stackalloc char[256] : null; ValueStringBuilder sb = buffer != null ? new ValueStringBuilder(buffer) : new ValueStringBuilder(value.Length + 200); sb.Append(valueSpan.Slice(0, index)); HtmlEncode(valueSpan.Slice(index), ref sb); return sb.ToString(); } public static void HtmlEncode(string? value, TextWriter output) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (string.IsNullOrEmpty(value)) { output.Write(value); return; } ReadOnlySpan<char> valueSpan = value.AsSpan(); // Don't create ValueStringBuilder if we don't have anything to encode int index = IndexOfHtmlEncodingChars(valueSpan); if (index == -1) { output.Write(value); return; } // For small inputs we allocate on the stack. In most cases a buffer three // times larger the original string should be sufficient as usually not all // characters need to be encoded. // For larger string we rent the input string's length plus a fixed // conservative amount of chars from the ArrayPool. Span<char> buffer = value.Length < 80 ? stackalloc char[256] : null; ValueStringBuilder sb = buffer != null ? new ValueStringBuilder(buffer) : new ValueStringBuilder(value.Length + 200); sb.Append(valueSpan.Slice(0, index)); HtmlEncode(valueSpan.Slice(index), ref sb); output.Write(sb.AsSpan()); sb.Dispose(); } private static void HtmlEncode(ReadOnlySpan<char> input, ref ValueStringBuilder output) { for (int i = 0; i < input.Length; i++) { char ch = input[i]; if (ch <= '>') { switch (ch) { case '<': output.Append("&lt;"); break; case '>': output.Append("&gt;"); break; case '"': output.Append("&quot;"); break; case '\'': output.Append("&#39;"); break; case '&': output.Append("&amp;"); break; default: output.Append(ch); break; } } else { int valueToEncode = -1; // set to >= 0 if needs to be encoded #if ENTITY_ENCODE_HIGH_ASCII_CHARS if (ch >= 160 && ch < 256) { // The seemingly arbitrary 160 comes from RFC valueToEncode = ch; } else #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS if (char.IsSurrogate(ch)) { int scalarValue = GetNextUnicodeScalarValueFromUtf16Surrogate(input, ref i); if (scalarValue >= UNICODE_PLANE01_START) { valueToEncode = scalarValue; } else { // Don't encode BMP characters (like U+FFFD) since they wouldn't have // been encoded if explicitly present in the string anyway. ch = (char)scalarValue; } } if (valueToEncode >= 0) { // value needs to be encoded output.Append("&#"); // Use the buffer directly and reserve a conservative estimate of 10 chars. Span<char> encodingBuffer = output.AppendSpan(MaxInt32Digits); valueToEncode.TryFormat(encodingBuffer, out int charsWritten); // Invariant output.Length -= (MaxInt32Digits - charsWritten); output.Append(';'); } else { // write out the character directly output.Append(ch); } } } } [return: NotNullIfNotNull("value")] public static string? HtmlDecode(string? value) { if (string.IsNullOrEmpty(value)) { return value; } ReadOnlySpan<char> valueSpan = value.AsSpan(); int index = IndexOfHtmlDecodingChars(valueSpan); if (index == -1) { return value; } // In the worst case the decoded string has the same length. // For small inputs we use stack allocation. Span<char> buffer = value.Length <= 256 ? stackalloc char[256] : null; ValueStringBuilder sb = buffer != null ? new ValueStringBuilder(buffer) : new ValueStringBuilder(value.Length); sb.Append(valueSpan.Slice(0, index)); HtmlDecode(valueSpan.Slice(index), ref sb); return sb.ToString(); } public static void HtmlDecode(string? value, TextWriter output) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (string.IsNullOrEmpty(value)) { output.Write(value); return; } ReadOnlySpan<char> valueSpan = value.AsSpan(); int index = IndexOfHtmlDecodingChars(valueSpan); if (index == -1) { output.Write(value); return; } // In the worst case the decoded string has the same length. // For small inputs we use stack allocation. Span<char> buffer = value.Length <= 256 ? stackalloc char[256] : null; ValueStringBuilder sb = buffer != null ? new ValueStringBuilder(buffer) : new ValueStringBuilder(value.Length); sb.Append(valueSpan.Slice(0, index)); HtmlDecode(valueSpan.Slice(index), ref sb); output.Write(sb.AsSpan()); sb.Dispose(); } private static void HtmlDecode(ReadOnlySpan<char> input, ref ValueStringBuilder output) { for (int i = 0; i < input.Length; i++) { char ch = input[i]; if (ch == '&') { // We found a '&'. Now look for the next ';' or '&'. The idea is that // if we find another '&' before finding a ';', then this is not an entity, // and the next '&' might start a real entity (VSWhidbey 275184) ReadOnlySpan<char> inputSlice = input.Slice(i + 1); int entityLength = inputSlice.IndexOf(';'); if (entityLength >= 0) { int entityEndPosition = (i + 1) + entityLength; if (entityLength > 1 && inputSlice[0] == '#') { // The # syntax can be in decimal or hex, e.g. // &#229; --> decimal // &#xE5; --> same char in hex // See http://www.w3.org/TR/REC-html40/charset.html#entities bool parsedSuccessfully = inputSlice[1] == 'x' || inputSlice[1] == 'X' ? uint.TryParse(inputSlice.Slice(2, entityLength - 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out uint parsedValue) : uint.TryParse(inputSlice.Slice(1, entityLength - 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedValue); if (parsedSuccessfully) { // decoded character must be U+0000 .. U+10FFFF, excluding surrogates parsedSuccessfully = ((parsedValue < HIGH_SURROGATE_START) || (LOW_SURROGATE_END < parsedValue && parsedValue <= UNICODE_PLANE16_END)); } if (parsedSuccessfully) { if (parsedValue <= UNICODE_PLANE00_END) { // single character output.Append((char)parsedValue); } else { // multi-character ConvertSmpToUtf16(parsedValue, out char leadingSurrogate, out char trailingSurrogate); output.Append(leadingSurrogate); output.Append(trailingSurrogate); } i = entityEndPosition; // already looked at everything until semicolon continue; } } else { ReadOnlySpan<char> entity = inputSlice.Slice(0, entityLength); i = entityEndPosition; // already looked at everything until semicolon char entityChar = HtmlEntities.Lookup(entity); if (entityChar != (char)0) { ch = entityChar; } else { output.Append('&'); output.Append(entity); output.Append(';'); continue; } } } } output.Append(ch); } } private static int IndexOfHtmlEncodingChars(ReadOnlySpan<char> input) { for (int i = 0; i < input.Length; i++) { char ch = input[i]; if (ch <= '>') { switch (ch) { case '<': case '>': case '"': case '\'': case '&': return i; } } #if ENTITY_ENCODE_HIGH_ASCII_CHARS else if (ch >= 160 && ch < 256) { return i; } #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS else if (char.IsSurrogate(ch)) { return i; } } return -1; } #endregion #region UrlEncode implementation private static void GetEncodedBytes(byte[] originalBytes, int offset, int count, byte[] expandedBytes) { int pos = 0; int end = offset + count; Debug.Assert(offset < end && end <= originalBytes.Length); for (int i = offset; i < end; i++) { #if DEBUG // Make sure we never overwrite any bytes if originalBytes and // expandedBytes refer to the same array if (originalBytes == expandedBytes) { Debug.Assert(i >= pos); } #endif byte b = originalBytes[i]; char ch = (char)b; if (IsUrlSafeChar(ch)) { expandedBytes[pos++] = b; } else if (ch == ' ') { expandedBytes[pos++] = (byte)'+'; } else { expandedBytes[pos++] = (byte)'%'; expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf); expandedBytes[pos++] = (byte)IntToHex(b & 0x0f); } } } #endregion #region UrlEncode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")] [return: NotNullIfNotNull("value")] public static string? UrlEncode(string? value) { if (string.IsNullOrEmpty(value)) return value; int safeCount = 0; int spaceCount = 0; for (int i = 0; i < value.Length; i++) { char ch = value[i]; if (IsUrlSafeChar(ch)) { safeCount++; } else if (ch == ' ') { spaceCount++; } } int unexpandedCount = safeCount + spaceCount; if (unexpandedCount == value.Length) { if (spaceCount != 0) { // Only spaces to encode return value.Replace(' ', '+'); } // Nothing to expand return value; } int byteCount = Encoding.UTF8.GetByteCount(value); int unsafeByteCount = byteCount - unexpandedCount; int byteIndex = unsafeByteCount * 2; // Instead of allocating one array of length `byteCount` to store // the UTF-8 encoded bytes, and then a second array of length // `3 * byteCount - 2 * unexpandedCount` // to store the URL-encoded UTF-8 bytes, we allocate a single array of // the latter and encode the data in place, saving the first allocation. // We store the UTF-8 bytes to the end of this array, and then URL encode to the // beginning of the array. byte[] newBytes = new byte[byteCount + byteIndex]; Encoding.UTF8.GetBytes(value, 0, value.Length, newBytes, byteIndex); GetEncodedBytes(newBytes, byteIndex, byteCount, newBytes); return Encoding.UTF8.GetString(newBytes); } [return: NotNullIfNotNull("value")] public static byte[]? UrlEncodeToBytes(byte[]? value, int offset, int count) { if (!ValidateUrlEncodingParameters(value, offset, count)) { return null; } bool foundSpaces = false; int unsafeCount = 0; // count them first for (int i = 0; i < count; i++) { char ch = (char)value![offset + i]; if (ch == ' ') foundSpaces = true; else if (!IsUrlSafeChar(ch)) unsafeCount++; } // nothing to expand? if (!foundSpaces && unsafeCount == 0) { var subarray = new byte[count]; Buffer.BlockCopy(value!, offset, subarray, 0, count); return subarray; } // expand not 'safe' characters into %XX, spaces to +s byte[] expandedBytes = new byte[count + unsafeCount * 2]; GetEncodedBytes(value!, offset, count, expandedBytes); return expandedBytes; } #endregion #region UrlDecode implementation [return: NotNullIfNotNull("value")] private static string? UrlDecodeInternal(string? value, Encoding encoding) { if (string.IsNullOrEmpty(value)) { return value; } int count = value.Length; UrlDecoder helper = new UrlDecoder(count, encoding); // go through the string's chars collapsing %XX and // appending each char as char, with exception of %XX constructs // that are appended as bytes bool needsDecodingUnsafe = false; bool needsDecodingSpaces = false; for (int pos = 0; pos < count; pos++) { char ch = value[pos]; if (ch == '+') { needsDecodingSpaces = true; ch = ' '; } else if (ch == '%' && pos < count - 2) { int h1 = HexToInt(value[pos + 1]); int h2 = HexToInt(value[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars byte b = (byte)((h1 << 4) | h2); pos += 2; // don't add as char helper.AddByte(b); needsDecodingUnsafe = true; continue; } } if ((ch & 0xFF80) == 0) helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode else helper.AddChar(ch); } if (!needsDecodingUnsafe) { if (needsDecodingSpaces) { // Only spaces to decode return value.Replace('+', ' '); } // Nothing to decode return value; } return helper.GetString(); } [return: NotNullIfNotNull("bytes")] private static byte[]? UrlDecodeInternal(byte[]? bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int decodedBytesCount = 0; byte[] decodedBytes = new byte[count]; for (int i = 0; i < count; i++) { int pos = offset + i; byte b = bytes![pos]; if (b == '+') { b = (byte)' '; } else if (b == '%' && i < count - 2) { int h1 = HexToInt((char)bytes[pos + 1]); int h2 = HexToInt((char)bytes[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars b = (byte)((h1 << 4) | h2); i += 2; } } decodedBytes[decodedBytesCount++] = b; } if (decodedBytesCount < decodedBytes.Length) { Array.Resize(ref decodedBytes, decodedBytesCount); } return decodedBytes; } #endregion #region UrlDecode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")] [return: NotNullIfNotNull("encodedValue")] public static string? UrlDecode(string? encodedValue) { return UrlDecodeInternal(encodedValue, Encoding.UTF8); } [return: NotNullIfNotNull("encodedValue")] public static byte[]? UrlDecodeToBytes(byte[]? encodedValue, int offset, int count) { return UrlDecodeInternal(encodedValue, offset, count); } #endregion #region Helper methods // similar to Char.ConvertFromUtf32, but doesn't check arguments or generate strings // input is assumed to be an SMP character private static void ConvertSmpToUtf16(uint smpChar, out char leadingSurrogate, out char trailingSurrogate) { Debug.Assert(UNICODE_PLANE01_START <= smpChar && smpChar <= UNICODE_PLANE16_END); int utf32 = (int)(smpChar - UNICODE_PLANE01_START); leadingSurrogate = (char)((utf32 / 0x400) + HIGH_SURROGATE_START); trailingSurrogate = (char)((utf32 % 0x400) + LOW_SURROGATE_START); } private static int GetNextUnicodeScalarValueFromUtf16Surrogate(ReadOnlySpan<char> input, ref int index) { // invariants Debug.Assert(input.Length - index >= 1); Debug.Assert(char.IsSurrogate(input[index])); if (input.Length - index <= 1) { // not enough characters remaining to resurrect the original scalar value return UnicodeReplacementChar; } char leadingSurrogate = input[index]; char trailingSurrogate = input[index + 1]; if (!char.IsSurrogatePair(leadingSurrogate, trailingSurrogate)) { // unmatched surrogate return UnicodeReplacementChar; } // we're going to consume an extra char index++; // below code is from Char.ConvertToUtf32, but without the checks (since we just performed them) return (((leadingSurrogate - HIGH_SURROGATE_START) * 0x400) + (trailingSurrogate - LOW_SURROGATE_START) + UNICODE_PLANE01_START); } private static int HexToInt(char h) { return (h >= '0' && h <= '9') ? h - '0' : (h >= 'a' && h <= 'f') ? h - 'a' + 10 : (h >= 'A' && h <= 'F') ? h - 'A' + 10 : -1; } private static char IntToHex(int n) { Debug.Assert(n < 0x10); if (n <= 9) return (char)(n + (int)'0'); else return (char)(n - 10 + (int)'A'); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsUrlSafeChar(char ch) { // Set of safe chars, from RFC 1738.4 minus '+' /* if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') return true; switch (ch) { case '-': case '_': case '.': case '!': case '*': case '(': case ')': return true; } return false; */ // Optimized version of the above: int code = (int)ch; const int safeSpecialCharMask = 0x03FF0000 | // 0..9 1 << ((int)'!' - 0x20) | // 0x21 1 << ((int)'(' - 0x20) | // 0x28 1 << ((int)')' - 0x20) | // 0x29 1 << ((int)'*' - 0x20) | // 0x2A 1 << ((int)'-' - 0x20) | // 0x2D 1 << ((int)'.' - 0x20); // 0x2E unchecked { return ((uint)(code - 'a') <= (uint)('z' - 'a')) || ((uint)(code - 'A') <= (uint)('Z' - 'A')) || ((uint)(code - 0x20) <= (uint)('9' - 0x20) && ((1 << (code - 0x20)) & safeSpecialCharMask) != 0) || (code == (int)'_'); } } private static bool ValidateUrlEncodingParameters(byte[]? bytes, int offset, int count) { if (bytes == null && count == 0) return false; if (bytes == null) { throw new ArgumentNullException(nameof(bytes)); } if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || offset + count > bytes.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } return true; } private static int IndexOfHtmlDecodingChars(ReadOnlySpan<char> input) { // this string requires html decoding if it contains '&' or a surrogate character for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c == '&' || char.IsSurrogate(c)) { return i; } } return -1; } #endregion // Internal struct to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes private struct UrlDecoder { private readonly int _bufferSize; // Accumulate characters in a special array private int _numChars; private char[]? _charBuffer; // Accumulate bytes for decoding into characters in a special array private int _numBytes; private byte[]? _byteBuffer; // Encoding to convert chars to bytes private readonly Encoding _encoding; private void FlushBytes() { Debug.Assert(_numBytes > 0); if (_charBuffer == null) _charBuffer = new char[_bufferSize]; _numChars += _encoding.GetChars(_byteBuffer!, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } internal UrlDecoder(int bufferSize, Encoding encoding) { _bufferSize = bufferSize; _encoding = encoding; _charBuffer = null; // char buffer created on demand _numChars = 0; _numBytes = 0; _byteBuffer = null; // byte buffer created on demand } internal void AddChar(char ch) { if (_numBytes > 0) FlushBytes(); if (_charBuffer == null) _charBuffer = new char[_bufferSize]; _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { if (_byteBuffer == null) _byteBuffer = new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } internal string GetString() { if (_numBytes > 0) FlushBytes(); Debug.Assert(_numChars > 0); return new string(_charBuffer!, 0, _numChars); } } // helper class for lookup of HTML encoding entities private static class HtmlEntities { #if DEBUG static HtmlEntities() { // Make sure the initial capacity for s_lookupTable is correct Debug.Assert(s_lookupTable.Count == Count, $"There should be {Count} HTML entities, but {nameof(s_lookupTable)} has {s_lookupTable.Count} of them."); } #endif // The list is from http://www.w3.org/TR/REC-html40/sgml/entities.html, except for &apos;, which // is defined in http://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent. private const int Count = 253; // maps entity strings => unicode chars private static readonly Dictionary<ulong, char> s_lookupTable = new Dictionary<ulong, char>(Count) { [ToUInt64Key("quot")] = '\x0022', [ToUInt64Key("amp")] = '\x0026', [ToUInt64Key("apos")] = '\x0027', [ToUInt64Key("lt")] = '\x003c', [ToUInt64Key("gt")] = '\x003e', [ToUInt64Key("nbsp")] = '\x00a0', [ToUInt64Key("iexcl")] = '\x00a1', [ToUInt64Key("cent")] = '\x00a2', [ToUInt64Key("pound")] = '\x00a3', [ToUInt64Key("curren")] = '\x00a4', [ToUInt64Key("yen")] = '\x00a5', [ToUInt64Key("brvbar")] = '\x00a6', [ToUInt64Key("sect")] = '\x00a7', [ToUInt64Key("uml")] = '\x00a8', [ToUInt64Key("copy")] = '\x00a9', [ToUInt64Key("ordf")] = '\x00aa', [ToUInt64Key("laquo")] = '\x00ab', [ToUInt64Key("not")] = '\x00ac', [ToUInt64Key("shy")] = '\x00ad', [ToUInt64Key("reg")] = '\x00ae', [ToUInt64Key("macr")] = '\x00af', [ToUInt64Key("deg")] = '\x00b0', [ToUInt64Key("plusmn")] = '\x00b1', [ToUInt64Key("sup2")] = '\x00b2', [ToUInt64Key("sup3")] = '\x00b3', [ToUInt64Key("acute")] = '\x00b4', [ToUInt64Key("micro")] = '\x00b5', [ToUInt64Key("para")] = '\x00b6', [ToUInt64Key("middot")] = '\x00b7', [ToUInt64Key("cedil")] = '\x00b8', [ToUInt64Key("sup1")] = '\x00b9', [ToUInt64Key("ordm")] = '\x00ba', [ToUInt64Key("raquo")] = '\x00bb', [ToUInt64Key("frac14")] = '\x00bc', [ToUInt64Key("frac12")] = '\x00bd', [ToUInt64Key("frac34")] = '\x00be', [ToUInt64Key("iquest")] = '\x00bf', [ToUInt64Key("Agrave")] = '\x00c0', [ToUInt64Key("Aacute")] = '\x00c1', [ToUInt64Key("Acirc")] = '\x00c2', [ToUInt64Key("Atilde")] = '\x00c3', [ToUInt64Key("Auml")] = '\x00c4', [ToUInt64Key("Aring")] = '\x00c5', [ToUInt64Key("AElig")] = '\x00c6', [ToUInt64Key("Ccedil")] = '\x00c7', [ToUInt64Key("Egrave")] = '\x00c8', [ToUInt64Key("Eacute")] = '\x00c9', [ToUInt64Key("Ecirc")] = '\x00ca', [ToUInt64Key("Euml")] = '\x00cb', [ToUInt64Key("Igrave")] = '\x00cc', [ToUInt64Key("Iacute")] = '\x00cd', [ToUInt64Key("Icirc")] = '\x00ce', [ToUInt64Key("Iuml")] = '\x00cf', [ToUInt64Key("ETH")] = '\x00d0', [ToUInt64Key("Ntilde")] = '\x00d1', [ToUInt64Key("Ograve")] = '\x00d2', [ToUInt64Key("Oacute")] = '\x00d3', [ToUInt64Key("Ocirc")] = '\x00d4', [ToUInt64Key("Otilde")] = '\x00d5', [ToUInt64Key("Ouml")] = '\x00d6', [ToUInt64Key("times")] = '\x00d7', [ToUInt64Key("Oslash")] = '\x00d8', [ToUInt64Key("Ugrave")] = '\x00d9', [ToUInt64Key("Uacute")] = '\x00da', [ToUInt64Key("Ucirc")] = '\x00db', [ToUInt64Key("Uuml")] = '\x00dc', [ToUInt64Key("Yacute")] = '\x00dd', [ToUInt64Key("THORN")] = '\x00de', [ToUInt64Key("szlig")] = '\x00df', [ToUInt64Key("agrave")] = '\x00e0', [ToUInt64Key("aacute")] = '\x00e1', [ToUInt64Key("acirc")] = '\x00e2', [ToUInt64Key("atilde")] = '\x00e3', [ToUInt64Key("auml")] = '\x00e4', [ToUInt64Key("aring")] = '\x00e5', [ToUInt64Key("aelig")] = '\x00e6', [ToUInt64Key("ccedil")] = '\x00e7', [ToUInt64Key("egrave")] = '\x00e8', [ToUInt64Key("eacute")] = '\x00e9', [ToUInt64Key("ecirc")] = '\x00ea', [ToUInt64Key("euml")] = '\x00eb', [ToUInt64Key("igrave")] = '\x00ec', [ToUInt64Key("iacute")] = '\x00ed', [ToUInt64Key("icirc")] = '\x00ee', [ToUInt64Key("iuml")] = '\x00ef', [ToUInt64Key("eth")] = '\x00f0', [ToUInt64Key("ntilde")] = '\x00f1', [ToUInt64Key("ograve")] = '\x00f2', [ToUInt64Key("oacute")] = '\x00f3', [ToUInt64Key("ocirc")] = '\x00f4', [ToUInt64Key("otilde")] = '\x00f5', [ToUInt64Key("ouml")] = '\x00f6', [ToUInt64Key("divide")] = '\x00f7', [ToUInt64Key("oslash")] = '\x00f8', [ToUInt64Key("ugrave")] = '\x00f9', [ToUInt64Key("uacute")] = '\x00fa', [ToUInt64Key("ucirc")] = '\x00fb', [ToUInt64Key("uuml")] = '\x00fc', [ToUInt64Key("yacute")] = '\x00fd', [ToUInt64Key("thorn")] = '\x00fe', [ToUInt64Key("yuml")] = '\x00ff', [ToUInt64Key("OElig")] = '\x0152', [ToUInt64Key("oelig")] = '\x0153', [ToUInt64Key("Scaron")] = '\x0160', [ToUInt64Key("scaron")] = '\x0161', [ToUInt64Key("Yuml")] = '\x0178', [ToUInt64Key("fnof")] = '\x0192', [ToUInt64Key("circ")] = '\x02c6', [ToUInt64Key("tilde")] = '\x02dc', [ToUInt64Key("Alpha")] = '\x0391', [ToUInt64Key("Beta")] = '\x0392', [ToUInt64Key("Gamma")] = '\x0393', [ToUInt64Key("Delta")] = '\x0394', [ToUInt64Key("Epsilon")] = '\x0395', [ToUInt64Key("Zeta")] = '\x0396', [ToUInt64Key("Eta")] = '\x0397', [ToUInt64Key("Theta")] = '\x0398', [ToUInt64Key("Iota")] = '\x0399', [ToUInt64Key("Kappa")] = '\x039a', [ToUInt64Key("Lambda")] = '\x039b', [ToUInt64Key("Mu")] = '\x039c', [ToUInt64Key("Nu")] = '\x039d', [ToUInt64Key("Xi")] = '\x039e', [ToUInt64Key("Omicron")] = '\x039f', [ToUInt64Key("Pi")] = '\x03a0', [ToUInt64Key("Rho")] = '\x03a1', [ToUInt64Key("Sigma")] = '\x03a3', [ToUInt64Key("Tau")] = '\x03a4', [ToUInt64Key("Upsilon")] = '\x03a5', [ToUInt64Key("Phi")] = '\x03a6', [ToUInt64Key("Chi")] = '\x03a7', [ToUInt64Key("Psi")] = '\x03a8', [ToUInt64Key("Omega")] = '\x03a9', [ToUInt64Key("alpha")] = '\x03b1', [ToUInt64Key("beta")] = '\x03b2', [ToUInt64Key("gamma")] = '\x03b3', [ToUInt64Key("delta")] = '\x03b4', [ToUInt64Key("epsilon")] = '\x03b5', [ToUInt64Key("zeta")] = '\x03b6', [ToUInt64Key("eta")] = '\x03b7', [ToUInt64Key("theta")] = '\x03b8', [ToUInt64Key("iota")] = '\x03b9', [ToUInt64Key("kappa")] = '\x03ba', [ToUInt64Key("lambda")] = '\x03bb', [ToUInt64Key("mu")] = '\x03bc', [ToUInt64Key("nu")] = '\x03bd', [ToUInt64Key("xi")] = '\x03be', [ToUInt64Key("omicron")] = '\x03bf', [ToUInt64Key("pi")] = '\x03c0', [ToUInt64Key("rho")] = '\x03c1', [ToUInt64Key("sigmaf")] = '\x03c2', [ToUInt64Key("sigma")] = '\x03c3', [ToUInt64Key("tau")] = '\x03c4', [ToUInt64Key("upsilon")] = '\x03c5', [ToUInt64Key("phi")] = '\x03c6', [ToUInt64Key("chi")] = '\x03c7', [ToUInt64Key("psi")] = '\x03c8', [ToUInt64Key("omega")] = '\x03c9', [ToUInt64Key("thetasym")] = '\x03d1', [ToUInt64Key("upsih")] = '\x03d2', [ToUInt64Key("piv")] = '\x03d6', [ToUInt64Key("ensp")] = '\x2002', [ToUInt64Key("emsp")] = '\x2003', [ToUInt64Key("thinsp")] = '\x2009', [ToUInt64Key("zwnj")] = '\x200c', [ToUInt64Key("zwj")] = '\x200d', [ToUInt64Key("lrm")] = '\x200e', [ToUInt64Key("rlm")] = '\x200f', [ToUInt64Key("ndash")] = '\x2013', [ToUInt64Key("mdash")] = '\x2014', [ToUInt64Key("lsquo")] = '\x2018', [ToUInt64Key("rsquo")] = '\x2019', [ToUInt64Key("sbquo")] = '\x201a', [ToUInt64Key("ldquo")] = '\x201c', [ToUInt64Key("rdquo")] = '\x201d', [ToUInt64Key("bdquo")] = '\x201e', [ToUInt64Key("dagger")] = '\x2020', [ToUInt64Key("Dagger")] = '\x2021', [ToUInt64Key("bull")] = '\x2022', [ToUInt64Key("hellip")] = '\x2026', [ToUInt64Key("permil")] = '\x2030', [ToUInt64Key("prime")] = '\x2032', [ToUInt64Key("Prime")] = '\x2033', [ToUInt64Key("lsaquo")] = '\x2039', [ToUInt64Key("rsaquo")] = '\x203a', [ToUInt64Key("oline")] = '\x203e', [ToUInt64Key("frasl")] = '\x2044', [ToUInt64Key("euro")] = '\x20ac', [ToUInt64Key("image")] = '\x2111', [ToUInt64Key("weierp")] = '\x2118', [ToUInt64Key("real")] = '\x211c', [ToUInt64Key("trade")] = '\x2122', [ToUInt64Key("alefsym")] = '\x2135', [ToUInt64Key("larr")] = '\x2190', [ToUInt64Key("uarr")] = '\x2191', [ToUInt64Key("rarr")] = '\x2192', [ToUInt64Key("darr")] = '\x2193', [ToUInt64Key("harr")] = '\x2194', [ToUInt64Key("crarr")] = '\x21b5', [ToUInt64Key("lArr")] = '\x21d0', [ToUInt64Key("uArr")] = '\x21d1', [ToUInt64Key("rArr")] = '\x21d2', [ToUInt64Key("dArr")] = '\x21d3', [ToUInt64Key("hArr")] = '\x21d4', [ToUInt64Key("forall")] = '\x2200', [ToUInt64Key("part")] = '\x2202', [ToUInt64Key("exist")] = '\x2203', [ToUInt64Key("empty")] = '\x2205', [ToUInt64Key("nabla")] = '\x2207', [ToUInt64Key("isin")] = '\x2208', [ToUInt64Key("notin")] = '\x2209', [ToUInt64Key("ni")] = '\x220b', [ToUInt64Key("prod")] = '\x220f', [ToUInt64Key("sum")] = '\x2211', [ToUInt64Key("minus")] = '\x2212', [ToUInt64Key("lowast")] = '\x2217', [ToUInt64Key("radic")] = '\x221a', [ToUInt64Key("prop")] = '\x221d', [ToUInt64Key("infin")] = '\x221e', [ToUInt64Key("ang")] = '\x2220', [ToUInt64Key("and")] = '\x2227', [ToUInt64Key("or")] = '\x2228', [ToUInt64Key("cap")] = '\x2229', [ToUInt64Key("cup")] = '\x222a', [ToUInt64Key("int")] = '\x222b', [ToUInt64Key("there4")] = '\x2234', [ToUInt64Key("sim")] = '\x223c', [ToUInt64Key("cong")] = '\x2245', [ToUInt64Key("asymp")] = '\x2248', [ToUInt64Key("ne")] = '\x2260', [ToUInt64Key("equiv")] = '\x2261', [ToUInt64Key("le")] = '\x2264', [ToUInt64Key("ge")] = '\x2265', [ToUInt64Key("sub")] = '\x2282', [ToUInt64Key("sup")] = '\x2283', [ToUInt64Key("nsub")] = '\x2284', [ToUInt64Key("sube")] = '\x2286', [ToUInt64Key("supe")] = '\x2287', [ToUInt64Key("oplus")] = '\x2295', [ToUInt64Key("otimes")] = '\x2297', [ToUInt64Key("perp")] = '\x22a5', [ToUInt64Key("sdot")] = '\x22c5', [ToUInt64Key("lceil")] = '\x2308', [ToUInt64Key("rceil")] = '\x2309', [ToUInt64Key("lfloor")] = '\x230a', [ToUInt64Key("rfloor")] = '\x230b', [ToUInt64Key("lang")] = '\x2329', [ToUInt64Key("rang")] = '\x232a', [ToUInt64Key("loz")] = '\x25ca', [ToUInt64Key("spades")] = '\x2660', [ToUInt64Key("clubs")] = '\x2663', [ToUInt64Key("hearts")] = '\x2665', [ToUInt64Key("diams")] = '\x2666', }; public static char Lookup(ReadOnlySpan<char> entity) { // To avoid an allocation, keys of type "ulong" are used in the lookup table. // Since all entity strings comprise 8 characters or less and are ASCII-only, they "fit" into an ulong (8 bytes). if (entity.Length <= 8) { s_lookupTable.TryGetValue(ToUInt64Key(entity), out char result); return result; } else { // Currently, there are no entities that are longer than 8 characters. return (char)0; } } private static ulong ToUInt64Key(ReadOnlySpan<char> entity) { // The ulong key is the reversed single-byte character representation of the actual entity string. Debug.Assert(entity.Length <= 8); ulong key = 0; for (int i = 0; i < entity.Length; i++) { if (entity[i] > 0xFF) { return 0; } key = (key << 8) | entity[i]; } return key; } } } }
using ClosedXML.Excel.Drawings; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using Vml = DocumentFormat.OpenXml.Vml; using X14 = DocumentFormat.OpenXml.Office2010.Excel; using Xdr = DocumentFormat.OpenXml.Drawing.Spreadsheet; namespace ClosedXML.Excel { internal static class EnumConverter { #region To OpenXml public static UnderlineValues ToOpenXml(this XLFontUnderlineValues value) { switch (value) { case XLFontUnderlineValues.Double: return UnderlineValues.Double; case XLFontUnderlineValues.DoubleAccounting: return UnderlineValues.DoubleAccounting; case XLFontUnderlineValues.None: return UnderlineValues.None; case XLFontUnderlineValues.Single: return UnderlineValues.Single; case XLFontUnderlineValues.SingleAccounting: return UnderlineValues.SingleAccounting; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static OrientationValues ToOpenXml(this XLPageOrientation value) { switch (value) { case XLPageOrientation.Default: return OrientationValues.Default; case XLPageOrientation.Landscape: return OrientationValues.Landscape; case XLPageOrientation.Portrait: return OrientationValues.Portrait; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static VerticalAlignmentRunValues ToOpenXml(this XLFontVerticalTextAlignmentValues value) { switch (value) { case XLFontVerticalTextAlignmentValues.Baseline: return VerticalAlignmentRunValues.Baseline; case XLFontVerticalTextAlignmentValues.Subscript: return VerticalAlignmentRunValues.Subscript; case XLFontVerticalTextAlignmentValues.Superscript: return VerticalAlignmentRunValues.Superscript; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static PatternValues ToOpenXml(this XLFillPatternValues value) { switch (value) { case XLFillPatternValues.DarkDown: return PatternValues.DarkDown; case XLFillPatternValues.DarkGray: return PatternValues.DarkGray; case XLFillPatternValues.DarkGrid: return PatternValues.DarkGrid; case XLFillPatternValues.DarkHorizontal: return PatternValues.DarkHorizontal; case XLFillPatternValues.DarkTrellis: return PatternValues.DarkTrellis; case XLFillPatternValues.DarkUp: return PatternValues.DarkUp; case XLFillPatternValues.DarkVertical: return PatternValues.DarkVertical; case XLFillPatternValues.Gray0625: return PatternValues.Gray0625; case XLFillPatternValues.Gray125: return PatternValues.Gray125; case XLFillPatternValues.LightDown: return PatternValues.LightDown; case XLFillPatternValues.LightGray: return PatternValues.LightGray; case XLFillPatternValues.LightGrid: return PatternValues.LightGrid; case XLFillPatternValues.LightHorizontal: return PatternValues.LightHorizontal; case XLFillPatternValues.LightTrellis: return PatternValues.LightTrellis; case XLFillPatternValues.LightUp: return PatternValues.LightUp; case XLFillPatternValues.LightVertical: return PatternValues.LightVertical; case XLFillPatternValues.MediumGray: return PatternValues.MediumGray; case XLFillPatternValues.None: return PatternValues.None; case XLFillPatternValues.Solid: return PatternValues.Solid; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static BorderStyleValues ToOpenXml(this XLBorderStyleValues value) { switch (value) { case XLBorderStyleValues.DashDot: return BorderStyleValues.DashDot; case XLBorderStyleValues.DashDotDot: return BorderStyleValues.DashDotDot; case XLBorderStyleValues.Dashed: return BorderStyleValues.Dashed; case XLBorderStyleValues.Dotted: return BorderStyleValues.Dotted; case XLBorderStyleValues.Double: return BorderStyleValues.Double; case XLBorderStyleValues.Hair: return BorderStyleValues.Hair; case XLBorderStyleValues.Medium: return BorderStyleValues.Medium; case XLBorderStyleValues.MediumDashDot: return BorderStyleValues.MediumDashDot; case XLBorderStyleValues.MediumDashDotDot: return BorderStyleValues.MediumDashDotDot; case XLBorderStyleValues.MediumDashed: return BorderStyleValues.MediumDashed; case XLBorderStyleValues.None: return BorderStyleValues.None; case XLBorderStyleValues.SlantDashDot: return BorderStyleValues.SlantDashDot; case XLBorderStyleValues.Thick: return BorderStyleValues.Thick; case XLBorderStyleValues.Thin: return BorderStyleValues.Thin; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static HorizontalAlignmentValues ToOpenXml(this XLAlignmentHorizontalValues value) { switch (value) { case XLAlignmentHorizontalValues.Center: return HorizontalAlignmentValues.Center; case XLAlignmentHorizontalValues.CenterContinuous: return HorizontalAlignmentValues.CenterContinuous; case XLAlignmentHorizontalValues.Distributed: return HorizontalAlignmentValues.Distributed; case XLAlignmentHorizontalValues.Fill: return HorizontalAlignmentValues.Fill; case XLAlignmentHorizontalValues.General: return HorizontalAlignmentValues.General; case XLAlignmentHorizontalValues.Justify: return HorizontalAlignmentValues.Justify; case XLAlignmentHorizontalValues.Left: return HorizontalAlignmentValues.Left; case XLAlignmentHorizontalValues.Right: return HorizontalAlignmentValues.Right; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static VerticalAlignmentValues ToOpenXml(this XLAlignmentVerticalValues value) { switch (value) { case XLAlignmentVerticalValues.Bottom: return VerticalAlignmentValues.Bottom; case XLAlignmentVerticalValues.Center: return VerticalAlignmentValues.Center; case XLAlignmentVerticalValues.Distributed: return VerticalAlignmentValues.Distributed; case XLAlignmentVerticalValues.Justify: return VerticalAlignmentValues.Justify; case XLAlignmentVerticalValues.Top: return VerticalAlignmentValues.Top; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static PageOrderValues ToOpenXml(this XLPageOrderValues value) { switch (value) { case XLPageOrderValues.DownThenOver: return PageOrderValues.DownThenOver; case XLPageOrderValues.OverThenDown: return PageOrderValues.OverThenDown; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static CellCommentsValues ToOpenXml(this XLShowCommentsValues value) { switch (value) { case XLShowCommentsValues.AsDisplayed: return CellCommentsValues.AsDisplayed; case XLShowCommentsValues.AtEnd: return CellCommentsValues.AtEnd; case XLShowCommentsValues.None: return CellCommentsValues.None; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static PrintErrorValues ToOpenXml(this XLPrintErrorValues value) { switch (value) { case XLPrintErrorValues.Blank: return PrintErrorValues.Blank; case XLPrintErrorValues.Dash: return PrintErrorValues.Dash; case XLPrintErrorValues.Displayed: return PrintErrorValues.Displayed; case XLPrintErrorValues.NA: return PrintErrorValues.NA; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static CalculateModeValues ToOpenXml(this XLCalculateMode value) { switch (value) { case XLCalculateMode.Auto: return CalculateModeValues.Auto; case XLCalculateMode.AutoNoTable: return CalculateModeValues.AutoNoTable; case XLCalculateMode.Manual: return CalculateModeValues.Manual; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static ReferenceModeValues ToOpenXml(this XLReferenceStyle value) { switch (value) { case XLReferenceStyle.R1C1: return ReferenceModeValues.R1C1; case XLReferenceStyle.A1: return ReferenceModeValues.A1; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static uint ToOpenXml(this XLAlignmentReadingOrderValues value) { switch (value) { case XLAlignmentReadingOrderValues.ContextDependent: return 0; case XLAlignmentReadingOrderValues.LeftToRight: return 1; case XLAlignmentReadingOrderValues.RightToLeft: return 2; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static TotalsRowFunctionValues ToOpenXml(this XLTotalsRowFunction value) { switch (value) { case XLTotalsRowFunction.None: return TotalsRowFunctionValues.None; case XLTotalsRowFunction.Sum: return TotalsRowFunctionValues.Sum; case XLTotalsRowFunction.Minimum: return TotalsRowFunctionValues.Minimum; case XLTotalsRowFunction.Maximum: return TotalsRowFunctionValues.Maximum; case XLTotalsRowFunction.Average: return TotalsRowFunctionValues.Average; case XLTotalsRowFunction.Count: return TotalsRowFunctionValues.Count; case XLTotalsRowFunction.CountNumbers: return TotalsRowFunctionValues.CountNumbers; case XLTotalsRowFunction.StandardDeviation: return TotalsRowFunctionValues.StandardDeviation; case XLTotalsRowFunction.Variance: return TotalsRowFunctionValues.Variance; case XLTotalsRowFunction.Custom: return TotalsRowFunctionValues.Custom; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static DataValidationValues ToOpenXml(this XLAllowedValues value) { switch (value) { case XLAllowedValues.AnyValue: return DataValidationValues.None; case XLAllowedValues.Custom: return DataValidationValues.Custom; case XLAllowedValues.Date: return DataValidationValues.Date; case XLAllowedValues.Decimal: return DataValidationValues.Decimal; case XLAllowedValues.List: return DataValidationValues.List; case XLAllowedValues.TextLength: return DataValidationValues.TextLength; case XLAllowedValues.Time: return DataValidationValues.Time; case XLAllowedValues.WholeNumber: return DataValidationValues.Whole; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static DataValidationErrorStyleValues ToOpenXml(this XLErrorStyle value) { switch (value) { case XLErrorStyle.Information: return DataValidationErrorStyleValues.Information; case XLErrorStyle.Warning: return DataValidationErrorStyleValues.Warning; case XLErrorStyle.Stop: return DataValidationErrorStyleValues.Stop; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static DataValidationOperatorValues ToOpenXml(this XLOperator value) { switch (value) { case XLOperator.Between: return DataValidationOperatorValues.Between; case XLOperator.EqualOrGreaterThan: return DataValidationOperatorValues.GreaterThanOrEqual; case XLOperator.EqualOrLessThan: return DataValidationOperatorValues.LessThanOrEqual; case XLOperator.EqualTo: return DataValidationOperatorValues.Equal; case XLOperator.GreaterThan: return DataValidationOperatorValues.GreaterThan; case XLOperator.LessThan: return DataValidationOperatorValues.LessThan; case XLOperator.NotBetween: return DataValidationOperatorValues.NotBetween; case XLOperator.NotEqualTo: return DataValidationOperatorValues.NotEqual; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static SheetStateValues ToOpenXml(this XLWorksheetVisibility value) { switch (value) { case XLWorksheetVisibility.Visible: return SheetStateValues.Visible; case XLWorksheetVisibility.Hidden: return SheetStateValues.Hidden; case XLWorksheetVisibility.VeryHidden: return SheetStateValues.VeryHidden; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static PhoneticAlignmentValues ToOpenXml(this XLPhoneticAlignment value) { switch (value) { case XLPhoneticAlignment.Center: return PhoneticAlignmentValues.Center; case XLPhoneticAlignment.Distributed: return PhoneticAlignmentValues.Distributed; case XLPhoneticAlignment.Left: return PhoneticAlignmentValues.Left; case XLPhoneticAlignment.NoControl: return PhoneticAlignmentValues.NoControl; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static PhoneticValues ToOpenXml(this XLPhoneticType value) { switch (value) { case XLPhoneticType.FullWidthKatakana: return PhoneticValues.FullWidthKatakana; case XLPhoneticType.HalfWidthKatakana: return PhoneticValues.HalfWidthKatakana; case XLPhoneticType.Hiragana: return PhoneticValues.Hiragana; case XLPhoneticType.NoConversion: return PhoneticValues.NoConversion; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static DataConsolidateFunctionValues ToOpenXml(this XLPivotSummary value) { switch (value) { case XLPivotSummary.Sum: return DataConsolidateFunctionValues.Sum; case XLPivotSummary.Count: return DataConsolidateFunctionValues.Count; case XLPivotSummary.Average: return DataConsolidateFunctionValues.Average; case XLPivotSummary.Minimum: return DataConsolidateFunctionValues.Minimum; case XLPivotSummary.Maximum: return DataConsolidateFunctionValues.Maximum; case XLPivotSummary.Product: return DataConsolidateFunctionValues.Product; case XLPivotSummary.CountNumbers: return DataConsolidateFunctionValues.CountNumbers; case XLPivotSummary.StandardDeviation: return DataConsolidateFunctionValues.StandardDeviation; case XLPivotSummary.PopulationStandardDeviation: return DataConsolidateFunctionValues.StandardDeviationP; case XLPivotSummary.Variance: return DataConsolidateFunctionValues.Variance; case XLPivotSummary.PopulationVariance: return DataConsolidateFunctionValues.VarianceP; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static ShowDataAsValues ToOpenXml(this XLPivotCalculation value) { switch (value) { case XLPivotCalculation.Normal: return ShowDataAsValues.Normal; case XLPivotCalculation.DifferenceFrom: return ShowDataAsValues.Difference; case XLPivotCalculation.PercentageOf: return ShowDataAsValues.Percent; case XLPivotCalculation.PercentageDifferenceFrom: return ShowDataAsValues.PercentageDifference; case XLPivotCalculation.RunningTotal: return ShowDataAsValues.RunTotal; case XLPivotCalculation.PercentageOfRow: return ShowDataAsValues.PercentOfRaw; // There's a typo in the OpenXML SDK =) case XLPivotCalculation.PercentageOfColumn: return ShowDataAsValues.PercentOfColumn; case XLPivotCalculation.PercentageOfTotal: return ShowDataAsValues.PercentOfTotal; case XLPivotCalculation.Index: return ShowDataAsValues.Index; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static FilterOperatorValues ToOpenXml(this XLFilterOperator value) { switch (value) { case XLFilterOperator.Equal: return FilterOperatorValues.Equal; case XLFilterOperator.NotEqual: return FilterOperatorValues.NotEqual; case XLFilterOperator.GreaterThan: return FilterOperatorValues.GreaterThan; case XLFilterOperator.EqualOrGreaterThan: return FilterOperatorValues.GreaterThanOrEqual; case XLFilterOperator.LessThan: return FilterOperatorValues.LessThan; case XLFilterOperator.EqualOrLessThan: return FilterOperatorValues.LessThanOrEqual; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static DynamicFilterValues ToOpenXml(this XLFilterDynamicType value) { switch (value) { case XLFilterDynamicType.AboveAverage: return DynamicFilterValues.AboveAverage; case XLFilterDynamicType.BelowAverage: return DynamicFilterValues.BelowAverage; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static DateTimeGroupingValues ToOpenXml(this XLDateTimeGrouping value) { switch (value) { case XLDateTimeGrouping.Year: return DateTimeGroupingValues.Year; case XLDateTimeGrouping.Month: return DateTimeGroupingValues.Month; case XLDateTimeGrouping.Day: return DateTimeGroupingValues.Day; case XLDateTimeGrouping.Hour: return DateTimeGroupingValues.Hour; case XLDateTimeGrouping.Minute: return DateTimeGroupingValues.Minute; case XLDateTimeGrouping.Second: return DateTimeGroupingValues.Second; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static SheetViewValues ToOpenXml(this XLSheetViewOptions value) { switch (value) { case XLSheetViewOptions.Normal: return SheetViewValues.Normal; case XLSheetViewOptions.PageBreakPreview: return SheetViewValues.PageBreakPreview; case XLSheetViewOptions.PageLayout: return SheetViewValues.PageLayout; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static Vml.StrokeLineStyleValues ToOpenXml(this XLLineStyle value) { switch (value) { case XLLineStyle.Single: return Vml.StrokeLineStyleValues.Single; case XLLineStyle.ThickBetweenThin: return Vml.StrokeLineStyleValues.ThickBetweenThin; case XLLineStyle.ThickThin: return Vml.StrokeLineStyleValues.ThickThin; case XLLineStyle.ThinThick: return Vml.StrokeLineStyleValues.ThinThick; case XLLineStyle.ThinThin: return Vml.StrokeLineStyleValues.ThinThin; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static ConditionalFormatValues ToOpenXml(this XLConditionalFormatType value) { switch (value) { case XLConditionalFormatType.Expression: return ConditionalFormatValues.Expression; case XLConditionalFormatType.CellIs: return ConditionalFormatValues.CellIs; case XLConditionalFormatType.ColorScale: return ConditionalFormatValues.ColorScale; case XLConditionalFormatType.DataBar: return ConditionalFormatValues.DataBar; case XLConditionalFormatType.IconSet: return ConditionalFormatValues.IconSet; case XLConditionalFormatType.Top10: return ConditionalFormatValues.Top10; case XLConditionalFormatType.IsUnique: return ConditionalFormatValues.UniqueValues; case XLConditionalFormatType.IsDuplicate: return ConditionalFormatValues.DuplicateValues; case XLConditionalFormatType.ContainsText: return ConditionalFormatValues.ContainsText; case XLConditionalFormatType.NotContainsText: return ConditionalFormatValues.NotContainsText; case XLConditionalFormatType.StartsWith: return ConditionalFormatValues.BeginsWith; case XLConditionalFormatType.EndsWith: return ConditionalFormatValues.EndsWith; case XLConditionalFormatType.IsBlank: return ConditionalFormatValues.ContainsBlanks; case XLConditionalFormatType.NotBlank: return ConditionalFormatValues.NotContainsBlanks; case XLConditionalFormatType.IsError: return ConditionalFormatValues.ContainsErrors; case XLConditionalFormatType.NotError: return ConditionalFormatValues.NotContainsErrors; case XLConditionalFormatType.TimePeriod: return ConditionalFormatValues.TimePeriod; case XLConditionalFormatType.AboveAverage: return ConditionalFormatValues.AboveAverage; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static ConditionalFormatValueObjectValues ToOpenXml(this XLCFContentType value) { switch (value) { case XLCFContentType.Number: return ConditionalFormatValueObjectValues.Number; case XLCFContentType.Percent: return ConditionalFormatValueObjectValues.Percent; case XLCFContentType.Maximum: return ConditionalFormatValueObjectValues.Max; case XLCFContentType.Minimum: return ConditionalFormatValueObjectValues.Min; case XLCFContentType.Formula: return ConditionalFormatValueObjectValues.Formula; case XLCFContentType.Percentile: return ConditionalFormatValueObjectValues.Percentile; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static ConditionalFormattingOperatorValues ToOpenXml(this XLCFOperator value) { switch (value) { case XLCFOperator.LessThan: return ConditionalFormattingOperatorValues.LessThan; case XLCFOperator.EqualOrLessThan: return ConditionalFormattingOperatorValues.LessThanOrEqual; case XLCFOperator.Equal: return ConditionalFormattingOperatorValues.Equal; case XLCFOperator.NotEqual: return ConditionalFormattingOperatorValues.NotEqual; case XLCFOperator.EqualOrGreaterThan: return ConditionalFormattingOperatorValues.GreaterThanOrEqual; case XLCFOperator.GreaterThan: return ConditionalFormattingOperatorValues.GreaterThan; case XLCFOperator.Between: return ConditionalFormattingOperatorValues.Between; case XLCFOperator.NotBetween: return ConditionalFormattingOperatorValues.NotBetween; case XLCFOperator.Contains: return ConditionalFormattingOperatorValues.ContainsText; case XLCFOperator.NotContains: return ConditionalFormattingOperatorValues.NotContains; case XLCFOperator.StartsWith: return ConditionalFormattingOperatorValues.BeginsWith; case XLCFOperator.EndsWith: return ConditionalFormattingOperatorValues.EndsWith; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static IconSetValues ToOpenXml(this XLIconSetStyle value) { switch (value) { case XLIconSetStyle.ThreeArrows: return IconSetValues.ThreeArrows; case XLIconSetStyle.ThreeArrowsGray: return IconSetValues.ThreeArrowsGray; case XLIconSetStyle.ThreeFlags: return IconSetValues.ThreeFlags; case XLIconSetStyle.ThreeTrafficLights1: return IconSetValues.ThreeTrafficLights1; case XLIconSetStyle.ThreeTrafficLights2: return IconSetValues.ThreeTrafficLights2; case XLIconSetStyle.ThreeSigns: return IconSetValues.ThreeSigns; case XLIconSetStyle.ThreeSymbols: return IconSetValues.ThreeSymbols; case XLIconSetStyle.ThreeSymbols2: return IconSetValues.ThreeSymbols2; case XLIconSetStyle.FourArrows: return IconSetValues.FourArrows; case XLIconSetStyle.FourArrowsGray: return IconSetValues.FourArrowsGray; case XLIconSetStyle.FourRedToBlack: return IconSetValues.FourRedToBlack; case XLIconSetStyle.FourRating: return IconSetValues.FourRating; case XLIconSetStyle.FourTrafficLights: return IconSetValues.FourTrafficLights; case XLIconSetStyle.FiveArrows: return IconSetValues.FiveArrows; case XLIconSetStyle.FiveArrowsGray: return IconSetValues.FiveArrowsGray; case XLIconSetStyle.FiveRating: return IconSetValues.FiveRating; case XLIconSetStyle.FiveQuarters: return IconSetValues.FiveQuarters; default: throw new ArgumentOutOfRangeException("Not implemented value!"); } } public static TimePeriodValues ToOpenXml(this XLTimePeriod value) { switch (value) { case XLTimePeriod.Yesterday: return TimePeriodValues.Yesterday; case XLTimePeriod.Today: return TimePeriodValues.Today; case XLTimePeriod.Tomorrow: return TimePeriodValues.Tomorrow; case XLTimePeriod.InTheLast7Days: return TimePeriodValues.Last7Days; case XLTimePeriod.LastWeek: return TimePeriodValues.LastWeek; case XLTimePeriod.ThisWeek: return TimePeriodValues.ThisWeek; case XLTimePeriod.NextWeek: return TimePeriodValues.NextWeek; case XLTimePeriod.LastMonth: return TimePeriodValues.LastMonth; case XLTimePeriod.ThisMonth: return TimePeriodValues.ThisMonth; case XLTimePeriod.NextMonth: return TimePeriodValues.NextMonth; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static ImagePartType ToOpenXml(this XLPictureFormat value) { return Enum.Parse(typeof(ImagePartType), value.ToString()).CastTo<ImagePartType>(); } public static Xdr.EditAsValues ToOpenXml(this XLPicturePlacement value) { switch (value) { case XLPicturePlacement.FreeFloating: return Xdr.EditAsValues.Absolute; case XLPicturePlacement.Move: return Xdr.EditAsValues.OneCell; case XLPicturePlacement.MoveAndSize: return Xdr.EditAsValues.TwoCell; default: throw new ArgumentOutOfRangeException("Not implemented value!"); } } public static PivotAreaValues ToOpenXml(this XLPivotAreaValues value) { switch (value) { case XLPivotAreaValues.None: return PivotAreaValues.None; case XLPivotAreaValues.Normal: return PivotAreaValues.Normal; case XLPivotAreaValues.Data: return PivotAreaValues.Data; case XLPivotAreaValues.All: return PivotAreaValues.All; case XLPivotAreaValues.Origin: return PivotAreaValues.Origin; case XLPivotAreaValues.Button: return PivotAreaValues.Button; case XLPivotAreaValues.TopRight: return PivotAreaValues.TopRight; case XLPivotAreaValues.TopEnd: return PivotAreaValues.TopEnd; default: throw new ArgumentOutOfRangeException(nameof(value), "XLPivotAreaValues value not implemented"); } } public static X14.SparklineTypeValues ToOpenXml(this XLSparklineType value) { switch (value) { case XLSparklineType.Line: return X14.SparklineTypeValues.Line; case XLSparklineType.Column: return X14.SparklineTypeValues.Column; case XLSparklineType.Stacked: return X14.SparklineTypeValues.Stacked; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static X14.SparklineAxisMinMaxValues ToOpenXml(this XLSparklineAxisMinMax value) { switch (value) { case XLSparklineAxisMinMax.Automatic: return X14.SparklineAxisMinMaxValues.Individual; case XLSparklineAxisMinMax.SameForAll: return X14.SparklineAxisMinMaxValues.Group; case XLSparklineAxisMinMax.Custom: return X14.SparklineAxisMinMaxValues.Custom; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static X14.DisplayBlanksAsValues ToOpenXml(this XLDisplayBlanksAsValues value) { switch (value) { case XLDisplayBlanksAsValues.Interpolate: return X14.DisplayBlanksAsValues.Span; case XLDisplayBlanksAsValues.NotPlotted: return X14.DisplayBlanksAsValues.Gap; case XLDisplayBlanksAsValues.Zero: return X14.DisplayBlanksAsValues.Zero; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } #endregion To OpenXml #region To ClosedXml public static XLFontUnderlineValues ToClosedXml(this UnderlineValues value) { switch (value) { case UnderlineValues.Double: return XLFontUnderlineValues.Double; case UnderlineValues.DoubleAccounting: return XLFontUnderlineValues.DoubleAccounting; case UnderlineValues.None: return XLFontUnderlineValues.None; case UnderlineValues.Single: return XLFontUnderlineValues.Single; case UnderlineValues.SingleAccounting: return XLFontUnderlineValues.SingleAccounting; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLPageOrientation ToClosedXml(this OrientationValues value) { switch (value) { case OrientationValues.Default: return XLPageOrientation.Default; case OrientationValues.Landscape: return XLPageOrientation.Landscape; case OrientationValues.Portrait: return XLPageOrientation.Portrait; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLFontVerticalTextAlignmentValues ToClosedXml(this VerticalAlignmentRunValues value) { switch (value) { case VerticalAlignmentRunValues.Baseline: return XLFontVerticalTextAlignmentValues.Baseline; case VerticalAlignmentRunValues.Subscript: return XLFontVerticalTextAlignmentValues.Subscript; case VerticalAlignmentRunValues.Superscript: return XLFontVerticalTextAlignmentValues.Superscript; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLFillPatternValues ToClosedXml(this PatternValues value) { switch (value) { case PatternValues.DarkDown: return XLFillPatternValues.DarkDown; case PatternValues.DarkGray: return XLFillPatternValues.DarkGray; case PatternValues.DarkGrid: return XLFillPatternValues.DarkGrid; case PatternValues.DarkHorizontal: return XLFillPatternValues.DarkHorizontal; case PatternValues.DarkTrellis: return XLFillPatternValues.DarkTrellis; case PatternValues.DarkUp: return XLFillPatternValues.DarkUp; case PatternValues.DarkVertical: return XLFillPatternValues.DarkVertical; case PatternValues.Gray0625: return XLFillPatternValues.Gray0625; case PatternValues.Gray125: return XLFillPatternValues.Gray125; case PatternValues.LightDown: return XLFillPatternValues.LightDown; case PatternValues.LightGray: return XLFillPatternValues.LightGray; case PatternValues.LightGrid: return XLFillPatternValues.LightGrid; case PatternValues.LightHorizontal: return XLFillPatternValues.LightHorizontal; case PatternValues.LightTrellis: return XLFillPatternValues.LightTrellis; case PatternValues.LightUp: return XLFillPatternValues.LightUp; case PatternValues.LightVertical: return XLFillPatternValues.LightVertical; case PatternValues.MediumGray: return XLFillPatternValues.MediumGray; case PatternValues.None: return XLFillPatternValues.None; case PatternValues.Solid: return XLFillPatternValues.Solid; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLBorderStyleValues ToClosedXml(this BorderStyleValues value) { switch (value) { case BorderStyleValues.DashDot: return XLBorderStyleValues.DashDot; case BorderStyleValues.DashDotDot: return XLBorderStyleValues.DashDotDot; case BorderStyleValues.Dashed: return XLBorderStyleValues.Dashed; case BorderStyleValues.Dotted: return XLBorderStyleValues.Dotted; case BorderStyleValues.Double: return XLBorderStyleValues.Double; case BorderStyleValues.Hair: return XLBorderStyleValues.Hair; case BorderStyleValues.Medium: return XLBorderStyleValues.Medium; case BorderStyleValues.MediumDashDot: return XLBorderStyleValues.MediumDashDot; case BorderStyleValues.MediumDashDotDot: return XLBorderStyleValues.MediumDashDotDot; case BorderStyleValues.MediumDashed: return XLBorderStyleValues.MediumDashed; case BorderStyleValues.None: return XLBorderStyleValues.None; case BorderStyleValues.SlantDashDot: return XLBorderStyleValues.SlantDashDot; case BorderStyleValues.Thick: return XLBorderStyleValues.Thick; case BorderStyleValues.Thin: return XLBorderStyleValues.Thin; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLAlignmentHorizontalValues ToClosedXml(this HorizontalAlignmentValues value) { switch (value) { case HorizontalAlignmentValues.Center: return XLAlignmentHorizontalValues.Center; case HorizontalAlignmentValues.CenterContinuous: return XLAlignmentHorizontalValues.CenterContinuous; case HorizontalAlignmentValues.Distributed: return XLAlignmentHorizontalValues.Distributed; case HorizontalAlignmentValues.Fill: return XLAlignmentHorizontalValues.Fill; case HorizontalAlignmentValues.General: return XLAlignmentHorizontalValues.General; case HorizontalAlignmentValues.Justify: return XLAlignmentHorizontalValues.Justify; case HorizontalAlignmentValues.Left: return XLAlignmentHorizontalValues.Left; case HorizontalAlignmentValues.Right: return XLAlignmentHorizontalValues.Right; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLAlignmentVerticalValues ToClosedXml(this VerticalAlignmentValues value) { switch (value) { case VerticalAlignmentValues.Bottom: return XLAlignmentVerticalValues.Bottom; case VerticalAlignmentValues.Center: return XLAlignmentVerticalValues.Center; case VerticalAlignmentValues.Distributed: return XLAlignmentVerticalValues.Distributed; case VerticalAlignmentValues.Justify: return XLAlignmentVerticalValues.Justify; case VerticalAlignmentValues.Top: return XLAlignmentVerticalValues.Top; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLPageOrderValues ToClosedXml(this PageOrderValues value) { switch (value) { case PageOrderValues.DownThenOver: return XLPageOrderValues.DownThenOver; case PageOrderValues.OverThenDown: return XLPageOrderValues.OverThenDown; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLShowCommentsValues ToClosedXml(this CellCommentsValues value) { switch (value) { case CellCommentsValues.AsDisplayed: return XLShowCommentsValues.AsDisplayed; case CellCommentsValues.AtEnd: return XLShowCommentsValues.AtEnd; case CellCommentsValues.None: return XLShowCommentsValues.None; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLPrintErrorValues ToClosedXml(this PrintErrorValues value) { switch (value) { case PrintErrorValues.Blank: return XLPrintErrorValues.Blank; case PrintErrorValues.Dash: return XLPrintErrorValues.Dash; case PrintErrorValues.Displayed: return XLPrintErrorValues.Displayed; case PrintErrorValues.NA: return XLPrintErrorValues.NA; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLCalculateMode ToClosedXml(this CalculateModeValues value) { switch (value) { case CalculateModeValues.Auto: return XLCalculateMode.Auto; case CalculateModeValues.AutoNoTable: return XLCalculateMode.AutoNoTable; case CalculateModeValues.Manual: return XLCalculateMode.Manual; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLReferenceStyle ToClosedXml(this ReferenceModeValues value) { switch (value) { case ReferenceModeValues.R1C1: return XLReferenceStyle.R1C1; case ReferenceModeValues.A1: return XLReferenceStyle.A1; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLAlignmentReadingOrderValues ToClosedXml(this uint value) { switch (value) { case 0: return XLAlignmentReadingOrderValues.ContextDependent; case 1: return XLAlignmentReadingOrderValues.LeftToRight; case 2: return XLAlignmentReadingOrderValues.RightToLeft; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLTotalsRowFunction ToClosedXml(this TotalsRowFunctionValues value) { switch (value) { case TotalsRowFunctionValues.None: return XLTotalsRowFunction.None; case TotalsRowFunctionValues.Sum: return XLTotalsRowFunction.Sum; case TotalsRowFunctionValues.Minimum: return XLTotalsRowFunction.Minimum; case TotalsRowFunctionValues.Maximum: return XLTotalsRowFunction.Maximum; case TotalsRowFunctionValues.Average: return XLTotalsRowFunction.Average; case TotalsRowFunctionValues.Count: return XLTotalsRowFunction.Count; case TotalsRowFunctionValues.CountNumbers: return XLTotalsRowFunction.CountNumbers; case TotalsRowFunctionValues.StandardDeviation: return XLTotalsRowFunction.StandardDeviation; case TotalsRowFunctionValues.Variance: return XLTotalsRowFunction.Variance; case TotalsRowFunctionValues.Custom: return XLTotalsRowFunction.Custom; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLAllowedValues ToClosedXml(this DataValidationValues value) { switch (value) { case DataValidationValues.None: return XLAllowedValues.AnyValue; case DataValidationValues.Custom: return XLAllowedValues.Custom; case DataValidationValues.Date: return XLAllowedValues.Date; case DataValidationValues.Decimal: return XLAllowedValues.Decimal; case DataValidationValues.List: return XLAllowedValues.List; case DataValidationValues.TextLength: return XLAllowedValues.TextLength; case DataValidationValues.Time: return XLAllowedValues.Time; case DataValidationValues.Whole: return XLAllowedValues.WholeNumber; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLErrorStyle ToClosedXml(this DataValidationErrorStyleValues value) { switch (value) { case DataValidationErrorStyleValues.Information: return XLErrorStyle.Information; case DataValidationErrorStyleValues.Warning: return XLErrorStyle.Warning; case DataValidationErrorStyleValues.Stop: return XLErrorStyle.Stop; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLOperator ToClosedXml(this DataValidationOperatorValues value) { switch (value) { case DataValidationOperatorValues.Between: return XLOperator.Between; case DataValidationOperatorValues.GreaterThanOrEqual: return XLOperator.EqualOrGreaterThan; case DataValidationOperatorValues.LessThanOrEqual: return XLOperator.EqualOrLessThan; case DataValidationOperatorValues.Equal: return XLOperator.EqualTo; case DataValidationOperatorValues.GreaterThan: return XLOperator.GreaterThan; case DataValidationOperatorValues.LessThan: return XLOperator.LessThan; case DataValidationOperatorValues.NotBetween: return XLOperator.NotBetween; case DataValidationOperatorValues.NotEqual: return XLOperator.NotEqualTo; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLWorksheetVisibility ToClosedXml(this SheetStateValues value) { switch (value) { case SheetStateValues.Visible: return XLWorksheetVisibility.Visible; case SheetStateValues.Hidden: return XLWorksheetVisibility.Hidden; case SheetStateValues.VeryHidden: return XLWorksheetVisibility.VeryHidden; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLPhoneticAlignment ToClosedXml(this PhoneticAlignmentValues value) { switch (value) { case PhoneticAlignmentValues.Center: return XLPhoneticAlignment.Center; case PhoneticAlignmentValues.Distributed: return XLPhoneticAlignment.Distributed; case PhoneticAlignmentValues.Left: return XLPhoneticAlignment.Left; case PhoneticAlignmentValues.NoControl: return XLPhoneticAlignment.NoControl; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLPhoneticType ToClosedXml(this PhoneticValues value) { switch (value) { case PhoneticValues.FullWidthKatakana: return XLPhoneticType.FullWidthKatakana; case PhoneticValues.HalfWidthKatakana: return XLPhoneticType.HalfWidthKatakana; case PhoneticValues.Hiragana: return XLPhoneticType.Hiragana; case PhoneticValues.NoConversion: return XLPhoneticType.NoConversion; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLPivotSummary ToClosedXml(this DataConsolidateFunctionValues value) { switch (value) { case DataConsolidateFunctionValues.Sum: return XLPivotSummary.Sum; case DataConsolidateFunctionValues.Count: return XLPivotSummary.Count; case DataConsolidateFunctionValues.Average: return XLPivotSummary.Average; case DataConsolidateFunctionValues.Minimum: return XLPivotSummary.Minimum; case DataConsolidateFunctionValues.Maximum: return XLPivotSummary.Maximum; case DataConsolidateFunctionValues.Product: return XLPivotSummary.Product; case DataConsolidateFunctionValues.CountNumbers: return XLPivotSummary.CountNumbers; case DataConsolidateFunctionValues.StandardDeviation: return XLPivotSummary.StandardDeviation; case DataConsolidateFunctionValues.StandardDeviationP: return XLPivotSummary.PopulationStandardDeviation; case DataConsolidateFunctionValues.Variance: return XLPivotSummary.Variance; case DataConsolidateFunctionValues.VarianceP: return XLPivotSummary.PopulationVariance; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLPivotCalculation ToClosedXml(this ShowDataAsValues value) { switch (value) { case ShowDataAsValues.Normal: return XLPivotCalculation.Normal; case ShowDataAsValues.Difference: return XLPivotCalculation.DifferenceFrom; case ShowDataAsValues.Percent: return XLPivotCalculation.PercentageOf; case ShowDataAsValues.PercentageDifference: return XLPivotCalculation.PercentageDifferenceFrom; case ShowDataAsValues.RunTotal: return XLPivotCalculation.RunningTotal; case ShowDataAsValues.PercentOfRaw: return XLPivotCalculation.PercentageOfRow; // There's a typo in the OpenXML SDK =) case ShowDataAsValues.PercentOfColumn: return XLPivotCalculation.PercentageOfColumn; case ShowDataAsValues.PercentOfTotal: return XLPivotCalculation.PercentageOfTotal; case ShowDataAsValues.Index: return XLPivotCalculation.Index; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLFilterOperator ToClosedXml(this FilterOperatorValues value) { switch (value) { case FilterOperatorValues.Equal: return XLFilterOperator.Equal; case FilterOperatorValues.NotEqual: return XLFilterOperator.NotEqual; case FilterOperatorValues.GreaterThan: return XLFilterOperator.GreaterThan; case FilterOperatorValues.LessThan: return XLFilterOperator.LessThan; case FilterOperatorValues.GreaterThanOrEqual: return XLFilterOperator.EqualOrGreaterThan; case FilterOperatorValues.LessThanOrEqual: return XLFilterOperator.EqualOrLessThan; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLFilterDynamicType ToClosedXml(this DynamicFilterValues value) { switch (value) { case DynamicFilterValues.AboveAverage: return XLFilterDynamicType.AboveAverage; case DynamicFilterValues.BelowAverage: return XLFilterDynamicType.BelowAverage; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLDateTimeGrouping ToClosedXml(this DateTimeGroupingValues value) { switch (value) { case DateTimeGroupingValues.Year: return XLDateTimeGrouping.Year; case DateTimeGroupingValues.Month: return XLDateTimeGrouping.Month; case DateTimeGroupingValues.Day: return XLDateTimeGrouping.Day; case DateTimeGroupingValues.Hour: return XLDateTimeGrouping.Hour; case DateTimeGroupingValues.Minute: return XLDateTimeGrouping.Minute; case DateTimeGroupingValues.Second: return XLDateTimeGrouping.Second; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLSheetViewOptions ToClosedXml(this SheetViewValues value) { switch (value) { case SheetViewValues.Normal: return XLSheetViewOptions.Normal; case SheetViewValues.PageBreakPreview: return XLSheetViewOptions.PageBreakPreview; case SheetViewValues.PageLayout: return XLSheetViewOptions.PageLayout; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLLineStyle ToClosedXml(this Vml.StrokeLineStyleValues value) { switch (value) { case Vml.StrokeLineStyleValues.Single: return XLLineStyle.Single; case Vml.StrokeLineStyleValues.ThickBetweenThin: return XLLineStyle.ThickBetweenThin; case Vml.StrokeLineStyleValues.ThickThin: return XLLineStyle.ThickThin; case Vml.StrokeLineStyleValues.ThinThick: return XLLineStyle.ThinThick; case Vml.StrokeLineStyleValues.ThinThin: return XLLineStyle.ThinThin; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLConditionalFormatType ToClosedXml(this ConditionalFormatValues value) { switch (value) { case ConditionalFormatValues.Expression: return XLConditionalFormatType.Expression; case ConditionalFormatValues.CellIs: return XLConditionalFormatType.CellIs; case ConditionalFormatValues.ColorScale: return XLConditionalFormatType.ColorScale; case ConditionalFormatValues.DataBar: return XLConditionalFormatType.DataBar; case ConditionalFormatValues.IconSet: return XLConditionalFormatType.IconSet; case ConditionalFormatValues.Top10: return XLConditionalFormatType.Top10; case ConditionalFormatValues.UniqueValues: return XLConditionalFormatType.IsUnique; case ConditionalFormatValues.DuplicateValues: return XLConditionalFormatType.IsDuplicate; case ConditionalFormatValues.ContainsText: return XLConditionalFormatType.ContainsText; case ConditionalFormatValues.NotContainsText: return XLConditionalFormatType.NotContainsText; case ConditionalFormatValues.BeginsWith: return XLConditionalFormatType.StartsWith; case ConditionalFormatValues.EndsWith: return XLConditionalFormatType.EndsWith; case ConditionalFormatValues.ContainsBlanks: return XLConditionalFormatType.IsBlank; case ConditionalFormatValues.NotContainsBlanks: return XLConditionalFormatType.NotBlank; case ConditionalFormatValues.ContainsErrors: return XLConditionalFormatType.IsError; case ConditionalFormatValues.NotContainsErrors: return XLConditionalFormatType.NotError; case ConditionalFormatValues.TimePeriod: return XLConditionalFormatType.TimePeriod; case ConditionalFormatValues.AboveAverage: return XLConditionalFormatType.AboveAverage; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLCFContentType ToClosedXml(this ConditionalFormatValueObjectValues value) { switch (value) { case ConditionalFormatValueObjectValues.Number: return XLCFContentType.Number; case ConditionalFormatValueObjectValues.Percent: return XLCFContentType.Percent; case ConditionalFormatValueObjectValues.Max: return XLCFContentType.Maximum; case ConditionalFormatValueObjectValues.Min: return XLCFContentType.Minimum; case ConditionalFormatValueObjectValues.Formula: return XLCFContentType.Formula; case ConditionalFormatValueObjectValues.Percentile: return XLCFContentType.Percentile; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLCFOperator ToClosedXml(this ConditionalFormattingOperatorValues value) { switch (value) { case ConditionalFormattingOperatorValues.LessThan: return XLCFOperator.LessThan; case ConditionalFormattingOperatorValues.LessThanOrEqual: return XLCFOperator.EqualOrLessThan; case ConditionalFormattingOperatorValues.Equal: return XLCFOperator.Equal; case ConditionalFormattingOperatorValues.NotEqual: return XLCFOperator.NotEqual; case ConditionalFormattingOperatorValues.GreaterThanOrEqual: return XLCFOperator.EqualOrGreaterThan; case ConditionalFormattingOperatorValues.GreaterThan: return XLCFOperator.GreaterThan; case ConditionalFormattingOperatorValues.Between: return XLCFOperator.Between; case ConditionalFormattingOperatorValues.NotBetween: return XLCFOperator.NotBetween; case ConditionalFormattingOperatorValues.ContainsText: return XLCFOperator.Contains; case ConditionalFormattingOperatorValues.NotContains: return XLCFOperator.NotContains; case ConditionalFormattingOperatorValues.BeginsWith: return XLCFOperator.StartsWith; case ConditionalFormattingOperatorValues.EndsWith: return XLCFOperator.EndsWith; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLIconSetStyle ToClosedXml(this IconSetValues value) { switch (value) { case IconSetValues.ThreeArrows: return XLIconSetStyle.ThreeArrows; case IconSetValues.ThreeArrowsGray: return XLIconSetStyle.ThreeArrowsGray; case IconSetValues.ThreeFlags: return XLIconSetStyle.ThreeFlags; case IconSetValues.ThreeTrafficLights1: return XLIconSetStyle.ThreeTrafficLights1; case IconSetValues.ThreeTrafficLights2: return XLIconSetStyle.ThreeTrafficLights2; case IconSetValues.ThreeSigns: return XLIconSetStyle.ThreeSigns; case IconSetValues.ThreeSymbols: return XLIconSetStyle.ThreeSymbols; case IconSetValues.ThreeSymbols2: return XLIconSetStyle.ThreeSymbols2; case IconSetValues.FourArrows: return XLIconSetStyle.FourArrows; case IconSetValues.FourArrowsGray: return XLIconSetStyle.FourArrowsGray; case IconSetValues.FourRedToBlack: return XLIconSetStyle.FourRedToBlack; case IconSetValues.FourRating: return XLIconSetStyle.FourRating; case IconSetValues.FourTrafficLights: return XLIconSetStyle.FourTrafficLights; case IconSetValues.FiveArrows: return XLIconSetStyle.FiveArrows; case IconSetValues.FiveArrowsGray: return XLIconSetStyle.FiveArrowsGray; case IconSetValues.FiveRating: return XLIconSetStyle.FiveRating; case IconSetValues.FiveQuarters: return XLIconSetStyle.FiveQuarters; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLTimePeriod ToClosedXml(this TimePeriodValues value) { switch (value) { case TimePeriodValues.Yesterday: return XLTimePeriod.Yesterday; case TimePeriodValues.Today: return XLTimePeriod.Today; case TimePeriodValues.Tomorrow: return XLTimePeriod.Tomorrow; case TimePeriodValues.Last7Days: return XLTimePeriod.InTheLast7Days; case TimePeriodValues.LastWeek: return XLTimePeriod.LastWeek; case TimePeriodValues.ThisWeek: return XLTimePeriod.ThisWeek; case TimePeriodValues.NextWeek: return XLTimePeriod.NextWeek; case TimePeriodValues.LastMonth: return XLTimePeriod.LastMonth; case TimePeriodValues.ThisMonth: return XLTimePeriod.ThisMonth; case TimePeriodValues.NextMonth: return XLTimePeriod.NextMonth; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLPictureFormat ToClosedXml(this ImagePartType value) { return Enum.Parse(typeof(XLPictureFormat), value.ToString()).CastTo<XLPictureFormat>(); } public static XLPicturePlacement ToClosedXml(this Xdr.EditAsValues value) { switch (value) { case Xdr.EditAsValues.Absolute: return XLPicturePlacement.FreeFloating; case Xdr.EditAsValues.OneCell: return XLPicturePlacement.Move; case Xdr.EditAsValues.TwoCell: return XLPicturePlacement.MoveAndSize; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLPivotAreaValues ToClosedXml(this PivotAreaValues value) { switch (value) { case PivotAreaValues.None: return XLPivotAreaValues.None; case PivotAreaValues.Normal: return XLPivotAreaValues.Normal; case PivotAreaValues.Data: return XLPivotAreaValues.Data; case PivotAreaValues.All: return XLPivotAreaValues.All; case PivotAreaValues.Origin: return XLPivotAreaValues.Origin; case PivotAreaValues.Button: return XLPivotAreaValues.Button; case PivotAreaValues.TopRight: return XLPivotAreaValues.TopRight; case PivotAreaValues.TopEnd: return XLPivotAreaValues.TopEnd; default: throw new ArgumentOutOfRangeException(nameof(value), "PivotAreaValues value not implemented"); } } public static XLSparklineType ToClosedXml(this X14.SparklineTypeValues value) { switch (value) { case X14.SparklineTypeValues.Line: return XLSparklineType.Line; case X14.SparklineTypeValues.Column: return XLSparklineType.Column; case X14.SparklineTypeValues.Stacked: return XLSparklineType.Stacked; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLSparklineAxisMinMax ToClosedXml(this X14.SparklineAxisMinMaxValues value) { switch (value) { case X14.SparklineAxisMinMaxValues.Individual: return XLSparklineAxisMinMax.Automatic; case X14.SparklineAxisMinMaxValues.Group: return XLSparklineAxisMinMax.SameForAll; case X14.SparklineAxisMinMaxValues.Custom: return XLSparklineAxisMinMax.Custom; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } public static XLDisplayBlanksAsValues ToClosedXml(this X14.DisplayBlanksAsValues value) { switch (value) { case X14.DisplayBlanksAsValues.Span: return XLDisplayBlanksAsValues.Interpolate; case X14.DisplayBlanksAsValues.Gap: return XLDisplayBlanksAsValues.NotPlotted; case X14.DisplayBlanksAsValues.Zero: return XLDisplayBlanksAsValues.Zero; default: throw new ArgumentOutOfRangeException(nameof(value), "Not implemented value!"); } } #endregion To ClosedXml } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MusicStore.WebAPI.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
namespace Boxed.Mapping { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; /// <summary> /// <see cref="IAsyncMapper{TSource, TDestination}"/> extension methods. /// </summary> public static class AsyncMapperExtensions { #if NETSTANDARD2_1 /// <summary> /// Maps the <see cref="IAsyncEnumerable{TSource}"/> into <see cref="IAsyncEnumerable{TDestination}"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source asynchronous enumerable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An <see cref="IAsyncEnumerable{TDestination}"/> collection.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async IAsyncEnumerable<TDestination> MapEnumerableAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, IAsyncEnumerable<TSource> source, [EnumeratorCancellation] CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } await foreach (var sourceItem in source.ConfigureAwait(false).WithCancellation(cancellationToken)) { var destinationItem = Factory<TDestination>.CreateInstance(); await mapper.MapAsync(sourceItem, destinationItem, cancellationToken).ConfigureAwait(false); yield return destinationItem; } } #endif /// <summary> /// Maps the specified source object to a new object with a type of <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source object.</typeparam> /// <typeparam name="TDestination">The type of the destination object.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source object.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The mapped object of type <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper" /> or <paramref name="source" /> is /// <c>null</c>.</exception> public static async Task<TDestination> MapAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, TSource source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var destination = Factory<TDestination>.CreateInstance(); await mapper.MapAsync(source, destination, cancellationToken).ConfigureAwait(false); return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSourceCollection">The type of the source collection.</typeparam> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source collection.</param> /// <param name="destination">The destination collection.</param> /// <param name="sourceCount">The number of items in the source collection.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<TDestination[]> MapArrayAsync<TSourceCollection, TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, TSourceCollection source, TDestination[] destination, int? sourceCount = null, CancellationToken cancellationToken = default) where TSourceCollection : IEnumerable<TSource> where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } if (destination is null) { throw new ArgumentNullException(nameof(destination)); } var tasks = new Task[sourceCount ?? source.Count()]; var i = 0; foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); destination[i] = destinationItem; tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); ++i; } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<TDestination[]> MapArrayAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, List<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count; var tasks = new Task[sourceCount]; var destination = new TDestination[sourceCount]; for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination[i] = destinationItem; tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<TDestination[]> MapArrayAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, Collection<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count; var tasks = new Task[sourceCount]; var destination = new TDestination[sourceCount]; for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination[i] = destinationItem; tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<TDestination[]> MapArrayAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, TSource[] source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Length; var tasks = new Task[sourceCount]; var destination = new TDestination[sourceCount]; for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination[i] = destinationItem; tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into an array of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An array of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<TDestination[]> MapArrayAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, IEnumerable<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count(); var tasks = new Task[sourceCount]; var destination = new TDestination[sourceCount]; var i = 0; foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); destination[i] = destinationItem; tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); ++i; } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource" /> into a collection of type /// <typeparamref name="TDestinationCollection" /> containing objects of type <typeparamref name="TDestination" />. /// </summary> /// <typeparam name="TSourceCollection">The type of the source collection.</typeparam> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestinationCollection">The type of the destination collection.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source collection.</param> /// <param name="destination">The destination collection.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A collection of type <typeparamref name="TDestinationCollection"/> containing objects of type /// <typeparamref name="TDestination" />. /// </returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper" /> or <paramref name="source" /> is /// <c>null</c>.</exception> public static async Task<TDestinationCollection> MapCollectionAsync<TSourceCollection, TSource, TDestinationCollection, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, TSourceCollection source, TDestinationCollection destination, CancellationToken cancellationToken = default) where TSourceCollection : IEnumerable<TSource> where TDestinationCollection : ICollection<TDestination> where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } if (destination is null) { throw new ArgumentNullException(nameof(destination)); } var sourceCount = source.Count(); var tasks = new Task[sourceCount]; var i = 0; foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); destination.Add(destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); ++i; } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<Collection<TDestination>> MapCollectionAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, List<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count; var tasks = new Task[sourceCount]; var destination = new Collection<TDestination>(); for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<Collection<TDestination>> MapCollectionAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, Collection<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count; var tasks = new Task[sourceCount]; var destination = new Collection<TDestination>(); for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<Collection<TDestination>> MapCollectionAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, TSource[] source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Length; var tasks = new Task[sourceCount]; var destination = new Collection<TDestination>(); for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into a collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<Collection<TDestination>> MapCollectionAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, IEnumerable<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count(); var tasks = new Task[sourceCount]; var destination = new Collection<TDestination>(); var i = 0; foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); ++i; } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<List<TDestination>> MapListAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, List<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count; var tasks = new Task[sourceCount]; var destination = new List<TDestination>(sourceCount); for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<List<TDestination>> MapListAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, Collection<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count; var tasks = new Task[sourceCount]; var destination = new List<TDestination>(sourceCount); for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<List<TDestination>> MapListAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, TSource[] source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Length; var tasks = new Task[sourceCount]; var destination = new List<TDestination>(sourceCount); for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into a list of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A list of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<List<TDestination>> MapListAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, IEnumerable<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count(); var tasks = new Task[sourceCount]; var destination = new List<TDestination>(sourceCount); var i = 0; foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); ++i; } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the list of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<ObservableCollection<TDestination>> MapObservableCollectionAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, List<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count; var tasks = new Task[sourceCount]; var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the collection of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<ObservableCollection<TDestination>> MapObservableCollectionAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, Collection<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count; var tasks = new Task[sourceCount]; var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the array of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<ObservableCollection<TDestination>> MapObservableCollectionAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, TSource[] source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Length; var tasks = new Task[sourceCount]; var destination = new ObservableCollection<TDestination>(); for (var i = 0; i < sourceCount; ++i) { var sourceItem = source[i]; var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } /// <summary> /// Maps the enumerable of <typeparamref name="TSource"/> into an observable collection of /// <typeparamref name="TDestination"/>. /// </summary> /// <typeparam name="TSource">The type of the source objects.</typeparam> /// <typeparam name="TDestination">The type of the destination objects.</typeparam> /// <param name="mapper">The mapper.</param> /// <param name="source">The source objects.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An observable collection of <typeparamref name="TDestination"/>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="mapper"/> or <paramref name="source"/> is /// <c>null</c>.</exception> public static async Task<ObservableCollection<TDestination>> MapObservableCollectionAsync<TSource, TDestination>( this IAsyncMapper<TSource, TDestination> mapper, IEnumerable<TSource> source, CancellationToken cancellationToken = default) where TDestination : new() { if (mapper is null) { throw new ArgumentNullException(nameof(mapper)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceCount = source.Count(); var tasks = new Task[sourceCount]; var destination = new ObservableCollection<TDestination>(); var i = 0; foreach (var sourceItem in source) { var destinationItem = Factory<TDestination>.CreateInstance(); destination.Insert(i, destinationItem); tasks[i] = mapper.MapAsync(sourceItem, destinationItem, cancellationToken); ++i; } await Task.WhenAll(tasks).ConfigureAwait(false); return destination; } } }
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF // OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // =========================================================== using System.Collections.Generic; using System.Web; using System; using System.IO; using System.Security.Authentication.ExtendedProtection; using System.Text; using System.Collections.Specialized; using System.Security.Principal; using System.Web.Routing; using System.Threading; using Http.Contexts.GenericUtils; using Http.Shared.Contexts; namespace Http.Contexts { public class DefaultHttpRequest : HttpRequestBase, IHttpRequest { public DefaultHttpRequest() { } private readonly HttpRequest _httpRequest; public object SourceObject { get { return _httpRequest; } } public DefaultHttpRequest(HttpRequest httpRequest) { _httpRequest = httpRequest; InitializeUnsettable(); } public override void Abort() { _httpRequest.Abort(); } public override Byte[] BinaryRead(Int32 count) { return _httpRequest.BinaryRead(count); } public override Stream GetBufferedInputStream() { return _httpRequest.GetBufferedInputStream(); } public override Stream GetBufferlessInputStream() { return _httpRequest.GetBufferlessInputStream(); } public override Stream GetBufferlessInputStream(Boolean disableMaxRequestLength) { return _httpRequest.GetBufferlessInputStream(disableMaxRequestLength); } public override void InsertEntityBody() { _httpRequest.InsertEntityBody(); } public override void InsertEntityBody(Byte[] buffer, Int32 offset, Int32 count) { _httpRequest.InsertEntityBody(buffer, offset, count); } public override Int32[] MapImageCoordinates(String imageFieldName) { return _httpRequest.MapImageCoordinates(imageFieldName); } public override Double[] MapRawImageCoordinates(String imageFieldName) { return _httpRequest.MapRawImageCoordinates(imageFieldName); } public override String MapPath(String virtualPath) { return _httpRequest.MapPath(virtualPath); } public override String MapPath(String virtualPath, String baseVirtualDir, Boolean allowCrossAppMapping) { return _httpRequest.MapPath(virtualPath, baseVirtualDir, allowCrossAppMapping); } public override void ValidateInput() { _httpRequest.ValidateInput(); } public override void SaveAs(String filename, Boolean includeHeaders) { _httpRequest.SaveAs(filename, includeHeaders); } public override String[] AcceptTypes { get { return _httpRequest.AcceptTypes; } } public Dictionary<string, string> ItemDictionary { get { throw new NotImplementedException(); } } public void SetAcceptTypes(String[] val) { } public override String ApplicationPath { get { return _httpRequest.ApplicationPath; } } public void SetApplicationPath(String val) { } public override String AnonymousID { get { return _httpRequest.AnonymousID; } } public void SetAnonymousID(String val) { } public override String AppRelativeCurrentExecutionFilePath { get { return _httpRequest.AppRelativeCurrentExecutionFilePath; } } public void SetAppRelativeCurrentExecutionFilePath(String val) { } public override ChannelBinding HttpChannelBinding { get { return _httpRequest.HttpChannelBinding; } } public void SetHttpChannelBinding(ChannelBinding val) { } public override HttpClientCertificate ClientCertificate { get { return _httpRequest.ClientCertificate; } } public void SetClientCertificate(HttpClientCertificate val) { } public override Encoding ContentEncoding { set { _httpRequest.ContentEncoding = value; } get { return _httpRequest.ContentEncoding; } } public override Int32 ContentLength { get { return _httpRequest.ContentLength; } } public void SetContentLength(Int32 val) { } public override String ContentType { set { _httpRequest.ContentType = value; } get { return _httpRequest.ContentType; } } public override HttpCookieCollection Cookies { get { return _httpRequest.Cookies; } } public void SetCookies(HttpCookieCollection val) { } public override String CurrentExecutionFilePath { get { return _httpRequest.CurrentExecutionFilePath; } } public void SetCurrentExecutionFilePath(String val) { } public override String CurrentExecutionFilePathExtension { get { return _httpRequest.CurrentExecutionFilePathExtension; } } public void SetCurrentExecutionFilePathExtension(String val) { } public override String FilePath { get { return _httpRequest.FilePath; } } public void SetFilePath(String val) { } public override Stream Filter { set { _httpRequest.Filter = value; } get { return _httpRequest.Filter; } } public override NameValueCollection Form { get { return _httpRequest.Form; } } public void SetForm(NameValueCollection val) { } public override String HttpMethod { get { return _httpRequest.HttpMethod; } } public void SetHttpMethod(String val) { } public override Stream InputStream { get { return _httpRequest.InputStream; } } public void SetInputStream(Stream val) { } public override Boolean IsAuthenticated { get { return _httpRequest.IsAuthenticated; } } public void SetIsAuthenticated(Boolean val) { } public override Boolean IsLocal { get { return _httpRequest.IsLocal; } } public void SetIsLocal(Boolean val) { } public override Boolean IsSecureConnection { get { return _httpRequest.IsSecureConnection; } } public void SetIsSecureConnection(Boolean val) { } public override WindowsIdentity LogonUserIdentity { get { return _httpRequest.LogonUserIdentity; } } public void SetLogonUserIdentity(WindowsIdentity val) { } public override NameValueCollection Params { get { return _httpRequest.Params; } } public void SetParams(NameValueCollection val) { } public override String Path { get { return _httpRequest.Path; } } public void SetPath(String val) { } public override String PathInfo { get { return _httpRequest.PathInfo; } } public void SetPathInfo(String val) { } public override String PhysicalApplicationPath { get { return _httpRequest.PhysicalApplicationPath; } } public void SetPhysicalApplicationPath(String val) { } public override String PhysicalPath { get { return _httpRequest.PhysicalPath; } } public void SetPhysicalPath(String val) { } public override String RawUrl { get { return _httpRequest.RawUrl; } } public void SetRawUrl(String val) { } public override ReadEntityBodyMode ReadEntityBodyMode { get { return _httpRequest.ReadEntityBodyMode; } } public void SetReadEntityBodyMode(ReadEntityBodyMode val) { } public override RequestContext RequestContext { set { _httpRequest.RequestContext = value; } get { return _httpRequest.RequestContext; } } public override String RequestType { set { _httpRequest.RequestType = value; } get { return _httpRequest.RequestType; } } public override NameValueCollection ServerVariables { get { return _httpRequest.ServerVariables; } } public void SetServerVariables(NameValueCollection val) { } public override CancellationToken TimedOutToken { get { return _httpRequest.TimedOutToken; } } public void SetTimedOutToken(CancellationToken val) { } public override Int32 TotalBytes { get { return _httpRequest.TotalBytes; } } public void SetTotalBytes(Int32 val) { } public override Uri Url { get { return _httpRequest.Url; } } public void SetUrl(Uri val) { } public override Uri UrlReferrer { get { return _httpRequest.UrlReferrer; } } public void SetUrlReferrer(Uri val) { } public override String UserAgent { get { return _httpRequest.UserAgent; } } public void SetUserAgent(String val) { } public override String[] UserLanguages { get { return _httpRequest.UserLanguages; } } public void SetUserLanguages(String[] val) { } public override String UserHostAddress { get { return _httpRequest.UserHostAddress; } } public void SetUserHostAddress(String val) { } public override String UserHostName { get { return _httpRequest.UserHostName; } } public void SetUserHostName(String val) { } public override NameValueCollection Headers { get { return _httpRequest.Headers; } } public void SetHeaders(NameValueCollection val) { } public override NameValueCollection QueryString { get { return _httpRequest.QueryString; } } public void SetQueryString(NameValueCollection val) { } private HttpBrowserCapabilitiesBase _browser; public override HttpBrowserCapabilitiesBase Browser { get { return _browser; } } public void SetBrowser(HttpBrowserCapabilitiesBase val) { } private HttpFileCollectionBase _files; public override HttpFileCollectionBase Files { get { return _files; } } public void SetFiles(HttpFileCollectionBase val) { } private UnvalidatedRequestValuesBase _unvalidated; public override UnvalidatedRequestValuesBase Unvalidated { get { return _unvalidated; } } public void SetUnvalidated(UnvalidatedRequestValuesBase val) { } public override string this[string key] { get { return _httpRequest[key]; } } public void InitializeUnsettable() { _browser = ConvertBrowser(_httpRequest.Browser); _files = ConvertFiles(_httpRequest.Files); _unvalidated = ConvertUnvalidated(_httpRequest.Unvalidated); } // ReSharper disable once UnusedParameter.Local private UnvalidatedRequestValuesBase ConvertUnvalidated(UnvalidatedRequestValues unvalidated) { return null; } // ReSharper disable once UnusedParameter.Local private HttpBrowserCapabilitiesBase ConvertBrowser(HttpBrowserCapabilities browser) { return null; } private HttpFileCollectionBase ConvertFiles(HttpFileCollection files) { var dict = new Dictionary<string, PostedFile>(); foreach (var file in files.AllKeys) { dict.Add(file, new PostedFile(files[file])); } return new FileCollection(dict); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using Xunit; namespace System { public static partial class PlatformDetection { public static Version OSXKernelVersion => throw new PlatformNotSupportedException(); public static bool IsSuperUser => throw new PlatformNotSupportedException(); public static bool IsOpenSUSE => false; public static bool IsUbuntu => false; public static bool IsDebian => false; public static bool IsDebian8 => false; public static bool IsUbuntu1404 => false; public static bool IsUbuntu1604 => false; public static bool IsUbuntu1704 => false; public static bool IsUbuntu1710 => false; public static bool IsCentos7 => false; public static bool IsTizen => false; public static bool IsNotFedoraOrRedHatOrCentos => true; public static bool IsFedora => false; public static bool IsWindowsNanoServer => (IsNotWindowsIoTCore && GetInstallationType().Equals("Nano Server", StringComparison.OrdinalIgnoreCase)); public static bool IsWindowsServerCore => GetInstallationType().Equals("Server Core", StringComparison.OrdinalIgnoreCase); public static int WindowsVersion => GetWindowsVersion(); public static bool IsMacOsHighSierraOrHigher { get; } = false; public static Version ICUVersion => new Version(0, 0, 0, 0); public static bool IsRedHat => false; public static bool IsNotRedHat => true; public static bool IsRedHat69 => false; public static bool IsNotRedHat69 => true; public static bool IsWindows10Version1607OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393; public static bool IsWindows10Version1703OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063; public static bool IsWindows10InsiderPreviewBuild16215OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16215; public static bool IsWindows10Version16251OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16251; public static bool IsWindowsRedStone2 => // Creators Update version GetWindowsVersion() == 10 && (GetWindowsBuildNumber() / 1000) == 15; // any build with 15xxx. e.g 15063 // Windows OneCoreUAP SKU doesn't have httpapi.dll public static bool IsNotOneCoreUAP => File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "httpapi.dll")); public static bool IsWindowsIoTCore { get { int productType = GetWindowsProductType(); if ((productType == PRODUCT_IOTUAPCOMMERCIAL) || (productType == PRODUCT_IOTUAP)) { return true; } return false; } } public static bool IsWindows => true; public static bool IsWindows7 => GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1; public static bool IsWindows8x => GetWindowsVersion() == 6 && (GetWindowsMinorVersion() == 2 || GetWindowsMinorVersion() == 3); public static bool IsNetfx462OrNewer() { if (!IsFullFramework) { return false; } Version net462 = new Version(4, 6, 2); Version runningVersion = GetFrameworkVersion(); return runningVersion != null && runningVersion >= net462; } public static bool IsNetfx470OrNewer() { if (!IsFullFramework) { return false; } Version net470 = new Version(4, 7, 0); Version runningVersion = GetFrameworkVersion(); return runningVersion != null && runningVersion >= net470; } public static bool IsNetfx471OrNewer() { if (!IsFullFramework) { return false; } Version net471 = new Version(4, 7, 1); Version runningVersion = GetFrameworkVersion(); return runningVersion != null && runningVersion >= net471; } private static Version GetFrameworkVersion() { string[] descriptionArray = RuntimeInformation.FrameworkDescription.Split(' '); if (descriptionArray.Length < 3) return null; if (!Version.TryParse(descriptionArray[2], out Version actualVersion)) return null; foreach (Range currentRange in FrameworkRanges) { if (currentRange.IsInRange(actualVersion)) return currentRange.FrameworkVersion; } return null; } public static string GetDistroVersionString() { return "ProductType=" + GetWindowsProductType() + "InstallationType=" + GetInstallationType(); } private static int s_isInAppContainer = -1; public static bool IsInAppContainer { // This actually checks whether code is running in a modern app. // Currently this is the only situation where we run in app container. // If we want to distinguish the two cases in future, // EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token. get { if (s_isInAppContainer != -1) return s_isInAppContainer == 1; if (!IsWindows || IsWindows7) { s_isInAppContainer = 0; return false; } byte[] buffer = new byte[0]; uint bufferSize = 0; try { int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer); switch (result) { case 15703: // APPMODEL_ERROR_NO_APPLICATION s_isInAppContainer = 0; break; case 0: // ERROR_SUCCESS case 122: // ERROR_INSUFFICIENT_BUFFER // Success is actually insufficent buffer as we're really only looking for // not NO_APPLICATION and we're not actually giving a buffer here. The // API will always return NO_APPLICATION if we're not running under a // WinRT process, no matter what size the buffer is. s_isInAppContainer = 1; break; default: throw new InvalidOperationException($"Failed to get AppId, result was {result}."); } } catch (Exception e) { // We could catch this here, being friendly with older portable surface area should we // desire to use this method elsewhere. if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal)) { // API doesn't exist, likely pre Win8 s_isInAppContainer = 0; } else { throw; } } return s_isInAppContainer == 1; } } private static int s_isWindowsElevated = -1; public static bool IsWindowsAndElevated { get { if (s_isWindowsElevated != -1) return s_isWindowsElevated == 1; if (!IsWindows || IsInAppContainer) { s_isWindowsElevated = 0; return false; } IntPtr processToken; Assert.True(OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out processToken)); try { uint tokenInfo; uint returnLength; Assert.True(GetTokenInformation( processToken, TokenElevation, out tokenInfo, sizeof(uint), out returnLength)); s_isWindowsElevated = tokenInfo == 0 ? 0 : 1; } finally { CloseHandle(processToken); } return s_isWindowsElevated == 1; } } private static string GetInstallationType() { string key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"; string value = ""; try { value = (string)Registry.GetValue(key, "InstallationType", defaultValue: ""); } catch (Exception e) when (e is SecurityException || e is InvalidCastException || e is PlatformNotSupportedException /* UAP */) { } return value; } private static int GetWindowsProductType() { Assert.True(GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, out int productType)); return productType; } private static int GetWindowsMinorVersion() { RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); Assert.Equal(0, RtlGetVersion(out osvi)); return (int)osvi.dwMinorVersion; } private static int GetWindowsBuildNumber() { RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); Assert.Equal(0, RtlGetVersion(out osvi)); return (int)osvi.dwBuildNumber; } private const uint TokenElevation = 20; private const uint STANDARD_RIGHTS_READ = 0x00020000; private const uint TOKEN_QUERY = 0x0008; private const uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY; [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] private static extern bool GetTokenInformation( IntPtr TokenHandle, uint TokenInformationClass, out uint TokenInformation, uint TokenInformationLength, out uint ReturnLength); private const int PRODUCT_IOTUAP = 0x0000007B; private const int PRODUCT_IOTUAPCOMMERCIAL = 0x00000083; [DllImport("kernel32.dll", SetLastError = false)] private static extern bool GetProductInfo( int dwOSMajorVersion, int dwOSMinorVersion, int dwSpMajorVersion, int dwSpMinorVersion, out int pdwReturnedProductType ); [DllImport("ntdll.dll")] private static extern int RtlGetVersion(out RTL_OSVERSIONINFOEX lpVersionInformation); [StructLayout(LayoutKind.Sequential)] private struct RTL_OSVERSIONINFOEX { internal uint dwOSVersionInfoSize; internal uint dwMajorVersion; internal uint dwMinorVersion; internal uint dwBuildNumber; internal uint dwPlatformId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal string szCSDVersion; } private static int GetWindowsVersion() { RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); Assert.Equal(0, RtlGetVersion(out osvi)); return (int)osvi.dwMajorVersion; } [DllImport("kernel32.dll", ExactSpelling = true)] private static extern int GetCurrentApplicationUserModelId(ref uint applicationUserModelIdLength, byte[] applicationUserModelId); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] private static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle); // The process handle does NOT need closing [DllImport("kernel32.dll", ExactSpelling = true)] private static extern IntPtr GetCurrentProcess(); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using mshtml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Mshtml; namespace OpenLiveWriter.Mshtml { [Flags] public enum MarkupPointerAdjacency : ulong { BeforeText = 0x000, AfterEnterBlock = 0x001, BeforeExitBlock = 0x002, BeforeVisible = 0x004, BeforeEnterScope = 0x008, //Flag6 = 0x010, //Flag7 = 0x020, //Flag8 = 0x040, //Flag9 = 0x080, //Flag10 = 0x100, //AllFlags = 0xffff } public class MarkupPointerMoveHelper { private enum MoveFilterResult { CONTINUE, STOP, STOP_BACK } private delegate MoveFilterResult MoveContextFilter(MarkupContext mc); public enum MoveDirection { LEFT, RIGHT }; private static MoveContextFilter CreateMoveContextFilter(MarkupPointerAdjacency stopRule) { ArrayList stopFilters = new ArrayList(); if (FlagIsSet(MarkupPointerAdjacency.BeforeText, stopRule)) stopFilters.Add(new MoveContextFilter(StopBeforeText)); if (FlagIsSet(MarkupPointerAdjacency.AfterEnterBlock, stopRule)) stopFilters.Add(new MoveContextFilter(StopAfterEnterBlock)); if (FlagIsSet(MarkupPointerAdjacency.BeforeExitBlock, stopRule)) stopFilters.Add(new MoveContextFilter(StopBeforeExitBlock)); if (FlagIsSet(MarkupPointerAdjacency.BeforeVisible, stopRule)) stopFilters.Add(new MoveContextFilter(StopBeforeVisible)); if (FlagIsSet(MarkupPointerAdjacency.BeforeEnterScope, stopRule)) stopFilters.Add(new MoveContextFilter(StopBeforeEnterScope)); if (stopFilters.Count > 0) return MergeContextFilters((MoveContextFilter[])stopFilters.ToArray(typeof(MoveContextFilter))); else return new MoveContextFilter(ContinueFilter); } public static void MoveUnitBounded(MarkupPointer p, MoveDirection direction, MarkupPointerAdjacency stopRule, MarkupPointer boundary) { MoveContextFilter filter = CreateMoveContextFilter(stopRule); MoveUnitBounded(p, direction, filter, boundary); } public static void MoveUnitBounded(MarkupPointer p, MoveDirection direction, MarkupPointerAdjacency stopRule, IHTMLElement boundary) { MarkupPointer pBoundary = p.Clone(); pBoundary.MoveAdjacentToElement(boundary, direction == MoveDirection.LEFT ? _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin : _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd); MoveUnitBounded(p, direction, stopRule, pBoundary); } private static void MoveUnitBounded(MarkupPointer p, MoveDirection direction, MoveContextFilter continueFilter, MarkupPointer boundary) { MarkupPointer p1 = p.Clone(); MarkupPointer lastGoodPosition = p.Clone(); MarkupContext context = new MarkupContext(); MoveFilterResult result = MoveFilterResult.CONTINUE; while (CheckMoveBoundary(p1, boundary, direction) && result == MoveFilterResult.CONTINUE) { lastGoodPosition.MoveToPointer(p1); MovePointer(p1, direction, context); result = continueFilter(context); } if (result == MoveFilterResult.CONTINUE) { //we hit the boundary, so position pointer at the boundary p1.MoveToPointer(boundary); } else if (result == MoveFilterResult.STOP_BACK) { p1.MoveToPointer(lastGoodPosition); } p.MoveToPointer(p1); } private static bool CheckMoveBoundary(MarkupPointer p, MarkupPointer boundary, MoveDirection d) { if (d == MoveDirection.LEFT) return p.IsRightOf(boundary); else return p.IsLeftOf(boundary); } private static void MovePointer(MarkupPointer p, MoveDirection d, MarkupContext context) { if (d == MoveDirection.LEFT) p.Left(true, context); else p.Right(true, context); } private static MoveFilterResult ContinueFilter(MarkupContext mc) { return MoveFilterResult.CONTINUE; } private static MoveFilterResult StopAfterEnterBlock(MarkupContext mc) { if (mc.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope && ElementFilters.IsBlockElement(mc.Element)) return MoveFilterResult.STOP; return MoveFilterResult.CONTINUE; } private static MoveFilterResult StopBeforeExitBlock(MarkupContext mc) { if (mc.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope && ElementFilters.IsBlockElement(mc.Element)) return MoveFilterResult.STOP_BACK; return MoveFilterResult.CONTINUE; } private static MoveFilterResult StopBeforeText(MarkupContext mc) { if (mc.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text) return MoveFilterResult.STOP_BACK; return MoveFilterResult.CONTINUE; } private static MoveFilterResult StopBeforeVisible(MarkupContext mc) { if (mc.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_Text) return MoveFilterResult.STOP_BACK; if (mc.Element != null && ElementFilters.IsInlineElement(mc.Element) && !ElementFilters.IsVisibleEmptyElement(mc.Element)) return MoveFilterResult.CONTINUE; return MoveFilterResult.STOP_BACK; } private static MoveFilterResult StopBeforeEnterScope(MarkupContext mc) { if (mc.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope) return MoveFilterResult.STOP_BACK; return MoveFilterResult.CONTINUE; } private static MoveContextFilter MergeContextFilters(params MoveContextFilter[] filters) { return new MoveContextFilter(new CompoundMoveContextFilter(filters).MergeContextFilters); } private class CompoundMoveContextFilter { private MoveContextFilter[] _filters; public CompoundMoveContextFilter(MoveContextFilter[] filters) { _filters = filters; } public MoveFilterResult MergeContextFilters(MarkupContext mc) { foreach (MoveContextFilter filter in _filters) { MoveFilterResult result = filter(mc); if (result != MoveFilterResult.CONTINUE) return result; } return MoveFilterResult.CONTINUE; } } private static bool FlagNotSet(MarkupPointerAdjacency flag, MarkupPointerAdjacency flagMask) { return !FlagIsSet(flag, flagMask); } private static bool FlagIsSet(MarkupPointerAdjacency flag, MarkupPointerAdjacency flagMask) { ulong flagLong = (ulong)flag; ulong mask = ((ulong)flagMask) & flagLong; return mask == flagLong; } /// <summary> /// Find the most logic direction to move the cursor so that it matches the where has clicked /// </summary> /// <param name="Selection"></param> /// <returns></returns> public static Direction FindSelectionToLogicalPosition(MarkupRange Selection, IHTMLElement body, bool? forward) { // There is a selection, not just a click if (!Selection.Start.IsEqualTo(Selection.End)) return Direction.None; Direction dir = ImageBreakout(Selection.Start); if (dir != Direction.None) { return dir; } MarkupContext contextRight = Selection.Start.Right(false); MarkupContext contextLeft = Selection.Start.Left(false); // there is text or some other type of content around the click if (!((contextLeft.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope || contextLeft.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope) && (contextRight.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope || contextRight.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope))) return Direction.None; // The click is not between two block elements, so it should be fine where it is if (!ElementFilters.IsBlockElement(contextLeft.Element) || !ElementFilters.IsBlockElement(contextRight.Element)) return Direction.None; // </blockElement>|</postBody> if (contextLeft.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope && !IsSmartContent(contextLeft) && contextRight.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope && contextRight.Element.id == body.id) return Direction.Left; // <postBody>|<blockElement> if (contextRight.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope && !IsSmartContent(contextRight) && contextLeft.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_ExitScope && contextLeft.Element.id == body.id) return Direction.Right; // </blockElement>|<blockElement> if (contextLeft.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope && !IsSmartContent(contextLeft) && contextRight.Context == _MARKUP_CONTEXT_TYPE.CONTEXT_TYPE_EnterScope && !IsSmartContent(contextRight)) return forward == null || forward == true ? Direction.Right : Direction.Left; return Direction.None; } /// <summary> /// Checks if the MarkupPointer is inside of an anchor that only contains /// an image, and if so, moves the pointer to be outside the anchor. /// This prevents cases where hyperlinked images were getting nested inside /// of each other as a result of drag and drop. /// </summary> public static Direction ImageBreakout(MarkupPointer p) { // If inside <a><img></a>, then move to outside IHTMLElement currentScope = p.CurrentScope; if (currentScope is IHTMLAnchorElement) { IHTMLDOMNode anchor = (IHTMLDOMNode)currentScope; if (anchor.hasChildNodes() && anchor.firstChild is IHTMLImgElement && anchor.firstChild.nextSibling == null) { // Figure out if we are positioned before or after the image; this will determine // whether we want to move before or after the anchor return (p.Right(false).Element is IHTMLImgElement) ? Direction.Left : Direction.Right; } } return Direction.None; } private static bool IsSmartContent(MarkupContext ctx) { return ((IHTMLElement3)ctx.Element).contentEditable.ToUpperInvariant() == "FALSE"; } public static bool DriveSelectionToLogicalPosition(MarkupRange Selection, IHTMLElement body) { return DriveSelectionToLogicalPosition(Selection, body, null); } /// <summary> /// Find the most logic direction to move to visible location that is where it appears to the user. /// And then moves it to that location. Returns true if it moved the pointer. /// </summary> /// <param name="Selection"></param> /// <returns></returns> public static bool DriveSelectionToLogicalPosition(MarkupRange Selection, IHTMLElement body, bool? forward) { Direction dir = FindSelectionToLogicalPosition(Selection, body, forward); if (dir == Direction.None) return false; if (dir == Direction.Right) { Selection.End.Right(true); Selection.Start.Right(true); } else if (dir == Direction.Left) { Selection.End.Left(true); Selection.Start.Left(true); } return true; } public static void PerformImageBreakout(MarkupPointer p) { Direction dir = ImageBreakout(p); if (dir == Direction.Right) { p.MoveAdjacentToElement(p.CurrentScope, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd); } if (dir == Direction.Left) { p.MoveAdjacentToElement(p.CurrentScope, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin); } } } public enum Direction { None = 0, Left = 1, Right = 2 } }
// <developer>niklas@protocol7.com</developer> // <completed>100</completed> using System; using System.Xml; namespace SharpVectors.Dom.Svg { /// <summary> /// The SvgEllipseElement class corresponds to the 'ellipse' element. /// </summary> public sealed class SvgEllipseElement : SvgTransformableElement, ISvgEllipseElement { #region Private Fields private ISvgAnimatedLength cx; private ISvgAnimatedLength cy; private ISvgAnimatedLength rx; private ISvgAnimatedLength ry; private SvgTests svgTests; private SvgExternalResourcesRequired svgExternalResourcesRequired; #endregion #region Constructors and Destructor public SvgEllipseElement(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { svgExternalResourcesRequired = new SvgExternalResourcesRequired(this); svgTests = new SvgTests(this); } #endregion #region Public Methods public void Invalidate() { } public override void HandleAttributeChange(XmlAttribute attribute) { if (attribute.NamespaceURI.Length == 0) { switch (attribute.LocalName) { case "cx": cx = null; Invalidate(); return; case "cy": cy = null; Invalidate(); return; case "rx": rx = null; Invalidate(); return; case "ry": ry = null; Invalidate(); return; // Color.attrib, Paint.attrib case "color": case "fill": case "fill-rule": case "stroke": case "stroke-dasharray": case "stroke-dashoffset": case "stroke-linecap": case "stroke-linejoin": case "stroke-miterlimit": case "stroke-width": // Opacity.attrib case "opacity": case "stroke-opacity": case "fill-opacity": // Graphics.attrib case "display": case "image-rendering": case "shape-rendering": case "text-rendering": case "visibility": Invalidate(); break; case "transform": Invalidate(); break; } base.HandleAttributeChange(attribute); } } #endregion #region ISvgElement Members /// <summary> /// Gets a value providing a hint on the rendering defined by this element. /// </summary> /// <value> /// An enumeration of the <see cref="SvgRenderingHint"/> specifying the rendering hint. /// This will always return <see cref="SvgRenderingHint.Shape"/> /// </value> public override SvgRenderingHint RenderingHint { get { return SvgRenderingHint.Shape; } } #endregion #region ISvgEllipseElement Members public ISvgAnimatedLength Cx { get { if (cx == null) { cx = new SvgAnimatedLength(this, "cx", SvgLengthDirection.Horizontal, "0"); } return cx; } } public ISvgAnimatedLength Cy { get { if (cy == null) { cy = new SvgAnimatedLength(this, "cy", SvgLengthDirection.Vertical, "0"); } return cy; } } public ISvgAnimatedLength Rx { get { if (rx == null) { rx = new SvgAnimatedLength(this, "rx", SvgLengthDirection.Horizontal, "100"); } return rx; } } public ISvgAnimatedLength Ry { get { if (ry == null) { ry = new SvgAnimatedLength(this, "ry", SvgLengthDirection.Vertical, "100"); } return ry; } } #endregion #region ISvgExternalResourcesRequired Members public ISvgAnimatedBoolean ExternalResourcesRequired { get { return svgExternalResourcesRequired.ExternalResourcesRequired; } } #endregion #region ISvgTests Members public ISvgStringList RequiredFeatures { get { return svgTests.RequiredFeatures; } } public ISvgStringList RequiredExtensions { get { return svgTests.RequiredExtensions; } } public ISvgStringList SystemLanguage { get { return svgTests.SystemLanguage; } } public bool HasExtension(string extension) { return svgTests.HasExtension(extension); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.Unicode; using Xunit; namespace System.Text.Encodings.Web.Tests { public unsafe class UnicodeHelpersTests { // If updating the version of UnicodeData.txt, update the below string with the new file name. private const string UnicodeDataFileName = "UnicodeData.12.1.txt"; private const int UnicodeReplacementChar = '\uFFFD'; private static readonly UTF8Encoding _utf8EncodingThrowOnInvalidBytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); // To future refactorers: // The following GetScalarValueFromUtf16_* tests must not be done as a [Theory]. If done via [InlineData], the invalid // code points will get sanitized with replacement characters before they even reach the test, as the strings are parsed // from the attributes in reflection. And if done via [MemberData], the XmlWriter used by xunit will throw exceptions // when it attempts to write out the test arguments, due to the invalid text. [Fact] public void GetScalarValueFromUtf16_NormalBMPChar_EndOfString() { GetScalarValueFromUtf16("a", 'a'); } [Fact] public void GetScalarValueFromUtf16_NormalBMPChar_NotEndOfString() { GetScalarValueFromUtf16("ab", 'a'); } [Fact] public void GetScalarValueFromUtf16_TrailingSurrogate_EndOfString() { GetScalarValueFromUtf16("\uDFFF", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_TrailingSurrogate_NotEndOfString() { GetScalarValueFromUtf16("\uDFFFx", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_LeadingSurrogate_EndOfString() { GetScalarValueFromUtf16("\uD800", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_LeadingSurrogate_NotEndOfString() { GetScalarValueFromUtf16("\uD800x", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_LeadingSurrogate_NotEndOfString_FollowedByLeadingSurrogate() { GetScalarValueFromUtf16("\uD800\uD800", UnicodeReplacementChar); } [Fact] public void GetScalarValueFromUtf16_LeadingSurrogate_NotEndOfString_FollowedByTrailingSurrogate() { GetScalarValueFromUtf16("\uD800\uDFFF", 0x103FF); } private void GetScalarValueFromUtf16(string input, int expectedResult) { fixed (char* pInput = input) { Assert.Equal(expectedResult, UnicodeHelpers.GetScalarValueFromUtf16(pInput, endOfString: (input.Length == 1))); } } [Fact] public void GetUtf8RepresentationForScalarValue() { for (int i = 0; i <= 0x10FFFF; i++) { if (i <= 0xFFFF && char.IsSurrogate((char)i)) { continue; // no surrogates } // Arrange byte[] expectedUtf8Bytes = _utf8EncodingThrowOnInvalidBytes.GetBytes(char.ConvertFromUtf32(i)); // Act List<byte> actualUtf8Bytes = new List<byte>(4); uint asUtf8 = unchecked((uint)UnicodeHelpers.GetUtf8RepresentationForScalarValue((uint)i)); do { actualUtf8Bytes.Add(unchecked((byte)asUtf8)); } while ((asUtf8 >>= 8) != 0); // Assert Assert.Equal(expectedUtf8Bytes, actualUtf8Bytes); } } [Fact] public void IsCharacterDefined() { Assert.All(ReadListOfDefinedCharacters().Select((defined, idx) => new { defined, idx }), c => Assert.Equal(c.defined, UnicodeHelpers.IsCharacterDefined((char)c.idx))); } private static bool[] ReadListOfDefinedCharacters() { HashSet<string> allowedCategories = new HashSet<string>(); // Letters allowedCategories.Add("Lu"); allowedCategories.Add("Ll"); allowedCategories.Add("Lt"); allowedCategories.Add("Lm"); allowedCategories.Add("Lo"); // Marks allowedCategories.Add("Mn"); allowedCategories.Add("Mc"); allowedCategories.Add("Me"); // Numbers allowedCategories.Add("Nd"); allowedCategories.Add("Nl"); allowedCategories.Add("No"); // Punctuation allowedCategories.Add("Pc"); allowedCategories.Add("Pd"); allowedCategories.Add("Ps"); allowedCategories.Add("Pe"); allowedCategories.Add("Pi"); allowedCategories.Add("Pf"); allowedCategories.Add("Po"); // Symbols allowedCategories.Add("Sm"); allowedCategories.Add("Sc"); allowedCategories.Add("Sk"); allowedCategories.Add("So"); // Separators // With the exception of U+0020 SPACE, these aren't allowed // Other // We only allow one category of 'other' characters allowedCategories.Add("Cf"); HashSet<string> seenCategories = new HashSet<string>(); bool[] retVal = new bool[0x10000]; string[] allLines = new StreamReader(typeof(UnicodeHelpersTests).GetTypeInfo().Assembly.GetManifestResourceStream(UnicodeDataFileName)).ReadAllLines(); uint startSpanCodepoint = 0; foreach (string line in allLines) { string[] splitLine = line.Split(';'); uint codePoint = uint.Parse(splitLine[0], NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); if (codePoint >= retVal.Length) { continue; // don't care about supplementary chars } if (codePoint == (uint)' ') { retVal[codePoint] = true; // we allow U+0020 SPACE as our only valid Zs (whitespace) char } else if (codePoint == 0xFEFF) { retVal[codePoint] = false; // we explicitly forbid U+FEFF ZERO WIDTH NO-BREAK SPACE because it's also the byte order mark (BOM) } else { string category = splitLine[2]; if (allowedCategories.Contains(category)) { retVal[codePoint] = true; // chars in this category are allowable seenCategories.Add(category); if (splitLine[1].EndsWith("First>")) { startSpanCodepoint = codePoint; } else if (splitLine[1].EndsWith("Last>")) { for (uint spanCounter = startSpanCodepoint; spanCounter < codePoint; spanCounter++) { retVal[spanCounter] = true; // chars in this category are allowable } } } } } // Finally, we need to make sure we've seen every category which contains // allowed characters. This provides extra defense against having a typo // in the list of categories. Assert.Equal(allowedCategories.OrderBy(c => c), seenCategories.OrderBy(c => c)); return retVal; } } }
// 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; using System.ServiceModel.Security; using System.Threading.Tasks; using Microsoft.Xml; namespace System.ServiceModel.Channels { internal abstract class SessionConnectionReader : IMessageSource { private bool _isAtEOF; private bool _usingAsyncReadBuffer; private IConnection _connection; private byte[] _buffer; private int _offset; private int _size; private byte[] _envelopeBuffer; private int _envelopeOffset; private int _envelopeSize; private bool _readIntoEnvelopeBuffer; private Message _pendingMessage; private Exception _pendingException; private SecurityMessageProperty _security; // Raw connection that we will revert to after end handshake private IConnection _rawConnection; protected SessionConnectionReader(IConnection connection, IConnection rawConnection, int offset, int size, SecurityMessageProperty security) { _offset = offset; _size = size; if (size > 0) { _buffer = connection.AsyncReadBuffer; } _connection = connection; _rawConnection = rawConnection; _security = security; } private Message DecodeMessage(TimeSpan timeout) { if (!_readIntoEnvelopeBuffer) { return DecodeMessage(_buffer, ref _offset, ref _size, ref _isAtEOF, timeout); } else { // decode from the envelope buffer int dummyOffset = _envelopeOffset; return DecodeMessage(_envelopeBuffer, ref dummyOffset, ref _size, ref _isAtEOF, timeout); } } protected abstract Message DecodeMessage(byte[] buffer, ref int offset, ref int size, ref bool isAtEof, TimeSpan timeout); protected byte[] EnvelopeBuffer { get { return _envelopeBuffer; } set { _envelopeBuffer = value; } } protected int EnvelopeOffset { get { return _envelopeOffset; } set { _envelopeOffset = value; } } protected int EnvelopeSize { get { return _envelopeSize; } set { _envelopeSize = value; } } public IConnection GetRawConnection() { IConnection result = null; if (_rawConnection != null) { result = _rawConnection; _rawConnection = null; if (_size > 0) { PreReadConnection preReadConnection = result as PreReadConnection; if (preReadConnection != null) // make sure we don't keep wrapping { preReadConnection.AddPreReadData(_buffer, _offset, _size); } else { result = new PreReadConnection(result, _buffer, _offset, _size); } } } return result; } public async Task<Message> ReceiveAsync(TimeSpan timeout) { Message message = GetPendingMessage(); if (message != null) { return message; } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (; ; ) { if (_isAtEOF) { return null; } if (_size > 0) { message = DecodeMessage(timeoutHelper.RemainingTime()); if (message != null) { PrepareMessage(message); return message; } else if (_isAtEOF) // could have read the END record under DecodeMessage { return null; } } if (_size != 0) { throw new Exception("Receive: DecodeMessage() should consume the outstanding buffer or return a message."); } if (!_usingAsyncReadBuffer) { _buffer = _connection.AsyncReadBuffer; _usingAsyncReadBuffer = true; } int bytesRead; var tcs = new TaskCompletionSource<bool>(); var result = _connection.BeginRead(0, _buffer.Length, timeoutHelper.RemainingTime(), TaskHelpers.OnAsyncCompletionCallback, tcs); if (result == AsyncCompletionResult.Completed) { tcs.TrySetResult(true); } await tcs.Task; bytesRead = _connection.EndRead(); HandleReadComplete(bytesRead, false); } } public Message Receive(TimeSpan timeout) { Message message = GetPendingMessage(); if (message != null) { return message; } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (; ; ) { if (_isAtEOF) { return null; } if (_size > 0) { message = DecodeMessage(timeoutHelper.RemainingTime()); if (message != null) { PrepareMessage(message); return message; } else if (_isAtEOF) // could have read the END record under DecodeMessage { return null; } } if (_size != 0) { throw new Exception("Receive: DecodeMessage() should consume the outstanding buffer or return a message."); } if (_buffer == null) { _buffer = Fx.AllocateByteArray(_connection.AsyncReadBufferSize); } int bytesRead; if (EnvelopeBuffer != null && (EnvelopeSize - EnvelopeOffset) >= _buffer.Length) { bytesRead = _connection.Read(EnvelopeBuffer, EnvelopeOffset, _buffer.Length, timeoutHelper.RemainingTime()); HandleReadComplete(bytesRead, true); } else { bytesRead = _connection.Read(_buffer, 0, _buffer.Length, timeoutHelper.RemainingTime()); HandleReadComplete(bytesRead, false); } } } public Message EndReceive() { return GetPendingMessage(); } private Message GetPendingMessage() { if (_pendingException != null) { Exception exception = _pendingException; _pendingException = null; throw exception; } if (_pendingMessage != null) { Message message = _pendingMessage; _pendingMessage = null; return message; } return null; } public async Task<bool> WaitForMessageAsync(TimeSpan timeout) { try { Message message = await ReceiveAsync(timeout); _pendingMessage = message; return true; } catch (TimeoutException e) { if (WcfEventSource.Instance.ReceiveTimeoutIsEnabled()) { WcfEventSource.Instance.ReceiveTimeout(e.Message); } return false; } } public bool WaitForMessage(TimeSpan timeout) { try { Message message = Receive(timeout); _pendingMessage = message; return true; } catch (TimeoutException e) { if (WcfEventSource.Instance.ReceiveTimeoutIsEnabled()) { WcfEventSource.Instance.ReceiveTimeout(e.Message); } return false; } } protected abstract void EnsureDecoderAtEof(); private void HandleReadComplete(int bytesRead, bool readIntoEnvelopeBuffer) { _readIntoEnvelopeBuffer = readIntoEnvelopeBuffer; if (bytesRead == 0) { EnsureDecoderAtEof(); _isAtEOF = true; } else { _offset = 0; _size = bytesRead; } } protected virtual void PrepareMessage(Message message) { if (_security != null) { message.Properties.Security = (SecurityMessageProperty)_security.CreateCopy(); } } } internal class ClientDuplexConnectionReader : SessionConnectionReader { private ClientDuplexDecoder _decoder; private int _maxBufferSize; private BufferManager _bufferManager; private MessageEncoder _messageEncoder; private ClientFramingDuplexSessionChannel _channel; public ClientDuplexConnectionReader(ClientFramingDuplexSessionChannel channel, IConnection connection, ClientDuplexDecoder decoder, IConnectionOrientedTransportFactorySettings settings, MessageEncoder messageEncoder) : base(connection, null, 0, 0, null) { _decoder = decoder; _maxBufferSize = settings.MaxBufferSize; _bufferManager = settings.BufferManager; _messageEncoder = messageEncoder; _channel = channel; } protected override void EnsureDecoderAtEof() { if (!(_decoder.CurrentState == ClientFramingDecoderState.End || _decoder.CurrentState == ClientFramingDecoderState.EnvelopeEnd || _decoder.CurrentState == ClientFramingDecoderState.ReadingUpgradeRecord || _decoder.CurrentState == ClientFramingDecoderState.UpgradeResponse)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_decoder.CreatePrematureEOFException()); } } private static IDisposable CreateProcessActionActivity() { return null; } protected override Message DecodeMessage(byte[] buffer, ref int offset, ref int size, ref bool isAtEOF, TimeSpan timeout) { while (size > 0) { int bytesRead = _decoder.Decode(buffer, offset, size); if (bytesRead > 0) { if (EnvelopeBuffer != null) { if (!object.ReferenceEquals(buffer, EnvelopeBuffer)) System.Buffer.BlockCopy(buffer, offset, EnvelopeBuffer, EnvelopeOffset, bytesRead); EnvelopeOffset += bytesRead; } offset += bytesRead; size -= bytesRead; } switch (_decoder.CurrentState) { case ClientFramingDecoderState.Fault: _channel.Session.CloseOutputSession(_channel.GetInternalCloseTimeout()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(FaultStringDecoder.GetFaultException(_decoder.Fault, _channel.RemoteAddress.Uri.ToString(), _messageEncoder.ContentType)); case ClientFramingDecoderState.End: isAtEOF = true; return null; // we're done case ClientFramingDecoderState.EnvelopeStart: int envelopeSize = _decoder.EnvelopeSize; if (envelopeSize > _maxBufferSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ExceptionHelper.CreateMaxReceivedMessageSizeExceededException(_maxBufferSize)); } EnvelopeBuffer = _bufferManager.TakeBuffer(envelopeSize); EnvelopeOffset = 0; EnvelopeSize = envelopeSize; break; case ClientFramingDecoderState.EnvelopeEnd: if (EnvelopeBuffer != null) { Message message = null; try { IDisposable activity = ClientDuplexConnectionReader.CreateProcessActionActivity(); using (activity) { message = _messageEncoder.ReadMessage(new ArraySegment<byte>(EnvelopeBuffer, 0, EnvelopeSize), _bufferManager); } } catch (XmlException xmlException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SRServiceModel.MessageXmlProtocolError, xmlException)); } EnvelopeBuffer = null; return message; } break; } } return null; } } }
// 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.ApplicationInsights.Management.Models { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.ApplicationInsights; using Microsoft.Azure.Management.ApplicationInsights.Management; using Newtonsoft.Json; using System.Linq; /// <summary> /// Properties that define a Continuous Export configuration. /// </summary> public partial class ApplicationInsightsComponentExportConfiguration { /// <summary> /// Initializes a new instance of the /// ApplicationInsightsComponentExportConfiguration class. /// </summary> public ApplicationInsightsComponentExportConfiguration() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// ApplicationInsightsComponentExportConfiguration class. /// </summary> /// <param name="exportId">The unique ID of the export configuration /// inside an Applciation Insights component. It is auto generated when /// the Continuous Export configuration is created.</param> /// <param name="instrumentationKey">The instrumentation key of the /// Application Insights component.</param> /// <param name="recordTypes">This comma separated list of document /// types that will be exported. The possible values include /// 'Requests', 'Event', 'Exceptions', 'Metrics', 'PageViews', /// 'PageViewPerformance', 'Rdd', 'PerformanceCounters', /// 'Availability', 'Messages'.</param> /// <param name="applicationName">The name of the Application Insights /// component.</param> /// <param name="subscriptionId">The subscription of the Application /// Insights component.</param> /// <param name="resourceGroup">The resource group of the Application /// Insights component.</param> /// <param name="destinationStorageSubscriptionId">The destination /// storage account subscription ID.</param> /// <param name="destinationStorageLocationId">The destination account /// location ID.</param> /// <param name="destinationAccountId">The name of destination /// account.</param> /// <param name="destinationType">The destination type.</param> /// <param name="isUserEnabled">This will be 'true' if the Continuous /// Export configuration is enabled, otherwise it will be /// 'false'.</param> /// <param name="lastUserUpdate">Last time the Continuous Export /// configuration was updated.</param> /// <param name="notificationQueueEnabled">Deprecated</param> /// <param name="exportStatus">This indicates current Continuous Export /// configuration status. The possible values are 'Preparing', /// 'Success', 'Failure'.</param> /// <param name="lastSuccessTime">The last time data was successfully /// delivered to the destination storage container for this Continuous /// Export configuration.</param> /// <param name="lastGapTime">The last time the Continuous Export /// configuration started failing.</param> /// <param name="permanentErrorReason">This is the reason the /// Continuous Export configuration started failing. It can be /// 'AzureStorageNotFound' or 'AzureStorageAccessDenied'.</param> /// <param name="storageName">The name of the destination storage /// account.</param> /// <param name="containerName">The name of the destination storage /// container.</param> public ApplicationInsightsComponentExportConfiguration(string exportId = default(string), string instrumentationKey = default(string), string recordTypes = default(string), string applicationName = default(string), string subscriptionId = default(string), string resourceGroup = default(string), string destinationStorageSubscriptionId = default(string), string destinationStorageLocationId = default(string), string destinationAccountId = default(string), string destinationType = default(string), string isUserEnabled = default(string), string lastUserUpdate = default(string), string notificationQueueEnabled = default(string), string exportStatus = default(string), string lastSuccessTime = default(string), string lastGapTime = default(string), string permanentErrorReason = default(string), string storageName = default(string), string containerName = default(string)) { ExportId = exportId; InstrumentationKey = instrumentationKey; RecordTypes = recordTypes; ApplicationName = applicationName; SubscriptionId = subscriptionId; ResourceGroup = resourceGroup; DestinationStorageSubscriptionId = destinationStorageSubscriptionId; DestinationStorageLocationId = destinationStorageLocationId; DestinationAccountId = destinationAccountId; DestinationType = destinationType; IsUserEnabled = isUserEnabled; LastUserUpdate = lastUserUpdate; NotificationQueueEnabled = notificationQueueEnabled; ExportStatus = exportStatus; LastSuccessTime = lastSuccessTime; LastGapTime = lastGapTime; PermanentErrorReason = permanentErrorReason; StorageName = storageName; ContainerName = containerName; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets the unique ID of the export configuration inside an /// Applciation Insights component. It is auto generated when the /// Continuous Export configuration is created. /// </summary> [JsonProperty(PropertyName = "ExportId")] public string ExportId { get; private set; } /// <summary> /// Gets the instrumentation key of the Application Insights component. /// </summary> [JsonProperty(PropertyName = "InstrumentationKey")] public string InstrumentationKey { get; private set; } /// <summary> /// Gets or sets this comma separated list of document types that will /// be exported. The possible values include 'Requests', 'Event', /// 'Exceptions', 'Metrics', 'PageViews', 'PageViewPerformance', 'Rdd', /// 'PerformanceCounters', 'Availability', 'Messages'. /// </summary> [JsonProperty(PropertyName = "RecordTypes")] public string RecordTypes { get; set; } /// <summary> /// Gets the name of the Application Insights component. /// </summary> [JsonProperty(PropertyName = "ApplicationName")] public string ApplicationName { get; private set; } /// <summary> /// Gets the subscription of the Application Insights component. /// </summary> [JsonProperty(PropertyName = "SubscriptionId")] public string SubscriptionId { get; private set; } /// <summary> /// Gets the resource group of the Application Insights component. /// </summary> [JsonProperty(PropertyName = "ResourceGroup")] public string ResourceGroup { get; private set; } /// <summary> /// Gets the destination storage account subscription ID. /// </summary> [JsonProperty(PropertyName = "DestinationStorageSubscriptionId")] public string DestinationStorageSubscriptionId { get; private set; } /// <summary> /// Gets the destination account location ID. /// </summary> [JsonProperty(PropertyName = "DestinationStorageLocationId")] public string DestinationStorageLocationId { get; private set; } /// <summary> /// Gets the name of destination account. /// </summary> [JsonProperty(PropertyName = "DestinationAccountId")] public string DestinationAccountId { get; private set; } /// <summary> /// Gets the destination type. /// </summary> [JsonProperty(PropertyName = "DestinationType")] public string DestinationType { get; private set; } /// <summary> /// Gets this will be 'true' if the Continuous Export configuration is /// enabled, otherwise it will be 'false'. /// </summary> [JsonProperty(PropertyName = "IsUserEnabled")] public string IsUserEnabled { get; private set; } /// <summary> /// Gets last time the Continuous Export configuration was updated. /// </summary> [JsonProperty(PropertyName = "LastUserUpdate")] public string LastUserUpdate { get; private set; } /// <summary> /// Gets or sets deprecated /// </summary> [JsonProperty(PropertyName = "NotificationQueueEnabled")] public string NotificationQueueEnabled { get; set; } /// <summary> /// Gets this indicates current Continuous Export configuration status. /// The possible values are 'Preparing', 'Success', 'Failure'. /// </summary> [JsonProperty(PropertyName = "ExportStatus")] public string ExportStatus { get; private set; } /// <summary> /// Gets the last time data was successfully delivered to the /// destination storage container for this Continuous Export /// configuration. /// </summary> [JsonProperty(PropertyName = "LastSuccessTime")] public string LastSuccessTime { get; private set; } /// <summary> /// Gets the last time the Continuous Export configuration started /// failing. /// </summary> [JsonProperty(PropertyName = "LastGapTime")] public string LastGapTime { get; private set; } /// <summary> /// Gets this is the reason the Continuous Export configuration started /// failing. It can be 'AzureStorageNotFound' or /// 'AzureStorageAccessDenied'. /// </summary> [JsonProperty(PropertyName = "PermanentErrorReason")] public string PermanentErrorReason { get; private set; } /// <summary> /// Gets the name of the destination storage account. /// </summary> [JsonProperty(PropertyName = "StorageName")] public string StorageName { get; private set; } /// <summary> /// Gets the name of the destination storage container. /// </summary> [JsonProperty(PropertyName = "ContainerName")] public string ContainerName { get; private set; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for operating on Azure SQL Database /// restore points. Contains operations to: List restore points. /// </summary> internal partial class DatabaseBackupOperations : IServiceOperations<SqlManagementClient>, IDatabaseBackupOperations { /// <summary> /// Initializes a new instance of the DatabaseBackupOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DatabaseBackupOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Returns a list of Azure SQL Database restore points. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database from which to retrieve /// available restore points. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List Azure Sql Database restore points /// request. /// </returns> public async Task<RestorePointListResponse> ListRestorePointsAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); TracingAdapter.Enter(invocationId, this, "ListRestorePointsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/databases/"; url = url + Uri.EscapeDataString(databaseName); url = url + "/restorePoints"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); 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 // 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 RestorePointListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RestorePointListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { RestorePoint restorePointInstance = new RestorePoint(); result.RestorePoints.Add(restorePointInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { RestorePointProperties propertiesInstance = new RestorePointProperties(); restorePointInstance.Properties = propertiesInstance; JToken restorePointTypeValue = propertiesValue["restorePointType"]; if (restorePointTypeValue != null && restorePointTypeValue.Type != JTokenType.Null) { string restorePointTypeInstance = ((string)restorePointTypeValue); propertiesInstance.RestorePointType = restorePointTypeInstance; } JToken restorePointCreationDateValue = propertiesValue["restorePointCreationDate"]; if (restorePointCreationDateValue != null && restorePointCreationDateValue.Type != JTokenType.Null) { DateTime restorePointCreationDateInstance = ((DateTime)restorePointCreationDateValue); propertiesInstance.RestorePointCreationDate = restorePointCreationDateInstance; } JToken earliestRestoreDateValue = propertiesValue["earliestRestoreDate"]; if (earliestRestoreDateValue != null && earliestRestoreDateValue.Type != JTokenType.Null) { DateTime earliestRestoreDateInstance = ((DateTime)earliestRestoreDateValue); propertiesInstance.EarliestRestoreDate = earliestRestoreDateInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); restorePointInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); restorePointInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); restorePointInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); restorePointInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); restorePointInstance.Tags.Add(tagsKey, tagsValue); } } } } } } 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(); } } } } }
// 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 OLEDB.Test.ModuleCore; using System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { [InheritRequired()] public abstract partial class TCErrorCondition : TCXMLReaderBaseGeneral { public static string xmlStr = "<a></a>"; //[Variation("XmlReader.Create((string)null)", Param = 1)] //[Variation("XmlReader.Create((TextReader)null)", Param = 2)] //[Variation("XmlReader.Create((Stream)null)", Param = 3)] //[Variation("XmlReader.Create((string)null, null)", Param = 4)] //[Variation("XmlReader.Create((TextReader)null, null)", Param = 5)] //[Variation("XmlReader.Create((Stream)null, null)", Param = 6)] //[Variation("XmlReader.Create((XmlReader)null, null)", Param = 7)] //[Variation("XmlReader.Create((Stream)null, null, (string) null)", Param = 8)] //[Variation("XmlReader.Create((Stream)null, null, (XmlParserContext)null)", Param = 9)] //[Variation("XmlReader.Create((string)null, null, null)", Param = 10)] //[Variation("XmlReader.Create((TextReader)null, null, (string)null)", Param = 11)] //[Variation("XmlReader.Create((TextReader)null, null, (XmlParserContext)null)", Param = 12)] //[Variation("new XmlNamespaceManager(null)", Param = 13)] //[Variation("XmlReader.IsName(null)", Param = 14)] //[Variation("XmlReader.IsNameToken(null)", Param = 15)] //[Variation("new XmlValidatingReader(null)", Param = 16)] //[Variation("new XmlTextReader(null)", Param = 17)] //[Variation("new XmlNodeReader(null)", Param = 18)] public int v1() { int param = (int)CurVariation.Param; try { switch (param) { case 1: ReaderHelper.Create((string)null); break; case 2: ReaderHelper.Create((TextReader)null); break; case 3: ReaderHelper.Create((Stream)null); break; case 4: ReaderHelper.Create((string)null, null); break; case 5: ReaderHelper.Create((TextReader)null, null); break; case 6: ReaderHelper.Create((Stream)null, null); break; case 7: ReaderHelper.Create((XmlReader)null, null); break; case 8: ReaderHelper.Create((Stream)null, null, (string)null); break; case 9: ReaderHelper.Create((Stream)null, null, (XmlParserContext)null); break; case 10: ReaderHelper.Create((string)null, null, null); break; case 11: ReaderHelper.Create((TextReader)null, null, (string)null); break; case 12: ReaderHelper.Create((TextReader)null, null, (XmlParserContext)null); break; case 13: new XmlNamespaceManager(null); break; case 14: XmlReader.IsName(null); break; case 15: XmlReader.IsNameToken(null); break; default: return TEST_PASS; } } catch (ArgumentNullException) { try { switch (param) { case 1: ReaderHelper.Create((string)null); break; case 2: ReaderHelper.Create((TextReader)null); break; case 3: ReaderHelper.Create((Stream)null); break; case 4: ReaderHelper.Create((string)null, null); break; case 5: ReaderHelper.Create((TextReader)null, null); break; case 6: ReaderHelper.Create((Stream)null, null); break; case 7: ReaderHelper.Create((XmlReader)null, null); break; case 8: ReaderHelper.Create((Stream)null, null, (string)null); break; case 9: ReaderHelper.Create((Stream)null, null, (XmlParserContext)null); break; case 10: ReaderHelper.Create((string)null, null, null); break; case 11: ReaderHelper.Create((TextReader)null, null, (string)null); break; case 12: ReaderHelper.Create((TextReader)null, null, (XmlParserContext)null); break; default: return TEST_PASS; } } catch (ArgumentNullException) { return TEST_PASS; } } catch (NullReferenceException) { try { switch (param) { case 13: new XmlNamespaceManager(null); break; case 14: XmlReader.IsName(null); break; case 15: XmlReader.IsNameToken(null); break; default: return TEST_PASS; } } catch (NullReferenceException) { return TEST_PASS; } } return TEST_FAIL; } //[Variation("XmlReader.Create(String.Empty)", Param = 1)] //[Variation("XmlReader.Create(String.Empty, null)", Param = 2)] //[Variation("XmlReader.Create(String.Empty, null, (XmlParserContext)null)", Param = 3)] //[Variation("XmlReader.Create(new Stream(), null, (string)null)", Param = 4)] //[Variation("XmlReader.Create(new Stream(), null, (XmlParserContext)null)", Param = 5)] public int v1a() { int param = (int)CurVariation.Param; try { switch (param) { case 1: ReaderHelper.Create(String.Empty); break; case 2: ReaderHelper.Create(String.Empty, null); break; case 3: ReaderHelper.Create(String.Empty, null, (XmlParserContext)null); break; } } catch (ArgumentException) { try { switch (param) { case 1: ReaderHelper.Create(String.Empty); break; case 2: ReaderHelper.Create(String.Empty, null); break; case 3: ReaderHelper.Create(String.Empty, null, (XmlParserContext)null); break; } } catch (ArgumentException) { return TEST_PASS; } } return TEST_FAIL; } //[Variation("XmlReader.Create(Stream)", Param = 1)] //[Variation("XmlReader.Create(String)", Param = 2)] //[Variation("XmlReader.Create(TextReader)", Param = 3)] //[Variation("XmlReader.Create(Stream, XmlReaderSettings)", Param = 4)] //[Variation("XmlReader.Create(String, XmlReaderSettings)", Param = 5)] //[Variation("XmlReader.Create(TextReader, XmlReaderSettings)", Param = 6)] //[Variation("XmlReader.Create(XmlReader, XmlReaderSettings)", Param = 7)] //[Variation("XmlReader.Create(Stream, XmlReaderSettings, string)", Param = 8)] //[Variation("XmlReader.Create(Stream, XmlReaderSettings, XmlParserContext)", Param = 9)] //[Variation("XmlReader.Create(String, XmlReaderSettings, XmlParserContext)", Param = 10)] //[Variation("XmlReader.Create(TextReader, XmlReaderSettings, string)", Param = 11)] //[Variation("XmlReader.Create(TextReader, XmlReaderSettings, XmlParserContext)", Param = 12)] public int v1b() { int param = (int)CurVariation.Param; XmlReaderSettings rs = new XmlReaderSettings(); XmlReader r = ReaderHelper.Create(new StringReader("<a/>")); string uri = TestData + @"Common/file_23.xml"; try { switch (param) { case 2: ReaderHelper.Create(uri); break; case 3: ReaderHelper.Create(new StringReader("<a/>")); break; case 5: ReaderHelper.Create(uri, rs); break; case 6: ReaderHelper.Create(new StringReader("<a/>"), rs); break; case 7: ReaderHelper.Create(r, rs); break; case 10: ReaderHelper.Create(uri, rs, (XmlParserContext)null); break; case 11: ReaderHelper.Create(new StringReader("<a/>"), rs, uri); break; case 12: ReaderHelper.Create(new StringReader("<a/>"), rs, (XmlParserContext)null); break; } } catch (FileNotFoundException) { return (IsXsltReader()) ? TEST_PASS : TEST_FAIL; } return TEST_PASS; } //[Variation("XmlReader[null])", Param = 1)] //[Variation("XmlReader[null, null]", Param = 2)] //[Variation("XmlReader.GetAttribute(null)", Param = 3)] //[Variation("XmlReader.GetAttribute(null, null)", Param = 4)] //[Variation("XmlReader.MoveToAttribute(null)", Param = 5)] //[Variation("XmlReader.MoveToAttribute(null, null)", Param = 6)] //[Variation("XmlReader.ReadContentAsBase64(null, 0, 0)", Param = 7)] //[Variation("XmlReader.ReadContentAsBinHex(null, 0, 0)", Param = 8)] //[Variation("XmlReader.ReadElementContentAs(null, null, null, null)", Param = 9)] //[Variation("XmlReader.ReadElementContentAs(null, null, 'a', null)", Param = 10)] //[Variation("XmlReader.ReadElementContentAsBase64(null, 0, 0)", Param = 11)] //[Variation("XmlReader.ReadElementContentAsBinHex(null, 0, 0)", Param = 12)] //[Variation("XmlReader.ReadElementContentAsBoolean(null, null)", Param = 13)] //[Variation("XmlReader.ReadElementContentAsBoolean('a', null)", Param = 14)] //[Variation("XmlReader.ReadElementContentAsDateTime(null, null)", Param = 15)] //[Variation("XmlReader.ReadElementContentAsDateTime('a', null)", Param = 16)] //[Variation("XmlReader.ReadElementContentAsDecimal(null, null)", Param = 17)] //[Variation("XmlReader.ReadElementContentAsDecimal('a', null)", Param = 18)] //[Variation("XmlReader.ReadElementContentAsDouble(null, null)", Param = 19)] //[Variation("XmlReader.ReadElementContentAsDouble('a', null)", Param = 20)] //[Variation("XmlReader.ReadElementContentAsFloat(null, null)", Param = 21)] //[Variation("XmlReader.ReadElementContentAsFloat('a', null)", Param = 22)] //[Variation("XmlReader.ReadElementContentAsInt(null, null)", Param = 23)] //[Variation("XmlReader.ReadElementContentAsInt('a', null)", Param = 24)] //[Variation("XmlReader.ReadElementContentAsLong(null, null)", Param = 25)] //[Variation("XmlReader.ReadElementContentAsLong('a', null)", Param = 26)] //[Variation("XmlReader.ReadElementContentAsObject(null, null)", Param = 27)] //[Variation("XmlReader.ReadElementContentAsObject('a', null)", Param = 28)] //[Variation("XmlReader.ReadElementContentAsString(null, null)", Param = 29)] //[Variation("XmlReader.ReadElementContentAsString('a', null)", Param = 30)] //[Variation("XmlReader.ReadToDescendant(null)", Param = 31)] //[Variation("XmlReader.ReadToDescendant(null, null)", Param = 32)] //[Variation("XmlReader.ReadToDescendant('a', null)", Param = 33)] //[Variation("XmlReader.ReadToFollowing(null)", Param = 34)] //[Variation("XmlReader.ReadToFollowing(null, null)", Param = 35)] //[Variation("XmlReader.ReadToFollowing('a', null)", Param = 36)] //[Variation("XmlReader.ReadToNextSibling(null)", Param = 37)] //[Variation("XmlReader.ReadToNextSibling(null, null)", Param = 38)] //[Variation("XmlReader.ReadToNextSibling('a', null)", Param = 39)] //[Variation("XmlReader.ReadValueChunk(null, 0, 0)", Param = 40)] //[Variation("XmlReader.ReadContentAs(null, null)", Param = 41)] public int v2() { int param = (int)CurVariation.Param; ReloadSource(new StringReader(@"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + "<b><c xsi:type='f:mytype'>some content</c></b></a>")); string s = ""; try { switch (param) { case 1: s = DataReader[null]; break; case 2: s = DataReader[null, null]; break; case 3: s = DataReader.GetAttribute(null); break; case 4: s = DataReader.GetAttribute(null, null); break; case 5: DataReader.MoveToAttribute(null); break; case 6: DataReader.MoveToAttribute(null, null); break; case 7: DataReader.ReadContentAsBase64(null, 0, 0); break; case 8: DataReader.ReadContentAsBinHex(null, 0, 0); break; case 9: DataReader.ReadElementContentAs(null, null, null, null); break; case 10: DataReader.ReadElementContentAs(null, null, "a", null); break; case 11: DataReader.ReadElementContentAsBase64(null, 0, 0); break; case 12: DataReader.ReadElementContentAsBinHex(null, 0, 0); break; case 13: DataReader.ReadElementContentAsBoolean(null, null); break; case 14: DataReader.ReadElementContentAsBoolean("a", null); break; case 17: DataReader.ReadElementContentAsDecimal(null, null); break; case 18: DataReader.ReadElementContentAsDecimal("a", null); break; case 19: DataReader.ReadElementContentAsDouble(null, null); break; case 20: DataReader.ReadElementContentAsDouble("a", null); break; case 21: DataReader.ReadElementContentAsFloat(null, null); break; case 22: DataReader.ReadElementContentAsFloat("a", null); break; case 23: DataReader.ReadElementContentAsInt(null, null); break; case 24: DataReader.ReadElementContentAsInt("a", null); break; case 25: DataReader.ReadElementContentAsLong(null, null); break; case 26: DataReader.ReadElementContentAsLong("a", null); break; case 27: DataReader.ReadElementContentAsObject(null, null); break; case 28: DataReader.ReadElementContentAsObject("a", null); break; case 29: DataReader.Read(); DataReader.ReadElementContentAsString(null, null); break; case 30: DataReader.Read(); DataReader.ReadElementContentAsString("a", null); break; case 31: DataReader.ReadToDescendant(null); break; case 32: DataReader.ReadToDescendant(null, null); break; case 33: DataReader.ReadToDescendant("a", null); break; case 34: DataReader.ReadToFollowing(null); break; case 35: DataReader.ReadToFollowing(null, null); break; case 36: DataReader.ReadToFollowing("a", null); break; case 37: DataReader.ReadToNextSibling(null); break; case 38: DataReader.ReadToNextSibling(null, null); break; case 39: DataReader.ReadToNextSibling("a", null); break; case 40: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(null, 0, 0); break; case 41: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadContentAs(null, null); break; } } catch (ArgumentNullException) { try { switch (param) { case 2: s = DataReader[null, null]; break; case 4: s = DataReader.GetAttribute(null, null); break; case 6: DataReader.MoveToAttribute(null, null); break; case 7: DataReader.ReadContentAsBase64(null, 0, 0); break; case 8: DataReader.ReadContentAsBinHex(null, 0, 0); break; case 9: DataReader.ReadElementContentAs(null, null, null, null); break; case 10: DataReader.ReadElementContentAs(null, null, "a", null); break; case 11: DataReader.ReadElementContentAsBase64(null, 0, 0); break; case 12: DataReader.ReadElementContentAsBinHex(null, 0, 0); break; case 13: DataReader.ReadElementContentAsBoolean(null, null); break; case 14: DataReader.ReadElementContentAsBoolean("a", null); break; case 17: DataReader.ReadElementContentAsDecimal(null, null); break; case 18: DataReader.ReadElementContentAsDecimal("a", null); break; case 19: DataReader.ReadElementContentAsDouble(null, null); break; case 20: DataReader.ReadElementContentAsDouble("a", null); break; case 21: DataReader.ReadElementContentAsFloat(null, null); break; case 22: DataReader.ReadElementContentAsFloat("a", null); break; case 23: DataReader.ReadElementContentAsInt(null, null); break; case 24: DataReader.ReadElementContentAsInt("a", null); break; case 25: DataReader.ReadElementContentAsLong(null, null); break; case 26: DataReader.ReadElementContentAsLong("a", null); break; case 27: DataReader.ReadElementContentAsObject(null, null); break; case 28: DataReader.ReadElementContentAsObject("a", null); break; case 29: DataReader.ReadElementContentAsString(null, null); break; case 30: DataReader.ReadElementContentAsString("a", null); break; case 31: DataReader.ReadToDescendant(null); break; case 32: DataReader.ReadToDescendant(null, null); break; case 33: DataReader.ReadToDescendant("a", null); break; case 34: DataReader.ReadToFollowing(null); break; case 35: DataReader.ReadToFollowing(null, null); break; case 36: DataReader.ReadToFollowing("a", null); break; case 37: DataReader.ReadToNextSibling(null); break; case 38: DataReader.ReadToNextSibling(null, null); break; case 39: DataReader.ReadToNextSibling("a", null); break; case 40: DataReader.ReadValueChunk(null, 0, 0); break; case 41: DataReader.ReadContentAs(null, null); break; } } catch (ArgumentNullException) { return TEST_PASS; } catch (InvalidOperationException) { if (IsSubtreeReader()) return TEST_PASS; } } catch (NotSupportedException) { if (IsCustomReader() && (param == 7 || param == 8 || param == 11 || param == 12 || param == 40)) return TEST_PASS; if ((IsCharCheckingReader() || IsXmlTextReader()) && param == 40) return TEST_PASS; return TEST_FAIL; } catch (NullReferenceException) { try { switch (param) { case 1: s = DataReader[null]; break; case 3: s = DataReader.GetAttribute(null); break; case 5: DataReader.MoveToAttribute(null); break; } } catch (NullReferenceException) { return TEST_PASS; } } finally { DataReader.Close(); } return (IsCharCheckingReader() && (param == 7 || param == 8) || IsSubtreeReader()) ? TEST_PASS : TEST_FAIL; } //[Variation("XmlReader[-1]", Param = 1)] //[Variation("XmlReader[0]", Param = 2)] //[Variation("XmlReader.GetAttribute(-1)", Param = 3)] //[Variation("XmlReader.GetAttribute(0)", Param = 4)] //[Variation("XmlReader.MoveToAttribute(-1)", Param = 5)] //[Variation("XmlReader.MoveToAttribute(0)", Param = 6)] public int v3() { int param = (int)CurVariation.Param; ReloadSource(new StringReader(xmlStr)); string s = ""; try { switch (param) { case 1: s = DataReader[-1]; break; case 2: s = DataReader[0]; break; case 3: s = DataReader.GetAttribute(-1); break; case 4: s = DataReader.GetAttribute(0); break; case 5: DataReader.MoveToAttribute(-1); break; case 6: DataReader.MoveToAttribute(0); break; } } catch (ArgumentOutOfRangeException) { try { switch (param) { case 1: s = DataReader[-1]; break; case 2: s = DataReader[0]; break; case 3: s = DataReader.GetAttribute(-1); break; case 4: s = DataReader.GetAttribute(0); break; case 5: DataReader.MoveToAttribute(-1); break; case 6: DataReader.MoveToAttribute(0); break; } } catch (ArgumentOutOfRangeException) { return TEST_PASS; } } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("nsm.AddNamespace('p', null)", Param = 1)] //[Variation("nsm.RemoveNamespace('p', null)", Param = 2)] public int v4() { int param = (int)CurVariation.Param; string xml = @"<a>p:foo</a>"; ReloadSource(new StringReader(xml)); DataReader.Read(); DataReader.Read(); XmlNamespaceManager nsm = new XmlNamespaceManager(DataReader.NameTable); try { if (param == 1) nsm.AddNamespace("p", null); else nsm.RemoveNamespace("p", null); } catch (ArgumentNullException) { try { if (param == 1) nsm.AddNamespace("p", null); else nsm.RemoveNamespace("p", null); } catch (ArgumentNullException) { return TEST_PASS; } } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("nsm.AddNamespace(null, 'ns1')", Param = 1)] //[Variation("nsm.RemoveNamespace(null, 'ns1')", Param = 2)] public int v5() { int param = (int)CurVariation.Param; string xml = @"<a>p:foo</a>"; ReloadSource(new StringReader(xml)); DataReader.Read(); DataReader.Read(); XmlNamespaceManager nsm = new XmlNamespaceManager(DataReader.NameTable); try { if (param == 1) nsm.AddNamespace(null, "ns1"); else nsm.RemoveNamespace(null, "ns1"); } catch (ArgumentNullException) { try { if (param == 1) nsm.AddNamespace(null, "ns1"); else nsm.RemoveNamespace(null, "ns1"); } catch (ArgumentNullException) { return TEST_PASS; } } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("DataReader.ReadContentAs(null, nsm)")] public int v6() { string xml = @"<a>p:foo</a>"; ReloadSource(new StringReader(xml)); DataReader.Read(); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); XmlNamespaceManager nsm = new XmlNamespaceManager(DataReader.NameTable); nsm.AddNamespace("p", "ns1"); try { XmlQualifiedName qname = (XmlQualifiedName)DataReader.ReadContentAs(null, nsm); } catch (ArgumentNullException) { try { XmlQualifiedName qname = (XmlQualifiedName)DataReader.ReadContentAs(null, nsm); } catch (ArgumentNullException) { return TEST_PASS; } catch (InvalidOperationException) { if (IsSubtreeReader()) return TEST_PASS; } } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("nsm.AddNamespace('xml', 'ns1')")] public int v7() { string xml = @"<a>p:foo</a>"; ReloadSource(new StringReader(xml)); DataReader.Read(); DataReader.Read(); XmlNamespaceManager nsm = new XmlNamespaceManager(DataReader.NameTable); try { nsm.AddNamespace("xml", "ns1"); } catch (ArgumentException) { try { nsm.AddNamespace("xml", "ns1"); } catch (ArgumentException) { return TEST_PASS; } } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("Test Integrity of all values after Error")] public int V8() { ReloadSourceStr(@"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + "<b><c xsi:type='f:mytype'>some content</c></b></a>"); try { DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(null, 0, 0); } catch (Exception) { CError.Compare(DataReader.AttributeCount, 2, "AttributeCount"); CError.Compare(DataReader.BaseURI, string.Empty, "BaseURI"); CError.Compare(DataReader.CanReadBinaryContent, IsCustomReader() ? false : true, "CanReadBinaryContent"); CError.Compare(DataReader.CanReadValueChunk, (IsCharCheckingReader() || IsCustomReader() || IsXmlTextReader()) ? false : true, "CanReadValueChunk"); CError.Compare(DataReader.Depth, 1, "Depth"); CError.Compare(DataReader.EOF, false, "EOF"); CError.Compare(DataReader.HasAttributes, true, "HasAttributes"); CError.Compare(DataReader.IsDefault, false, "IsDefault"); CError.Compare(DataReader.IsEmptyElement, false, "IsEmptyElement"); if (!(IsCustomReader())) { CError.Compare(DataReader.LineNumber, 1, "LN"); CError.Compare(DataReader.LinePosition, 4, "LP"); } CError.Compare(DataReader.LocalName, "f", "LocalName"); CError.Compare(DataReader.Name, "xmlns:f", "Name"); CError.Compare(DataReader.NamespaceURI, "http://www.w3.org/2000/xmlns/", "NamespaceURI"); CError.Compare(DataReader.NodeType, XmlNodeType.Attribute, "NodeType"); CError.Compare(DataReader.Prefix, "xmlns", "Prefix"); CError.Compare(DataReader.Read(), true, "Read"); CError.Compare(DataReader.ReadInnerXml(), "<c xsi:type=\"f:mytype\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">some content</c>", "ReadInnerXml"); CError.Compare(DataReader.ReadOuterXml(), string.Empty, "ReadOuterXml"); CError.Compare(DataReader.ReadState, ReadState.EndOfFile, "ReadState"); CError.Compare(DataReader.ReadToDescendant("b"), false, "ReadToDescendant"); CError.Compare(DataReader.ReadToFollowing("b"), false, "ReadToFollowing"); CError.Compare(DataReader.ReadToNextSibling("b"), false, "ReadToNextSibling"); if ((DataReader.Settings != null)) { CError.Compare(DataReader.Settings.CheckCharacters, true, "CheckCharacters"); CError.Compare(DataReader.Settings.CloseInput, false, "CloseInput"); CError.Compare(DataReader.Settings.ConformanceLevel, ConformanceLevel.Fragment, "ConformanceLevel"); CError.Compare(DataReader.Settings.IgnoreComments, false, "IgnoreComments"); CError.Compare(DataReader.Settings.IgnoreProcessingInstructions, false, "IgnoreProcessingInstructions"); CError.Compare(DataReader.Settings.IgnoreWhitespace, false, "IgnoreWhitespace"); CError.Compare(DataReader.Settings.LineNumberOffset, 0, "LineNumberOffset"); CError.Compare(DataReader.Settings.LinePositionOffset, 0, "LinePositionOffset"); CError.Compare(DataReader.Settings.MaxCharactersInDocument, 0L, "MaxCharactersInDocument"); CError.Compare(DataReader.Settings.NameTable, null, "Settings.NameTable"); } CError.Compare(DataReader.Value, string.Empty, "Value"); CError.Compare(DataReader.ValueType, typeof(System.String), "ValueType"); CError.Compare(DataReader.XmlLang, string.Empty, "XmlLang"); CError.Compare(DataReader.XmlSpace, XmlSpace.None, "XmlSpace"); CError.Compare(DataReader.GetAttribute("b"), null, "GetAttribute('b')"); CError.Compare(DataReader.Equals(null), false, "Equals(null)"); CError.Compare(DataReader.IsStartElement(), false, "IsStartElement()"); CError.Compare(DataReader.LookupNamespace("b"), null, "LookupNamespace('b')"); CError.Compare(DataReader.MoveToAttribute("b"), false, "MoveToAttribute('b')"); CError.Compare(DataReader.MoveToContent(), XmlNodeType.None, "MoveToContent()"); CError.Compare(DataReader.MoveToElement(), false, "MoveToElement()"); CError.Compare(DataReader.MoveToFirstAttribute(), false, "MoveToFirstAttribute()"); CError.Compare(DataReader.MoveToNextAttribute(), false, "MoveToNextAttribute()"); CError.Equals(DataReader.HasValue, false, "HasValue"); CError.Equals(DataReader.CanResolveEntity, true, "CanResolveEntity"); CError.Equals(DataReader.ReadAttributeValue(), false, "ReadAttributeValue()"); try { DataReader.ResolveEntity(); CError.Compare(false, "failed0"); } catch (InvalidOperationException) { } try { DataReader.ReadContentAsObject(); CError.Compare(false, "failed1"); } catch (InvalidOperationException) { } try { DataReader.ReadContentAsString(); CError.Compare(false, "failed2"); } catch (InvalidOperationException) { } } return TEST_PASS; } //[Variation("2.Test Integrity of all values after Dispose")] public int V9a() { ReloadSource(); DataReader.Dispose(); DataReader.Dispose(); DataReader.Dispose(); CError.Compare(DataReader.AttributeCount, 0, "AttributeCount"); CError.Compare(DataReader.BaseURI, string.Empty, "BaseURI"); CError.Compare(DataReader.CanReadBinaryContent, IsCustomReader() ? false : true, "CanReadBinaryContent"); CError.Compare(DataReader.CanReadValueChunk, (IsCharCheckingReader() || IsCustomReader() || IsXmlTextReader()) ? false : true, "CanReadValueChunk"); CError.Compare(DataReader.Depth, 0, "Depth"); CError.Compare(DataReader.EOF, IsSubtreeReader() ? true : false, "EOF"); CError.Compare(DataReader.HasAttributes, false, "HasAttributes"); CError.Compare(DataReader.IsDefault, false, "IsDefault"); CError.Compare(DataReader.IsEmptyElement, false, "IsEmptyElement"); if (!IsCustomReader()) { CError.Compare(DataReader.LineNumber, 0, "LN"); CError.Compare(DataReader.LinePosition, 0, "LP"); } CError.Compare(DataReader.LocalName, String.Empty, "LocalName"); CError.Compare(DataReader.Name, String.Empty, "Name"); CError.Compare(DataReader.NamespaceURI, String.Empty, "NamespaceURI"); CError.Compare(DataReader.NodeType, XmlNodeType.None, "NodeType"); CError.Compare(DataReader.Prefix, String.Empty, "Prefix"); CError.Compare(DataReader.Read(), IsCharCheckingReader(), "Read"); CError.Compare(DataReader.ReadInnerXml(), String.Empty, "ReadInnerXml"); CError.Compare(DataReader.ReadOuterXml(), String.Empty, "ReadOuterXml"); CError.Compare(DataReader.ReadState, ReadState.Closed, "ReadState"); CError.Compare(DataReader.ReadToDescendant("b"), false, "ReadToDescendant"); CError.Compare(DataReader.ReadToFollowing("b"), false, "ReadToFollowing"); CError.Compare(DataReader.ReadToNextSibling("b"), false, "ReadToNextSibling"); if ((DataReader.Settings != null)) { CError.Compare(DataReader.Settings.CheckCharacters, true, "CheckCharacters"); CError.Compare(DataReader.Settings.CloseInput, false, "CloseInput"); CError.Compare(DataReader.Settings.ConformanceLevel, ConformanceLevel.Document, "ConformanceLevel"); CError.Compare(DataReader.Settings.IgnoreComments, false, "IgnoreComments"); CError.Compare(DataReader.Settings.IgnoreProcessingInstructions, false, "IgnoreProcessingInstructions"); CError.Compare(DataReader.Settings.IgnoreWhitespace, false, "IgnoreWhitespace"); CError.Compare(DataReader.Settings.LineNumberOffset, 0, "LineNumberOffset"); CError.Compare(DataReader.Settings.LinePositionOffset, 0, "LinePositionOffset"); CError.Compare(DataReader.Settings.MaxCharactersInDocument, 0L, "MaxCharactersInDocument"); CError.Compare(DataReader.Settings.NameTable, null, "Settings.NameTable"); } CError.Compare(DataReader.Value, string.Empty, "Value"); CError.Compare(DataReader.ValueType, typeof(System.String), "ValueType"); CError.Compare(DataReader.XmlLang, string.Empty, "XmlLang"); CError.Compare(DataReader.XmlSpace, XmlSpace.None, "XmlSpace"); CError.Compare(DataReader.GetAttribute("b"), null, "GetAttribute('b')"); CError.Compare(DataReader.Equals(null), false, "Equals(null)"); CError.Compare(DataReader.IsStartElement(), false, "IsStartElement()"); CError.Compare(DataReader.LookupNamespace("b"), null, "LookupNamespace('b')"); CError.Compare(DataReader.MoveToAttribute("b"), false, "MoveToAttribute('b')"); CError.Compare(DataReader.MoveToContent(), XmlNodeType.None, "MoveToContent()"); CError.Compare(DataReader.MoveToElement(), false, "MoveToElement()"); CError.Compare(DataReader.MoveToFirstAttribute(), false, "MoveToFirstAttribute()"); CError.Compare(DataReader.MoveToNextAttribute(), false, "MoveToNextAttribute()"); CError.Equals(DataReader.HasValue, false, "HasValue"); CError.Equals(DataReader.CanResolveEntity, true, "CanResolveEntity"); CError.Equals(DataReader.ReadAttributeValue(), false, "ReadAttributeValue()"); try { DataReader.ResolveEntity(); CError.Compare(false, "failed0"); } catch (InvalidOperationException) { } try { DataReader.ReadContentAsObject(); CError.Compare(false, "failed1"); } catch (InvalidOperationException) { } try { DataReader.ReadContentAsString(); CError.Compare(false, "failed2"); } catch (InvalidOperationException) { } return TEST_PASS; } //[Variation("XmlCharType::IsName, IsNmToken")] public int v10() { CError.Compare(XmlReader.IsName("a"), "Error1"); CError.Compare(!XmlReader.IsName("@a"), "Error2"); CError.Compare(!XmlReader.IsName("b@a"), "Error3"); CError.Compare(XmlReader.IsNameToken("a"), "Error4"); CError.Compare(!XmlReader.IsNameToken("@a"), "Error5"); CError.Compare(!XmlReader.IsNameToken("b@a"), "Error6"); return TEST_PASS; } //[Variation("XmlReader[String.Empty])", Param = 1)] //[Variation("XmlReader[String.Empty, String.Empty]", Param = 2)] //[Variation("XmlReader.GetAttribute(String.Empty)", Param = 3)] //[Variation("XmlReader.GetAttribute(String.Empty, String.Empty)", Param = 4)] //[Variation("XmlReader.MoveToAttribute(String.Empty)", Param = 5)] //[Variation("XmlReader.MoveToAttribute(String.Empty, String.Empty)", Param = 6)] //[Variation("XmlReader.ReadElementContentAs(String.Empty, String.Empty, String.Empty, String.Empty)", Param = 9)] //[Variation("XmlReader.ReadElementContentAs(String.Empty, String.Empty, 'a', String.Empty)", Param = 10)] //[Variation("XmlReader.ReadElementContentAsBoolean(String.Empty, String.Empty)", Param = 13)] //[Variation("XmlReader.ReadElementContentAsBoolean('a', String.Empty)", Param = 14)] //[Variation("XmlReader.ReadElementContentAsDateTime(String.Empty, String.Empty)", Param = 15)] //[Variation("XmlReader.ReadElementContentAsDateTime('a', String.Empty)", Param = 16)] //[Variation("XmlReader.ReadElementContentAsDecimal(String.Empty, String.Empty)", Param = 17)] //[Variation("XmlReader.ReadElementContentAsDecimal('a', String.Empty)", Param = 18)] //[Variation("XmlReader.ReadElementContentAsDouble(String.Empty, String.Empty)", Param = 19)] //[Variation("XmlReader.ReadElementContentAsDouble('a', String.Empty)", Param = 20)] //[Variation("XmlReader.ReadElementContentAsFloat(String.Empty, String.Empty)", Param = 21)] //[Variation("XmlReader.ReadElementContentAsFloat('a', String.Empty)", Param = 22)] //[Variation("XmlReader.ReadElementContentAsInt(String.Empty, String.Empty)", Param = 23)] //[Variation("XmlReader.ReadElementContentAsInt('a', String.Empty)", Param = 24)] //[Variation("XmlReader.ReadElementContentAsLong(String.Empty, String.Empty)", Param = 25)] //[Variation("XmlReader.ReadElementContentAsLong('a', String.Empty)", Param = 26)] //[Variation("XmlReader.ReadElementContentAsObject(String.Empty, String.Empty)", Param = 27)] //[Variation("XmlReader.ReadElementContentAsObject('a', String.Empty)", Param = 28)] //[Variation("XmlReader.ReadElementContentAsString(String.Empty, String.Empty)", Param = 29)] //[Variation("XmlReader.ReadElementContentAsString('a', String.Empty)", Param = 30)] //[Variation("XmlReader.ReadToDescendant(String.Empty)", Param = 31)] //[Variation("XmlReader.ReadToDescendant(String.Empty, String.Empty)", Param = 32)] //[Variation("XmlReader.ReadToDescendant('a', String.Empty)", Param = 33)] //[Variation("XmlReader.ReadToFollowing(String.Empty)", Param = 34)] //[Variation("XmlReader.ReadToFollowing(String.Empty, String.Empty)", Param = 35)] //[Variation("XmlReader.ReadToFollowing('a', String.Empty)", Param = 36)] //[Variation("XmlReader.ReadToNextSibling(String.Empty)", Param = 37)] //[Variation("XmlReader.ReadToNextSibling(String.Empty, String.Empty)", Param = 38)] //[Variation("XmlReader.ReadToNextSibling('a', String.Empty)", Param = 39)] public int v11() { int param = (int)CurVariation.Param; ReloadSource(new StringReader(xmlStr)); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); string s = ""; switch (param) { case 1: s = DataReader[String.Empty]; return TEST_PASS; case 2: s = DataReader[String.Empty, String.Empty]; return TEST_PASS; case 3: s = DataReader.GetAttribute(String.Empty); return TEST_PASS; case 4: s = DataReader.GetAttribute(String.Empty, String.Empty); return TEST_PASS; case 5: DataReader.MoveToAttribute(String.Empty); return TEST_PASS; case 6: DataReader.MoveToAttribute(String.Empty, String.Empty); return TEST_PASS; case 10: DataReader.ReadElementContentAs(typeof(String), null, "a", String.Empty); return TEST_PASS; case 28: DataReader.ReadElementContentAsObject("a", String.Empty); return TEST_PASS; case 30: DataReader.ReadElementContentAsString("a", String.Empty); return TEST_PASS; case 33: DataReader.ReadToDescendant("a", String.Empty); return TEST_PASS; case 36: DataReader.ReadToFollowing("a", String.Empty); return TEST_PASS; case 39: DataReader.ReadToNextSibling("a", String.Empty); return TEST_PASS; } try { switch (param) { case 9: DataReader.ReadElementContentAs(typeof(String), null, String.Empty, String.Empty); break; case 13: DataReader.ReadElementContentAsBoolean(String.Empty, String.Empty); break; case 14: DataReader.ReadElementContentAsBoolean("a", String.Empty); break; case 17: DataReader.ReadElementContentAsDecimal(String.Empty, String.Empty); break; case 18: DataReader.ReadElementContentAsDecimal("a", String.Empty); break; case 19: DataReader.ReadElementContentAsDouble(String.Empty, String.Empty); break; case 20: DataReader.ReadElementContentAsDouble("a", String.Empty); break; case 21: DataReader.ReadElementContentAsFloat(String.Empty, String.Empty); break; case 22: DataReader.ReadElementContentAsFloat("a", String.Empty); break; case 23: DataReader.ReadElementContentAsInt(String.Empty, String.Empty); break; case 24: DataReader.ReadElementContentAsInt("a", String.Empty); break; case 25: DataReader.ReadElementContentAsLong(String.Empty, String.Empty); break; case 26: DataReader.ReadElementContentAsLong("a", String.Empty); break; case 27: DataReader.ReadElementContentAsObject(String.Empty, String.Empty); break; case 29: DataReader.ReadElementContentAsString(String.Empty, String.Empty); break; case 31: DataReader.ReadToDescendant(String.Empty); break; case 32: DataReader.ReadToDescendant(String.Empty, String.Empty); break; case 34: DataReader.ReadToFollowing(String.Empty); break; case 35: DataReader.ReadToFollowing(String.Empty, String.Empty); break; case 37: DataReader.ReadToNextSibling(String.Empty); break; case 38: DataReader.ReadToNextSibling(String.Empty, String.Empty); break; } } catch (ArgumentException) { try { switch (param) { case 9: DataReader.ReadElementContentAs(typeof(String), null, String.Empty, String.Empty); break; case 13: DataReader.ReadElementContentAsBoolean(String.Empty, String.Empty); break; case 14: DataReader.ReadElementContentAsBoolean("a", String.Empty); break; case 17: DataReader.ReadElementContentAsDecimal(String.Empty, String.Empty); break; case 18: DataReader.ReadElementContentAsDecimal("a", String.Empty); break; case 19: DataReader.ReadElementContentAsDouble(String.Empty, String.Empty); break; case 20: DataReader.ReadElementContentAsDouble("a", String.Empty); break; case 21: DataReader.ReadElementContentAsFloat(String.Empty, String.Empty); break; case 22: DataReader.ReadElementContentAsFloat("a", String.Empty); break; case 23: DataReader.ReadElementContentAsInt(String.Empty, String.Empty); break; case 24: DataReader.ReadElementContentAsInt("a", String.Empty); break; case 25: DataReader.ReadElementContentAsLong(String.Empty, String.Empty); break; case 26: DataReader.ReadElementContentAsLong("a", String.Empty); break; case 27: DataReader.ReadElementContentAsObject(String.Empty, String.Empty); break; case 29: DataReader.ReadElementContentAsString(String.Empty, String.Empty); break; case 31: DataReader.ReadToDescendant(String.Empty); break; case 32: DataReader.ReadToDescendant(String.Empty, String.Empty); break; case 34: DataReader.ReadToFollowing(String.Empty); break; case 35: DataReader.ReadToFollowing(String.Empty, String.Empty); break; case 37: DataReader.ReadToNextSibling(String.Empty); break; case 38: DataReader.ReadToNextSibling(String.Empty, String.Empty); break; } } catch (ArgumentException) { return TEST_PASS; } } catch (NotSupportedException) { if (IsCustomReader() && (param == 7 || param == 8 || param == 11 || param == 12)) return TEST_PASS; return TEST_FAIL; } catch (FormatException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation(Desc = "XmlReaderSettings.ConformanceLevel - invalid values", Priority = 2)] public int var12() { return TEST_SKIPPED; } //[Variation(Desc = "XmlReaderSettings.LineNumberOffset - invalid values", Param = 1)] //[Variation(Desc = "XmlReaderSettings.LinePositionOffset - invalid values", Param = 2)] public int var13() { int param = (int)CurVariation.Param; XmlReaderSettings rs = new XmlReaderSettings(); if (param == 1) rs.LineNumberOffset = -10; else rs.LinePositionOffset = -10; return TEST_PASS; } //[Variation("XmlReader.ReadContentAsBase64(b, -1, 0)", Param = 1)] //[Variation("XmlReader.ReadContentAsBinHex(b, -1, 0)", Param = 2)] //[Variation("XmlReader.ReadContentAsBase64(b, 0, -1)", Param = 3)] //[Variation("XmlReader.ReadContentAsBinHex(b, 0, -1)", Param = 4)] //[Variation("XmlReader.ReadContentAsBase64(b, 0, 2)", Param = 5)] //[Variation("XmlReader.ReadContentAsBinHex(b, 0, 2)", Param = 6)] //[Variation("XmlReader.ReadElementContentAsBase64(b, -1, 0)", Param = 7)] //[Variation("XmlReader.ReadElementContentAsBinHex(b, -1, 0)", Param = 8)] //[Variation("XmlReader.ReadValueChunk(c, 0, -1)", Param = 9)] //[Variation("XmlReader.ReadElementContentAsBase64(b, 0, -1)", Param = 10)] //[Variation("XmlReader.ReadElementContentAsBinHex(b, 0, -1)", Param = 11)] //[Variation("XmlReader.ReadValueChunk(c, 0, -1)", Param = 12)] //[Variation("XmlReader.ReadElementContentAsBase64(b, 0, 2)", Param = 13)] //[Variation("XmlReader.ReadElementContentAsBinHex(b, 0, 2)", Param = 14)] //[Variation("XmlReader.ReadValueChunk(c, 0, 2)", Param = 15)] //[Variation("XmlReader.ReadValueChunk(c, -1, 1)", Param = 16)] public int v14() { int param = (int)CurVariation.Param; ReloadSource(new StringReader(@"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + "<b><c xsi:type='f:mytype'>some content</c></b></a>")); char[] c = new char[1]; byte[] b = new byte[1]; try { switch (param) { case 1: DataReader.ReadContentAsBase64(b, -1, 0); break; case 2: DataReader.ReadContentAsBinHex(b, -1, 0); break; case 3: DataReader.ReadContentAsBase64(b, 0, -1); break; case 4: DataReader.ReadContentAsBinHex(b, 0, -1); break; case 5: DataReader.ReadContentAsBase64(b, 0, 2); break; case 6: DataReader.ReadContentAsBinHex(b, 0, 2); break; case 7: DataReader.ReadElementContentAsBase64(b, -1, 0); break; case 8: DataReader.ReadElementContentAsBinHex(b, -1, 0); break; case 9: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(c, 0, -1); break; case 10: DataReader.ReadElementContentAsBase64(b, 0, -10); break; case 11: DataReader.ReadElementContentAsBinHex(b, 0, -1); break; case 12: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(c, 0, -1); break; case 13: DataReader.ReadElementContentAsBase64(b, 0, 2); break; case 14: DataReader.ReadElementContentAsBinHex(b, 0, 2); break; case 15: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(c, 0, 2); break; case 16: DataReader.Read(); DataReader.MoveToFirstAttribute(); DataReader.ReadValueChunk(c, -1, 2); break; } } catch (ArgumentOutOfRangeException) { try { switch (param) { case 1: DataReader.ReadContentAsBase64(b, -1, 0); break; case 2: DataReader.ReadContentAsBinHex(b, -1, 0); break; case 3: DataReader.ReadContentAsBase64(b, 0, -1); break; case 4: DataReader.ReadContentAsBinHex(b, 0, -1); break; case 5: DataReader.ReadContentAsBase64(b, 0, 2); break; case 6: DataReader.ReadContentAsBinHex(b, 0, 2); break; case 7: DataReader.ReadElementContentAsBase64(b, -1, 0); break; case 8: DataReader.ReadElementContentAsBinHex(b, -1, 0); break; case 9: DataReader.ReadValueChunk(c, 0, -1); break; case 10: DataReader.ReadElementContentAsBase64(b, 0, -10); break; case 11: DataReader.ReadElementContentAsBinHex(b, 0, -1); break; case 12: DataReader.ReadValueChunk(c, 0, -1); break; case 13: DataReader.ReadElementContentAsBase64(b, 0, 2); break; case 14: DataReader.ReadElementContentAsBinHex(b, 0, 2); break; case 15: DataReader.ReadValueChunk(c, 0, 2); break; case 16: DataReader.ReadValueChunk(c, -1, 2); break; } } catch (ArgumentOutOfRangeException) { return TEST_PASS; } } catch (NotSupportedException) { if (IsCustomReader() || IsCharCheckingReader() || IsXmlTextReader()) return TEST_PASS; } finally { DataReader.Close(); } return ((IsCharCheckingReader() && param >= 1 && param <= 6) || IsSubtreeReader()) ? TEST_PASS : TEST_FAIL; } //[Variation(Desc = "DataReader.Settings.LineNumberOffset - readonly", Param = 1)] //[Variation(Desc = "DataReader.Settings.LinePositionOffset - readonly", Param = 2)] //[Variation(Desc = "DataReader.Settings.CheckCharacters - readonly", Param = 3)] //[Variation(Desc = "DataReader.Settings.CloseInput - readonly", Param = 4)] //[Variation(Desc = "DataReader.Settings.ConformanceLevel - readonly", Param = 5)] //[Variation(Desc = "DataReader.Settings.IgnoreComments - readonly", Param = 6)] //[Variation(Desc = "DataReader.Settings.IgnoreProcessingInstructions - readonly", Param = 7)] //[Variation(Desc = "DataReader.Settings.IgnoreWhitespace - readonly", Param = 8)] //[Variation(Desc = "DataReader.Settings.MaxCharactersInDocument - readonly", Param = 9)] //[Variation(Desc = "DataReader.Settings.ProhibitDtd - readonly", Param = 10)] //[Variation(Desc = "DataReader.Settings.XmlResolver - readonly", Param = 11)] //[Variation(Desc = "DataReader.Settings.MaxCharactersFromEntities - readonly", Param = 12)] //[Variation(Desc = "DataReader.Settings.DtdProcessing - readonly", Param = 13)] public int var15() { if (IsCustomReader() || IsXmlTextReader()) return TEST_SKIPPED; int param = (int)CurVariation.Param; ReloadSource(new StringReader(@"<a xmlns:f='urn:foobar' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + "<b><c xsi:type='f:mytype'>some content</c></b></a>")); try { switch (param) { case 1: DataReader.Settings.LineNumberOffset = -10; break; case 2: DataReader.Settings.LinePositionOffset = -10; break; case 3: DataReader.Settings.CheckCharacters = false; break; case 4: DataReader.Settings.CloseInput = false; break; case 5: DataReader.Settings.ConformanceLevel = ConformanceLevel.Fragment; break; case 6: DataReader.Settings.IgnoreComments = false; break; case 7: DataReader.Settings.IgnoreProcessingInstructions = false; break; case 8: DataReader.Settings.IgnoreWhitespace = false; break; case 9: DataReader.Settings.MaxCharactersInDocument = -10; break; case 12: DataReader.Settings.MaxCharactersFromEntities = -10; break; case 13: DataReader.Settings.DtdProcessing = (DtdProcessing)(-10); break; } } catch (XmlException) { try { switch (param) { case 1: DataReader.Settings.LineNumberOffset = -10; break; case 2: DataReader.Settings.LinePositionOffset = -10; break; case 3: DataReader.Settings.CheckCharacters = false; break; case 4: DataReader.Settings.CloseInput = false; break; case 5: DataReader.Settings.ConformanceLevel = ConformanceLevel.Fragment; break; case 6: DataReader.Settings.IgnoreComments = false; break; case 7: DataReader.Settings.IgnoreProcessingInstructions = false; break; case 8: DataReader.Settings.IgnoreWhitespace = false; break; case 9: DataReader.Settings.MaxCharactersInDocument = -10; break; case 12: DataReader.Settings.MaxCharactersFromEntities = -10; break; case 13: DataReader.Settings.DtdProcessing = (DtdProcessing)(-10); break; } } catch (XmlException) { return TEST_PASS; } } return TEST_FAIL; } //[Variation("Readcontentas in close state and call ReadContentAsBase64", Param = 1)] //[Variation("Readcontentas in close state and call ReadContentAsBinHex", Param = 2)] //[Variation("Readcontentas in close state and call ReadElementContentAsBase64", Param = 3)] //[Variation("Readcontentas in close state and call ReadElementContentAsBinHex", Param = 4)] //[Variation("Readcontentas in close state and call ReadValueChunk", Param = 5)] //[Variation("XmlReader[a])", Param = 6)] //[Variation("XmlReader[a, b]", Param = 7)] //[Variation("XmlReader.GetAttribute(a)", Param = 8)] //[Variation("XmlReader.GetAttribute(a, b)", Param = 9)] //[Variation("XmlReader.MoveToAttribute(a)", Param = 10)] //[Variation("XmlReader.MoveToAttribute(a, b)", Param = 11)] //[Variation("XmlReader.ReadElementContentAs(typeof(String), null)", Param = 12)] //[Variation("XmlReader.ReadElementContentAsObject()", Param = 13)] //[Variation("XmlReader.ReadElementContentAsString()", Param = 14)] //[Variation("XmlReader.ReadToDescendant(a, b)", Param = 15)] //[Variation("XmlReader.ReadToFollowing(a, b)", Param = 16)] //[Variation("XmlReader.ReadToNextSibling(a, b)", Param = 17)] //[Variation("XmlReader.ReadElementContentAs(typeof(String), null)", Param = 18)] //[Variation("XmlReader.ReadElementContentAsBoolean(a,b)", Param = 19)] //[Variation("XmlReader.ReadElementContentAsBoolean()", Param = 20)] //[Variation("XmlReader.ReadElementContentAsDateTime(a,b)", Param = 21)] //[Variation("XmlReader.ReadElementContentAsDateTime()", Param = 22)] //[Variation("XmlReader.ReadElementContentAsDecimal(a,b)", Param = 23)] //[Variation("XmlReader.ReadElementContentAsDecimal()", Param = 24)] //[Variation("XmlReader.ReadElementContentAsDouble(a,b)", Param = 25)] //[Variation("XmlReader.ReadElementContentAsDouble()", Param = 26)] //[Variation("XmlReader.ReadElementContentAsFloat(a,b)", Param = 27)] //[Variation("XmlReader.ReadElementContentAsFloat()", Param = 28)] //[Variation("XmlReader.ReadElementContentAsInt(a,b)", Param = 29)] //[Variation("XmlReader.ReadElementContentAsInt()", Param = 30)] //[Variation("XmlReader.ReadElementContentAsLong(a,b)", Param = 31)] //[Variation("XmlReader.ReadElementContentAsLong()", Param = 32)] //[Variation("XmlReader.ReadElementContentAsObject(a,b)", Param = 33)] //[Variation("XmlReader.ReadElementContentAsString(a,b)", Param = 34)] //[Variation("XmlReader.ReadToDescendant(a)", Param = 35)] //[Variation("XmlReader.ReadToFollowing(a)", Param = 36)] //[Variation("XmlReader.ReadToNextSibling(a)", Param = 37)] //[Variation("XmlReader.ReadAttributeValue()", Param = 38)] //[Variation("XmlReader.ResolveEntity()", Param = 39)] public int V16() { int param = (int)CurVariation.Param; byte[] buffer = new byte[3]; int[] skipParams = new int[] { 1, 2, 3, 4, 5, 35, 36, 37, 38 }; char[] chars = new char[3]; string s = ""; ReloadSource(new StringReader("<elem0>123 $%^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>")); DataReader.Read(); DataReader.Close(); try { DataReader.ReadContentAs(typeof(string), null); } catch (InvalidOperationException) { try { switch (param) { case 1: CError.Compare(DataReader.ReadContentAsBase64(buffer, 0, 3), 0, "size"); break; case 2: CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 3), 0, "size"); break; case 3: CError.Compare(DataReader.ReadElementContentAsBase64(buffer, 0, 3), 0, "size"); break; case 4: CError.Compare(DataReader.ReadElementContentAsBinHex(buffer, 0, 3), 0, "size"); break; case 5: CError.Compare(DataReader.ReadValueChunk(chars, 0, 3), 0, "size"); break; case 6: s = DataReader["a"]; return TEST_PASS; case 7: s = DataReader["a", "b"]; return TEST_PASS; case 8: s = DataReader.GetAttribute("a"); return TEST_PASS; case 9: s = DataReader.GetAttribute("a", "b"); return TEST_PASS; case 10: DataReader.MoveToAttribute("a"); return TEST_PASS; case 11: DataReader.MoveToAttribute("a", "b"); return TEST_PASS; case 12: DataReader.ReadElementContentAs(typeof(String), null, "a", "b"); return TEST_PASS; case 13: DataReader.ReadElementContentAsObject(); return TEST_PASS; case 14: DataReader.ReadElementContentAsString(); return TEST_PASS; case 15: DataReader.ReadToDescendant("a", "b"); return TEST_PASS; case 16: DataReader.ReadToFollowing("a", "b"); return TEST_PASS; case 17: DataReader.ReadToNextSibling("a", "b"); return TEST_PASS; case 18: DataReader.ReadElementContentAs(typeof(String), null); break; case 19: DataReader.ReadElementContentAsBoolean("a", "b"); break; case 20: DataReader.ReadElementContentAsBoolean(); break; case 23: DataReader.ReadElementContentAsDecimal("a", "b"); break; case 24: DataReader.ReadElementContentAsDecimal(); break; case 25: DataReader.ReadElementContentAsDouble("a", "b"); break; case 26: DataReader.ReadElementContentAsDouble(); break; case 27: DataReader.ReadElementContentAsFloat("a", "b"); break; case 28: DataReader.ReadElementContentAsFloat(); break; case 29: DataReader.ReadElementContentAsInt("a", "b"); break; case 30: DataReader.ReadElementContentAsInt(); break; case 31: DataReader.ReadElementContentAsLong(); break; case 32: DataReader.ReadElementContentAsLong("a", "b"); break; case 33: DataReader.ReadElementContentAsObject("a", "b"); break; case 34: DataReader.ReadElementContentAsString("a", "b"); break; case 35: DataReader.ReadToDescendant("a"); break; case 36: DataReader.ReadToFollowing("a"); break; case 37: DataReader.ReadToNextSibling("a"); break; case 38: DataReader.ReadAttributeValue(); break; case 39: DataReader.ResolveEntity(); break; } } catch (NotSupportedException) { return TEST_PASS; } catch (InvalidOperationException) { return TEST_PASS; } catch (XmlException) { return TEST_PASS; } } foreach (int p in skipParams) { if (param == p) return TEST_PASS; } return TEST_FAIL; } //[Variation("Assertion when creating validating reader from a XmlReader.Create reader")] public int Dev10_67883() { return TEST_SKIPPED; } } }
using UnityEngine; using System; using System.Collections; using System.Runtime.InteropServices; using MiniJSON; #if UNITY_ANDROID /* * SessionM Android Native Implementation. */ public class ISessionM_Android : ISessionM { private SessionM sessionMGameObject; private ISessionMCallback callback; private SessionMEventListener listener; private static AndroidJavaObject androidInstance; private Boolean isPresented = false; public ISessionM_Android(SessionM sessionMParent) { sessionMGameObject = sessionMParent; initAndroidInstance(); CreateListenerObject(); if(sessionMGameObject.androidAppId != null) { SetServiceRegion(SessionM.serviceRegion); StartSession(null); } } private void CreateListenerObject() { listener = sessionMGameObject.gameObject.AddComponent<SessionMEventListener>(); using (AndroidJavaObject activityObject = GetCurrentActivity()) { activityObject.CallStatic("setCallbackGameObjectName", sessionMGameObject.gameObject.name); } listener.SetNativeParent(this); if(callback != null) { listener.SetCallback(callback); } } public void StartSession(string appId) { using (AndroidJavaObject activityObject = GetCurrentActivity()) { if(sessionMGameObject.androidAppId != null) { androidInstance.Call("startSession", activityObject, sessionMGameObject.androidAppId); } else { androidInstance.Call("startSession", activityObject, appId); } } } public SessionState GetSessionState() { SessionState state = SessionState.Stopped; using (AndroidJavaObject stateObject = androidInstance.Call<AndroidJavaObject>("getSessionState")) { string stateName = stateObject.Call<string>("name"); if(stateName.Equals("STOPPED")) { state = SessionState.Stopped; } else if(stateName.Equals("STARTED_ONLINE")) { state = SessionState.StartedOnline; } else if(stateName.Equals("STARTED_OFFLINE")) { state = SessionState.StartedOffline; } } return state; } public string GetUser() { string userJSON = null; using (AndroidJavaObject activityObject = GetCurrentActivity()) { userJSON = activityObject.Call<string>("getUser"); } return userJSON; } public void SetUserOptOutStatus(bool status){ using (AndroidJavaObject activityObject = GetCurrentActivity()) { activityObject.Call("setUserOptOutStatus", status); } } public void SetShouldAutoUpdateAchievementsList(bool shouldAutoUpdate) { using (AndroidJavaObject activityObject = GetCurrentActivity()) { activityObject.Call("setShouldAutoUpdateAchievementsList", shouldAutoUpdate); } } public void UpdateAchievementsList() { using (AndroidJavaObject activityObject = GetCurrentActivity()) { activityObject.Call("updateAchievementsList"); } } public int GetUnclaimedAchievementCount() { int count = 0; using (AndroidJavaObject activityObject = GetCurrentActivity()) { count = activityObject.Call<int>("getUnclaimedAchievementCount"); } return count; } public string GetUnclaimedAchievementData() { string achievementJSON = null; using (AndroidJavaObject activityObject = GetCurrentActivity()) { achievementJSON = activityObject.Call<string>("getUnclaimedAchievementJSON"); } return achievementJSON; } public void LogAction(string action) { androidInstance.Call("logAction", action); } public void LogAction(string action, int count) { androidInstance.Call("logAction", action, count); } public bool PresentActivity(ActivityType type) { using (AndroidJavaObject activityType = GetAndroidActivityTypeObject(type), activityObject = GetCurrentActivity()) { isPresented = activityObject.Call<bool>("presentActivity", activityType); } return isPresented; } public void DismissActivity() { if (isPresented) { androidInstance.Call ("dismissActivity"); isPresented = false; } } public bool IsActivityPresented() { bool presented = false; presented = androidInstance.Call<bool>("isActivityPresented"); return presented; } public bool IsActivityAvailable(ActivityType type) { bool available = false; using (AndroidJavaObject activityType = GetAndroidActivityTypeObject(type), activityObject = GetCurrentActivity()) { available = activityObject.Call<bool>("isActivityAvailable", activityType); } return available; } public void SetLogLevel(LogLevel level) { // use logcat on Android } public LogLevel GetLogLevel() { return LogLevel.Off; } public string GetSDKVersion() { return androidInstance.Call<string>("getSDKVersion"); } public string GetRewards() { string rewardsJSON = null; using (AndroidJavaObject activityObject = GetCurrentActivity()) { rewardsJSON = activityObject.Call<string>("getRewardsJSON"); } return rewardsJSON; } public void SetMetaData(string data, string key) { androidInstance.Call("setMetaData", key, data); } public void SetServiceRegion(ServiceRegion serviceRegion) { using (AndroidJavaObject activityObject = GetCurrentActivity()) { //Always 0 for now activityObject.Call("setServiceRegion", 0); } } public void NotifyPresented() { using (AndroidJavaObject activityObject = GetCurrentActivity()) { isPresented = activityObject.Call<bool>("notifyCustomAchievementPresented"); } } public void NotifyDismissed() { if (isPresented) { using (AndroidJavaObject activityObject = GetCurrentActivity()) { activityObject.Call ("notifyCustomAchievementCancelled"); isPresented = false; } } } public void NotifyClaimed() { if (isPresented) { using (AndroidJavaObject activityObject = GetCurrentActivity()) { activityObject.Call ("notifyCustomAchievementClaimed"); isPresented = false; } } } public void SetCallback(ISessionMCallback callback) { this.callback = callback; listener.SetCallback(callback); } public ISessionMCallback GetCallback() { return this.callback; } // MonoBehavior public AndroidJavaObject GetCurrentActivity() { using (AndroidJavaClass playerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { return playerClass.GetStatic<AndroidJavaObject>("currentActivity"); } } private AndroidJavaObject GetAndroidActivityTypeObject(ActivityType type) { if(Application.platform != RuntimePlatform.Android) { return null; } using (AndroidJavaClass typeClass = new AndroidJavaClass("com.sessionm.api.SessionM$ActivityType")) { string typeString = null; if(type == ActivityType.Achievement) { typeString = "ACHIEVEMENT"; } else if(type == ActivityType.Portal) { typeString = "PORTAL"; } AndroidJavaObject activityType = typeClass.CallStatic<AndroidJavaObject>("valueOf", typeString); return activityType; } } protected static void initAndroidInstance() { using (AndroidJavaClass sessionMClass = new AndroidJavaClass("com.sessionm.api.SessionM")) { androidInstance = sessionMClass.CallStatic<AndroidJavaObject>("getInstance"); } } } #endif
/* * 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 sqs-2012-11-05.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.SQS.Model; namespace Amazon.SQS { /// <summary> /// Interface for accessing SQS /// /// Welcome to the <i>Amazon Simple Queue Service API Reference</i>. This section describes /// who should read this guide, how the guide is organized, and other resources related /// to the Amazon Simple Queue Service (Amazon SQS). /// /// /// <para> /// Amazon SQS offers reliable and scalable hosted queues for storing messages as they /// travel between computers. By using Amazon SQS, you can move data between distributed /// components of your applications that perform different tasks without losing messages /// or requiring each component to be always available. /// </para> /// /// <para> /// Helpful Links: <ul> <li><a href="http://queue.amazonaws.com/doc/2012-11-05/QueueService.wsdl">Current /// WSDL (2012-11-05)</a></li> <li><a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/MakingRequestsArticle.html">Making /// API Requests</a></li> <li><a href="http://aws.amazon.com/sqs/">Amazon SQS product /// page</a></li> <li><a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSMessageAttributes.html">Using /// Amazon SQS Message Attributes</a></li> <li><a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/SQSDeadLetterQueue.html">Using /// Amazon SQS Dead Letter Queues</a></li> <li><a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#sqs_region">Regions /// and Endpoints</a></li> </ul> /// </para> /// /// <para> /// We also provide SDKs that enable you to access Amazon SQS from your preferred programming /// language. The SDKs contain functionality that automatically takes care of tasks such /// as: /// </para> /// /// <para> /// <ul> <li>Cryptographically signing your service requests</li> <li>Retrying requests</li> /// <li>Handling error responses</li> </ul> /// </para> /// /// <para> /// For a list of available SDKs, go to <a href="http://aws.amazon.com/tools/">Tools for /// Amazon Web Services</a>. /// </para> /// </summary> public partial interface IAmazonSQS : IDisposable { #region AddPermission /// <summary> /// Initiates the asynchronous execution of the AddPermission operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AddPermission operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<AddPermissionResponse> AddPermissionAsync(AddPermissionRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ChangeMessageVisibility /// <summary> /// Initiates the asynchronous execution of the ChangeMessageVisibility operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ChangeMessageVisibility operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ChangeMessageVisibilityResponse> ChangeMessageVisibilityAsync(ChangeMessageVisibilityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ChangeMessageVisibilityBatch /// <summary> /// Initiates the asynchronous execution of the ChangeMessageVisibilityBatch operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ChangeMessageVisibilityBatch operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ChangeMessageVisibilityBatchResponse> ChangeMessageVisibilityBatchAsync(ChangeMessageVisibilityBatchRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateQueue /// <summary> /// Initiates the asynchronous execution of the CreateQueue operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateQueue operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateQueueResponse> CreateQueueAsync(CreateQueueRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteMessage /// <summary> /// Initiates the asynchronous execution of the DeleteMessage operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteMessage operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteMessageResponse> DeleteMessageAsync(DeleteMessageRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteMessageBatch /// <summary> /// Initiates the asynchronous execution of the DeleteMessageBatch operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteMessageBatch operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteMessageBatchResponse> DeleteMessageBatchAsync(DeleteMessageBatchRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteQueue /// <summary> /// Initiates the asynchronous execution of the DeleteQueue operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteQueue operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteQueueResponse> DeleteQueueAsync(DeleteQueueRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetQueueAttributes /// <summary> /// Initiates the asynchronous execution of the GetQueueAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetQueueAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetQueueAttributesResponse> GetQueueAttributesAsync(GetQueueAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetQueueUrl /// <summary> /// Initiates the asynchronous execution of the GetQueueUrl operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetQueueUrl operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetQueueUrlResponse> GetQueueUrlAsync(GetQueueUrlRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListDeadLetterSourceQueues /// <summary> /// Initiates the asynchronous execution of the ListDeadLetterSourceQueues operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDeadLetterSourceQueues operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListDeadLetterSourceQueuesResponse> ListDeadLetterSourceQueuesAsync(ListDeadLetterSourceQueuesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListQueues /// <summary> /// Initiates the asynchronous execution of the ListQueues operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListQueues operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListQueuesResponse> ListQueuesAsync(ListQueuesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PurgeQueue /// <summary> /// Initiates the asynchronous execution of the PurgeQueue operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PurgeQueue operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PurgeQueueResponse> PurgeQueueAsync(PurgeQueueRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ReceiveMessage /// <summary> /// Initiates the asynchronous execution of the ReceiveMessage operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReceiveMessage operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ReceiveMessageResponse> ReceiveMessageAsync(ReceiveMessageRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RemovePermission /// <summary> /// Initiates the asynchronous execution of the RemovePermission operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RemovePermission operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RemovePermissionResponse> RemovePermissionAsync(RemovePermissionRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SendMessage /// <summary> /// Initiates the asynchronous execution of the SendMessage operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SendMessage operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SendMessageResponse> SendMessageAsync(SendMessageRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SendMessageBatch /// <summary> /// Initiates the asynchronous execution of the SendMessageBatch operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SendMessageBatch operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SendMessageBatchResponse> SendMessageBatchAsync(SendMessageBatchRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetQueueAttributes /// <summary> /// Initiates the asynchronous execution of the SetQueueAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetQueueAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetQueueAttributesResponse> SetQueueAttributesAsync(SetQueueAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising 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. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace CallButler.Manager.Forms { public partial class PersonalizedGreetingForm : CallButler.Manager.Forms.EditorWizardFormBase { private bool extensionSelected = false; WOSI.CallButler.Data.CallButlerDataset.PersonalizedGreetingsRow personalizedGreeting; public PersonalizedGreetingForm(WOSI.CallButler.Data.CallButlerDataset.PersonalizedGreetingsRow personalizedGreeting, WOSI.CallButler.Data.CallButlerDataset.ExtensionsDataTable extensions) { InitializeComponent(); this.personalizedGreeting = personalizedGreeting; LoadData(); wizard.PageIndex = 0; txtCallerID.Select(); rbScript.Visible = true; lblScript.Visible = true; btnImportOutlook.Enabled = Utilities.ContactManagement.ContactManagerFactory.CreateContactManager(Utilities.ContactManagement.ContactType.Outlook).IsInstalled; Utils.PrivateLabelUtils.ReplaceProductNameControl(this); } public Manager.Controls.GreetingControl GreetingControl { get { return greetingControl; } } private void LoadData() { txtCallerID.Text = personalizedGreeting.CallerDisplayName; txtTelephoneNumber.Text = personalizedGreeting.CallerUsername; cbPlayOnce.Checked = personalizedGreeting.PlayOnce; txtNotes.Text = personalizedGreeting.Notes; cbRegex.Checked = personalizedGreeting.UseRegex; txtDialedNumber.Text = personalizedGreeting.DialedUsername; addOnModuleChooserControl.Load(); extensionsView.LoadData(); switch (personalizedGreeting.Type) { case (short)WOSI.CallButler.Data.PersonalizedGreetingType.Continue: rbContinue.Checked = true; break; case (short)WOSI.CallButler.Data.PersonalizedGreetingType.Hangup: rbHangup.Checked = true; break; case (short)WOSI.CallButler.Data.PersonalizedGreetingType.SendToExtension: rbExtension.Checked = true; break; case (short)WOSI.CallButler.Data.PersonalizedGreetingType.CustomScript: rbScript.Checked = true; txtScriptFile.Text = personalizedGreeting.Data; break; case (short)WOSI.CallButler.Data.PersonalizedGreetingType.Module: rbModule.Checked = true; try { if (personalizedGreeting.Data != null && personalizedGreeting.Data.Length > 0) addOnModuleChooserControl.SelectedAddOnModule = new Guid(personalizedGreeting.Data); } catch { } break; } } private void UpdateData() { personalizedGreeting.CustomerID = Properties.Settings.Default.CustomerID; personalizedGreeting.CallerDisplayName = txtCallerID.Text; personalizedGreeting.CallerUsername = txtTelephoneNumber.Text; personalizedGreeting.DialedUsername = txtDialedNumber.Text; personalizedGreeting.PlayOnce = cbPlayOnce.Checked; if (!personalizedGreeting.PlayOnce) personalizedGreeting.HasPlayed = false; personalizedGreeting.Notes = txtNotes.Text; personalizedGreeting.Data = ""; personalizedGreeting.UseRegex = cbRegex.Checked; if (rbContinue.Checked) personalizedGreeting.Type = (short)WOSI.CallButler.Data.PersonalizedGreetingType.Continue; else if (rbHangup.Checked) personalizedGreeting.Type = (short)WOSI.CallButler.Data.PersonalizedGreetingType.Hangup; else if (rbExtension.Checked) { personalizedGreeting.Type = (short)WOSI.CallButler.Data.PersonalizedGreetingType.SendToExtension; personalizedGreeting.Data = ""; if (extensionsView.SelectedExensionID != Guid.Empty) { personalizedGreeting.Data = extensionsView.SelectedExensionID.ToString(); } else { personalizedGreeting.Data = ""; } } else if (rbScript.Checked) { personalizedGreeting.Type = (short)WOSI.CallButler.Data.PersonalizedGreetingType.CustomScript; personalizedGreeting.Data = txtScriptFile.Text; } else if (rbModule.Checked) { personalizedGreeting.Type = (short)WOSI.CallButler.Data.PersonalizedGreetingType.Module; Guid moduleID = addOnModuleChooserControl.SelectedAddOnModule; if (moduleID == Guid.Empty) personalizedGreeting.Data = ""; else personalizedGreeting.Data = moduleID.ToString(); } } private void wizard_WizardFinished(object sender, global::Controls.Wizard.PageChangedEventArgs e) { UpdateData(); } private void btnImportOutlook_Click(object sender, EventArgs e) { OutlookContactForm ocForm = new OutlookContactForm(); ocForm.MultiSelect = false; if (ocForm.ShowDialog(this) == DialogResult.OK) { if (ocForm.SelectedContacts.Length > 0) { txtTelephoneNumber.Text = ocForm.SelectedContacts[0].BusinessTelephoneNumber; } } } private void btnScriptBrowse_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog(this) == DialogResult.OK) txtScriptFile.Text = openFileDialog.FileName; } private void Type_CheckedChanged(object sender, EventArgs e) { if (rbExtension.Checked) { wizType.PageIndex = 1; wizType.Visible = true; } else if (rbScript.Checked) { wizType.PageIndex = 0; wizType.Visible = true; } else if (rbModule.Checked) { try { if (personalizedGreeting.Data != null && personalizedGreeting.Data.Length > 0) addOnModuleChooserControl.SelectedAddOnModule = new Guid(personalizedGreeting.Data); } catch { } wizType.PageIndex = 2; wizType.Visible = true; } else { wizType.Visible = false; } } private void wizard_PageChanged(object sender, EventArgs e) { if (wizard.PageIndex == 2 && rbExtension.Checked) { if (!extensionSelected) { extensionSelected = true; // Select our extension row try { Guid extID = new Guid(personalizedGreeting.Data); extensionsView.SelectedExensionID = extID; } catch { } } } } private void PersonalizedGreetingForm_FormClosing(object sender, FormClosingEventArgs e) { greetingControl.StopSounds(); } private void lblRegex_Click(object sender, EventArgs e) { cbRegex.Checked = !cbRegex.Checked; } private void lblOneTime_Click(object sender, EventArgs e) { cbPlayOnce.Checked = !cbPlayOnce.Checked; } private void lblContinueCall_Click(object sender, EventArgs e) { rbContinue.Checked = true; } private void lblTransfer_Click(object sender, EventArgs e) { rbExtension.Checked = true; } private void lblHangUp_Click(object sender, EventArgs e) { rbHangup.Checked = true; } private void lblScript_Click(object sender, EventArgs e) { rbScript.Checked = true; } private void lblModule_Click(object sender, EventArgs e) { rbModule.Checked = true; } } }
using System; using System.Collections; using System.Drawing; using System.Drawing.Imaging; using System.IO; using IBatisNet.Common.Utilities; using IBatisNet.DataMapper.Test.Domain; using NUnit.Framework; namespace IBatisNet.DataMapper.Test.NUnit.SqlMapTests { /// <summary> /// Summary description for ParameterMapTest. /// </summary> [TestFixture] public class ParameterMapTest : BaseTest { #region SetUp & TearDown /// <summary> /// SetUp /// </summary> [SetUp] public void Init() { InitScript( sqlMap.DataSource, ScriptDirectory+"account-init.sql" ); InitScript( sqlMap.DataSource, ScriptDirectory+"account-procedure.sql", false ); InitScript( sqlMap.DataSource, ScriptDirectory+"order-init.sql" ); InitScript( sqlMap.DataSource, ScriptDirectory+"line-item-init.sql" ); InitScript( sqlMap.DataSource, ScriptDirectory+"category-init.sql" ); } /// <summary> /// TearDown /// </summary> [TearDown] public void Dispose() { /* ... */ } #endregion #region Parameter map tests /// <summary> /// Test null replacement in ParameterMap property /// </summary> [Test] public void TestNullValueReplacement() { Account account = NewAccount6(); sqlMap.Insert("InsertAccountViaParameterMap", account); account = (Account) sqlMap.QueryForObject("GetAccountNullableEmail", 6); AssertAccount6(account); } /// <summary> /// Test Test Null Value Replacement Inline /// </summary> [Test] public void TestNullValueReplacementInline() { Account account = NewAccount6(); sqlMap.Insert("InsertAccountViaInlineParameters", account); account = sqlMap.QueryForObject("GetAccountNullableEmail", 6) as Account; AssertAccount6(account); } /// <summary> /// Test Test Null Value Replacement Inline /// </summary> [Test] public void TestSpecifiedType() { Account account = NewAccount6(); account.EmailAddress = null; sqlMap.Insert("InsertAccountNullableEmail", account); account = sqlMap.QueryForObject("GetAccountNullableEmail", 6) as Account; AssertAccount6(account); } /// <summary> /// Test Test Null Value Replacement Inline /// </summary> [Test] public void TestUnknownParameterClass() { Account account = NewAccount6(); account.EmailAddress = null; sqlMap.Insert("InsertAccountUknownParameterClass", account); account = sqlMap.QueryForObject("GetAccountNullableEmail", 6) as Account; AssertAccount6(account); } /// <summary> /// Test null replacement in ParameterMap property /// for System.DateTime.MinValue /// </summary> [Test] public void TestNullValueReplacementForDateTimeMinValue() { Account account = NewAccount6(); sqlMap.Insert("InsertAccountViaParameterMap", account); Order order = new Order(); order.Id = 99; order.CardExpiry = "09/11"; order.Account = account; order.CardNumber = "154564656"; order.CardType = "Visa"; order.City = "Lyon"; order.Date = DateTime.MinValue; //<-- null replacement order.PostalCode = "69004"; order.Province = "Rhone"; order.Street = "rue Durand"; sqlMap.Insert("InsertOrderViaParameterMap", order); Order orderTest = (Order) sqlMap.QueryForObject("GetOrderLiteByColumnName", 99); Assert.AreEqual(order.City, orderTest.City); } /// <summary> /// Test null replacement in ParameterMap/Hahstable property /// for System.DateTime.MinValue /// </summary> [Test] public void TestNullValueReplacementForDateTimeWithHashtable() { Account account = NewAccount6(); sqlMap.Insert("InsertAccountViaParameterMap", account); Order order = new Order(); order.Id = 99; order.CardExpiry = "09/11"; order.Account = account; order.CardNumber = "154564656"; order.CardType = "Visa"; order.City = "Lyon"; order.Date = DateTime.MinValue; //<-- null replacement order.PostalCode = "69004"; order.Province = "Rhone"; order.Street = "rue Durand"; sqlMap.Insert("InsertOrderViaParameterMap", order); Hashtable orderTest = (Hashtable) sqlMap.QueryForObject("GetOrderByHashTable", 99); Assert.AreEqual(orderTest["Date"], DateTime.MinValue); } /// <summary> /// Test null replacement in ParameterMap property /// for Guid /// </summary> [Test] public void TestNullValueReplacementForGuidValue() { Category category = new Category(); category.Name = "Toto"; category.Guid = Guid.Empty; int key = (int)sqlMap.Insert("InsertCategoryNull", category); Category categoryRead = null; categoryRead = (Category)sqlMap.QueryForObject("GetCategoryWithNullValueReplacementGuid", key); Assert.AreEqual(category.Name, categoryRead.Name); Assert.AreEqual(category.Guid.ToString(), categoryRead.Guid.ToString()); } /// <summary> /// Test complex mapping Via hasTable /// </summary> /// <example> /// /// map.Add("Item", Item); /// map.Add("Order", Order); /// /// <statement> /// ... #Item.prop1#...#Order.prop2# /// </statement> /// /// </example> [Test] public void TestComplexMappingViaHasTable() { Hashtable param = new Hashtable(); Account a = new Account(); a.FirstName = "Joe"; param.Add("Account",a); Order o = new Order(); o.City = "Dalton"; param.Add("Order", o); Account accountTest = (Account) sqlMap.QueryForObject("GetAccountComplexMapping", param); AssertAccount1(accountTest); } /// <summary> /// Test ByteArrayTypeHandler via Picture Property /// </summary> [Test] public void TestByteArrayTypeHandler() { Account account = NewAccount6(); sqlMap.Insert("InsertAccountViaParameterMap", account); Order order = new Order(); order.Id = 99; order.CardExpiry = "09/11"; order.Account = account; order.CardNumber = "154564656"; order.CardType = "Visa"; order.City = "Lyon"; order.Date = DateTime.MinValue; order.PostalCode = "69004"; order.Province = "Rhone"; order.Street = "rue Durand"; sqlMap.Insert("InsertOrderViaParameterMap", order); LineItem item = new LineItem(); item.Id = 99; item.Code = "test"; item.Price = -99.99m; item.Quantity = 99; item.Order = order; item.Picture = this.GetPicture(); // Check insert sqlMap.Insert("InsertLineItemWithPicture", item); // select item = null; Hashtable param = new Hashtable(); param.Add("LineItem_ID", 99); param.Add("Order_ID", 99); item = sqlMap.QueryForObject("GetSpecificLineItemWithPicture", param) as LineItem; Assert.IsNotNull( item ); Assert.IsNotNull( item.Picture ); Assert.AreEqual( GetSize(item.Picture), this.GetSize( this.GetPicture() )); } [Test] [Category("JIRA")] [Category("JIRA-253")] public void Null_byte_array_should_return_null() { Account account = NewAccount6(); sqlMap.Insert("InsertAccountViaParameterMap", account); Order order = new Order(); order.Id = 99; order.CardExpiry = "09/11"; order.Account = account; order.CardNumber = "154564656"; order.CardType = "Visa"; order.City = "Lyon"; order.Date = DateTime.MinValue; order.PostalCode = "69004"; order.Province = "Rhone"; order.Street = "rue Durand"; sqlMap.Insert("InsertOrderViaParameterMap", order); LineItem item = new LineItem(); item.Id = 99; item.Code = "test"; item.Price = -99.99m; item.Quantity = 99; item.Order = order; item.Picture = null; // Check insert sqlMap.Insert("InsertLineItemWithPicture", item); // select item = null; Hashtable param = new Hashtable(); param.Add("LineItem_ID", 99); param.Add("Order_ID", 99); item = sqlMap.QueryForObject("GetSpecificLineItemWithPicture", param) as LineItem; Assert.IsNotNull(item); Assert.IsNull(item.Picture); } /// <summary> /// Test extend parameter map capacity /// (Support Requests 1043181) /// </summary> [Test] public void TestInsertOrderViaExtendParameterMap() { Account account = NewAccount6(); sqlMap.Insert("InsertAccountViaParameterMap", account); Order order = new Order(); order.Id = 99; order.CardExpiry = "09/11"; order.Account = account; order.CardNumber = "154564656"; order.CardType = "Visa"; order.City = "Lyon"; order.Date = DateTime.MinValue; //<-- null replacement order.PostalCode = "69004"; order.Province = "Rhone"; order.Street = "rue Durand"; sqlMap.Insert("InsertOrderViaExtendParameterMap", order); Order orderTest = (Order) sqlMap.QueryForObject("GetOrderLiteByColumnName", 99); Assert.AreEqual(order.City, orderTest.City); } #endregion #region Picture methods private Image GetPicture() { Image _picture = null; // first try without path _picture = Image.FromFile( Path.Combine(Resources.ApplicationBase, "cool.jpg") ); Assert.IsNotNull( _picture ); return _picture; } private int GetSize( Image picture ) { MemoryStream memoryStream = new MemoryStream(); picture.Save (memoryStream, ImageFormat.Jpeg); return memoryStream.ToArray ().Length; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using Xunit; namespace System.Linq.Tests { public class QueryFromExpressionTests { private class SimplePair : IEnumerable<int> { public int First { get; set; } public int Second { get; set; } public IEnumerator<int> GetEnumerator() { yield return First; yield return Second; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private static IQueryProvider _prov = Enumerable.Empty<int>().AsQueryable().Provider; [Fact] public void ExpressionToQueryFromProvider() { Expression exp = Expression.Constant(Enumerable.Range(0, 2).AsQueryable()); IQueryable<int> q = _prov.CreateQuery<int>(exp); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact] public void ExpressionToQueryByConstructor() { Expression exp = Expression.Constant(Enumerable.Range(0, 2).AsQueryable()); IQueryable<int> q = new EnumerableQuery<int>(exp); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact] public void ConditionalEqualModuloConstantConstant() { Expression cond = Expression.Condition( Expression.Equal( Expression.Modulo(Expression.Constant(1), Expression.Constant(2)), Expression.Constant(0) ), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(cond); Assert.Equal(Enumerable.Range(3, 2), q); } private static IQueryable<char> AsciiControlCharacters { get { return Enumerable.Range(0, 128).AsQueryable() .Select(i => (char)i) .Where(c => char.IsControl(c)); } } [Fact] public void PropertyAccess() { Expression access = Expression.Property(null, typeof(QueryFromExpressionTests), "AsciiControlCharacters"); IQueryable<char> q = _prov.CreateQuery<char>(access); Assert.Equal(Enumerable.Range(0, 128).Select(i => (char)i).Where(c => char.IsControl(c)), q); } [Fact] public void ArrayIndex() { Expression array = Expression.Constant("abcd".ToArray()); Expression call = Expression.Call( typeof(Queryable), "AsQueryable", new[] { typeof(char) }, Expression.NewArrayInit( typeof(char), Expression.ArrayIndex(array, Expression.Constant(0)), Expression.ArrayIndex(array, Expression.Constant(2))) ); Assert.Equal(new[] { 'a', 'c' }, _prov.CreateQuery<char>(call)); } [Fact] public void ConditionalNotNotEqualAddPlusConstantNegateConstant() { Expression cond = Expression.Condition( Expression.Not( Expression.NotEqual( Expression.Add(Expression.UnaryPlus(Expression.Constant(1)), Expression.Negate(Expression.Constant(2))), Expression.Constant(-1) ) ), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(cond); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact] public void ConditionalNotNotEqualAddCheckedPlusConstantNegateCheckedConstant() { Expression cond = Expression.Condition( Expression.Not( Expression.NotEqual( Expression.AddChecked(Expression.UnaryPlus(Expression.Constant(1)), Expression.NegateChecked(Expression.Constant(2))), Expression.Constant(-1) ) ), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(cond); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact] public void ConditionalLogicalOperators() { Expression logic = Expression.OrElse( Expression.AndAlso( Expression.LessThanOrEqual(Expression.Constant(3), Expression.Constant(4)), Expression.LessThan(Expression.Constant(2), Expression.Constant(1)) ), Expression.Or( Expression.And( Expression.GreaterThan(Expression.Constant(2), Expression.Constant(1)), Expression.GreaterThanOrEqual( Expression.Constant(8), Expression.ExclusiveOr(Expression.Constant(3), Expression.Constant(5)) ) ), Expression.Constant(true) ) ); Expression cond = Expression.Condition( logic, Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(cond); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact] public void SubtractionAndCalls() { Expression rangeCall = Expression.Call( typeof(Enumerable), "Range", new Type[0], Expression.Subtract(Expression.Constant(6), Expression.Constant(2)), Expression.SubtractChecked(Expression.Constant(12), Expression.Constant(3)) ); Expression call = Expression.Call( typeof(Queryable), "AsQueryable", new[] { typeof(int) }, rangeCall ); IQueryable<int> q = _prov.CreateQuery<int>(call); Assert.Equal(Enumerable.Range(4, 9), q); } [Fact] public void MultiplicationAndCalls() { Expression rangeCall = Expression.Call( typeof(Enumerable), "Range", new Type[0], Expression.Multiply(Expression.Constant(4), Expression.Constant(5)), Expression.MultiplyChecked(Expression.Constant(3), Expression.Constant(2)) ); Expression call = Expression.Call( typeof(Queryable), "AsQueryable", new[] { typeof(int) }, rangeCall ); IQueryable<int> q = _prov.CreateQuery<int>(call); Assert.Equal(Enumerable.Range(20, 6), q); } [Fact] public void DivisionAndPower() { Expression rangeCall = Expression.Call( typeof(Enumerable), "Range", new Type[0], Expression.Convert(Expression.Power(Expression.Constant(4.0), Expression.Constant(5.0)), typeof(int)), Expression.Divide(Expression.Constant(20), Expression.Constant(10)) ); Expression call = Expression.Call( typeof(Queryable), "AsQueryable", new[] { typeof(int) }, rangeCall ); IQueryable<int> q = _prov.CreateQuery<int>(call); Assert.Equal(Enumerable.Range(1024, 2), q); } [Fact] public void ConvertsNewArrayAndArrayLength() { Expression cond = Expression.Condition( Expression.Equal( Expression.AddChecked( Expression.Convert( Expression.ArrayLength(Expression.NewArrayInit(typeof(int), Enumerable.Range(0, 3).Select(i => Expression.Constant(i)))), typeof(long)), Expression.ConvertChecked( Expression.ArrayLength(Expression.NewArrayBounds(typeof(bool), Expression.Constant(2))), typeof(long) ) ), Expression.Constant(5L) ), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(cond); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact] public void CoalesceShifts() { Expression list = Expression.ListInit( Expression.New(typeof(List<int>)), Expression.LeftShift(Expression.Constant(5), Expression.Constant(2)), Expression.RightShift(Expression.Constant(31), Expression.Constant(1)) ); Expression call = Expression.Call( typeof(Queryable), "AsQueryable", new[] { typeof(int) }, list ); Expression coal = Expression.Coalesce(Expression.Constant(null, typeof(IQueryable<int>)), call); IQueryable<int> q = _prov.CreateQuery<int>(coal); Assert.Equal(new[] { 20, 15 }, q); } [Fact] public void TypeAs() { Expression cond = Expression.Condition( Expression.Equal( Expression.Constant(null), Expression.TypeAs(Expression.Constant("", typeof(object)), typeof(string)) ), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(cond); Assert.Equal(Enumerable.Range(3, 2), q); cond = Expression.Condition( Expression.Equal( Expression.Constant(null), Expression.TypeAs(Expression.Constant("", typeof(object)), typeof(Uri)) ), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); q = _prov.CreateQuery<int>(cond); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact] public void TypeIs() { Expression cond = Expression.Condition( Expression.TypeIs(Expression.Constant("", typeof(object)), typeof(string)), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(cond); Assert.Equal(Enumerable.Range(0, 2), q); cond = Expression.Condition( Expression.TypeIs(Expression.New(typeof(object)), typeof(string)), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); q = _prov.CreateQuery<int>(cond); Assert.Equal(Enumerable.Range(3, 2), q); } [Fact] public void MemberInit() { Expression init = Expression.MemberInit( Expression.New(typeof(SimplePair)), Expression.Bind(typeof(SimplePair).GetMember("First")[0], Expression.Constant(8)), Expression.Bind(typeof(SimplePair).GetMember("Second")[0], Expression.Constant(13)) ); Expression call = Expression.Call( typeof(Queryable), "AsQueryable", new[] { typeof(int) }, init ); IQueryable<int> q = _prov.CreateQuery<int>(call); Assert.Equal(new[] { 8, 13 }, q); } [Fact] public void InvokeAndMemberAccess() { Expression<Func<int, IQueryable<char>>> lambda = start => "acbdefghijklmnop".AsQueryable().Skip(start); Expression invoke = Expression.Invoke(lambda, Expression.Constant(2)); IQueryable<char> q = _prov.CreateQuery<char>(invoke); Assert.Equal("bdefghijklmnop".ToCharArray(), q.ToArray()); } [Fact] public void QueryWrappedAsConstant() { Expression cond = Expression.Condition( Expression.Equal( Expression.Modulo(Expression.Constant(1), Expression.Constant(2)), Expression.Constant(0) ), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()), Expression.Constant(Enumerable.Range(3, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(Expression.Constant(_prov.CreateQuery<int>(cond))); Assert.Equal(Enumerable.Range(3, 2), q); } private sealed class BogusExpression : Expression { public override ExpressionType NodeType { get { return (ExpressionType)(-1); } } public override Type Type { get { return typeof(IQueryable<bool>); } } } [Fact] public void UnknownExpressionType() { IQueryable<bool> q = _prov.CreateQuery<bool>(new BogusExpression()); Assert.Throws<ArgumentException>(() => q.GetEnumerator()); } private IQueryable<string> SimpleMethod() { return new[] { "a", "b", "c" }.AsQueryable(); } [Fact] public void SimpleMethodCall() { Expression call = Expression.Call(Expression.Constant(this), "SimpleMethod", new Type[0]); IQueryable<string> q = _prov.CreateQuery<string>(call); Assert.Equal(new[] { "a", "b", "c" }, q); } private static IEnumerable<char> IncrementCharacters(char start, char end) { for (; start != end; ++start) { yield return start; } } private IQueryable<char> ParameterMethod(char start, char end) { return IncrementCharacters(start, end).AsQueryable(); } [Fact] public void ParameterMethodCallViaLambda() { ParameterExpression start = Expression.Parameter(typeof(char)); ParameterExpression end = Expression.Parameter(typeof(char)); Expression call = Expression.Call(Expression.Constant(this), "ParameterMethod", new Type[0], start, end); Expression lambda = Expression.Lambda<Func<char, char, IQueryable<char>>>(call, start, end); Expression invoke = Expression.Invoke(lambda, Expression.Constant('b'), Expression.Constant('g')); Assert.Equal("bcdef".ToCharArray(), _prov.CreateQuery<char>(invoke)); } private static class TestLinqExtensions { public static IEnumerable<int> RunningTotals(IEnumerable<int> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return RunningTotalsIterator(source); } public static IEnumerable<int> RunningTotalsIterator(IEnumerable<int> source) { using (var en = source.GetEnumerator()) { if (en.MoveNext()) { int current = en.Current; yield return current; while (en.MoveNext()) yield return current += en.Current; } } } public static IQueryable<int> RunningTotals(IQueryable<int> source) { // A real class would only overload for IQueryable separately if there // was a reason for doing so, but this suffices to test. return RunningTotals(source.AsEnumerable()).AsQueryable(); } public static IQueryable<int> RunningTotalsNoMatch(IQueryable<int> source) { return RunningTotals(source); } public static IQueryable<int> RunningTotals(IQueryable<int> source, int initialTally) { return RunningTotals(Enumerable.Repeat(initialTally, 1).AsQueryable().Concat(source)); } } private class TestLinqInstanceNoMatch { public IQueryable<int> RunningTotals(IQueryable<int> source) { return TestLinqExtensions.RunningTotals(source); } } [Fact] public void EnumerableQueryableAsInternalArgumentToMethod() { Expression call = Expression.Call( typeof(TestLinqExtensions) .GetMethods() .First(mi => mi.Name == "RunningTotals" && mi.GetParameters().Length == 1 && mi.GetParameters()[0].ParameterType == typeof(IQueryable<int>)), Expression.Constant(Enumerable.Range(1, 3).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(call); Assert.Equal(new[] { 1, 3, 6 }, q); } [Fact] public void EnumerableQueryableAsInternalArgumentToMethodNoMatch() { Expression call = Expression.Call( typeof(TestLinqExtensions) .GetMethods() .First(mi => mi.Name == "RunningTotalsNoMatch" && mi.GetParameters()[0].ParameterType == typeof(IQueryable<int>)), Expression.Constant(Enumerable.Range(1, 3).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(call); Assert.Throws<InvalidOperationException>(() => q.GetEnumerator()); } [Fact] public void EnumerableQueryableAsInternalArgumentToMethodNoArgumentMatch() { Expression call = Expression.Call( typeof(TestLinqExtensions) .GetMethods() .First(mi => mi.Name == "RunningTotals" && mi.GetParameters().Length == 2), Expression.Constant(Enumerable.Range(1, 3).AsQueryable()), Expression.Constant(3) ); IQueryable<int> q = _prov.CreateQuery<int>(call); Assert.Throws<InvalidOperationException>(() => q.GetEnumerator()); } [Fact] public void EnumerableQueryableAsInternalArgumentToInstanceMethodNoMatch() { Expression call = Expression.Call( Expression.Constant(new TestLinqInstanceNoMatch()), typeof(TestLinqInstanceNoMatch) .GetMethods() .First(mi => mi.Name == "RunningTotals"), Expression.Constant(Enumerable.Range(1, 3).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(call); Assert.Throws<InvalidOperationException>(() => q.GetEnumerator()); } [Fact] public void EnumerableQueryAsInternalArgumentToQueryableMethod() { Expression call = Expression.Call(typeof(Queryable), "AsQueryable", new[] { typeof(int) }, Expression.Constant(Enumerable.Range(1, 3).AsQueryable(), typeof(IQueryable<int>))); IQueryable<int> q = _prov.CreateQuery<int>(call); Assert.Equal(new[] { 1, 2, 3 }, q); } [Fact] public void NonGeneric() { Expression call = Expression.Call(typeof(Queryable), "AsQueryable", new[] { typeof(int) }, Expression.Constant(Enumerable.Range(1, 3).AsQueryable(), typeof(IQueryable<int>))); IQueryable q = _prov.CreateQuery(call); Assert.Equal(new[] { 1, 2, 3 }, q.Cast<int>()); } [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop Framework doesn't support ConditionalExpression in EnumerableQuery")] public void ExplicitlyTypedConditional() { Expression call = Expression.Call( typeof(Queryable), "OfType", new[] { typeof(long) }, Expression.Condition( Expression.Constant(true), Expression.Constant(new long?[] { 2, 3, null, 1 }.AsQueryable()), Expression.Constant(Enumerable.Range(0, 3).AsQueryable().Select(i => (long)i)), typeof(IQueryable) ) ); IQueryable<long> q = _prov.CreateQuery<long>(call); Assert.Equal(new long[] { 2, 3, 1 }, q); } [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop Framework doesn't support BlockExpression in EnumerableQuery")] public void Block() { Expression block = Expression.Block( Expression.Empty(), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(block); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop Framework doesn't support BlockExpression in EnumerableQuery")] public void ExplicitlyTypedBlock() { Expression block = Expression.Block( typeof(IQueryable<int>), Expression.Empty(), Expression.Constant(Enumerable.Range(0, 2).AsQueryable()) ); IQueryable<int> q = _prov.CreateQuery<int>(block); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop Framework doesn't support BlockExpression in EnumerableQuery")] public void Return() { LabelTarget target = Expression.Label(typeof(IQueryable<int>)); Expression block = Expression.Block( Expression.Return(target, Expression.Constant(Enumerable.Range(0, 2).AsQueryable())), Expression.Label(target, Expression.Default(typeof(IQueryable<int>))) ); IQueryable<int> q = _prov.CreateQuery<int>(block); Assert.Equal(Enumerable.Range(0, 2), q); } [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop Framework doesn't support BlockExpression in EnumerableQuery")] public void ReturnArray() { LabelTarget target = Expression.Label(typeof(IQueryable<int>)); Expression block = Expression.Block( Expression.Return(target, Expression.Constant(new[] { 1, 1, 2, 3, 5, 8 }.AsQueryable())), Expression.Label(target, Expression.Default(typeof(IQueryable<int>))) ); IQueryable<int> q = _prov.CreateQuery<int>(block); Assert.Equal(new[] { 1, 1, 2, 3, 5, 8 }, q); } [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop Framework doesn't support BlockExpression in EnumerableQuery")] public void ReturnOrdered() { LabelTarget target = Expression.Label(typeof(IQueryable<int>)); Expression block = Expression.Block( Expression.Return(target, Expression.Constant(Enumerable.Range(0, 3).OrderByDescending(i => i).AsQueryable())), Expression.Label(target, Expression.Default(typeof(IOrderedQueryable<int>))) ); IQueryable<int> q = _prov.CreateQuery<int>(block); Assert.Equal(new[] { 2, 1, 0 }, q); } [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop Framework doesn't support BlockExpression in EnumerableQuery")] public void ReturnOrderedAfterAsQueryable() { LabelTarget target = Expression.Label(typeof(IQueryable<int>)); Expression block = Expression.Block( Expression.Return(target, Expression.Constant(Enumerable.Range(0, 3).AsQueryable().OrderByDescending(i => i))), Expression.Label(target, Expression.Default(typeof(IOrderedQueryable<int>))) ); IQueryable<int> q = _prov.CreateQuery<int>(block); Assert.Equal(new[] { 2, 1, 0 }, q); } [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop Framework doesn't support BlockExpression in EnumerableQuery")] public void ReturnNonQueryable() { LabelTarget target = Expression.Label(typeof(int)); Expression block = Expression.Block( Expression.Condition( Expression.Constant(true), Expression.Return(target, Expression.Constant(3)), Expression.Return(target, Expression.Constant(1)) ), Expression.Return(target, Expression.Constant(2)), Expression.Label(target, Expression.Default(typeof(int))) ); Assert.Equal(3, _prov.Execute<int>(block)); } [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop Framework doesn't support BlockExpression in EnumerableQuery")] public void ReturnNonQueryableUntyped() { LabelTarget target = Expression.Label(typeof(int)); Expression block = Expression.Block( Expression.Condition( Expression.Constant(true), Expression.Return(target, Expression.Constant(3)), Expression.Return(target, Expression.Constant(1)) ), Expression.Return(target, Expression.Constant(2)), Expression.Label(target, Expression.Default(typeof(int))) ); Assert.Equal(3, _prov.Execute(block)); } } }
using System; using System.Collections; using Stetic.Wrapper; using Mono.Unix; namespace Stetic.Editor { public class ActionGroupEditor: Gtk.EventBox, IMenuItemContainer { ActionGroup actionGroup; Gtk.Table table; IProject project; ArrayList items = new ArrayList (); Gtk.EventBox emptyLabel; EditableLabel headerLabel; uint columns = 2; bool modified; bool disposed; ObjectWrapperEventHandler changedEvent; IDesignArea darea; public EventHandler GroupModified; public EventHandler SelectionChanged; public ActionGroupEditor () { changedEvent = new ObjectWrapperEventHandler (OnActionChanged); Gtk.Fixed fx = new Gtk.Fixed (); table = new Gtk.Table (0, 0, false); table.RowSpacing = 8; table.ColumnSpacing = 8; table.BorderWidth = 12; Gtk.EventBox ebox = new Gtk.EventBox (); ebox.ModifyBg (Gtk.StateType.Normal, this.Style.Backgrounds [0]); headerLabel = new EditableLabel (); headerLabel.MarkupTemplate = "<b>$TEXT</b>"; headerLabel.Changed += OnGroupNameChanged; Gtk.VBox vbox = new Gtk.VBox (); Gtk.Label grpLabel = new Gtk.Label (); grpLabel.Xalign = 0; grpLabel.Markup = "<small><i>Action Group</i></small>"; // vbox.PackStart (grpLabel, false, false, 0); vbox.PackStart (headerLabel, false, false, 3); vbox.BorderWidth = 12; ebox.Add (vbox); Gtk.VBox box = new Gtk.VBox (); box.Spacing = 6; box.PackStart (ebox, false, false, 0); box.PackStart (table, false, false, 0); fx.Put (box, 0, 0); Add (fx); ShowAll (); } public override void Dispose () { if (disposed) return; disposed = true; headerLabel.Changed -= OnGroupNameChanged; if (emptyLabel != null) emptyLabel.ButtonPressEvent -= OnAddClicked; foreach (ActionMenuItem aitem in items) { aitem.KeyPressEvent -= OnItemKeyPress; aitem.Node.Dispose (); aitem.Detach (); aitem.Destroy (); } items.Clear (); ActionGroup = null; project = null; headerLabel = null; if (darea != null) { darea.SelectionChanged -= OnSelectionChanged; darea = null; } base.Dispose (); } public ActionGroup ActionGroup { get { return actionGroup; } set { if (actionGroup != null) { actionGroup.ObjectChanged -= OnGroupChanged; actionGroup.ActionAdded -= OnActionAdded; actionGroup.ActionRemoved -= OnActionRemoved; foreach (Wrapper.Action a in actionGroup.Actions) a.ObjectChanged -= changedEvent; } actionGroup = value; if (actionGroup != null) { headerLabel.Text = actionGroup.Name; actionGroup.ObjectChanged += OnGroupChanged; actionGroup.ActionAdded += OnActionAdded; actionGroup.ActionRemoved += OnActionRemoved; foreach (Wrapper.Action a in actionGroup.Actions) a.ObjectChanged += changedEvent; } if (!disposed) Fill (); } } public IProject Project { get { return project; } set { project = value; } } public bool Modified { get { return modified; } set { modified = value; } } public Wrapper.Action SelectedAction { get { IDesignArea designArea = GetDesignArea (); IObjectSelection sel = designArea.GetSelection (); if (sel != null) return ObjectWrapper.Lookup (sel.DataObject) as Wrapper.Action; else return null; } set { foreach (ActionMenuItem item in items) { if (item.Node.Action == value) item.Select (); } } } ActionMenuItem SelectedActionMenuItem { get { IDesignArea designArea = GetDesignArea (); IObjectSelection sel = designArea.GetSelection (); if (sel != null) return sel.Widget as ActionMenuItem; else return null; } } public void StartEditing () { IDesignArea designArea = GetDesignArea (); designArea.SetSelection (headerLabel, null); headerLabel.StartEditing (); } void Fill () { IDesignArea designArea = GetDesignArea (); if (designArea == null) return; Wrapper.Action selAction = null; foreach (ActionMenuItem item in items) { if (designArea.IsSelected (item)) selAction = item.Node.Action; item.Node.Dispose (); item.Detach (); item.Destroy (); } items.Clear (); if (actionGroup != null) { Wrapper.Action[] sortedActions = new Wrapper.Action [actionGroup.Actions.Count]; actionGroup.Actions.CopyTo (sortedActions, 0); Array.Sort (sortedActions, new ActionComparer ()); for (int n = 0; n < sortedActions.Length; n++) { Wrapper.Action action = (Wrapper.Action) sortedActions [n]; ActionMenuItem item = InsertAction (action, n); if (selAction == action) item.Select (); } if (selAction == null) designArea.SetSelection (null, null); headerLabel.Sensitive = true; PlaceAddLabel (actionGroup.Actions.Count); } else { HideAddLabel (); headerLabel.Text = Catalog.GetString ("No selection"); headerLabel.Sensitive = false; } ShowAll (); } ActionMenuItem InsertAction (Wrapper.Action action, int n) { uint row = (uint) n / columns; uint col = (uint) (n % columns) * 3; IDesignArea designArea = GetDesignArea (); ActionTreeNode node = new ActionTreeNode (Gtk.UIManagerItemType.Menuitem, "", action); ActionMenuItem aitem = new ActionMenuItem (designArea, project, this, node); aitem.KeyPressEvent += OnItemKeyPress; aitem.MinWidth = 150; aitem.Attach (table, row, col); Gtk.Frame fr = new Gtk.Frame (); fr.Shadow = Gtk.ShadowType.Out; aitem.Add (fr); items.Add (aitem); return aitem; } void PlaceAddLabel (int n) { HideAddLabel (); uint r = (uint) n / columns; uint c = (uint) (n % columns) * 3; emptyLabel = new Gtk.EventBox (); emptyLabel.VisibleWindow = false; Gtk.Label label = new Gtk.Label (); label.Xalign = 0; label.Markup = "<i><span foreground='darkgrey'>" + Catalog.GetString ("Click to create action") + "</span></i>"; emptyLabel.Add (label); emptyLabel.ButtonPressEvent += OnAddClicked; table.Attach (emptyLabel, c, c+3, r, r+1); } void HideAddLabel () { if (emptyLabel != null) { table.Remove (emptyLabel); emptyLabel.ButtonPressEvent -= OnAddClicked; } emptyLabel = null; } void OnGroupChanged (object s, ObjectWrapperEventArgs args) { headerLabel.Text = actionGroup.Name; NotifyModified (); } void OnActionAdded (object s, ActionEventArgs args) { args.Action.ObjectChanged += changedEvent; Fill (); NotifyModified (); } void OnActionRemoved (object s, ActionEventArgs args) { args.Action.ObjectChanged -= changedEvent; Fill (); NotifyModified (); } void OnActionChanged (object s, ObjectWrapperEventArgs args) { NotifyModified (); } void NotifyModified () { modified = true; if (GroupModified != null) GroupModified (this, EventArgs.Empty); } void OnAddClicked (object s, Gtk.ButtonPressEventArgs args) { Wrapper.Action ac = (Wrapper.Action) ObjectWrapper.Create (project, new Gtk.Action ("", "", null, null)); ActionMenuItem item = InsertAction (ac, actionGroup.Actions.Count); item.EditingDone += OnEditDone; item.Select (); item.StartEditing (); HideAddLabel (); ShowAll (); } void OnEditDone (object sender, EventArgs args) { ActionMenuItem item = (ActionMenuItem) sender; item.EditingDone -= OnEditDone; if (item.Node.Action.GtkAction.Label.Length > 0 || item.Node.Action.GtkAction.StockId != null) { actionGroup.Actions.Add (item.Node.Action); } else { IDesignArea designArea = GetDesignArea (); designArea.ResetSelection (item); item.Detach (); item.Node.Dispose (); items.Remove (item); item.Destroy (); PlaceAddLabel (actionGroup.Actions.Count); ShowAll (); } } protected override bool OnButtonPressEvent (Gdk.EventButton ev) { IDesignArea designArea = GetDesignArea (); designArea.SetSelection (null, null); return true; } void OnItemKeyPress (object s, Gtk.KeyPressEventArgs args) { int pos = items.IndexOf (s); switch (args.Event.Key) { case Gdk.Key.Up: pos -= (int) columns; break; case Gdk.Key.Down: pos += (int) columns; break; case Gdk.Key.Right: pos ++; break; case Gdk.Key.Left: pos --; break; } if (pos >= 0 && pos < items.Count) { ((ActionMenuItem)items[pos]).Select (); args.RetVal = true; } else if (pos == items.Count) { OnAddClicked (null, null); args.RetVal = true; } } void OnGroupNameChanged (object s, EventArgs args) { if (actionGroup != null) actionGroup.Name = headerLabel.Text; } void OnSelectionChanged (object s, EventArgs args) { if (SelectionChanged != null) SelectionChanged (this, args); } public void Cut () { ActionMenuItem menuItem = SelectedActionMenuItem; if (menuItem != null) Cut (SelectedActionMenuItem); } public void Copy () { ActionMenuItem menuItem = SelectedActionMenuItem; if (menuItem != null) Copy (SelectedActionMenuItem); } public void Paste () { } public void Delete () { ActionMenuItem menuItem = SelectedActionMenuItem; if (menuItem != null) Delete (SelectedActionMenuItem); } void Cut (ActionMenuItem menuItem) { } void Copy (ActionMenuItem menuItem) { } void Paste (ActionMenuItem menuItem) { } void Delete (ActionMenuItem menuItem) { string msg = string.Format (Catalog.GetString ("Are you sure you want to delete the action '{0}'? It will be removed from all menus and toolbars."), menuItem.Node.Action.Name); Gtk.MessageDialog md = new Gtk.MessageDialog (null, Gtk.DialogFlags.Modal, Gtk.MessageType.Question, Gtk.ButtonsType.YesNo, msg); if (md.Run () == (int) Gtk.ResponseType.Yes) { menuItem.Node.Action.Delete (); darea.SetSelection (null, null); } md.Destroy (); } void IMenuItemContainer.ShowContextMenu (ActionItem aitem) { ActionMenuItem menuItem = aitem as ActionMenuItem; Gtk.Menu m = new Gtk.Menu (); Gtk.MenuItem item = new Gtk.ImageMenuItem (Gtk.Stock.Cut, null); m.Add (item); item.Activated += delegate (object s, EventArgs a) { Cut (menuItem); }; item.Visible = false; // No copy & paste for now item = new Gtk.ImageMenuItem (Gtk.Stock.Copy, null); m.Add (item); item.Activated += delegate (object s, EventArgs a) { Copy (menuItem); }; item.Visible = false; // No copy & paste for now item = new Gtk.ImageMenuItem (Gtk.Stock.Paste, null); m.Add (item); item.Activated += delegate (object s, EventArgs a) { Paste (menuItem); }; item.Visible = false; // No copy & paste for now item = new Gtk.ImageMenuItem (Gtk.Stock.Delete, null); m.Add (item); item.Activated += delegate (object s, EventArgs a) { Delete (menuItem); }; m.ShowAll (); m.Popup (); } IDesignArea GetDesignArea () { if (darea != null) return darea; darea = WidgetUtils.GetDesignArea (this); darea.SelectionChanged += OnSelectionChanged; return darea; } ActionMenu IMenuItemContainer.OpenSubmenu { get { return null; } set { } } bool IMenuItemContainer.IsTopMenu { get { return false; } } Gtk.Widget IMenuItemContainer.Widget { get { return this; } } class ActionComparer: IComparer { public int Compare (object x, object y) { return string.Compare (((Wrapper.Action)x).GtkAction.Label, ((Wrapper.Action)y).GtkAction.Label); } } } public class EditableLabel: Gtk.EventBox { string text; string markup; public EditableLabel (): this ("") { } public EditableLabel (string txt) { VisibleWindow = false; text = txt; Add (CreateLabel ()); } public string Text { get { return text; } set { text = value; if (Child is Gtk.Entry) ((Gtk.Entry)Child).Text = text; else ((Gtk.Label)Child).Markup = Markup; } } public string MarkupTemplate { get { return markup; } set { markup = value; if (Child is Gtk.Label) ((Gtk.Label)Child).Markup = Markup; } } public string Markup { get { return markup != null ? markup.Replace ("$TEXT",text) : text; } } protected override bool OnButtonPressEvent (Gdk.EventButton ev) { IDesignArea d = WidgetUtils.GetDesignArea (this); if (d.IsSelected (this)) { if (Child is Gtk.Label) { StartEditing (); return true; } } else { d.SetSelection (this, null); return true; } return false; } void SelectionDisposed (object s, EventArgs args) { EndEditing (); } public void StartEditing () { if (Child is Gtk.Label) { IDesignArea d = WidgetUtils.GetDesignArea (this); IObjectSelection sel = d.GetSelection (this); if (sel == null) sel = d.SetSelection (this, null); sel.Disposed += SelectionDisposed; Remove (Child); Add (CreateEntry ()); ShowAll (); Child.GrabFocus (); } } public void EndEditing () { if (Child is Gtk.Entry) { Remove (Child); Add (CreateLabel ()); ShowAll (); } } Gtk.Label CreateLabel () { Gtk.Label label = new Gtk.Label (); label.Markup = Markup; label.Xalign = 0; return label; } Gtk.Entry CreateEntry () { Gtk.Entry e = new Gtk.Entry (text); e.Changed += delegate (object s, EventArgs a) { text = e.Text; if (Changed != null) Changed (this, a); }; e.Activated += delegate (object s, EventArgs a) { EndEditing (); }; return e; } public event EventHandler Changed; } }
using System; using Csla; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERLevel; namespace ParentLoad.Business.ERLevel { /// <summary> /// A11_City_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="A11_City_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="A10_City"/> collection. /// </remarks> [Serializable] public partial class A11_City_ReChild : BusinessBase<A11_City_ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int city_ID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "City Child Name"); /// <summary> /// Gets or sets the City Child Name. /// </summary> /// <value>The City Child Name.</value> public string City_Child_Name { get { return GetProperty(City_Child_NameProperty); } set { SetProperty(City_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A11_City_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="A11_City_ReChild"/> object.</returns> internal static A11_City_ReChild NewA11_City_ReChild() { return DataPortal.CreateChild<A11_City_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="A11_City_ReChild"/> object from the given A11_City_ReChildDto. /// </summary> /// <param name="data">The <see cref="A11_City_ReChildDto"/>.</param> /// <returns>A reference to the fetched <see cref="A11_City_ReChild"/> object.</returns> internal static A11_City_ReChild GetA11_City_ReChild(A11_City_ReChildDto data) { A11_City_ReChild obj = new A11_City_ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); // check all object rules and property rules obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A11_City_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public A11_City_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A11_City_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A11_City_ReChild"/> object from the given <see cref="A11_City_ReChildDto"/>. /// </summary> /// <param name="data">The A11_City_ReChildDto to use.</param> private void Fetch(A11_City_ReChildDto data) { // Value properties LoadProperty(City_Child_NameProperty, data.City_Child_Name); // parent properties city_ID2 = data.Parent_City_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="A11_City_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A10_City parent) { var dto = new A11_City_ReChildDto(); dto.Parent_City_ID = parent.City_ID; dto.City_Child_Name = City_Child_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IA11_City_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="A11_City_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(A10_City parent) { if (!IsDirty) return; var dto = new A11_City_ReChildDto(); dto.Parent_City_ID = parent.City_ID; dto.City_Child_Name = City_Child_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IA11_City_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="A11_City_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(A10_City parent) { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IA11_City_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.City_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; namespace SmallSharpTools.EmbeddedScripts.Controls { /// <summary> /// </summary> public class EmbeddedScriptsActionList : DesignerActionList { #region " Variables " private EmbeddedScriptsManager _ctrl = null; #endregion #region " Methods " /// <summary> /// </summary> public EmbeddedScriptsActionList(IComponent component) : base(component) { _ctrl = component as EmbeddedScriptsManager; } /// <summary> /// </summary> public void LaunchWebsite() { Process.Start("http://www.smallsharptools.com/"); } /// <summary> /// </summary> public override DesignerActionItemCollection GetSortedActionItems() { DesignerActionItemCollection actionItems = new DesignerActionItemCollection(); actionItems.Add(new DesignerActionHeaderItem("Scripts")); actionItems.Add(new DesignerActionHeaderItem("Support")); actionItems.Add(new DesignerActionPropertyItem("IsVerbose", "Verbose", "Scripts")); actionItems.Add(new DesignerActionPropertyItem("UseJQueryScript", "Use jQuery", "Scripts")); actionItems.Add(new DesignerActionPropertyItem("UseJQueryJsonScript", "Use jQuery JSON", "Scripts")); actionItems.Add(new DesignerActionPropertyItem("UseJQueryInterfaceScript", "Use jQuery Interface", "Scripts")); actionItems.Add(new DesignerActionPropertyItem("UseJQueryDimensionsScript", "Use jQuery Dimensions", "Scripts")); actionItems.Add(new DesignerActionPropertyItem("UseJQueryTooltipScript", "Use jQuery Tooltip", "Scripts")); actionItems.Add(new DesignerActionPropertyItem("UseJQueryContextMenuScript", "Use jQuery Context Menu", "Scripts")); actionItems.Add(new DesignerActionPropertyItem("UsePrototypeScript", "Use Prototype", "Scripts")); actionItems.Add(new DesignerActionPropertyItem("UseScriptaculousScript", "Use Scriptaculous", "Scripts")); actionItems.Add(new DesignerActionMethodItem(this, "LaunchWebsite", "SmallSharpTools.com", "Support")); return actionItems; } private PropertyDescriptor GetControlProperty(string propertyName) { PropertyDescriptor pd = TypeDescriptor.GetProperties(_ctrl)[propertyName]; if (pd != null) { return pd; } else { throw new ArgumentException("Invalid property", propertyName); } } #endregion #region " Properties " /// <summary> /// </summary> public bool IsVerbose { get { return _ctrl.IsVerbose; } set { GetControlProperty("IsVerbose").SetValue(_ctrl, value); } } /// <summary> /// </summary> public bool UseJQueryScript { get { return _ctrl.UseJQueryScript; } set { GetControlProperty("UseJQueryScript").SetValue(_ctrl, value); } } /// <summary> /// </summary> public bool UseJQueryJsonScript { get { return _ctrl.UseJQueryJsonScript; } set { GetControlProperty("UseJQueryJsonScript").SetValue(_ctrl, value); } } /// <summary> /// </summary> public bool UseJQueryInterfaceScript { get { return _ctrl.UseJQueryInterfaceScript; } set { GetControlProperty("UseJQueryInterfaceScript").SetValue(_ctrl, value); } } /// <summary> /// </summary> public bool UseJQueryDimensionsScript { get { return _ctrl.UseJQueryDimensionsScript; } set { GetControlProperty("UseJQueryDimensionsScript").SetValue(_ctrl, value); } } /// <summary> /// </summary> public bool UseJQueryTooltipScript { get { return _ctrl.UseJQueryTooltipScript; } set { GetControlProperty("UseJQueryTooltipScript").SetValue(_ctrl, value); } } /// <summary> /// </summary> public bool UseJQueryContextMenuScript { get { return _ctrl.UseJQueryContextMenuScript; } set { GetControlProperty("UseJQueryContextMenuScript").SetValue(_ctrl, value); } } /// <summary> /// </summary> public bool UsePrototypeScript { get { return _ctrl.UsePrototypeScript; } set { GetControlProperty("UsePrototypeScript").SetValue(_ctrl, value); } } /// <summary> /// </summary> public bool UseScriptaculousScript { get { return _ctrl.UseScriptaculousScript; } set { GetControlProperty("UseScriptaculousScript").SetValue(_ctrl, value); } } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcbsv = Google.Cloud.BigQuery.Storage.V1; using sys = System; namespace Google.Cloud.BigQuery.Storage.V1 { /// <summary>Resource name for the <c>Table</c> resource.</summary> public sealed partial class TableName : gax::IResourceName, sys::IEquatable<TableName> { /// <summary>The possible contents of <see cref="TableName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/datasets/{dataset}/tables/{table}</c>. /// </summary> ProjectDatasetTable = 1, } private static gax::PathTemplate s_projectDatasetTable = new gax::PathTemplate("projects/{project}/datasets/{dataset}/tables/{table}"); /// <summary>Creates a <see cref="TableName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TableName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static TableName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TableName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TableName"/> with the pattern <c>projects/{project}/datasets/{dataset}/tables/{table}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TableName"/> constructed from the provided ids.</returns> public static TableName FromProjectDatasetTable(string projectId, string datasetId, string tableId) => new TableName(ResourceNameType.ProjectDatasetTable, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TableName"/> with pattern /// <c>projects/{project}/datasets/{dataset}/tables/{table}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TableName"/> with pattern /// <c>projects/{project}/datasets/{dataset}/tables/{table}</c>. /// </returns> public static string Format(string projectId, string datasetId, string tableId) => FormatProjectDatasetTable(projectId, datasetId, tableId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TableName"/> with pattern /// <c>projects/{project}/datasets/{dataset}/tables/{table}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TableName"/> with pattern /// <c>projects/{project}/datasets/{dataset}/tables/{table}</c>. /// </returns> public static string FormatProjectDatasetTable(string projectId, string datasetId, string tableId) => s_projectDatasetTable.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId))); /// <summary>Parses the given resource name string into a new <see cref="TableName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/datasets/{dataset}/tables/{table}</c></description></item> /// </list> /// </remarks> /// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TableName"/> if successful.</returns> public static TableName Parse(string tableName) => Parse(tableName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TableName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/datasets/{dataset}/tables/{table}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TableName"/> if successful.</returns> public static TableName Parse(string tableName, bool allowUnparsed) => TryParse(tableName, allowUnparsed, out TableName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TableName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/datasets/{dataset}/tables/{table}</c></description></item> /// </list> /// </remarks> /// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TableName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tableName, out TableName result) => TryParse(tableName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TableName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/datasets/{dataset}/tables/{table}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tableName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TableName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string tableName, bool allowUnparsed, out TableName result) { gax::GaxPreconditions.CheckNotNull(tableName, nameof(tableName)); gax::TemplatedResourceName resourceName; if (s_projectDatasetTable.TryParseName(tableName, out resourceName)) { result = FromProjectDatasetTable(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(tableName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TableName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string datasetId = null, string projectId = null, string tableId = null) { Type = type; UnparsedResource = unparsedResourceName; DatasetId = datasetId; ProjectId = projectId; TableId = tableId; } /// <summary> /// Constructs a new instance of a <see cref="TableName"/> class from the component parts of pattern /// <c>projects/{project}/datasets/{dataset}/tables/{table}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="datasetId">The <c>Dataset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tableId">The <c>Table</c> ID. Must not be <c>null</c> or empty.</param> public TableName(string projectId, string datasetId, string tableId) : this(ResourceNameType.ProjectDatasetTable, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), datasetId: gax::GaxPreconditions.CheckNotNullOrEmpty(datasetId, nameof(datasetId)), tableId: gax::GaxPreconditions.CheckNotNullOrEmpty(tableId, nameof(tableId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Dataset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string DatasetId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Table</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TableId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectDatasetTable: return s_projectDatasetTable.Expand(ProjectId, DatasetId, TableId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TableName); /// <inheritdoc/> public bool Equals(TableName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TableName a, TableName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TableName a, TableName b) => !(a == b); } public partial class CreateReadSessionRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ReadRowsRequest { /// <summary> /// <see cref="ReadStreamName"/>-typed view over the <see cref="ReadStream"/> resource name property. /// </summary> public ReadStreamName ReadStreamAsReadStreamName { get => string.IsNullOrEmpty(ReadStream) ? null : ReadStreamName.Parse(ReadStream, allowUnparsed: true); set => ReadStream = value?.ToString() ?? ""; } } public partial class SplitReadStreamRequest { /// <summary> /// <see cref="gcbsv::ReadStreamName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbsv::ReadStreamName ReadStreamName { get => string.IsNullOrEmpty(Name) ? null : gcbsv::ReadStreamName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateWriteStreamRequest { /// <summary><see cref="TableName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public TableName ParentAsTableName { get => string.IsNullOrEmpty(Parent) ? null : TableName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class AppendRowsRequest { /// <summary> /// <see cref="WriteStreamName"/>-typed view over the <see cref="WriteStream"/> resource name property. /// </summary> public WriteStreamName WriteStreamAsWriteStreamName { get => string.IsNullOrEmpty(WriteStream) ? null : WriteStreamName.Parse(WriteStream, allowUnparsed: true); set => WriteStream = value?.ToString() ?? ""; } } public partial class GetWriteStreamRequest { /// <summary> /// <see cref="gcbsv::WriteStreamName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbsv::WriteStreamName WriteStreamName { get => string.IsNullOrEmpty(Name) ? null : gcbsv::WriteStreamName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class FinalizeWriteStreamRequest { /// <summary> /// <see cref="gcbsv::WriteStreamName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbsv::WriteStreamName WriteStreamName { get => string.IsNullOrEmpty(Name) ? null : gcbsv::WriteStreamName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class FlushRowsRequest { /// <summary> /// <see cref="WriteStreamName"/>-typed view over the <see cref="WriteStream"/> resource name property. /// </summary> public WriteStreamName WriteStreamAsWriteStreamName { get => string.IsNullOrEmpty(WriteStream) ? null : WriteStreamName.Parse(WriteStream, allowUnparsed: true); set => WriteStream = value?.ToString() ?? ""; } } }
// // Copyright 2011-2013, Xamarin 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.Linq; using System.Text; using Android.Content; using Android.Content.Res; using Android.Database; using Android.Provider; using StructuredName = Android.Provider.ContactsContract.CommonDataKinds.StructuredName; using StructuredPostal = Android.Provider.ContactsContract.CommonDataKinds.StructuredPostal; using CommonColumns = Android.Provider.ContactsContract.CommonDataKinds.CommonColumns; using Uri = Android.Net.Uri; using InstantMessaging = Android.Provider.ContactsContract.CommonDataKinds.Im; using OrganizationData = Android.Provider.ContactsContract.CommonDataKinds.Organization; using WebsiteData = Android.Provider.ContactsContract.CommonDataKinds.Website; using Relation = Android.Provider.ContactsContract.CommonDataKinds.Relation; using Contacts.Plugin.Abstractions; using System.Threading.Tasks; namespace Contacts.Plugin { internal static class ContactHelper { internal static IEnumerable<Contact> GetContacts(bool rawContacts, ContentResolver content, Resources resources) { Uri curi = (rawContacts) ? ContactsContract.RawContacts.ContentUri : ContactsContract.Contacts.ContentUri; ICursor cursor = null; try { cursor = content.Query(curi, null, null, null, null); if (cursor == null) yield break; foreach (Contact contact in GetContacts(cursor, rawContacts, content, resources, 256)) yield return contact; } finally { if (cursor != null) cursor.Close(); } } internal static IEnumerable<Contact> GetContacts(ICursor cursor, bool rawContacts, ContentResolver content, Resources resources, int batchSize) { if (cursor == null) yield break; string column = (rawContacts) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; string[] ids = new string[batchSize]; int columnIndex = cursor.GetColumnIndex(column); HashSet<string> uniques = new HashSet<string>(); int i = 0; while (cursor.MoveToNext()) { if (i == batchSize) { i = 0; foreach (Contact c in GetContacts(rawContacts, content, resources, ids)) yield return c; } string id = cursor.GetString(columnIndex); if (uniques.Contains(id)) continue; uniques.Add(id); ids[i++] = id; } if (i > 0) { foreach (Contact c in GetContacts(rawContacts, content, resources, ids.Take(i).ToArray())) yield return c; } } internal static IEnumerable<Contact> GetContacts(bool rawContacts, ContentResolver content, Resources resources, string[] ids) { ICursor c = null; string column = (rawContacts) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; StringBuilder whereb = new StringBuilder(); for (int i = 0; i < ids.Length; i++) { if (i > 0) whereb.Append(" OR "); whereb.Append(column); whereb.Append("=?"); } int x = 0; var map = new Dictionary<string, Contact>(ids.Length); try { Contact currentContact = null; c = content.Query(ContactsContract.Data.ContentUri, null, whereb.ToString(), ids, ContactsContract.ContactsColumns.LookupKey); if (c == null) yield break; int idIndex = c.GetColumnIndex(column); int dnIndex = c.GetColumnIndex(ContactsContract.ContactsColumns.DisplayName); while (c.MoveToNext()) { string id = c.GetString(idIndex); if (currentContact == null || currentContact.Id != id) { // We need to yield these in the original ID order if (currentContact != null) { if (currentContact.Id == ids[x]) { yield return currentContact; x++; } else map.Add(currentContact.Id, currentContact); } currentContact = new Contact(id, !rawContacts) { Tag = content }; currentContact.DisplayName = c.GetString(dnIndex); } FillContactWithRow(resources, currentContact, c); } if (currentContact != null) map.Add(currentContact.Id, currentContact); for (; x < ids.Length; x++) { Contact tContact = null; if(map.TryGetValue(ids[x], out tContact)) yield return tContact; } } finally { if (c != null) c.Close(); } } internal static Contact GetContact(bool rawContact, ContentResolver content, Resources resources, ICursor cursor) { string id = (rawContact) ? cursor.GetString(cursor.GetColumnIndex(ContactsContract.RawContactsColumns.ContactId)) : cursor.GetString(cursor.GetColumnIndex(ContactsContract.ContactsColumns.LookupKey)); var contact = new Contact(id, !rawContact) { Tag = content }; contact.DisplayName = GetString(cursor, ContactsContract.ContactsColumns.DisplayName); FillContactExtras(rawContact, content, resources, id, contact); return contact; } internal static void FillContactExtras(bool rawContact, ContentResolver content, Resources resources, string recordId, Contact contact) { ICursor c = null; string column = (rawContact) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; try { if (string.IsNullOrWhiteSpace(recordId)) return; c = content.Query(ContactsContract.Data.ContentUri, null, column + " = ?", new[] { recordId }, null); if (c == null) return; while (c.MoveToNext()) FillContactWithRow(resources, contact, c); } finally { if (c != null) c.Close(); } } private static void FillContactWithRow(Resources resources, Contact contact, ICursor c) { string dataType = c.GetString(c.GetColumnIndex(ContactsContract.DataColumns.Mimetype)); switch (dataType) { case ContactsContract.CommonDataKinds.Nickname.ContentItemType: contact.Nickname = c.GetString(c.GetColumnIndex(ContactsContract.CommonDataKinds.Nickname.Name)); break; case StructuredName.ContentItemType: contact.Prefix = c.GetString(StructuredName.Prefix); contact.FirstName = c.GetString(StructuredName.GivenName); contact.MiddleName = c.GetString(StructuredName.MiddleName); contact.LastName = c.GetString(StructuredName.FamilyName); contact.Suffix = c.GetString(StructuredName.Suffix); break; case ContactsContract.CommonDataKinds.Phone.ContentItemType: contact.Phones.Add(GetPhone(c, resources)); break; case ContactsContract.CommonDataKinds.Email.ContentItemType: contact.Emails.Add(GetEmail(c, resources)); break; case ContactsContract.CommonDataKinds.Note.ContentItemType: contact.Notes.Add(GetNote(c, resources)); break; case ContactsContract.CommonDataKinds.Organization.ContentItemType: contact.Organizations.Add(GetOrganization(c, resources)); break; case StructuredPostal.ContentItemType: contact.Addresses.Add(GetAddress(c, resources)); break; case InstantMessaging.ContentItemType: contact.InstantMessagingAccounts.Add(GetImAccount(c, resources)); break; case WebsiteData.ContentItemType: contact.Websites.Add(GetWebsite(c, resources)); break; case Relation.ContentItemType: contact.Relationships.Add(GetRelationship(c, resources)); break; } } internal static Note GetNote(ICursor c, Resources resources) { return new Note { Contents = GetString(c, ContactsContract.DataColumns.Data1) }; } internal static Relationship GetRelationship(ICursor c, Resources resources) { Relationship r = new Relationship { Name = c.GetString(Relation.Name) }; RelationDataKind rtype = (RelationDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); switch (rtype) { case RelationDataKind.DomesticPartner: case RelationDataKind.Spouse: case RelationDataKind.Friend: r.Type = RelationshipType.SignificantOther; break; case RelationDataKind.Child: r.Type = RelationshipType.Child; break; default: r.Type = RelationshipType.Other; break; } return r; } internal static InstantMessagingAccount GetImAccount(ICursor c, Resources resources) { InstantMessagingAccount ima = new InstantMessagingAccount(); ima.Account = c.GetString(CommonColumns.Data); //IMTypeDataKind imKind = (IMTypeDataKind) c.GetInt (c.GetColumnIndex (CommonColumns.Type)); //ima.Type = imKind.ToInstantMessagingType(); //ima.Label = InstantMessaging.GetTypeLabel (resources, imKind, c.GetString (CommonColumns.Label)); IMProtocolDataKind serviceKind = (IMProtocolDataKind)c.GetInt(c.GetColumnIndex(InstantMessaging.Protocol)); ima.Service = serviceKind.ToInstantMessagingService(); ima.ServiceLabel = (serviceKind != IMProtocolDataKind.Custom) ? InstantMessaging.GetProtocolLabel(resources, serviceKind, String.Empty) : c.GetString(InstantMessaging.CustomProtocol); return ima; } internal static Address GetAddress(ICursor c, Resources resources) { Address a = new Address(); a.Country = c.GetString(StructuredPostal.Country); a.Region = c.GetString(StructuredPostal.Region); a.City = c.GetString(StructuredPostal.City); a.PostalCode = c.GetString(StructuredPostal.Postcode); AddressDataKind kind = (AddressDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); a.Type = kind.ToAddressType(); a.Label = (kind != AddressDataKind.Custom) ? StructuredPostal.GetTypeLabel(resources, kind, String.Empty) : c.GetString(CommonColumns.Label); string street = c.GetString(StructuredPostal.Street); string pobox = c.GetString(StructuredPostal.Pobox); if (street != null) a.StreetAddress = street; if (pobox != null) { if (street != null) a.StreetAddress += Environment.NewLine; a.StreetAddress += pobox; } return a; } internal static Phone GetPhone(ICursor c, Resources resources) { Phone p = new Phone(); p.Number = GetString(c, ContactsContract.CommonDataKinds.Phone.Number); PhoneDataKind pkind = (PhoneDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); p.Type = pkind.ToPhoneType(); p.Label = (pkind != PhoneDataKind.Custom) ? ContactsContract.CommonDataKinds.Phone.GetTypeLabel(resources, pkind, String.Empty) : c.GetString(CommonColumns.Label); return p; } internal static Email GetEmail(ICursor c, Resources resources) { Email e = new Email(); e.Address = c.GetString(ContactsContract.DataColumns.Data1); EmailDataKind ekind = (EmailDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); e.Type = ekind.ToEmailType(); e.Label = (ekind != EmailDataKind.Custom) ? ContactsContract.CommonDataKinds.Email.GetTypeLabel(resources, ekind, String.Empty) : c.GetString(CommonColumns.Label); return e; } internal static Organization GetOrganization(ICursor c, Resources resources) { Organization o = new Organization(); o.Name = c.GetString(OrganizationData.Company); o.ContactTitle = c.GetString(OrganizationData.Title); OrganizationDataKind d = (OrganizationDataKind)c.GetInt(c.GetColumnIndex(CommonColumns.Type)); o.Type = d.ToOrganizationType(); o.Label = (d != OrganizationDataKind.Custom) ? OrganizationData.GetTypeLabel(resources, d, String.Empty) : c.GetString(CommonColumns.Label); return o; } internal static Website GetWebsite(ICursor c, Resources resources) { Website w = new Website(); w.Address = c.GetString(WebsiteData.Url); //WebsiteDataKind kind = (WebsiteDataKind)c.GetInt (c.GetColumnIndex (CommonColumns.Type)); //w.Type = kind.ToWebsiteType(); //w.Label = (kind != WebsiteDataKind.Custom) // ? resources.GetString ((int) kind) // : c.GetString (CommonColumns.Label); return w; } //internal static WebsiteType ToWebsiteType (this WebsiteDataKind websiteKind) //{ // switch (websiteKind) // { // case WebsiteDataKind.Work: // return WebsiteType.Work; // case WebsiteDataKind.Home: // return WebsiteType.Home; // default: // return WebsiteType.Other; // } //} internal static string GetString(this ICursor c, string colName) { return c.GetString(c.GetColumnIndex(colName)); } internal static AddressType ToAddressType(this AddressDataKind addressKind) { switch (addressKind) { case AddressDataKind.Home: return AddressType.Home; case AddressDataKind.Work: return AddressType.Work; default: return AddressType.Other; } } internal static EmailType ToEmailType(this EmailDataKind emailKind) { switch (emailKind) { case EmailDataKind.Home: return EmailType.Home; case EmailDataKind.Work: return EmailType.Work; default: return EmailType.Other; } } internal static PhoneType ToPhoneType(this PhoneDataKind phoneKind) { switch (phoneKind) { case PhoneDataKind.Home: return PhoneType.Home; case PhoneDataKind.Mobile: return PhoneType.Mobile; case PhoneDataKind.FaxHome: return PhoneType.HomeFax; case PhoneDataKind.Work: return PhoneType.Work; case PhoneDataKind.FaxWork: return PhoneType.WorkFax; case PhoneDataKind.Pager: case PhoneDataKind.WorkPager: return PhoneType.Pager; default: return PhoneType.Other; } } internal static OrganizationType ToOrganizationType(this OrganizationDataKind organizationKind) { switch (organizationKind) { case OrganizationDataKind.Work: return OrganizationType.Work; default: return OrganizationType.Other; } } internal static InstantMessagingService ToInstantMessagingService(this IMProtocolDataKind protocolKind) { switch (protocolKind) { case IMProtocolDataKind.Aim: return InstantMessagingService.Aim; case IMProtocolDataKind.Msn: return InstantMessagingService.Msn; case IMProtocolDataKind.Yahoo: return InstantMessagingService.Yahoo; case IMProtocolDataKind.Jabber: return InstantMessagingService.Jabber; case IMProtocolDataKind.Icq: return InstantMessagingService.Icq; default: return InstantMessagingService.Other; } } //internal static InstantMessagingType ToInstantMessagingType (this IMTypeDataKind imKind) //{ // switch (imKind) // { // case IMTypeDataKind.Home: // return InstantMessagingType.Home; // case IMTypeDataKind.Work: // return InstantMessagingType.Work; // default: // return InstantMessagingType.Other; // } //} } }
using System; using System.Collections; using System.IO; using Raksha.Security.Certificates; using Raksha.Asn1; using Raksha.Asn1.Ocsp; using Raksha.Asn1.X509; using Raksha.Crypto; using Raksha.Security; using Raksha.Utilities; using Raksha.X509; using Raksha.X509.Store; namespace Raksha.Ocsp { /** * <pre> * OcspRequest ::= SEQUENCE { * tbsRequest TBSRequest, * optionalSignature [0] EXPLICIT Signature OPTIONAL } * * TBSRequest ::= SEQUENCE { * version [0] EXPLICIT Version DEFAULT v1, * requestorName [1] EXPLICIT GeneralName OPTIONAL, * requestList SEQUENCE OF Request, * requestExtensions [2] EXPLICIT Extensions OPTIONAL } * * Signature ::= SEQUENCE { * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING, * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL} * * Version ::= INTEGER { v1(0) } * * Request ::= SEQUENCE { * reqCert CertID, * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } * * CertID ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * issuerNameHash OCTET STRING, -- Hash of Issuer's DN * issuerKeyHash OCTET STRING, -- Hash of Issuers public key * serialNumber CertificateSerialNumber } * </pre> */ public class OcspReq : X509ExtensionBase { private OcspRequest req; public OcspReq( OcspRequest req) { this.req = req; } public OcspReq( byte[] req) : this(new Asn1InputStream(req)) { } public OcspReq( Stream inStr) : this(new Asn1InputStream(inStr)) { } private OcspReq( Asn1InputStream aIn) { try { this.req = OcspRequest.GetInstance(aIn.ReadObject()); } catch (ArgumentException e) { throw new IOException("malformed request: " + e.Message); } catch (InvalidCastException e) { throw new IOException("malformed request: " + e.Message); } } /** * Return the DER encoding of the tbsRequest field. * @return DER encoding of tbsRequest * @throws OcspException in the event of an encoding error. */ public byte[] GetTbsRequest() { try { return req.TbsRequest.GetEncoded(); } catch (IOException e) { throw new OcspException("problem encoding tbsRequest", e); } } public int Version { get { return req.TbsRequest.Version.Value.IntValue + 1; } } public GeneralName RequestorName { get { return GeneralName.GetInstance(req.TbsRequest.RequestorName); } } public Req[] GetRequestList() { Asn1Sequence seq = req.TbsRequest.RequestList; Req[] requests = new Req[seq.Count]; for (int i = 0; i != requests.Length; i++) { requests[i] = new Req(Request.GetInstance(seq[i])); } return requests; } public X509Extensions RequestExtensions { get { return X509Extensions.GetInstance(req.TbsRequest.RequestExtensions); } } protected override X509Extensions GetX509Extensions() { return RequestExtensions; } /** * return the object identifier representing the signature algorithm */ public string SignatureAlgOid { get { if (!this.IsSigned) return null; return req.OptionalSignature.SignatureAlgorithm.ObjectID.Id; } } public byte[] GetSignature() { if (!this.IsSigned) return null; return req.OptionalSignature.SignatureValue.GetBytes(); } private IList GetCertList() { // load the certificates if we have any IList certs = Platform.CreateArrayList(); Asn1Sequence s = req.OptionalSignature.Certs; if (s != null) { foreach (Asn1Encodable ae in s) { try { certs.Add(new X509CertificateParser().ReadCertificate(ae.GetEncoded())); } catch (Exception e) { throw new OcspException("can't re-encode certificate!", e); } } } return certs; } public X509Certificate[] GetCerts() { if (!this.IsSigned) return null; IList certs = this.GetCertList(); X509Certificate[] result = new X509Certificate[certs.Count]; for (int i = 0; i < certs.Count; ++i) { result[i] = (X509Certificate)certs[i]; } return result; } /** * If the request is signed return a possibly empty CertStore containing the certificates in the * request. If the request is not signed the method returns null. * * @return null if not signed, a CertStore otherwise * @throws OcspException */ public IX509Store GetCertificates( string type) { if (!this.IsSigned) return null; try { return X509StoreFactory.Create( "Certificate/" + type, new X509CollectionStoreParameters(this.GetCertList())); } catch (Exception e) { throw new OcspException("can't setup the CertStore", e); } } /** * Return whether or not this request is signed. * * @return true if signed false otherwise. */ public bool IsSigned { get { return req.OptionalSignature != null; } } /** * Verify the signature against the TBSRequest object we contain. */ public bool Verify( AsymmetricKeyParameter publicKey) { if (!this.IsSigned) throw new OcspException("attempt to Verify signature on unsigned object"); try { ISigner signature = SignerUtilities.GetSigner(this.SignatureAlgOid); signature.Init(false, publicKey); byte[] encoded = req.TbsRequest.GetEncoded(); signature.BlockUpdate(encoded, 0, encoded.Length); return signature.VerifySignature(this.GetSignature()); } catch (Exception e) { throw new OcspException("exception processing sig: " + e, e); } } /** * return the ASN.1 encoded representation of this object. */ public byte[] GetEncoded() { return req.GetEncoded(); } } }
namespace Fakir.EntityFramework.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.AbpAuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256, storeType: "nvarchar"), MethodName = c.String(maxLength: 256, storeType: "nvarchar"), Parameters = c.String(maxLength: 1024, storeType: "nvarchar"), ExecutionTime = c.DateTime(nullable: false, precision: 0), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64, storeType: "nvarchar"), ClientName = c.String(maxLength: 128, storeType: "nvarchar"), BrowserInfo = c.String(maxLength: 256, storeType: "nvarchar"), Exception = c.String(maxLength: 2000, storeType: "nvarchar"), ImpersonatorUserId = c.Long(), ImpersonatorTenantId = c.Int(), CustomData = c.String(maxLength: 2000, storeType: "nvarchar"), }, annotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpBackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512, storeType: "nvarchar"), JobArgs = c.String(nullable: false, unicode: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false, precision: 0), LastTryTime = c.DateTime(precision: 0), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.AppBinaryObjects", c => new { Id = c.Guid(nullable: false), Bytes = c.Binary(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpFeatures", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), Value = c.String(nullable: false, maxLength: 2000, storeType: "nvarchar"), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpEditions", t => t.EditionId, cascadeDelete: true) .Index(t => t.EditionId); CreateTable( "dbo.AbpEditions", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 32, storeType: "nvarchar"), DisplayName = c.String(nullable: false, maxLength: 64, storeType: "nvarchar"), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(precision: 0), LastModificationTime = c.DateTime(precision: 0), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguages", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 10, storeType: "nvarchar"), DisplayName = c.String(nullable: false, maxLength: 64, storeType: "nvarchar"), Icon = c.String(maxLength: 128, storeType: "nvarchar"), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(precision: 0), LastModificationTime = c.DateTime(precision: 0), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguageTexts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), LanguageName = c.String(nullable: false, maxLength: 10, storeType: "nvarchar"), Source = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), Key = c.String(nullable: false, maxLength: 256, storeType: "nvarchar"), Value = c.String(nullable: false, unicode: false), LastModificationTime = c.DateTime(precision: 0), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 96, storeType: "nvarchar"), Data = c.String(unicode: false), DataTypeName = c.String(maxLength: 512, storeType: "nvarchar"), EntityTypeName = c.String(maxLength: 250, storeType: "nvarchar"), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512, storeType: "nvarchar"), EntityId = c.String(maxLength: 96, storeType: "nvarchar"), Severity = c.Byte(nullable: false), UserIds = c.String(unicode: false), ExcludedUserIds = c.String(unicode: false), TenantIds = c.String(unicode: false), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96, storeType: "nvarchar"), EntityTypeName = c.String(maxLength: 250, storeType: "nvarchar"), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512, storeType: "nvarchar"), EntityId = c.String(maxLength: 96, storeType: "nvarchar"), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.AbpOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), ParentId = c.Long(), Code = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), DisplayName = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(precision: 0), LastModificationTime = c.DateTime(precision: 0), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpOrganizationUnits", t => t.ParentId) .Index(t => t.ParentId); CreateTable( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), DisplayName = c.String(nullable: false, maxLength: 64, storeType: "nvarchar"), IsStatic = c.Boolean(nullable: false), IsDefault = c.Boolean(nullable: false), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32, storeType: "nvarchar"), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(precision: 0), LastModificationTime = c.DateTime(precision: 0), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), ProfilePictureId = c.Guid(), ShouldChangePasswordOnNextLogin = c.Boolean(nullable: false), UserLinkId = c.Long(), Mobile = c.String(unicode: false), AuthenticationSource = c.String(maxLength: 64, storeType: "nvarchar"), Name = c.String(nullable: false, maxLength: 32, storeType: "nvarchar"), Surname = c.String(nullable: false, maxLength: 32, storeType: "nvarchar"), Password = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), EmailAddress = c.String(nullable: false, maxLength: 256, storeType: "nvarchar"), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 128, storeType: "nvarchar"), PasswordResetCode = c.String(maxLength: 328, storeType: "nvarchar"), LastLoginTime = c.DateTime(precision: 0), IsActive = c.Boolean(nullable: false), UserName = c.String(nullable: false, maxLength: 32, storeType: "nvarchar"), TenantId = c.Int(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(precision: 0), LastModificationTime = c.DateTime(precision: 0), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), ProviderKey = c.String(nullable: false, maxLength: 256, storeType: "nvarchar"), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256, storeType: "nvarchar"), Value = c.String(maxLength: 2000, storeType: "nvarchar"), LastModificationTime = c.DateTime(precision: 0), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.UserId); CreateTable( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), TenancyName = c.String(nullable: false, maxLength: 64, storeType: "nvarchar"), EditionId = c.Int(), Name = c.String(nullable: false, maxLength: 128, storeType: "nvarchar"), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(precision: 0), LastModificationTime = c.DateTime(precision: 0), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpEditions", t => t.EditionId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.EditionId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64, storeType: "nvarchar"), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 256, storeType: "nvarchar"), ClientIpAddress = c.String(maxLength: 64, storeType: "nvarchar"), ClientName = c.String(maxLength: 128, storeType: "nvarchar"), BrowserInfo = c.String(maxLength: 256, storeType: "nvarchar"), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false, precision: 0), }) .PrimaryKey(t => t.Id) .Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result }); CreateTable( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), UserId = c.Long(nullable: false), NotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false, precision: 0), }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); CreateTable( "dbo.AbpUserOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), OrganizationUnitId = c.Long(nullable: false), CreationTime = c.DateTime(nullable: false, precision: 0), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); } public override void Down() { DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles"); DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "EditionId", "dbo.AbpEditions"); DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpOrganizationUnits", "ParentId", "dbo.AbpOrganizationUnits"); DropForeignKey("dbo.AbpFeatures", "EditionId", "dbo.AbpEditions"); DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" }); DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" }); DropIndex("dbo.AbpTenants", new[] { "EditionId" }); DropIndex("dbo.AbpSettings", new[] { "UserId" }); DropIndex("dbo.AbpSettings", new[] { "TenantId" }); DropIndex("dbo.AbpUserRoles", new[] { "UserId" }); DropIndex("dbo.AbpUserLogins", new[] { "UserId" }); DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" }); DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" }); DropIndex("dbo.AbpUsers", new[] { "TenantId" }); DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" }); DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" }); DropIndex("dbo.AbpRoles", new[] { "TenantId" }); DropIndex("dbo.AbpPermissions", new[] { "UserId" }); DropIndex("dbo.AbpPermissions", new[] { "RoleId" }); DropIndex("dbo.AbpOrganizationUnits", new[] { "ParentId" }); DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.AbpFeatures", new[] { "EditionId" }); DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.AbpUserOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserNotifications"); DropTable("dbo.AbpUserLoginAttempts"); DropTable("dbo.AbpTenants", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpSettings"); DropTable("dbo.AbpUserRoles"); DropTable("dbo.AbpUserLogins"); DropTable("dbo.AbpUsers", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpPermissions"); DropTable("dbo.AbpOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpNotificationSubscriptions"); DropTable("dbo.AbpNotifications"); DropTable("dbo.AbpLanguageTexts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpLanguages", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpEditions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpFeatures"); DropTable("dbo.AppBinaryObjects"); DropTable("dbo.AbpBackgroundJobs"); DropTable("dbo.AbpAuditLogs", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Reflection; using log4net.Core; using log4net.Repository; namespace log4net { /// <summary> /// This class is used by client applications to request logger instances. /// </summary> /// <remarks> /// <para> /// This class has static methods that are used by a client to request /// a logger instance. The <see cref="M:GetLogger(string)"/> method is /// used to retrieve a logger. /// </para> /// <para> /// See the <see cref="ILog"/> interface for more details. /// </para> /// </remarks> /// <example>Simple example of logging messages /// <code lang="C#"> /// ILog log = LogManager.GetLogger("application-log"); /// /// log.Info("Application Start"); /// log.Debug("This is a debug message"); /// /// if (log.IsDebugEnabled) /// { /// log.Debug("This is another debug message"); /// } /// </code> /// </example> /// <threadsafety static="true" instance="true" /> /// <seealso cref="ILog"/> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class LogManager { #region Private Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="LogManager" /> class. /// </summary> /// <remarks> /// Uses a private access modifier to prevent instantiation of this class. /// </remarks> private LogManager() { } #endregion Private Instance Constructors #region Type Specific Manager Methods #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). /// <overloads>Returns the named logger if it exists.</overloads> /// <summary> /// Returns the named logger if it exists. /// </summary> /// <remarks> /// <para> /// If the named logger exists (in the default repository) then it /// returns a reference to the logger, otherwise it returns <c>null</c>. /// </para> /// </remarks> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns>The logger found, or <c>null</c> if no logger could be found.</returns> public static ILog Exists(string name) { return Exists(Assembly.GetCallingAssembly(), name); } /// <overloads>Get the currently defined loggers.</overloads> /// <summary> /// Returns all the currently defined loggers in the default repository. /// </summary> /// <remarks> /// <para>The root logger is <b>not</b> included in the returned array.</para> /// </remarks> /// <returns>All the defined loggers.</returns> public static ILog[] GetCurrentLoggers() { return GetCurrentLoggers(Assembly.GetCallingAssembly()); } /// <overloads>Get or create a logger.</overloads> /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <remarks> /// <para> /// Retrieves a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para>By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(string name) { return GetLogger(Assembly.GetCallingAssembly(), name); } #endif // !NETSTANDARD1_3 /// <summary> /// Returns the named logger if it exists. /// </summary> /// <remarks> /// <para> /// If the named logger exists (in the specified repository) then it /// returns a reference to the logger, otherwise it returns /// <c>null</c>. /// </para> /// </remarks> /// <param name="repository">The repository to lookup in.</param> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns> /// The logger found, or <c>null</c> if the logger doesn't exist in the specified /// repository. /// </returns> public static ILog Exists(string repository, string name) { return WrapLogger(LoggerManager.Exists(repository, name)); } /// <summary> /// Returns the named logger if it exists. /// </summary> /// <remarks> /// <para> /// If the named logger exists (in the repository for the specified assembly) then it /// returns a reference to the logger, otherwise it returns /// <c>null</c>. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns> /// The logger, or <c>null</c> if the logger doesn't exist in the specified /// assembly's repository. /// </returns> public static ILog Exists(Assembly repositoryAssembly, string name) { return WrapLogger(LoggerManager.Exists(repositoryAssembly, name)); } /// <summary> /// Returns all the currently defined loggers in the specified repository. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <remarks> /// The root logger is <b>not</b> included in the returned array. /// </remarks> /// <returns>All the defined loggers.</returns> public static ILog[] GetCurrentLoggers(string repository) { return WrapLoggers(LoggerManager.GetCurrentLoggers(repository)); } /// <summary> /// Returns all the currently defined loggers in the specified assembly's repository. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <remarks> /// The root logger is <b>not</b> included in the returned array. /// </remarks> /// <returns>All the defined loggers.</returns> public static ILog[] GetCurrentLoggers(Assembly repositoryAssembly) { return WrapLoggers(LoggerManager.GetCurrentLoggers(repositoryAssembly)); } /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <remarks> /// <para> /// Retrieve a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para> /// By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> /// <param name="repository">The repository to lookup in.</param> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(string repository, string name) { return WrapLogger(LoggerManager.GetLogger(repository, name)); } /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <remarks> /// <para> /// Retrieve a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para> /// By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(Assembly repositoryAssembly, string name) { return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, name)); } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <remarks> /// Get the logger for the fully qualified name of the type specified. /// </remarks> /// <param name="type">The full name of <paramref name="type"/> will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(Type type) { #if NETSTANDARD1_3 return GetLogger(type.GetTypeInfo().Assembly, type.FullName); #else return GetLogger(Assembly.GetCallingAssembly(), type.FullName); #endif } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <remarks> /// Gets the logger for the fully qualified name of the type specified. /// </remarks> /// <param name="repository">The repository to lookup in.</param> /// <param name="type">The full name of <paramref name="type"/> will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(string repository, Type type) { return WrapLogger(LoggerManager.GetLogger(repository, type)); } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <remarks> /// Gets the logger for the fully qualified name of the type specified. /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="type">The full name of <paramref name="type"/> will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(Assembly repositoryAssembly, Type type) { return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, type)); } #endregion Type Specific Manager Methods #region Domain & Repository Manager Methods /// <summary> /// Shuts down the log4net system. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in all the /// default repositories. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para>The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void Shutdown() { LoggerManager.Shutdown(); } #if !NETSTANDARD1_3 /// <overloads>Shutdown a logger repository.</overloads> /// <summary> /// Shuts down the default repository. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// default repository. /// </para> /// <para>Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para>The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void ShutdownRepository() { ShutdownRepository(Assembly.GetCallingAssembly()); } #endif /// <summary> /// Shuts down the repository for the repository specified. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// <paramref name="repository"/> specified. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para>The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> /// <param name="repository">The repository to shutdown.</param> public static void ShutdownRepository(string repository) { LoggerManager.ShutdownRepository(repository); } /// <summary> /// Shuts down the repository specified. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// repository. The repository is looked up using /// the <paramref name="repositoryAssembly"/> specified. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para> /// The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> public static void ShutdownRepository(Assembly repositoryAssembly) { LoggerManager.ShutdownRepository(repositoryAssembly); } #if !NETSTANDARD1_3 /// <overloads>Reset the configuration of a repository</overloads> /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <remarks> /// <para> /// Resets all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set to its default "off" value. /// </para> /// </remarks> public static void ResetConfiguration() { ResetConfiguration(Assembly.GetCallingAssembly()); } #endif /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <remarks> /// <para> /// Reset all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set to its default "off" value. /// </para> /// </remarks> /// <param name="repository">The repository to reset.</param> public static void ResetConfiguration(string repository) { LoggerManager.ResetConfiguration(repository); } /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <remarks> /// <para> /// Reset all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set to its default "off" value. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository to reset.</param> public static void ResetConfiguration(Assembly repositoryAssembly) { LoggerManager.ResetConfiguration(repositoryAssembly); } #if !NETSTANDARD1_3 /// <overloads>Get the logger repository.</overloads> /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the callers assembly (<see cref="M:Assembly.GetCallingAssembly()"/>). /// </para> /// </remarks> /// <returns>The <see cref="ILoggerRepository"/> instance for the default repository.</returns> [Obsolete("Use GetRepository instead of GetLoggerRepository")] public static ILoggerRepository GetLoggerRepository() { return GetRepository(Assembly.GetCallingAssembly()); } #endif /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repository"/> argument. /// </para> /// </remarks> /// <param name="repository">The repository to lookup in.</param> [Obsolete("Use GetRepository instead of GetLoggerRepository")] public static ILoggerRepository GetLoggerRepository(string repository) { return GetRepository(repository); } /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repositoryAssembly"/> argument. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> [Obsolete("Use GetRepository instead of GetLoggerRepository")] public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) { return GetRepository(repositoryAssembly); } #if !NETSTANDARD1_3 /// <overloads>Get a logger repository.</overloads> /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the callers assembly (<see cref="M:Assembly.GetCallingAssembly()"/>). /// </para> /// </remarks> /// <returns>The <see cref="ILoggerRepository"/> instance for the default repository.</returns> public static ILoggerRepository GetRepository() { return GetRepository(Assembly.GetCallingAssembly()); } #endif /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repository"/> argument. /// </para> /// </remarks> /// <param name="repository">The repository to lookup in.</param> public static ILoggerRepository GetRepository(string repository) { return LoggerManager.GetRepository(repository); } /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repositoryAssembly"/> argument. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> public static ILoggerRepository GetRepository(Assembly repositoryAssembly) { return LoggerManager.GetRepository(repositoryAssembly); } #if !NETSTANDARD1_3 /// <overloads>Create a domain</overloads> /// <summary> /// Creates a repository with the specified repository type. /// </summary> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository()"/> will return /// the same repository instance. /// </para> /// </remarks> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> [Obsolete("Use CreateRepository instead of CreateDomain")] public static ILoggerRepository CreateDomain(Type repositoryType) { return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); } /// <overloads>Create a logger repository.</overloads> /// <summary> /// Creates a repository with the specified repository type. /// </summary> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository()"/> will return /// the same repository instance. /// </para> /// </remarks> public static ILoggerRepository CreateRepository(Type repositoryType) { return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); } #endif /// <summary> /// Creates a repository with the specified name. /// </summary> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// Creates the default type of <see cref="ILoggerRepository"/> which is a /// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object. /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <param name="repository">The name of the repository, this must be unique amongst repositories.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <exception cref="LogException">The specified repository already exists.</exception> [Obsolete("Use CreateRepository instead of CreateDomain")] public static ILoggerRepository CreateDomain(string repository) { return LoggerManager.CreateRepository(repository); } /// <summary> /// Creates a repository with the specified name. /// </summary> /// <remarks> /// <para> /// Creates the default type of <see cref="ILoggerRepository"/> which is a /// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object. /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <param name="repository">The name of the repository, this must be unique amongst repositories.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <exception cref="LogException">The specified repository already exists.</exception> public static ILoggerRepository CreateRepository(string repository) { return LoggerManager.CreateRepository(repository); } /// <summary> /// Creates a repository with the specified name and repository type. /// </summary> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <param name="repository">The name of the repository, this must be unique to the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <exception cref="LogException">The specified repository already exists.</exception> [Obsolete("Use CreateRepository instead of CreateDomain")] public static ILoggerRepository CreateDomain(string repository, Type repositoryType) { return LoggerManager.CreateRepository(repository, repositoryType); } /// <summary> /// Creates a repository with the specified name and repository type. /// </summary> /// <remarks> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <param name="repository">The name of the repository, this must be unique to the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <exception cref="LogException">The specified repository already exists.</exception> public static ILoggerRepository CreateRepository(string repository, Type repositoryType) { return LoggerManager.CreateRepository(repository, repositoryType); } /// <summary> /// Creates a repository for the specified assembly and repository type. /// </summary> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> [Obsolete("Use CreateRepository instead of CreateDomain")] public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) { return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); } /// <summary> /// Creates a repository for the specified assembly and repository type. /// </summary> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) { return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); } /// <summary> /// Gets the list of currently defined repositories. /// </summary> /// <remarks> /// <para> /// Get an array of all the <see cref="ILoggerRepository"/> objects that have been created. /// </para> /// </remarks> /// <returns>An array of all the known <see cref="ILoggerRepository"/> objects.</returns> public static ILoggerRepository[] GetAllRepositories() { return LoggerManager.GetAllRepositories(); } /// <summary> /// Flushes logging events buffered in all configured appenders in the default repository. /// </summary> /// <param name="millisecondsTimeout">The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed.</param> /// <returns><c>True</c> if all logging events were flushed successfully, else <c>false</c>.</returns> public static bool Flush(int millisecondsTimeout) { #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). Appender.IFlushable flushableRepository = LoggerManager.GetRepository(Assembly.GetCallingAssembly()) as Appender.IFlushable; if (flushableRepository == null) { return false; } else { return flushableRepository.Flush(millisecondsTimeout); } #else return false; #endif } #endregion Domain & Repository Manager Methods #region Extension Handlers /// <summary> /// Looks up the wrapper object for the logger specified. /// </summary> /// <param name="logger">The logger to get the wrapper for.</param> /// <returns>The wrapper for the logger specified.</returns> private static ILog WrapLogger(ILogger logger) { return (ILog)s_wrapperMap.GetWrapper(logger); } /// <summary> /// Looks up the wrapper objects for the loggers specified. /// </summary> /// <param name="loggers">The loggers to get the wrappers for.</param> /// <returns>The wrapper objects for the loggers specified.</returns> private static ILog[] WrapLoggers(ILogger[] loggers) { ILog[] results = new ILog[loggers.Length]; for(int i=0; i<loggers.Length; i++) { results[i] = WrapLogger(loggers[i]); } return results; } /// <summary> /// Create the <see cref="ILoggerWrapper"/> objects used by /// this manager. /// </summary> /// <param name="logger">The logger to wrap.</param> /// <returns>The wrapper for the logger specified.</returns> private static ILoggerWrapper WrapperCreationHandler(ILogger logger) { return new LogImpl(logger); } #endregion #region Private Static Fields /// <summary> /// The wrapper map to use to hold the <see cref="LogImpl"/> objects. /// </summary> private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler)); #endregion Private Static Fields } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace TableLib { /// <summary> /// Represents an entry in the TableErrors table /// </summary> public class TableError { /// <summary> /// The line number the occurred on. /// </summary> public int LineNumber; /// <summary> /// A description of the error. /// </summary> public string Description; } /// <summary> /// Linked entry. /// </summary> public class LinkedEntry { public string Text; public int Number; } internal class HexValuePair { public string HexNumber; public string Value; } /// <summary> /// Table reader type. /// ReadTypeInsert indicates that values are being inserted. /// ReadTypeDump indicates that values are being dumped. /// </summary> public enum TableReaderType { ReadTypeInsert, ReadTypeDump } /// <summary> /// Reads and parses a thingy table. /// </summary> public class TableReader { /// <summary> /// Stores all the errors that occurred while processing the table file. /// </summary> public List<TableError> TableErrors { get; private set; } /// <summary> /// The longest hex string processed in bytes. /// </summary> public int LongestHex { get; private set; } /// <summary> /// An array of the longest text strings processed per hex value. /// </summary> public int [] LongestText { get; private set; } /// <summary> /// Stores the linked entries. /// </summary> public SortedList <string, LinkedEntry> LinkedEntries { get; private set; } /// <summary> /// Stores the list of all the end tokens. /// </summary> public List<string> EndTokens { get; private set; } /// <summary> /// Stores the table values. Retrieve hex values in insert mode and text values in dump mode. /// </summary> public SortedList <string, string> LookupValue { get; private set; } private static string DefEndLine = "<LINE>"; private static string DefEndString = "<END>"; private static string HexAlphaNum = "ABCDEFabcdef0123456789"; private int LineNumber; private TableReaderType ReaderType; /// <summary> /// Initializes a new instance of the <see cref="TableLib.TableReader"/> class. /// </summary> /// <param name="type">Indicates whether values are being inserted or dumped.</param> public TableReader (TableReaderType type) { LongestHex = 1; LongestText = new int[1024]; LongestText['<'] = 6; ReaderType = type; TableErrors = new List<TableError>(); LinkedEntries = new SortedList <string, LinkedEntry>(); EndTokens = new List<string>(); LookupValue = new SortedList<string, string>(); if (ReaderType == TableReaderType.ReadTypeInsert) { InitHexTable(); } } public bool OpenTable (string tableFileName, string encoding = "utf-8") { return OpenTable(tableFileName, Encoding.GetEncoding(encoding)); } /// <summary> /// Opens the table. /// </summary> /// <returns><c>true</c>, if table was successfully processed, <c>false</c> otherwise.</returns> /// <param name="tableFileName">Table file name.</param> /// <param name="encoding">The character encoding of the table. Defaults to <c>utf-8</c></param> public bool OpenTable (string tableFileName, Encoding encoding) { LinkedList<string> entryList = new LinkedList<string>(); try { var tableFile = File.ReadAllText(tableFileName, encoding) .Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in tableFile) { entryList.AddLast(line); ++LineNumber; if (line.Length == 0) continue; switch (line[0]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': parseEntry(line); break; case '$': parseLink(line); break; case '/': parseEndString(line); break; case '*': parseEndLine(line); break; case '(': case '{': case '[': break; default: RecordError("First character of the line is not a" + " recognized table character"); break; } } } catch (Exception ex) { LineNumber = -1; RecordError(ex.Message); return false; } return TableErrors.Count == 0; } private bool addToMaps (string hexString, string textString) { string modString = textString; if (ReaderType == TableReaderType.ReadTypeDump) { modString = changeControlCodes(modString, true); if (LookupValue.ContainsKey(hexString)) { RecordError("Unable to add duplicate Hex tokens, causes dumping conflicts."); return false; } else { LookupValue.Add(hexString, modString); } } else if (ReaderType == TableReaderType.ReadTypeInsert) { modString = changeControlCodes(modString, false); if (LookupValue.ContainsKey(textString)) { RecordError("Unable to add duplicate Text tokens, causes dumping conflicts."); return false; } else { LookupValue.Add(modString, hexString); } } updateLongest(hexString, modString); return true; } private void InitHexTable () { string textVal; string hexVal; for (int i = 0; i < 0x100; ++i) { hexVal = i.ToString ("X2"); textVal = "<$" + hexVal + ">"; LookupValue.Add (textVal, hexVal); } } private bool parseEndLine (string line) { line = line.Substring (1); string hexstr, textstr; HexValuePair tokens = getTokens (line, false); if (tokens == null) { return false; } hexstr = tokens.HexNumber; textstr = string.IsNullOrEmpty(tokens.Value) ? DefEndLine : tokens.Value; return addToMaps(hexstr, textstr); } private bool parseEndString (string line) { line = line.Substring(1); string hexstr, textstr; HexValuePair tokens; // /<end> type entry if (line.IndexOfAny (HexAlphaNum.ToCharArray ()) != 0) { EndTokens.Add (line); return addToMaps (string.Empty, line); } tokens = getTokens (line, false); if (tokens == null) { return false; } hexstr = tokens.HexNumber; textstr = string.IsNullOrEmpty(tokens.Value) ? DefEndString : tokens.Value; line = changeControlCodes(textstr, false); EndTokens.Add (line); return addToMaps(hexstr, textstr); } private bool parseEntry (string line) { HexValuePair tokens = getTokens(line, true); if (tokens == null) { return false; } return addToMaps(tokens.HexNumber, tokens.Value); } private bool parseLink (string line) { LinkedEntry l = new LinkedEntry(); int pos; line = line.Substring(1); string hexstr, textstr; HexValuePair tokens = getTokens(line, true); if (tokens == null) { return false; } hexstr = tokens.HexNumber; pos = tokens.Value.LastIndexOf(','); if (pos == -1) { RecordError ("No comma, linked entry format is $XX=<text>,num"); return false; } textstr = tokens.Value.Substring(0, pos); tokens.Value = tokens.Value.Substring (pos + 1); pos = findFirstNotOf (tokens.Value, "0123456789"); if (pos >= 0) { RecordError ("Nonnumeric characters in num field, linked entry format is $XX=<text>,num"); return false; } l.Text = textstr; l.Number = int.Parse (tokens.Value); if (ReaderType == TableReaderType.ReadTypeDump) { l.Text = changeControlCodes(l.Text, true); if (LinkedEntries.ContainsKey(hexstr)) { RecordError("Linked entry with this hex token already exists."); return false; } else { LinkedEntries.Add(hexstr, l); } } else if (ReaderType == TableReaderType.ReadTypeInsert) { string modString = textstr; modString = changeControlCodes(modString, false); if (LookupValue.ContainsKey(modString)) { RecordError("Unable to add duplicate text token, causes dumper conflicts"); return false; } else { LookupValue.Add(modString, hexstr); updateLongest (hexstr, modString); } } return true; } private string changeControlCodes (string text, bool replace) { int pos = text.IndexOf(@"\n"); while (pos != -1) { text = text.Remove(pos, 2); if (replace) { text = text.Insert(pos, "\n"); } pos = text.IndexOf(@"\n", pos); } return text; } private HexValuePair getTokens (string line, bool isNormalEntry) { HexValuePair tokens = new HexValuePair(); int pos; //if "XX=" if ((pos = line.IndexOf ('=')) == line.Length - 1) { RecordError ("Entry is incomplete"); return null; } //if "XX" if (pos == -1) { if (isNormalEntry) { RecordError("No string token present"); return null; } else { pos = line.Length; } } else { tokens.Value = line.Substring (pos + 1); } string hexString = line.Substring (0, pos).ToUpper(); pos = findFirstNotOf (hexString, HexAlphaNum); if (pos >= 0) { hexString = hexString.Substring(0, pos); } if ((hexString.Length & 1) != 0) { RecordError("Incomplete hex token"); return null; } tokens.HexNumber = hexString; return tokens; } //code taken from //http://stackoverflow.com/questions/4498176/c-sharp-equivalent-of-c-stdstring-find-first-not-of-and-find-last-not-of private int findFirstNotOf (string source, string chars) { for (int i = 0; i < source.Length; ++i) { if (chars.IndexOf(source[i]) == -1) { return i; } } return -1; } private void updateLongest (string hexstr, string ModString) { int hexLength = hexstr.Length / 2; if (LongestHex < hexLength) { LongestHex = hexLength; } if (ModString.Length > 0 && LongestText[(byte)ModString[0]] < ModString.Length) { LongestText[(byte)ModString[0]] = ModString.Length; } } private void RecordError(string errString) { TableError err = new TableError(); err.LineNumber = LineNumber; err.Description = errString; TableErrors.Add(err); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using Orleans.CodeGeneration; using Orleans.Runtime; namespace Orleans.Serialization { internal static class BinaryTokenStreamWriterExtensions { internal static void Write<TWriter>(this TWriter @this, SerializationTokenType t) where TWriter : IBinaryTokenStreamWriter { @this.Write((byte)t); } /// <summary> Write a <c>CorrelationId</c> value to the stream. </summary> internal static void Write<TWriter>(this TWriter @this, CorrelationId id) where TWriter : IBinaryTokenStreamWriter { @this.Write(id.ToInt64()); } /// <summary> Write a <c>ActivationAddress</c> value to the stream. </summary> internal static void Write<TWriter>(this TWriter @this, ActivationAddress addr) where TWriter : IBinaryTokenStreamWriter { @this.Write(addr.Silo ?? SiloAddress.Zero); // GrainId must not be null @this.Write(addr.Grain); @this.Write(addr.Activation ?? ActivationId.Zero); } internal static void Write<TWriter>(this TWriter @this, UniqueKey key) where TWriter : IBinaryTokenStreamWriter { @this.Write(key.N0); @this.Write(key.N1); @this.Write(key.TypeCodeData); @this.Write(key.KeyExt); } /// <summary> Write a <c>ActivationId</c> value to the stream. </summary> internal static void Write<TWriter>(this TWriter @this, ActivationId id) where TWriter : IBinaryTokenStreamWriter { @this.Write(id.Key); } /// <summary> Write a <c>GrainId</c> value to the stream. </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] internal static void Write<TWriter>(this TWriter @this, GrainId id) where TWriter : IBinaryTokenStreamWriter { @this.Write(id.Type); @this.Write(id.Key); } /// <summary> Write a <c>GrainId</c> value to the stream. </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] internal static void Write<TWriter>(this TWriter @this, GrainType type) where TWriter : IBinaryTokenStreamWriter { @this.Write(type.Value); } internal static void Write<TWriter>(this TWriter @this, GrainInterfaceType type) where TWriter : IBinaryTokenStreamWriter { @this.Write(type.Value); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] internal static void Write<TWriter>(this TWriter @this, IdSpan value) where TWriter : IBinaryTokenStreamWriter { @this.Write(value.GetHashCode()); var array = IdSpan.UnsafeGetArray(value); if (array is object) { @this.Write((ushort)array.Length); @this.Write(array); } else { @this.Write((ushort)0); } } /// <summary> /// Write header for an <c>Array</c> to the output stream. /// </summary> /// <param name="this">The IBinaryTokenStreamReader to read from</param> /// <param name="a">Data object for which header should be written.</param> /// <param name="expected">The most recent Expected Type currently active for this stream.</param> internal static void WriteArrayHeader<TWriter>(this TWriter @this, Array a, Type expected = null) where TWriter : IBinaryTokenStreamWriter { @this.WriteTypeHeader(a.GetType(), expected); for (var i = 0; i < a.Rank; i++) { @this.Write(a.GetLength(i)); } } // Back-references internal static void WriteReference<TWriter>(this TWriter @this, int offset) where TWriter : IBinaryTokenStreamWriter { @this.Write((byte)SerializationTokenType.Reference); @this.Write(offset); } } /// <summary> /// Writer for Orleans binary token streams /// </summary> public class BinaryTokenStreamWriter : IBinaryTokenStreamWriter { private readonly ByteArrayBuilder ab; private static readonly Dictionary<RuntimeTypeHandle, SerializationTokenType> typeTokens; private static readonly Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>> writers; static BinaryTokenStreamWriter() { typeTokens = new Dictionary<RuntimeTypeHandle, SerializationTokenType>(RuntimeTypeHandlerEqualityComparer.Instance); typeTokens[typeof(bool).TypeHandle] = SerializationTokenType.Boolean; typeTokens[typeof(int).TypeHandle] = SerializationTokenType.Int; typeTokens[typeof(uint).TypeHandle] = SerializationTokenType.Uint; typeTokens[typeof(short).TypeHandle] = SerializationTokenType.Short; typeTokens[typeof(ushort).TypeHandle] = SerializationTokenType.Ushort; typeTokens[typeof(long).TypeHandle] = SerializationTokenType.Long; typeTokens[typeof(ulong).TypeHandle] = SerializationTokenType.Ulong; typeTokens[typeof(byte).TypeHandle] = SerializationTokenType.Byte; typeTokens[typeof(sbyte).TypeHandle] = SerializationTokenType.Sbyte; typeTokens[typeof(float).TypeHandle] = SerializationTokenType.Float; typeTokens[typeof(double).TypeHandle] = SerializationTokenType.Double; typeTokens[typeof(decimal).TypeHandle] = SerializationTokenType.Decimal; typeTokens[typeof(string).TypeHandle] = SerializationTokenType.String; typeTokens[typeof(char).TypeHandle] = SerializationTokenType.Character; typeTokens[typeof(Guid).TypeHandle] = SerializationTokenType.Guid; typeTokens[typeof(DateTime).TypeHandle] = SerializationTokenType.Date; typeTokens[typeof(TimeSpan).TypeHandle] = SerializationTokenType.TimeSpan; typeTokens[typeof(GrainId).TypeHandle] = SerializationTokenType.GrainId; typeTokens[typeof(ActivationId).TypeHandle] = SerializationTokenType.ActivationId; typeTokens[typeof(SiloAddress).TypeHandle] = SerializationTokenType.SiloAddress; typeTokens[typeof(ActivationAddress).TypeHandle] = SerializationTokenType.ActivationAddress; typeTokens[typeof(IPAddress).TypeHandle] = SerializationTokenType.IpAddress; typeTokens[typeof(IPEndPoint).TypeHandle] = SerializationTokenType.IpEndPoint; typeTokens[typeof(CorrelationId).TypeHandle] = SerializationTokenType.CorrelationId; typeTokens[typeof(InvokeMethodRequest).TypeHandle] = SerializationTokenType.Request; typeTokens[typeof(Response).TypeHandle] = SerializationTokenType.Response; typeTokens[typeof(Dictionary<string, object>).TypeHandle] = SerializationTokenType.StringObjDict; typeTokens[typeof(Object).TypeHandle] = SerializationTokenType.Object; typeTokens[typeof(List<>).TypeHandle] = SerializationTokenType.List; typeTokens[typeof(SortedList<,>).TypeHandle] = SerializationTokenType.SortedList; typeTokens[typeof(Dictionary<,>).TypeHandle] = SerializationTokenType.Dictionary; typeTokens[typeof(HashSet<>).TypeHandle] = SerializationTokenType.Set; typeTokens[typeof(SortedSet<>).TypeHandle] = SerializationTokenType.SortedSet; typeTokens[typeof(KeyValuePair<,>).TypeHandle] = SerializationTokenType.KeyValuePair; typeTokens[typeof(LinkedList<>).TypeHandle] = SerializationTokenType.LinkedList; typeTokens[typeof(Stack<>).TypeHandle] = SerializationTokenType.Stack; typeTokens[typeof(Queue<>).TypeHandle] = SerializationTokenType.Queue; typeTokens[typeof(Tuple<>).TypeHandle] = SerializationTokenType.Tuple + 1; typeTokens[typeof(Tuple<,>).TypeHandle] = SerializationTokenType.Tuple + 2; typeTokens[typeof(Tuple<,,>).TypeHandle] = SerializationTokenType.Tuple + 3; typeTokens[typeof(Tuple<,,,>).TypeHandle] = SerializationTokenType.Tuple + 4; typeTokens[typeof(Tuple<,,,,>).TypeHandle] = SerializationTokenType.Tuple + 5; typeTokens[typeof(Tuple<,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 6; typeTokens[typeof(Tuple<,,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 7; writers = new Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>>(RuntimeTypeHandlerEqualityComparer.Instance); writers[typeof(bool).TypeHandle] = (stream, obj) => stream.Write((bool) obj); writers[typeof(int).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Int); stream.Write((int) obj); }; writers[typeof(uint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Uint); stream.Write((uint) obj); }; writers[typeof(short).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Short); stream.Write((short) obj); }; writers[typeof(ushort).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ushort); stream.Write((ushort) obj); }; writers[typeof(long).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Long); stream.Write((long) obj); }; writers[typeof(ulong).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ulong); stream.Write((ulong) obj); }; writers[typeof(byte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Byte); stream.Write((byte) obj); }; writers[typeof(sbyte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Sbyte); stream.Write((sbyte) obj); }; writers[typeof(float).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Float); stream.Write((float) obj); }; writers[typeof(double).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Double); stream.Write((double) obj); }; writers[typeof(decimal).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Decimal); stream.Write((decimal)obj); }; writers[typeof(string).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.String); stream.Write((string)obj); }; writers[typeof(char).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Character); stream.Write((char) obj); }; writers[typeof(Guid).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Guid); stream.Write((Guid) obj); }; writers[typeof(DateTime).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Date); stream.Write((DateTime) obj); }; writers[typeof(TimeSpan).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.TimeSpan); stream.Write((TimeSpan) obj); }; writers[typeof(GrainId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.GrainId); stream.Write((GrainId) obj); }; writers[typeof(ActivationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationId); stream.Write((ActivationId) obj); }; writers[typeof(SiloAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.SiloAddress); stream.Write((SiloAddress) obj); }; writers[typeof(ActivationAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationAddress); stream.Write((ActivationAddress) obj); }; writers[typeof(IPAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpAddress); stream.Write((IPAddress) obj); }; writers[typeof(IPEndPoint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpEndPoint); stream.Write((IPEndPoint) obj); }; writers[typeof(CorrelationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.CorrelationId); stream.Write((CorrelationId) obj); }; } /// <summary> Default constructor. </summary> public BinaryTokenStreamWriter() { ab = new ByteArrayBuilder(); Trace("Starting new binary token stream"); } /// <summary> Return the output stream as a set of <c>ArraySegment</c>. </summary> /// <returns>Data from this stream, converted to output type.</returns> public List<ArraySegment<byte>> ToBytes() { return ab.ToBytes(); } /// <summary> Return the output stream as a <c>byte[]</c>. </summary> /// <returns>Data from this stream, converted to output type.</returns> public byte[] ToByteArray() { return ab.ToByteArray(); } /// <summary> Release any serialization buffers being used by this stream. </summary> public void ReleaseBuffers() { ab.ReleaseBuffers(); } /// <summary> Current write position in the stream. </summary> public int CurrentOffset { get { return ab.Length; } } // Numbers /// <summary> Write an <c>Int32</c> value to the stream. </summary> public void Write(int i) { Trace("--Wrote integer {0}", i); ab.Append(i); } /// <summary> Write an <c>Int16</c> value to the stream. </summary> public void Write(short s) { Trace("--Wrote short {0}", s); ab.Append(s); } /// <summary> Write an <c>Int64</c> value to the stream. </summary> public void Write(long l) { Trace("--Wrote long {0}", l); ab.Append(l); } /// <summary> Write a <c>sbyte</c> value to the stream. </summary> public void Write(sbyte b) { Trace("--Wrote sbyte {0}", b); ab.Append(b); } /// <summary> Write a <c>UInt32</c> value to the stream. </summary> public void Write(uint u) { Trace("--Wrote uint {0}", u); ab.Append(u); } /// <summary> Write a <c>UInt16</c> value to the stream. </summary> public void Write(ushort u) { Trace("--Wrote ushort {0}", u); ab.Append(u); } /// <summary> Write a <c>UInt64</c> value to the stream. </summary> public void Write(ulong u) { Trace("--Wrote ulong {0}", u); ab.Append(u); } /// <summary> Write a <c>byte</c> value to the stream. </summary> public void Write(byte b) { Trace("--Wrote byte {0}", b); ab.Append(b); } /// <summary> Write a <c>float</c> value to the stream. </summary> public void Write(float f) { Trace("--Wrote float {0}", f); ab.Append(f); } /// <summary> Write a <c>double</c> value to the stream. </summary> public void Write(double d) { Trace("--Wrote double {0}", d); ab.Append(d); } /// <summary> Write a <c>decimal</c> value to the stream. </summary> public void Write(decimal d) { Trace("--Wrote decimal {0}", d); ab.Append(Decimal.GetBits(d)); } // Text /// <summary> Write a <c>string</c> value to the stream. </summary> public void Write(string s) { Trace("--Wrote string '{0}'", s); if (null == s) { ab.Append(-1); } else { var bytes = Encoding.UTF8.GetBytes(s); ab.Append(bytes.Length); ab.Append(bytes); } } /// <summary> Write a <c>char</c> value to the stream. </summary> public void Write(char c) { Trace("--Wrote char {0}", c); ab.Append(Convert.ToInt16(c)); } // Other primitives /// <summary> Write a <c>bool</c> value to the stream. </summary> public void Write(bool b) { Trace("--Wrote Boolean {0}", b); ab.Append((byte)(b ? SerializationTokenType.True : SerializationTokenType.False)); } /// <summary> Write a <c>null</c> value to the stream. </summary> public void WriteNull() { Trace("--Wrote null"); ab.Append((byte)SerializationTokenType.Null); } // Types /// <summary> Write a type header for the specified Type to the stream. </summary> /// <param name="t">Type to write header for.</param> /// <param name="expected">Currently expected Type for this stream.</param> public void WriteTypeHeader(Type t, Type expected = null) { Trace("-Writing type header for type {0}, expected {1}", t, expected); if (t == expected) { ab.Append((byte)SerializationTokenType.ExpectedType); return; } ab.Append((byte) SerializationTokenType.SpecifiedType); if (t.IsArray) { ab.Append((byte)(SerializationTokenType.Array + (byte)t.GetArrayRank())); WriteTypeHeader(t.GetElementType()); return; } SerializationTokenType token; if (typeTokens.TryGetValue(t.TypeHandle, out token)) { ab.Append((byte) token); return; } if (t.IsGenericType) { if (typeTokens.TryGetValue(t.GetGenericTypeDefinition().TypeHandle, out token)) { ab.Append((byte)token); foreach (var tp in t.GetGenericArguments()) { WriteTypeHeader(tp); } return; } } ab.Append((byte)SerializationTokenType.NamedType); var typeKey = t.OrleansTypeKey(); ab.Append(typeKey.Length); ab.Append(typeKey); } // Primitive arrays /// <summary> Write a <c>byte[]</c> value to the stream. </summary> public void Write(byte[] b) { Trace("--Wrote byte array of length {0}", b.Length); ab.Append(b); } /// <summary> Write a list of byte array segments to the stream. </summary> public void Write(List<ArraySegment<byte>> bytes) { ab.Append(bytes); } /// <summary> Write the specified number of bytes to the stream, starting at the specified offset in the input <c>byte[]</c>. </summary> /// <param name="b">The input data to be written.</param> /// <param name="offset">The offset into the inout byte[] to start writing bytes from.</param> /// <param name="count">The number of bytes to be written.</param> public void Write(byte[] b, int offset, int count) { if (count <= 0) { return; } Trace("--Wrote byte array of length {0}", count); if ((offset == 0) && (count == b.Length)) { Write(b); } else { var temp = new byte[count]; Buffer.BlockCopy(b, offset, temp, 0, count); Write(temp); } } /// <summary> Write a <c>Int16[]</c> value to the stream. </summary> public void Write(short[] i) { Trace("--Wrote short array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>Int32[]</c> value to the stream. </summary> public void Write(int[] i) { Trace("--Wrote short array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>Int64[]</c> value to the stream. </summary> public void Write(long[] l) { Trace("--Wrote long array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>UInt16[]</c> value to the stream. </summary> public void Write(ushort[] i) { Trace("--Wrote ushort array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>UInt32[]</c> value to the stream. </summary> public void Write(uint[] i) { Trace("--Wrote uint array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>UInt64[]</c> value to the stream. </summary> public void Write(ulong[] l) { Trace("--Wrote ulong array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>sbyte[]</c> value to the stream. </summary> public void Write(sbyte[] l) { Trace("--Wrote sbyte array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>char[]</c> value to the stream. </summary> public void Write(char[] l) { Trace("--Wrote char array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>bool[]</c> value to the stream. </summary> public void Write(bool[] l) { Trace("--Wrote bool array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>double[]</c> value to the stream. </summary> public void Write(double[] d) { Trace("--Wrote double array of length {0}", d.Length); ab.Append(d); } /// <summary> Write a <c>float[]</c> value to the stream. </summary> public void Write(float[] f) { Trace("--Wrote float array of length {0}", f.Length); ab.Append(f); } // Other simple types /// <summary> Write a <c>IPEndPoint</c> value to the stream. </summary> public void Write(IPEndPoint ep) { Write(ep.Address); Write(ep.Port); } /// <summary> Write a <c>IPAddress</c> value to the stream. </summary> public void Write(IPAddress ip) { if (ip.AddressFamily == AddressFamily.InterNetwork) { for (var i = 0; i < 12; i++) { Write((byte)0); } Write(ip.GetAddressBytes()); // IPv4 -- 4 bytes } else { Write(ip.GetAddressBytes()); // IPv6 -- 16 bytes } } /// <summary> Write a <c>SiloAddress</c> value to the stream. </summary> public void Write(SiloAddress addr) { Write(addr.Endpoint); Write(addr.Generation); } /// <summary> Write a <c>TimeSpan</c> value to the stream. </summary> public void Write(TimeSpan ts) { Write(ts.Ticks); } /// <summary> Write a <c>DataTime</c> value to the stream. </summary> public void Write(DateTime dt) { Write(dt.ToBinary()); } /// <summary> Write a <c>Guid</c> value to the stream. </summary> public void Write(Guid id) { Write(id.ToByteArray()); } /// <summary> /// Try to write a simple type (non-array) value to the stream. /// </summary> /// <param name="obj">Input object to be written to the output stream.</param> /// <returns>Returns <c>true</c> if the value was successfully written to the output stream.</returns> public bool TryWriteSimpleObject(object obj) { if (obj == null) { WriteNull(); return true; } Action<BinaryTokenStreamWriter, object> writer; if (writers.TryGetValue(obj.GetType().TypeHandle, out writer)) { writer(this, obj); return true; } return false; } // General containers private StreamWriter trace; [Conditional("TRACE_SERIALIZATION")] private void Trace(string format, params object[] args) { if (trace == null) { var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks); Console.WriteLine("Opening trace file at '{0}'", path); trace = File.CreateText(path); } trace.Write(format, args); trace.WriteLine(" at offset {0}", CurrentOffset); trace.Flush(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using CmsEngine.Core; using CmsEngine.Data.Entities; using Microsoft.EntityFrameworkCore; namespace CmsEngine.Data.Repositories { public class PostRepository : Repository<Post>, IPostRepository { public PostRepository(CmsEngineContext context) : base(context) { } public async Task<IEnumerable<Post>> GetPublishedPostsOrderByDescending(Expression<Func<Post, DateTime>> orderBy) { return await Get(q => q.Status == DocumentStatus.Published).OrderByDescending(orderBy).ToListAsync(); } public async Task<IEnumerable<Post>> GetByStatusOrderByDescending(DocumentStatus documentStatus) { return await Get(q => q.Status == documentStatus).OrderByDescending(o => o.PublishedOn).ToListAsync(); } public async Task<Post> GetBySlug(string slug) { return await Get(q => q.Slug == slug) .Select(p => new Post { VanityId = p.VanityId, Title = p.Title, Slug = p.Slug, Description = p.Description, DocumentContent = p.DocumentContent, HeaderImage = p.HeaderImage, PublishedOn = p.PublishedOn, Categories = p.PostCategories.Select(pc => pc.Category).Select(c => new Category { VanityId = c.VanityId, Name = c.Name, Slug = c.Slug }), ApplicationUsers = p.PostApplicationUsers.Select(pau => pau.ApplicationUser).Select(au => new ApplicationUser { Id = au.Id, Name = au.Name, Surname = au.Surname, Email = au.Email }) }) .SingleOrDefaultAsync(); } public async Task<(IEnumerable<Post> Items, int Count)> GetPublishedByCategoryForPagination(string categorySlug, int page, int articleLimit) { var posts = Get(q => q.Status == DocumentStatus.Published) .Include(p => p.PostCategories) .ThenInclude(pc => pc.Category) .Include(p => p.PostApplicationUsers) .ThenInclude(pau => pau.ApplicationUser) .OrderByDescending(o => o.PublishedOn) .Where(q => q.PostCategories.Any(pc => pc.Category.Slug == categorySlug)); int count = posts.Count(); var items = await posts.Select(p => new Post { VanityId = p.VanityId, Title = p.Title, Slug = p.Slug, Description = p.Description, HeaderImage = p.HeaderImage, PublishedOn = p.PublishedOn, Categories = p.PostCategories.Select(pc => pc.Category).Select(c => new Category { VanityId = c.VanityId, Name = c.Name, Slug = c.Slug }), ApplicationUsers = p.PostApplicationUsers.Select(pau => pau.ApplicationUser).Select(au => new ApplicationUser { Id = au.Id, Name = au.Name, Surname = au.Surname, Email = au.Email }) }).Skip((page - 1) * articleLimit).Take(articleLimit).ToListAsync(); return (items, count); } public async Task<(IEnumerable<Post> Items, int Count)> GetPublishedByTagForPagination(string tagSlug, int page, int articleLimit) { var posts = Get(q => q.Status == DocumentStatus.Published).Include(p => p.PostTags) .ThenInclude(pt => pt.Tag) .Include(p => p.PostCategories) .ThenInclude(pc => pc.Category) .Include(p => p.PostApplicationUsers) .ThenInclude(pau => pau.ApplicationUser) .OrderByDescending(o => o.PublishedOn) .Where(q => q.PostTags.Any(pc => pc.Tag.Slug == tagSlug)); int count = posts.Count(); var items = await posts.Select(p => new Post { VanityId = p.VanityId, Title = p.Title, Slug = p.Slug, Description = p.Description, HeaderImage = p.HeaderImage, PublishedOn = p.PublishedOn, Categories = p.PostCategories.Select(pc => pc.Category).Select(c => new Category { VanityId = c.VanityId, Name = c.Name, Slug = c.Slug }), Tags = p.PostTags.Select(pt => pt.Tag).Select(c => new Tag { VanityId = c.VanityId, Name = c.Name, Slug = c.Slug }), ApplicationUsers = p.PostApplicationUsers.Select(pau => pau.ApplicationUser).Select(au => new ApplicationUser { Id = au.Id, Name = au.Name, Surname = au.Surname, Email = au.Email }) }).Skip((page - 1) * articleLimit).Take(articleLimit).ToListAsync(); return (items, count); } public async Task<(IEnumerable<Post> Items, int Count)> FindPublishedForPaginationOrderByDateDescending(int page, string searchTerm, int articleLimit) { var posts = string.IsNullOrWhiteSpace(searchTerm) ? Get(q => q.Status == DocumentStatus.Published) .Include(p => p.PostApplicationUsers) .ThenInclude(pau => pau.ApplicationUser) : Get(q => (q.Title.Contains(searchTerm) || q.DocumentContent.Contains(searchTerm)) && q.Status == DocumentStatus.Published) .Include(p => p.PostApplicationUsers) .ThenInclude(pau => pau.ApplicationUser); int count = await posts.CountAsync(); var items = await posts.Select(p => new Post { VanityId = p.VanityId, Title = p.Title, Slug = p.Slug, Description = p.Description, HeaderImage = p.HeaderImage, PublishedOn = p.PublishedOn, Categories = p.PostCategories.Select(pc => pc.Category).Select(c => new Category { VanityId = c.VanityId, Name = c.Name, Slug = c.Slug }), ApplicationUsers = p.PostApplicationUsers.Select(pau => pau.ApplicationUser).Select(au => new ApplicationUser { Id = au.Id, Name = au.Name, Surname = au.Surname, Email = au.Email }) }).OrderByDescending(o => o.PublishedOn).Skip((page - 1) * articleLimit).Take(articleLimit).ToListAsync(); return (items, count); } public async Task<(IEnumerable<Post> Items, int Count)> GetPublishedForPagination(int page, int articleLimit) { var posts = Get(q => q.Status == DocumentStatus.Published).Include(p => p.PostApplicationUsers) .ThenInclude(pau => pau.ApplicationUser); int count = posts.Count(); var items = await posts.Select(p => new Post { VanityId = p.VanityId, Title = p.Title, Slug = p.Slug, Description = p.Description, HeaderImage = p.HeaderImage, PublishedOn = p.PublishedOn, Categories = p.PostCategories.Select(pc => pc.Category).Select(c => new Category { VanityId = c.VanityId, Name = c.Name, Slug = c.Slug }), ApplicationUsers = p.PostApplicationUsers.Select(pau => pau.ApplicationUser).Select(au => new ApplicationUser { Id = au.Id, Name = au.Name, Surname = au.Surname, Email = au.Email }) }).OrderByDescending(o => o.PublishedOn).Skip((page - 1) * articleLimit).Take(articleLimit).ToListAsync(); return (items, count); } public async Task<IEnumerable<Post>> GetPublishedLatestPosts(int count) { return await Get(q => q.Status == DocumentStatus.Published) .Include(p => p.PostCategories) .ThenInclude(pc => pc.Category) .Include(p => p.PostApplicationUsers) .ThenInclude(pau => pau.ApplicationUser) .Select(p => new Post { VanityId = p.VanityId, Title = p.Title, Slug = p.Slug, Description = p.Description, HeaderImage = p.HeaderImage, PublishedOn = p.PublishedOn, Categories = p.PostCategories.Select(pc => pc.Category).Select(c => new Category { VanityId = c.VanityId, Name = c.Name, Slug = c.Slug }), ApplicationUsers = p.PostApplicationUsers.Select(pau => pau.ApplicationUser).Select(au => new ApplicationUser { Id = au.Id, Name = au.Name, Surname = au.Surname, Email = au.Email }) }) .OrderByDescending(o => o.PublishedOn).Take(count).ToListAsync(); } public async Task<IEnumerable<Post>> GetForDataTable() { return await Get().Select(p => new Post { VanityId = p.VanityId, Title = p.Title, Description = p.Description, Slug = p.Slug, PublishedOn = p.PublishedOn, Status = p.Status, ApplicationUsers = p.PostApplicationUsers.Select(pau => pau.ApplicationUser).Select(au => new ApplicationUser { Id = au.Id, Name = au.Name, Surname = au.Surname, Email = au.Email }) }).ToListAsync(); } public async Task<Post> GetForSavingById(Guid id) { return await Get(q => q.VanityId == id).Include(p => p.PostCategories) .Include(p => p.PostTags) .Include(p => p.PostApplicationUsers) .SingleOrDefaultAsync(); } public async Task<Post> GetForEditingById(Guid id) { return await Get(q => q.VanityId == id).Include(p => p.PostCategories) .ThenInclude(pc => pc.Category) .Include(p => p.PostTags) .ThenInclude(pt => pt.Tag) .SingleOrDefaultAsync(); } public void RemoveRelatedItems(Post post) { dbContext.RemoveRange(post.PostApplicationUsers); dbContext.RemoveRange(post.PostTags); dbContext.RemoveRange(post.PostCategories); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="CampaignCustomizerServiceClient"/> instances.</summary> public sealed partial class CampaignCustomizerServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CampaignCustomizerServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CampaignCustomizerServiceSettings"/>.</returns> public static CampaignCustomizerServiceSettings GetDefault() => new CampaignCustomizerServiceSettings(); /// <summary> /// Constructs a new <see cref="CampaignCustomizerServiceSettings"/> object with default settings. /// </summary> public CampaignCustomizerServiceSettings() { } private CampaignCustomizerServiceSettings(CampaignCustomizerServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateCampaignCustomizersSettings = existing.MutateCampaignCustomizersSettings; OnCopy(existing); } partial void OnCopy(CampaignCustomizerServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CampaignCustomizerServiceClient.MutateCampaignCustomizers</c> and /// <c>CampaignCustomizerServiceClient.MutateCampaignCustomizersAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateCampaignCustomizersSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CampaignCustomizerServiceSettings"/> object.</returns> public CampaignCustomizerServiceSettings Clone() => new CampaignCustomizerServiceSettings(this); } /// <summary> /// Builder class for <see cref="CampaignCustomizerServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class CampaignCustomizerServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignCustomizerServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CampaignCustomizerServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CampaignCustomizerServiceClientBuilder() { UseJwtAccessWithScopes = CampaignCustomizerServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CampaignCustomizerServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignCustomizerServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CampaignCustomizerServiceClient Build() { CampaignCustomizerServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CampaignCustomizerServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CampaignCustomizerServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CampaignCustomizerServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CampaignCustomizerServiceClient.Create(callInvoker, Settings); } private async stt::Task<CampaignCustomizerServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CampaignCustomizerServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CampaignCustomizerServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CampaignCustomizerServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignCustomizerServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CampaignCustomizerService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage campaign customizer /// </remarks> public abstract partial class CampaignCustomizerServiceClient { /// <summary> /// The default endpoint for the CampaignCustomizerService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default CampaignCustomizerService scopes.</summary> /// <remarks> /// The default CampaignCustomizerService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CampaignCustomizerServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="CampaignCustomizerServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CampaignCustomizerServiceClient"/>.</returns> public static stt::Task<CampaignCustomizerServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CampaignCustomizerServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CampaignCustomizerServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="CampaignCustomizerServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CampaignCustomizerServiceClient"/>.</returns> public static CampaignCustomizerServiceClient Create() => new CampaignCustomizerServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CampaignCustomizerServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="CampaignCustomizerServiceSettings"/>.</param> /// <returns>The created <see cref="CampaignCustomizerServiceClient"/>.</returns> internal static CampaignCustomizerServiceClient Create(grpccore::CallInvoker callInvoker, CampaignCustomizerServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CampaignCustomizerService.CampaignCustomizerServiceClient grpcClient = new CampaignCustomizerService.CampaignCustomizerServiceClient(callInvoker); return new CampaignCustomizerServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC CampaignCustomizerService client</summary> public virtual CampaignCustomizerService.CampaignCustomizerServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes campaign customizers. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCampaignCustomizersResponse MutateCampaignCustomizers(MutateCampaignCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes campaign customizers. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignCustomizersResponse> MutateCampaignCustomizersAsync(MutateCampaignCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes campaign customizers. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignCustomizersResponse> MutateCampaignCustomizersAsync(MutateCampaignCustomizersRequest request, st::CancellationToken cancellationToken) => MutateCampaignCustomizersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates or removes campaign customizers. Operation statuses are /// returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose campaign customizers are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual campaign customizers. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCampaignCustomizersResponse MutateCampaignCustomizers(string customerId, scg::IEnumerable<CampaignCustomizerOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCampaignCustomizers(new MutateCampaignCustomizersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes campaign customizers. Operation statuses are /// returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose campaign customizers are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual campaign customizers. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignCustomizersResponse> MutateCampaignCustomizersAsync(string customerId, scg::IEnumerable<CampaignCustomizerOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCampaignCustomizersAsync(new MutateCampaignCustomizersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes campaign customizers. Operation statuses are /// returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose campaign customizers are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual campaign customizers. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignCustomizersResponse> MutateCampaignCustomizersAsync(string customerId, scg::IEnumerable<CampaignCustomizerOperation> operations, st::CancellationToken cancellationToken) => MutateCampaignCustomizersAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CampaignCustomizerService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage campaign customizer /// </remarks> public sealed partial class CampaignCustomizerServiceClientImpl : CampaignCustomizerServiceClient { private readonly gaxgrpc::ApiCall<MutateCampaignCustomizersRequest, MutateCampaignCustomizersResponse> _callMutateCampaignCustomizers; /// <summary> /// Constructs a client wrapper for the CampaignCustomizerService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="CampaignCustomizerServiceSettings"/> used within this client. /// </param> public CampaignCustomizerServiceClientImpl(CampaignCustomizerService.CampaignCustomizerServiceClient grpcClient, CampaignCustomizerServiceSettings settings) { GrpcClient = grpcClient; CampaignCustomizerServiceSettings effectiveSettings = settings ?? CampaignCustomizerServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateCampaignCustomizers = clientHelper.BuildApiCall<MutateCampaignCustomizersRequest, MutateCampaignCustomizersResponse>(grpcClient.MutateCampaignCustomizersAsync, grpcClient.MutateCampaignCustomizers, effectiveSettings.MutateCampaignCustomizersSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateCampaignCustomizers); Modify_MutateCampaignCustomizersApiCall(ref _callMutateCampaignCustomizers); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateCampaignCustomizersApiCall(ref gaxgrpc::ApiCall<MutateCampaignCustomizersRequest, MutateCampaignCustomizersResponse> call); partial void OnConstruction(CampaignCustomizerService.CampaignCustomizerServiceClient grpcClient, CampaignCustomizerServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CampaignCustomizerService client</summary> public override CampaignCustomizerService.CampaignCustomizerServiceClient GrpcClient { get; } partial void Modify_MutateCampaignCustomizersRequest(ref MutateCampaignCustomizersRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates or removes campaign customizers. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateCampaignCustomizersResponse MutateCampaignCustomizers(MutateCampaignCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCampaignCustomizersRequest(ref request, ref callSettings); return _callMutateCampaignCustomizers.Sync(request, callSettings); } /// <summary> /// Creates, updates or removes campaign customizers. Operation statuses are /// returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateCampaignCustomizersResponse> MutateCampaignCustomizersAsync(MutateCampaignCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCampaignCustomizersRequest(ref request, ref callSettings); return _callMutateCampaignCustomizers.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.Linq; using MonoMac.Foundation; using MonoMac.AppKit; using System.IO; using NLog; using WatchThis.Models; using WatchThis.Controllers; using WatchThis.Utilities; using System.Drawing; namespace WatchThis { public partial class ShowListController : MonoMac.AppKit.NSWindowController, ISlideshowPickerViewer, IPlatformService { private static Logger logger = LogManager.GetCurrentClassLogger(); private SlideshowChooserController _controller; #region Constructors // Called when created from unmanaged code public ShowListController(IntPtr handle) : base(handle) { Initialize(); } // Called when created directly from a XIB file [Export("initWithCoder:")] public ShowListController(NSCoder coder) : base(coder) { Initialize(); } public ShowListController() : base("ShowList") { Initialize(); } void Initialize() { _controller = new SlideshowChooserController(this, this); } #endregion public new ShowList Window { get { return (ShowList)base.Window; } } public override void AwakeFromNib() { base.AwakeFromNib(); Window.RegisterForDraggedTypes(new string[] { NSPasteboard.NSFilenamesType } ); Window.DropAction = (l) => DroppedPaths(l); Window.Delegate = new SlideshowListDelegate(this); savedTableView.DoubleClick += (sender, e) => runSlideshow(); slideDurationStepper.Activated += (sender, e) => StepperDidChange(); NotifyPropertyChangedHelper.SetupPropertyChanged(_controller, PropertyChanged); _controller.FindSavedSlideshows(); // NativeCalls.PreventSleep("WatchThis"); } #region ISlideshowPickerViewer public string ChooseFolder(string message) { var openPanel = new NSOpenPanel { ReleasedWhenClosed = true, Prompt = message, CanChooseDirectories = true, CanChooseFiles = false }; var result = (NsButtonId)openPanel.RunModal(); if (result == NsButtonId.OK) { return openPanel.Url.Path; } return null; } public QuestionResponseType AskQuestion(string caption, string message) { var alert = NSAlert.WithMessage(message, "No", "Yes", "Cancel", ""); var response = (NSAlertType)alert.RunSheetModal(Window); logger.Info("responded {0} to '{1}'", response, message); switch (response) { case NSAlertType.AlternateReturn: return QuestionResponseType.Yes; case NSAlertType.DefaultReturn: return QuestionResponseType.No; default: return QuestionResponseType.Cancel; } } public void ShowMessage(string caption, string message) { logger.Info("ShowMessage: '{0}'; '{1}'", caption, message); NSAlert.WithMessage(message, "Close", "", "", "").RunSheetModal(Window); } public string GetValueFromUser(string caption, string message, string defaultValue) { var alert = NSAlert.WithMessage( message, "OK", "Cancel", "", ""); var textField = new NSTextField(new RectangleF(0, 0, 200, 24)); textField.StringValue = defaultValue; alert.AccessoryView = textField; alert.Window.InitialFirstResponder = textField; var response = (NSAlertType) alert.RunSheetModal(Window); logger.Info("ask value responded {0} to '{1}'", response, message); if (response == NSAlertType.DefaultReturn) { return textField.StringValue; } return null; } public void RunSlideshow(SlideshowModel model) { var controller = new SlideshowWindowController(); controller.Model = model; controller.Window.MakeKeyAndOrderFront(this); } public bool IsEditActive { get { return tabView.Selected.Identifier.Equals(editTabView.Identifier); } } public bool IsSavedActive { get { return tabView.Selected.Identifier.Equals(savedTabView.Identifier); } } public SlideshowModel SelectedSavedModel { get { return _controller.SavedSlideshows[savedTableView.SelectedRow]; } } #endregion #region Cocoa action handlers partial void addFolder(MonoMac.Foundation.NSObject sender) { _controller.AddEditFolder(); } partial void removeFolder(MonoMac.Foundation.NSObject sender) { logger.Info("Remove selected folders: {0}", folderTableView.SelectedRowCount); if (folderTableView.SelectedRow >= 0) { var selectedFolders = new List<FolderModel>(); foreach (var index in folderTableView.SelectedRows.ToArray()) { selectedFolders.Add(_controller.EditedSlideshow.FolderList[(int)index]); } _controller.RemoveEditFolders(selectedFolders); } } partial void runSlideshow(MonoMac.Foundation.NSObject sender) { _controller.RunSlideshow(); } [Export("doubleAction")] public void runSlideshow() { runSlideshow(null); } partial void clearEdit(MonoMac.Foundation.NSObject sender) { _controller.ClearEdit(); } partial void saveSlideshow(MonoMac.Foundation.NSObject sender) { _controller.SaveSlideshow(); } partial void deleteSlideshow(MonoMac.Foundation.NSObject sender) { _controller.DeleteSlideshow(); } partial void editSlideshow(MonoMac.Foundation.NSObject sender) { _controller.EditSlideshow(); } partial void openSlideshow(MonoMac.Foundation.NSObject sender) { _controller.OpenSlideshow(); } void StepperDidChange() { _controller.EditedSlideshow.SlideSeconds = slideDurationStepper.IntValue; } partial void activateEditTab(MonoMac.Foundation.NSObject sender) { tabView.Select(editTabView); } partial void activateSavedTab(MonoMac.Foundation.NSObject sender) { tabView.Select(savedTabView); } public bool WindowShouldClose() { return _controller.CanClose(); } #endregion #if false partial void openSlideshowFolder(MonoMac.Foundation.NSObject sender) { logger.Info("open slideshow folder"); var openPanel = new NSOpenPanel { ReleasedWhenClosed = true, Prompt = "Select folder", CanChooseDirectories = true, CanChooseFiles = false }; var result = (NsButtonId)openPanel.RunModal(); if (result == NsButtonId.OK) { Preferences.Instance.SlideshowwPath = openPanel.Url.Path; RefreshSlideshows(); Preferences.Instance.Save(); } } #endif [Export("numberOfRowsInTableView:")] public int numberOfRowsInTableView(NSTableView tv) { switch (tv.Tag) { case 0: return _controller.EditedSlideshow.FolderList.Count; case 1: return _controller.SavedSlideshows.Count; } logger.Error("Unexpected numberOfRowsinTableView: {0}", tv.Tag); return 0; } [Export("tableView:objectValueForTableColumn:row:")] public string objectValueForTableColumn(NSTableView table, NSTableColumn column, int rowIndex) { switch (table.Tag) { case 0: return _controller.EditedSlideshow.FolderList[rowIndex].Path; case 1: return _controller.SavedSlideshows[rowIndex].Name; } return "<Error!>"; } private void DroppedPaths(IList<string> paths) { _controller.AddEditDroppedFolders(paths); } public void InvokeOnUiThread(Action action) { BeginInvokeOnMainThread(delegate { action(); } ); } private void PropertyChanged(object sender, string propertyName) { var handled = false; if (sender == _controller) { switch (propertyName) { case "SavedSlideshows": savedTableView.ReloadData(); handled = true; break; case "EditedSlideshow": slideDurationStepper.IntValue = (int)_controller.EditedSlideshow.SlideSeconds; slideDuration.IntegerValue = (int)_controller.EditedSlideshow.SlideSeconds; handled = true; break; default: break; } } else if (sender == _controller.EditedSlideshow) { switch (propertyName) { case "SlideSeconds": slideDurationStepper.IntValue = (int)_controller.EditedSlideshow.SlideSeconds; slideDuration.IntegerValue = (int)_controller.EditedSlideshow.SlideSeconds; handled = true; break; default: break; } } else if (sender == _controller.EditedSlideshow.FolderList) { switch (propertyName) { case "collection": folderTableView.ReloadData(); handled = true; break; default: break; } } if (!handled) { logger.Info("Unhandled property updated: {0} [{1}]", propertyName, sender.GetType().Name); } } } class SlideshowListDelegate : NSWindowDelegate { private ShowListController controller; public SlideshowListDelegate(ShowListController controller) { this.controller = controller; } public override bool WindowShouldClose(NSObject sender) { return controller.WindowShouldClose(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; namespace OpenSim.Framework { /// <summary> /// Represent generic cache to store key/value pairs (elements) limited by time, size and count of elements. /// </summary> /// <typeparam name="TKey"> /// The type of keys in the cache. /// </typeparam> /// <typeparam name="TValue"> /// The type of values in the cache. /// </typeparam> /// <remarks> /// <para> /// Cache store limitations: /// </para> /// <list type="table"> /// <listheader> /// <term>Limitation</term> /// <description>Description</description> /// </listheader> /// <item> /// <term>Time</term> /// <description> /// Element that is not accessed through <see cref="TryGetValue"/> or <see cref="Set"/> in last <see cref="ExpirationTime"/> are /// removed from the cache automatically. Depending on implementation of the cache some of elements may stay longer in cache. /// <see cref="IsTimeLimited"/> returns <see langword="true"/>, if cache is limited by time. /// </description> /// </item> /// <item> /// <term>Count</term> /// <description> /// When adding an new element to cache that already have <see cref="MaxCount"/> of elements, cache will remove less recently /// used element(s) from the cache, until element fits to cache. /// <see cref="IsCountLimited"/> returns <see langword="true"/>, if cache is limiting element count. /// </description> /// </item> /// <item> /// <term>Size</term> /// <description> /// <description> /// When adding an new element to cache that already have <see cref="MaxSize"/> of elements, cache will remove less recently /// used element(s) from the cache, until element fits to cache. /// <see cref="IsSizeLimited"/> returns <see langword="true"/>, if cache is limiting total size of elements. /// Normally size is bytes used by element in the cache. But it can be any other suitable unit of measure. /// </description> /// </description> /// </item> /// </list> /// </remarks> public interface ICnmCache<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> { /// <summary> /// Gets current count of elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <remarks> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="MaxCount"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="IsTimeLimited"/> int Count { get; } /// <summary> /// Gets or sets elements expiration time. /// </summary> /// <value> /// Elements expiration time. /// </value> /// <remarks> /// <para> /// When element has been stored in <see cref="ICnmCache{TKey,TValue}"/> longer than <see cref="ExpirationTime"/> /// and it is not accessed through <see cref="TryGetValue"/> method or element's value is /// not replaced by <see cref="Set"/> method, then it is automatically removed from the /// <see cref="ICnmCache{TKey,TValue}"/>. /// </para> /// <para> /// It is possible that <see cref="ICnmCache{TKey,TValue}"/> implementation removes element before it's expiration time, /// because total size or count of elements stored to cache is larger than <see cref="MaxSize"/> or <see cref="MaxCount"/>. /// </para> /// <para> /// It is also possible that element stays in cache longer than <see cref="ExpirationTime"/>. /// </para> /// <para> /// Calling <see cref="PurgeExpired"/> try to remove all elements that are expired. /// </para> /// <para> /// To disable time limit in cache, set <see cref="ExpirationTime"/> to <see cref="DateTime.MaxValue"/>. /// </para> /// </remarks> /// <seealso cref="IsTimeLimited"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="PurgeExpired"/> /// <seealso cref="Count"/> /// <seealso cref="MaxCount"/> /// <seealso cref="MaxSize"/> /// <seealso cref="Size"/> TimeSpan ExpirationTime { get; set; } /// <summary> /// Gets a value indicating whether or not access to the <see cref="ICnmCache{TKey,TValue}"/> is synchronized (thread safe). /// </summary> /// <value> /// <see langword="true"/> if access to the <see cref="ICnmCache{TKey,TValue}"/> is synchronized (thread safe); /// otherwise, <see langword="false"/>. /// </value> /// <remarks> /// <para> /// To get synchronized (thread safe) access to <see cref="ICnmCache{TKey,TValue}"/> object, use /// <see cref="CnmSynchronizedCache{TKey,TValue}.Synchronized"/> in <see cref="CnmSynchronizedCache{TKey,TValue}"/> class /// to retrieve synchronized wrapper for <see cref="ICnmCache{TKey,TValue}"/> object. /// </para> /// </remarks> /// <seealso cref="SyncRoot"/> /// <seealso cref="CnmSynchronizedCache{TKey,TValue}"/> bool IsSynchronized { get; } /// <summary> /// Gets a value indicating whether <see cref="ICnmCache{TKey,TValue}"/> is limiting count of elements. /// </summary> /// <value> /// <see langword="true"/> if the <see cref="ICnmCache{TKey,TValue}"/> count of elements is limited; /// otherwise, <see langword="false"/>. /// </value> /// <remarks> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="Count"/> /// <seealso cref="MaxCount"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="IsTimeLimited"/> bool IsCountLimited { get; } /// <summary> /// Gets a value indicating whether <see cref="ICnmCache{TKey,TValue}"/> is limiting size of elements. /// </summary> /// <value> /// <see langword="true"/> if the <see cref="ICnmCache{TKey,TValue}"/> total size of elements is limited; /// otherwise, <see langword="false"/>. /// </value> /// <remarks> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="MaxElementSize"/> /// <seealso cref="Size"/> /// <seealso cref="MaxSize"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="IsTimeLimited"/> bool IsSizeLimited { get; } /// <summary> /// Gets a value indicating whether elements stored to <see cref="ICnmCache{TKey,TValue}"/> have limited inactivity time. /// </summary> /// <value> /// <see langword="true"/> if the <see cref="ICnmCache{TKey,TValue}"/> has a fixed total size of elements; /// otherwise, <see langword="false"/>. /// </value> /// <remarks> /// If <see cref="ICnmCache{TKey,TValue}"/> have limited inactivity time and element is not accessed through <see cref="Set"/> /// or <see cref="TryGetValue"/> methods in <see cref="ExpirationTime"/> , then element is automatically removed from /// the cache. Depending on implementation of the <see cref="ICnmCache{TKey,TValue}"/>, some of the elements may /// stay longer in cache. /// </remarks> /// <seealso cref="ExpirationTime"/> /// <seealso cref="PurgeExpired"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="IsSizeLimited"/> bool IsTimeLimited { get; } /// <summary> /// Gets or sets maximal allowed count of elements that can be stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <value> /// <see cref="int.MaxValue"/>, if <see cref="ICnmCache{TKey,TValue}"/> is not limited by count of elements; /// otherwise maximal allowed count of elements. /// </value> /// <remarks> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> int MaxCount { get; set; } /// <summary> /// <para>Gets maximal allowed element size.</para> /// </summary> /// <value> /// Maximal allowed element size. /// </value> /// <remarks> /// <para> /// If element's size is larger than <see cref="MaxElementSize"/>, then element is /// not added to the <see cref="ICnmCache{TKey,TValue}"/>. /// </para> /// </remarks> /// <seealso cref="Set"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="Size"/> /// <seealso cref="MaxSize"/> long MaxElementSize { get; } /// <summary> /// Gets or sets maximal allowed total size for elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <value> /// Maximal allowed total size for elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </value> /// <remarks> /// <para> /// Normally size is total bytes used by elements in the cache. But it can be any other suitable unit of measure. /// </para> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">value is less than 0.</exception> /// <seealso cref="MaxElementSize"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="Size"/> long MaxSize { get; set; } /// <summary> /// Gets total size of elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <value> /// Total size of elements stored to <see cref="ICnmCache{TKey,TValue}"/>. /// </value> /// <remarks> /// <para> /// Normally bytes, but can be any suitable unit of measure. /// </para> /// <para> /// Element's size is given when element is added or replaced by <see cref="Set"/> method. /// </para> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements, /// <see cref="ICnmCache{TKey,TValue}"/> will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="MaxElementSize"/> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="MaxSize"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="ExpirationTime"/> long Size { get; } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <value> /// An object that can be used to synchronize access to the <see cref="ICnmCache{TKey,TValue}"/>. /// </value> /// <remarks> /// <para> /// To get synchronized (thread safe) access to <see cref="ICnmCache{TKey,TValue}"/>, use <see cref="CnmSynchronizedCache{TKey,TValue}"/> /// method <see cref="CnmSynchronizedCache{TKey,TValue}.Synchronized"/> to retrieve synchronized wrapper interface to /// <see cref="ICnmCache{TKey,TValue}"/>. /// </para> /// </remarks> /// <seealso cref="IsSynchronized"/> /// <seealso cref="CnmSynchronizedCache{TKey,TValue}"/> object SyncRoot { get; } /// <summary> /// Removes all elements from the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <seealso cref="Set"/> /// <seealso cref="Remove"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="PurgeExpired"/> void Clear(); /// <summary> /// Purge expired elements from the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <remarks> /// <para> /// Element becomes expired when last access time to it has been longer time than <see cref="ExpirationTime"/>. /// </para> /// <para> /// Depending on <see cref="ICnmCache{TKey,TValue}"/> implementation, some of expired elements /// may stay longer than <see cref="ExpirationTime"/> in the cache. /// </para> /// </remarks> /// <seealso cref="IsTimeLimited"/> /// <seealso cref="ExpirationTime"/> /// <seealso cref="Set"/> /// <seealso cref="Remove"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="Clear"/> void PurgeExpired(); /// <summary> /// Removes element associated with <paramref name="key"/> from the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <param name="key"> /// The key that is associated with element to remove from the <see cref="ICnmCache{TKey,TValue}"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/> is <see langword="null"/>. /// </exception> /// <seealso cref="Set"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="Clear"/> /// <seealso cref="PurgeExpired"/> void Remove(TKey key); /// <summary> /// Removes elements that are associated with one of <paramref name="keys"/> from the <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <param name="keys"> /// The keys that are associated with elements to remove from the <see cref="ICnmCache{TKey,TValue}"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="keys"/> is <see langword="null"/>. /// </exception> /// <seealso cref="Set"/> /// <seealso cref="Remove"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="Clear"/> /// <seealso cref="PurgeExpired"/> void RemoveRange(IEnumerable<TKey> keys); /// <summary> /// Add or replace an element with the provided <paramref name="key"/>, <paramref name="value"/> and <paramref name="size"/> to /// <see cref="ICnmCache{TKey,TValue}"/>. /// </summary> /// <param name="key"> /// The object used as the key of the element. Can't be <see langword="null"/> reference. /// </param> /// <param name="value"> /// The object used as the value of the element to add or replace. <see langword="null"/> is allowed. /// </param> /// <param name="size"> /// The element's size. Normally bytes, but can be any suitable unit of measure. /// </param> /// <returns> /// <see langword="true"/> if element has been added successfully to the <see cref="ICnmCache{TKey,TValue}"/>; /// otherwise <see langword="false"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/>is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The element's <paramref name="size"/> is less than 0. /// </exception> /// <remarks> /// <para> /// If element's <paramref name="size"/> is larger than <see cref="MaxElementSize"/>, then element is /// not added to the <see cref="ICnmCache{TKey,TValue}"/>, however - possible older element is /// removed from the <see cref="ICnmCache{TKey,TValue}"/>. /// </para> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting total size of elements, /// <see cref="ICnmCache{TKey,TValue}"/>will remove less recently used elements until it can fit an new element. /// </para> /// <para> /// When adding an new element to <see cref="ICnmCache{TKey,TValue}"/> that is limiting element count, /// <see cref="ICnmCache{TKey,TValue}"/>will remove less recently used elements until it can fit an new element. /// </para> /// </remarks> /// <seealso cref="IsSizeLimited"/> /// <seealso cref="IsCountLimited"/> /// <seealso cref="Remove"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="TryGetValue"/> /// <seealso cref="Clear"/> /// <seealso cref="PurgeExpired"/> bool Set(TKey key, TValue value, long size); /// <summary> /// Gets the <paramref name="value"/> associated with the specified <paramref name="key"/>. /// </summary> /// <returns> /// <see langword="true"/>if the <see cref="ICnmCache{TKey,TValue}"/> contains an element with /// the specified key; otherwise, <see langword="false"/>. /// </returns> /// <param name="key"> /// The key whose <paramref name="value"/> to get. /// </param> /// <param name="value"> /// When this method returns, the value associated with the specified <paramref name="key"/>, /// if the <paramref name="key"/> is found; otherwise, the /// default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/>is <see langword="null"/>. /// </exception> /// <seealso cref="Set"/> /// <seealso cref="Remove"/> /// <seealso cref="RemoveRange"/> /// <seealso cref="Clear"/> /// <seealso cref="PurgeExpired"/> bool TryGetValue(TKey key, out TValue value); } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.Xml; using System.Net; using System.Net.Sockets; using XYNetSocketLib; using System.Text; using System.Data.SqlClient; using System.Threading; using System.Globalization; namespace HWDServer { public class Mein : System.ServiceProcess.ServiceBase { private System.ComponentModel.Container components = null; private XYNetSocketLib.XYNetClient xClient; private XYNetSocketLib.XYNetServer xServer; private string myIP; private bool xStatus; private XmlDocument xmldoc; private StringBuilder sb; private SqlConnection sqlConn; private Socket sokete; public Mein() { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); InitializeComponent(); } static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun; ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Mein() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } private void InitializeComponent() { components = new System.ComponentModel.Container(); this.ServiceName = "HWDServer"; } protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } protected override void OnStart(string[] args) { xStatus = false; IPHostEntry hostInfo = Dns.GetHostByName(Dns.GetHostName()); myIP = hostInfo.AddressList[0].ToString(); xServer = new XYNetServer(myIP, 16001, 2, 10); xServer.SetStringInputHandler(new StringInputHandlerDelegate(Receive)); if (xServer.StartServer() == false) this.Dispose(); else { if (CheckConnection()) { xStatus = true; this.SetMulticast(); System.Threading.Thread th = new Thread(new ThreadStart(ReceiveMess)); th.IsBackground = true; th.Start(); } else this.Dispose(); } } protected override void OnStop() { if(xStatus) xServer.StopServer(); if (this.sqlConn.State == ConnectionState.Open) this.sqlConn.Close(); } private void SetMulticast() { sokete =new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 5000); sokete.Bind(ipep); IPAddress ip=IPAddress.Parse("224.0.0.1"); sokete.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip,IPAddress.Any)); } private void ReceiveMess() { while(xStatus) { byte[] b = new byte[126]; sokete.Receive(b); this.SendMess(System.Text.Encoding.ASCII.GetString(b).Trim(), Environment.MachineName); } } private bool CheckConnection() { this.xmldoc = new XmlDocument(); this.xmldoc.Load(System.Environment.GetFolderPath(System.Environment.SpecialFolder.System) + "\\HWD\\config.xml"); string SQLServer = this.xmldoc.FirstChild["SQLServer"].InnerText; string SQLUser = this.xmldoc.FirstChild["SQLUser"].InnerText; string SQLPwd = Utilities.Decrypt(this.xmldoc.FirstChild["SQLPwd"].InnerText); string SQLCatalog = this.xmldoc.FirstChild["SQLCatalog"].InnerText; string strConn = "user id=" + SQLUser + ";password=" + SQLPwd + ";data source=\"" + SQLServer + "\";persist security info=True;initial catalog=" + SQLCatalog; this.sqlConn = new SqlConnection(strConn); try { this.sqlConn.Open(); return true; } catch { return false; } } private void Receive(string sHost, int nRemotePort, string sData) { if (sData.Substring(0,4) == "POLI") this.UpdatePolicie(sData, sHost); else if (sData.Substring(0,4) == "TICK") this.SaveTickets(sData, sHost); else SendMess(sHost,"I don't understand your command:\n\n\t"+sData+"\nTimespan: " + System.DateTime.Now.ToString()); } private void UpdatePolicie(string data, string host) { string[] mdata = data.Split(','); this.sb = new StringBuilder(); sb.Append("<bads>"); SqlCommand sqlcommand = new SqlCommand("SELECT DISTINCT InternalName FROM HWD_BLOCKEDS WHERE Owner in ('ALL', '" + mdata[1] + "', '" + mdata[2] + "')", this.sqlConn); SqlDataReader sqlread = sqlcommand.ExecuteReader(); while (sqlread.Read()) sb.Append("<i>" + sqlread.GetString(0).Trim() + "</i>"); sb.Append("</bads>"); sqlread.Close(); SendMess(host, this.sb.ToString()); } private void SaveTickets(string data, string host) { try { string[] mdata = data.Split('|'); xmldoc = new XmlDocument(); xmldoc.LoadXml(mdata[3]); foreach(XmlNode xmln in xmldoc.ChildNodes[1].ChildNodes) { string ID = xmln.ChildNodes[0].InnerText; string Kind = xmln.ChildNodes[1].InnerText; string Title = xmln.ChildNodes[2].InnerText; string Desc = xmln.ChildNodes[3].InnerText; string Status = xmln.ChildNodes[4].InnerText; bool insert; if (ID == "0") insert = true; else insert = false; string Showit = xmln.ChildNodes[5].InnerText; this.SaveData(insert, ID, Kind, Title, Desc, Status, mdata[1], mdata[2], Showit); } this.SendTicket(mdata[1], mdata[2]); } catch (Exception er) { EventLog.WriteEntry(er.ToString()); SendMess(host, "Can't save tickets, please try again later."); } } private void SaveData(bool insert, string ID, string Kind, string Title, string Desc, string Status, string Machine, string User, string Showit) { string sqlquery; DateTimeFormatInfo dfi = new CultureInfo("en-US", false).DateTimeFormat; DateTime dt = new DateTime(DateTime.Today.Ticks); if (insert) { sqlquery = "INSERT INTO HWD_TICKETS (Machine, Username, Kind, Title, Description, Status, Showit, CreateDate) values" + "('" + Machine + "', '" + User + "', '" + Kind + "', '" + Title + "', '" + Desc + "', '" + Status + "', " + Showit + ", '" + dt.ToString(dfi) + "')"; } else { if (Status.Trim() == "CLOSED") sqlquery = "UPDATE HWD_TICKETS SET Description = '"+ Desc +"', Status = 'CLOSED', Showit = " + Showit + " WHERE ID = " + ID; else sqlquery = "UPDATE HWD_TICKETS SET Description = '"+ Desc +"', Showit = " + Showit + " WHERE ID = " + ID; } SqlCommand sqlcom = new SqlCommand(sqlquery, this.sqlConn); sqlcom.ExecuteNonQuery(); GC.Collect(); } private void SendTicket(string Machine, string User) { this.sb = new StringBuilder(); this.sb.Append("<?xml version=\"1.0\" standalone=\"yes\"?>"); this.sb.Append("<NewDataSet xmlns=\"Tickets\">"); string sqlquery = "SELECT * FROM HWD_TICKETS WHERE Machine = '" + Machine + "' AND Username = '" + User + "' AND Showit = 1"; SqlCommand sqlcom = new SqlCommand(sqlquery,this.sqlConn); SqlDataReader sqlread = sqlcom.ExecuteReader(); while (sqlread.Read()) { this.sb.Append("\t<ticket>"); this.sb.Append("\t\t<ID>" + sqlread.GetInt32(0).ToString() + "</ID>"); this.sb.Append("\t\t<Kind>" + sqlread.GetString(3) + "</Kind>"); this.sb.Append("\t\t<Title>" + sqlread.GetString(4) + "</Title>"); this.sb.Append("\t\t<Desc>" + sqlread.GetString(5) + "</Desc>"); this.sb.Append("\t\t<Status>" + sqlread.GetString(6) + "</Status>"); this.sb.Append("\t\t<Showit>1</Showit>"); this.sb.Append("\t</ticket>"); } sqlread.Close(); this.sb.Append("</NewDataSet>"); this.SendMess(Machine, this.sb.ToString()); GC.Collect(); } private void SendMess(string host, string mess) { xClient = new XYNetClient(host,16000); if (xClient.Connect()) xClient.SendStringData(mess); else EventLog.WriteEntry(xClient.GetLastException().ToString()); xClient.Reset(); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections; using System.Collections.Generic; using System.Text; using OrderBoxCoreLib; using OrderBoxDomainsLib; using WebsitePanel.EnterpriseServer; using System.IO; using System.Reflection; using System.Diagnostics; namespace WebsitePanel.Ecommerce.EnterpriseServer { public class DirectiRegistrar : SystemPluginBase, IDomainRegistrar { static DirectiRegistrar() { // Resolve OrderBoxCoreLib library AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_OrderBoxCoreLib_AssemblyResolve); // Resolve OrderBoxDomains library AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_OrderBoxDomainsLib_AssemblyResolve); } static System.Reflection.Assembly CurrentDomain_OrderBoxCoreLib_AssemblyResolve(object sender, ResolveEventArgs args) { // if (!args.Name.Contains("OrderBoxCoreLib")) return null; // string assemblyFile = String.Empty; // if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("ProgramFiles(x86)"))) { assemblyFile = Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles(x86)"), "OrderBoxCoreLib\\OrderBoxCoreLib.dll"); } else { assemblyFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "OrderBoxCoreLib\\OrderBoxCoreLib.dll"); } // if (!File.Exists(assemblyFile)) { // EventLog.WriteEntry("WEBSITEPANELES:DIRECTI", "OrderBoxCoreLib assembly could not be found at " + assemblyFile, EventLogEntryType.Information); return null; } // return Assembly.LoadFrom(assemblyFile); } static System.Reflection.Assembly CurrentDomain_OrderBoxDomainsLib_AssemblyResolve(object sender, ResolveEventArgs args) { // if (!args.Name.Contains("OrderBoxDomainsLib")) return null; // string assemblyFile = String.Empty; // if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("ProgramFiles(x86)"))) { assemblyFile = Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles(x86)"), "OrderBoxDomainsLib\\OrderBoxDomainsLib.dll"); } else { assemblyFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "OrderBoxDomainsLib\\OrderBoxDomainsLib.dll"); } // if (!File.Exists(assemblyFile)) { // EventLog.WriteEntry("WEBSITEPANELES:DIRECTI", "OrderBoxDomainsLib assembly could not be found at " + assemblyFile, EventLogEntryType.Information); return null; } // return Assembly.LoadFrom(assemblyFile); } #region Registrar's constants public const string DEMO_SERVICE_URL = "http://api.onlyfordemo.net/anacreon/servlet/APIv3-XML"; public const string LIVE_SERVICE_URL = "http://www.myorderbox.com/anacreon/servlet/APIv3-XML"; public const string DEMO_SECURE_SERVICE_URL = "https://api.onlyfordemo.net/anacreon/servlet/APIv3-XML"; public const string LIVE_SECURE_SERVICE_URL = "https://www.myorderbox.com/anacreon/servlet/APIv3-XML"; public const string SERVICE_LANGUAGE = "en"; public const string RESELLER_ROLE = "reseller"; public const string CONTACT_ID = "contactid"; public const string NO_INVOICE = "NoInvoice"; public const string STATUS = "status"; public const string ENTITY_ID = "entityid"; public const string NO_OF_YEARS = "noofyears"; public const string EXPIRY_DATE = "expirydate"; public const string ENDTIME = "endtime"; public const string EAQID = "eaqid"; public const string ACTION_STATUS_DESC = "actionstatusdesc"; public const string ERROR = "error"; public const string RECORDS_ON_PAGE = "recsonpage"; public const string RECORDS_IN_DB = "recsindb"; #endregion #region Properties public override string[] SecureSettings { get { return new string[] { DirectiSettings.PASSWORD }; } } /// <summary> /// Gets whether plug-in use SSL secure channel /// </summary> public bool SecureChannel { get { return Convert.ToBoolean(PluginSettings[DirectiSettings.SECURE_CHANNEL]); } } /// <summary> /// Gets whether plug-in running in live mode /// </summary> public bool LiveMode { get { return Convert.ToBoolean(PluginSettings[DirectiSettings.LIVE_MODE]); } } /// <summary> /// Gets service username /// </summary> public string Username { get { return PluginSettings[DirectiSettings.USERNAME]; } } /// <summary> /// Gets service password /// </summary> public string Password { get { return PluginSettings[DirectiSettings.PASSWORD]; } } /// <summary> /// Gets service account parent id /// </summary> public int ParentId { get { return Convert.ToInt32(PluginSettings[DirectiSettings.PARENT_ID]); } } /// <summary> /// Gets service url /// </summary> public string ServiceUrl { get { if (LiveMode) { if (SecureChannel) return LIVE_SECURE_SERVICE_URL; // return unsecured service url return LIVE_SERVICE_URL; } if (SecureChannel) return DEMO_SECURE_SERVICE_URL; // return unsecured channel return DEMO_SERVICE_URL; } } public bool SubAccountRequired { get { return true; } } #endregion #region Helper routines private static string[] GetDomainNames(params string[] domains) { List<string> names = new List<string>(); foreach (string domain in domains) { string[] parts = domain.Split('.'); names.Add(parts[0]); } return names.ToArray(); } private static string[] GetTopLevelDomains(params string[] domains) { int length = domains.Length; List<string> tlds = new List<string>(); foreach (string domain in domains) { string[] parts = domain.Split('.'); tlds.Add(parts[1]); } return tlds.ToArray(); } private string GetDialingAreaCode(string phone) { if (String.IsNullOrEmpty(phone)) return "000"; char[] symbols = phone.ToCharArray(); StringBuilder builder = new StringBuilder(); int count = 0, index = 0; while (count < 3 && index < symbols.Length) { if (Char.IsDigit(symbols[index])) { builder.Append(symbols[index]); count++; } index++; } return builder.ToString(); } private string GetDialingNumber(string number) { if (String.IsNullOrEmpty(number)) return "00000000000"; StringBuilder builder = new StringBuilder(); char[] symbols = number.ToCharArray(); int count = 0, index = 0; while (index < symbols.Length) { if (count == 3 && Char.IsDigit(symbols[index])) builder.Append(symbols[index]); else if (Char.IsDigit(symbols[index])) count++; index++; } return builder.ToString(); } private string GetCompanyName(string companyName) { if (String.IsNullOrEmpty(companyName)) return "For Personal Usage Only"; return companyName; } private string GetAddress(string address) { if (String.IsNullOrEmpty(address)) return "-"; return address; } #endregion #region IDomainRegistrar Members private string registrarName; public string RegistrarName { get { return registrarName; } set { registrarName = value; } } public void AssemlyResolverTest() { // OrderBoxCoreLib test Customer customer = new Customer(); // OrderBoxDomainsLib test DomOrder domOrder = new DomOrder(); } public bool CheckSubAccountExists(string emailAddress) { if (String.IsNullOrEmpty(emailAddress)) throw new ArgumentNullException("emailAddress"); // check sub account exists OrderBoxCoreLib.APIKit.Properties.Url = ServiceUrl; // create an instance OrderBoxCoreLib.Customer customer = new OrderBoxCoreLib.Customer(); // search a user by email address Hashtable srchResults = customer.list(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, null, null, emailAddress, null, null, null, null, null, null, null, null, null, 10, 1, null); // check search result if (Convert.ToInt32(srchResults[RECORDS_ON_PAGE]) > 0 && Convert.ToInt32(srchResults[RECORDS_IN_DB]) > 0) return true; // customer account not found return false; } public int GetCustomerAccountId(string emailAddress) { // check email address if (String.IsNullOrEmpty(emailAddress)) throw new ArgumentNullException("emailAddress"); // create a customer OrderBoxCoreLib.APIKit.Properties.Url = ServiceUrl; // init customer api OrderBoxCoreLib.Customer customer = new OrderBoxCoreLib.Customer(); // check does the user is already Directi customer int customerId = customer.getCustomerId(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, emailAddress); // throws an exception if (customerId <= 0) throw new Exception("Couldn't find customer with the specified email: " + emailAddress); // return customerId; } public int GetDefaultContactId(int customerId) { // Default Contact Section OrderBoxDomainsLib.APIKit.Properties.Url = ServiceUrl; // init contact api OrderBoxDomainsLib.DomContact contact = new OrderBoxDomainsLib.DomContact(); // check whether a contact is already exists Hashtable ctHash = contact.listNames(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, customerId); // throws an exception if (!ctHash.ContainsKey("1")) throw new Exception("Couldn't find default contact for the specified account"); // gets contact info Hashtable infoHash = (Hashtable)ctHash["1"]; // return result return Convert.ToInt32(infoHash[CONTACT_ID]); } public int CreateCustomerAccount(ContractAccount accountInfo) { // setup url OrderBoxCoreLib.APIKit.Properties.Url = ServiceUrl; // init customer api OrderBoxCoreLib.Customer customer = new OrderBoxCoreLib.Customer(); // create customer account if it doesn't exist int customerId = customer.addCustomer(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, accountInfo[ContractAccount.EMAIL], accountInfo[ContractAccount.PASSWORD], String.Concat(accountInfo[ContractAccount.FIRST_NAME], " ", accountInfo[ContractAccount.LAST_NAME]), GetCompanyName(accountInfo[ContractAccount.COMPANY_NAME]), GetAddress(accountInfo[ContractAccount.ADDRESS]), GetAddress(null), GetAddress(null), accountInfo[ContractAccount.CITY], accountInfo[ContractAccount.STATE], accountInfo[ContractAccount.COUNTRY], accountInfo[ContractAccount.ZIP], GetDialingAreaCode(accountInfo[ContractAccount.PHONE_NUMBER]), GetDialingNumber(accountInfo[ContractAccount.PHONE_NUMBER]), String.Empty, String.Empty, GetDialingAreaCode(accountInfo[ContractAccount.FAX_NUMBER]), GetDialingNumber(accountInfo[ContractAccount.FAX_NUMBER]), "en"); // setup url OrderBoxDomainsLib.APIKit.Properties.Url = ServiceUrl; // init contact api OrderBoxDomainsLib.DomContact contact = new OrderBoxDomainsLib.DomContact(); // create default contact int defaultContactId = contact.addDefaultContact(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, customerId); // return result return customerId; } public int AddCustomerContact(int customerId, string contactType, ContractAccount accountInfo, Hashtable extraInfo) { // setup url OrderBoxCoreLib.APIKit.Properties.Url = ServiceUrl; // init customer api OrderBoxDomainsLib.DomContact contact = new DomContact(); // create customer account if it doesn't exist int contactId = contact.addContact(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, String.Concat(accountInfo[ContractAccount.FIRST_NAME], " ", accountInfo[ContractAccount.LAST_NAME]), accountInfo[ContractAccount.COMPANY_NAME], accountInfo[ContractAccount.EMAIL], GetAddress(accountInfo[ContractAccount.ADDRESS]), GetAddress(null), GetAddress(null), accountInfo[ContractAccount.CITY], accountInfo[ContractAccount.STATE], accountInfo[ContractAccount.COUNTRY], accountInfo[ContractAccount.ZIP], GetDialingAreaCode(accountInfo[ContractAccount.PHONE_NUMBER]), GetDialingNumber(accountInfo[ContractAccount.PHONE_NUMBER]), GetDialingAreaCode(accountInfo[ContractAccount.FAX_NUMBER]), GetDialingNumber(accountInfo[ContractAccount.FAX_NUMBER]), customerId, contactType, extraInfo); // return contactId; } public bool IsContactValidForProduct(int contactId, string productKey) { // setup service url OrderBoxDomainsLib.APIKit.Properties.Url = ServiceUrl; // OrderBoxDomainsLib.DomContactExt contactExt = new DomContactExt(); // Hashtable result = contactExt.isValidRegistrantContact(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, new int[] {contactId}, new string[] { productKey }); // Hashtable product = (Hashtable)result[productKey]; // if (Convert.ToString(product[contactId.ToString()]) == "true") return true; // return false; } public DomainStatus CheckDomain(string domain) { // check domain not empty if (String.IsNullOrEmpty(domain)) throw new ArgumentNullException("domain"); // format values string[] domains = GetDomainNames(domain); string[] tlds = GetTopLevelDomains(domain); // setup service url OrderBoxDomainsLib.APIKit.Properties.Url = ServiceUrl; // init domain order api OrderBoxDomainsLib.DomOrder domOrder = new OrderBoxDomainsLib.DomOrder(); // check domain availability Hashtable directiResult = domOrder.checkAvailabilityMultiple( Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, domains, tlds, false ); // get result by domain Hashtable bunch = (Hashtable)directiResult[domain]; // check result status if (String.Compare((String)bunch[STATUS], "available", true) == 0) return DomainStatus.NotFound; // return result return DomainStatus.Registered; } public void RegisterDomain(DomainNameSvc domainSvc, ContractAccount accountInfo, string[] nameServers) { int customerId = 0; // 1. check customer exists if (CheckSubAccountExists(accountInfo[ContractAccount.EMAIL])) customerId = GetCustomerAccountId(accountInfo[ContractAccount.EMAIL]); else customerId = CreateCustomerAccount(accountInfo); // obtain default contact id int contactId = GetDefaultContactId(customerId); // check for demo mode if so then set demo-nameservers. if (!LiveMode) nameServers = new string[] { "ns1.onlyfordemo.net", "ns2.onlyfordemo.net" }; // fill parameters hashtable Hashtable domainHash = new Hashtable(); // copy domain name domainHash[domainSvc.Fqdn] = domainSvc.PeriodLength.ToString(); // setup service url OrderBoxDomainsLib.APIKit.Properties.Url = ServiceUrl; // init domain order api OrderBoxDomainsLib.DomOrder domOrder = new OrderBoxDomainsLib.DomOrder(); // int validateAttempts = 0; VALIDATE_REGISTRATION: // validate params Hashtable valResult = domOrder.validateDomainRegistrationParams(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, domainHash, new ArrayList(nameServers), contactId, contactId, contactId, contactId, customerId, NO_INVOICE); // get domain name hashtable valResult = (Hashtable)valResult[domainSvc.Fqdn]; // check validation status if ((String)valResult[STATUS] == "error") { // try to update extended contact fields and re-validate params if (validateAttempts == 0 && domainSvc.Fqdn.EndsWith(".us")) { validateAttempts++; // OrderBoxDomainsLib.DomContactExt contactExt = new DomContactExt(); // fill extension hash Hashtable exthash = new Hashtable(); Hashtable domus = new Hashtable(); domus["nexusCategory"] = domainSvc["NexusCategory"]; domus["applicationPurpose"] = domainSvc["ApplicationPurpose"]; exthash["domus"] = domus; // set default contact extensions bool succeed = contactExt.setContactDetails(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, contactId, exthash, "domus"); // check result if (succeed) goto VALIDATE_REGISTRATION; } // throw new Exception((String)valResult[ERROR]); } // register domain Hashtable orderResult = domOrder.addWithoutValidation(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, domainHash, new ArrayList(nameServers), contactId, contactId, contactId, contactId, customerId, NO_INVOICE); // switch to the nested data bunch orderResult = (Hashtable)orderResult[domainSvc.Fqdn]; // check returned status switch ((String)orderResult[STATUS]) { case "error": // error throw new Exception(Convert.ToString(orderResult[ERROR])); case "Failed": // error throw new Exception(Convert.ToString(orderResult[ACTION_STATUS_DESC])); case "Success": // success case "InvoicePaid": // success // we are success so copy order number domainSvc[EAQID] = Convert.ToString(orderResult[EAQID]); domainSvc[ENTITY_ID] = Convert.ToString(orderResult[ENTITY_ID]); break; } } public void RenewDomain(DomainNameSvc domainSvc, ContractAccount accountInfo, string[] nameServers) { int customerId = GetCustomerAccountId(accountInfo[ContractAccount.EMAIL]); // setup service url OrderBoxDomainsLib.APIKit.Properties.Url = ServiceUrl; // init domain order api OrderBoxDomainsLib.DomOrder domOrder = new OrderBoxDomainsLib.DomOrder(); // Get all domain name registration details Hashtable domainDetails = domOrder.getDetailsByDomain(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, domainSvc.Fqdn, new ArrayList { "All" }); // fill parameters hashtable Hashtable domainHash = new Hashtable { { domainSvc.Fqdn, new Hashtable { {ENTITY_ID, domainDetails[ENTITY_ID]}, {NO_OF_YEARS, domainSvc.PeriodLength.ToString()}, {EXPIRY_DATE, domainDetails[ENDTIME]} } } }; // Send renewal request to the registrar Hashtable orderResult = domOrder.renewDomain(Username, Password, RESELLER_ROLE, SERVICE_LANGUAGE, ParentId, domainHash, NO_INVOICE); // switch to the nested data bunch of the result received orderResult = (Hashtable)orderResult[domainSvc.Fqdn]; // check returned status switch ((String)orderResult[STATUS]) { case "error": // error throw new Exception(Convert.ToString(orderResult[ERROR])); case "Failed": // error throw new Exception(Convert.ToString(orderResult[ACTION_STATUS_DESC])); case "Success": // success case "InvoicePaid": // success // we are success so copy order number domainSvc[EAQID] = Convert.ToString(orderResult[EAQID]); domainSvc[ENTITY_ID] = Convert.ToString(orderResult[ENTITY_ID]); break; } } public TransferDomainResult TransferDomain(CommandParams args, DomainContacts contacts) { throw new NotSupportedException(); } #endregion } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using ArcGIS.Core.CIM; using ArcGIS.Core.Geometry; using ArcGIS.Desktop.Core; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; namespace Symbology { internal class SymbologyPaneViewModel : DockPane { private const string _dockPaneID = "Symbology_SymbologyPane"; private static readonly object LockStyleItems = new object(); protected SymbologyPaneViewModel() { BindingOperations.EnableCollectionSynchronization(MyCustomStyleItems, LockStyleItems); lock (LockStyleItems) { MyCustomStyleItems.Clear(); } SelectedGeometry = SymbolGeometries.FirstOrDefault(); CreateStyleProjectItem(); } /// <summary> /// Show the DockPane. /// </summary> internal static void Show() { DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID); if (pane == null) return; pane.Activate(); } #region Public properties /// <summary> /// Text shown near the top of the DockPane. /// </summary> private string _heading = "Custom Symbols"; public string Heading { get { return _heading; } set { SetProperty(ref _heading, value, () => Heading); } } private ObservableCollection<CustomSymbolStyleItem> _myCustomStyleItems = new ObservableCollection<CustomSymbolStyleItem>(); /// <summary> /// Collection of Symbol Items. /// </summary> public ObservableCollection<CustomSymbolStyleItem> MyCustomStyleItems { get { return _myCustomStyleItems; } set { SetProperty(ref _myCustomStyleItems, value, () => MyCustomStyleItems); } } private ObservableCollection<string> _symbolGeometries = new ObservableCollection<string> { "Point", "Line", "Polygon", "Mesh" }; /// <summary> /// Collection of available symbol geometries /// </summary> public ObservableCollection<string> SymbolGeometries { get { return _symbolGeometries; } set { SetProperty(ref _symbolGeometries, value, () => SymbolGeometries); } } private string _selectedGeometry; /// <summary> /// The selected symbol geometry type /// </summary> public string SelectedGeometry { get { //Initialize(); This crashes return _selectedGeometry; } set { SetProperty(ref _selectedGeometry, value, () => SelectedGeometry); Initialize(); } } public StyleItemType styleItemType = StyleItemType.PointSymbol; #endregion #region private methods and properties private IDictionary<GeometryType, string> _geometriesDictionary = new Dictionary<GeometryType, string> { { GeometryType.Point, "Point" }, { GeometryType.Polyline, "Line"}, {GeometryType.Polygon, "Polygon" }, {GeometryType.Multipatch, "Mesh" } }; private static string _styleFilePath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\AppData\Roaming\ESRI\ArcGISPro\MyCustomSymbols.stylx"; private static StyleProjectItem _styleProjectItem = null; /// <summary> /// Initialize the list box with the symbol items /// </summary> /// <returns></returns> private async Task Initialize() { lock (LockStyleItems) { MyCustomStyleItems.Clear(); } var myGeometryTypeKey = _geometriesDictionary.FirstOrDefault(x => x.Value == SelectedGeometry).Key; var symbolsMapping = await GetSymbolDataMapping(myGeometryTypeKey); foreach (var symbol in symbolsMapping) { var symbolStyleItem = await CreateSymbolStyleItem(symbol.Key, symbol.Value); //define the symbol lock (LockStyleItems) { MyCustomStyleItems.Add(new CustomSymbolStyleItem(symbolStyleItem, symbol.Value)); } //Add styleItem to StyleProject Item bool styleItemExists = await DoesStyleItemExists(symbolStyleItem.ItemType, symbol.Value); if ((styleItemExists == false) && (_styleProjectItem != null)) await AddStyleItemToStyle(_styleProjectItem, symbolStyleItem); } } /// <summary> /// Creates a SymbolStyleItem from a symbol /// </summary> /// <param name="symbol"></param> /// <param name="data"></param> /// <returns></returns> private Task<SymbolStyleItem> CreateSymbolStyleItem(CIMSymbol symbol, string data) { var symbolStyleItem = QueuedTask.Run(() => { SymbolStyleItem sItem = null; try { sItem = new SymbolStyleItem() //define the symbol { Symbol = symbol, ItemType = styleItemType, //Category = "Shapes", Name = data, Key = data, Tags = data, }; } catch (Exception ) { } return sItem; }); return symbolStyleItem; } /// <summary> /// Gets all the symbols available for a particular geometry /// </summary> /// <param name="geometry"></param> /// <returns></returns> private async Task<Dictionary<CIMSymbol, string>> GetSymbolDataMapping(GeometryType geometry) { var myDictionary = new Dictionary<CIMSymbol, string>(); switch (geometry) { case GeometryType.Point: styleItemType = StyleItemType.PointSymbol; myDictionary = await MyPointSymbology.GetAllPointSymbolsAsync(); break; case GeometryType.Polygon: styleItemType = StyleItemType.PolygonSymbol; myDictionary = await MyPolygonSymbology.GetAllPolygonSymbolsAsync(); break; case GeometryType.Polyline: styleItemType = StyleItemType.LineSymbol; myDictionary = await MyLineSymbology.GetAllLineSymbolsAsync(); break; case GeometryType.Multipatch: styleItemType = StyleItemType.MeshSymbol; myDictionary = await MeshSymbology.GetAll3DSymbolsAsync(); break; } return myDictionary; } /// <summary> /// Create a styleProject item. /// </summary> /// <returns></returns> private static async Task CreateStyleProjectItem() { if (_styleProjectItem?.PhysicalPath == null) { await QueuedTask.Run(() => { if (File.Exists(_styleFilePath)) //check if the file is on disc. Add it to the project if it is. Project.Current.AddStyle(_styleFilePath); else //else create the style item { if (_styleProjectItem != null) Project.Current.RemoveStyle(_styleProjectItem.Name); //remove style from project Project.Current.CreateStyle($@"{_styleFilePath}"); } }); var styleItemsContainer = Project.Current.GetItems<StyleProjectItem>(); //gets all Style Project Items in the current project _styleProjectItem = styleItemsContainer.FirstOrDefault(s => s.Name.Contains("MyCustomSymbols")); } } /// <summary> /// Adds a styleitem to a style. /// </summary> /// <param name="styleProjectItem"></param> /// <param name="cimSymbolStyleItem"></param> /// <returns></returns> private Task AddStyleItemToStyle(StyleProjectItem styleProjectItem, SymbolStyleItem cimSymbolStyleItem) { return QueuedTask.Run(() => { if (styleProjectItem == null || cimSymbolStyleItem == null) { return; } try { styleProjectItem.AddItem(cimSymbolStyleItem); } catch(Exception ex) { } }); } public Task<bool> DoesStyleItemExists(StyleItemType styleItemType, string key) { var styleItemExists = QueuedTask.Run(() => { bool styleItem = false; //Search for a specific point symbol in style SymbolStyleItem item = (SymbolStyleItem)_styleProjectItem?.LookupItem(styleItemType, key); if (item == null) styleItem = false; else styleItem = true; return styleItem; }); return styleItemExists; } #endregion } /// <summary> /// Button implementation to show the DockPane. /// </summary> internal class SymbologyPane_ShowButton : Button { protected override void OnClick() { SymbologyPaneViewModel.Show(); } } }
// 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. //#define XSLT2 using System.Diagnostics; using System.Text; using System.Xml.XPath; using System.Collections.Generic; namespace System.Xml.Xsl.Xslt { using StringConcat = System.Xml.Xsl.Runtime.StringConcat; // a) Forward only, one pass. // b) You should call MoveToFirstChildren on nonempty element node. (or may be skip) internal class XsltInput : IErrorHelper { #if DEBUG const int InitRecordsSize = 1; #else private const int InitRecordsSize = 1 + 21; #endif private XmlReader _reader; private IXmlLineInfo _readerLineInfo; private bool _topLevelReader; private CompilerScopeManager<VarPar> _scopeManager; private KeywordsTable _atoms; private Compiler _compiler; private bool _reatomize; // Cached properties. MoveTo* functions set them. private XmlNodeType _nodeType; private Record[] _records = new Record[InitRecordsSize]; private int _currentRecord; private bool _isEmptyElement; private int _lastTextNode; private int _numAttributes; private ContextInfo _ctxInfo; private bool _attributesRead; public XsltInput(XmlReader reader, Compiler compiler, KeywordsTable atoms) { Debug.Assert(reader != null); Debug.Assert(atoms != null); EnsureExpandEntities(reader); IXmlLineInfo xmlLineInfo = reader as IXmlLineInfo; _atoms = atoms; _reader = reader; _reatomize = reader.NameTable != atoms.NameTable; _readerLineInfo = (xmlLineInfo != null && xmlLineInfo.HasLineInfo()) ? xmlLineInfo : null; _topLevelReader = reader.ReadState == ReadState.Initial; _scopeManager = new CompilerScopeManager<VarPar>(atoms); _compiler = compiler; _nodeType = XmlNodeType.Document; } // Cached properties public XmlNodeType NodeType { get { return _nodeType == XmlNodeType.Element && 0 < _currentRecord ? XmlNodeType.Attribute : _nodeType; } } public string LocalName { get { return _records[_currentRecord].localName; } } public string NamespaceUri { get { return _records[_currentRecord].nsUri; } } public string Prefix { get { return _records[_currentRecord].prefix; } } public string Value { get { return _records[_currentRecord].value; } } public string BaseUri { get { return _records[_currentRecord].baseUri; } } public string QualifiedName { get { return _records[_currentRecord].QualifiedName; } } public bool IsEmptyElement { get { return _isEmptyElement; } } public string Uri { get { return _records[_currentRecord].baseUri; } } public Location Start { get { return _records[_currentRecord].start; } } public Location End { get { return _records[_currentRecord].end; } } private static void EnsureExpandEntities(XmlReader reader) { XmlTextReader tr = reader as XmlTextReader; if (tr != null && tr.EntityHandling != EntityHandling.ExpandEntities) { Debug.Assert(tr.Settings == null, "XmlReader created with XmlReader.Create should always expand entities."); tr.EntityHandling = EntityHandling.ExpandEntities; } } private void ExtendRecordBuffer(int position) { if (_records.Length <= position) { int newSize = _records.Length * 2; if (newSize <= position) { newSize = position + 1; } Record[] tmp = new Record[newSize]; Array.Copy(_records, tmp, _records.Length); _records = tmp; } } public bool FindStylesheetElement() { if (!_topLevelReader) { if (_reader.ReadState != ReadState.Interactive) { return false; } } // The stylesheet may be an embedded stylesheet. If this is the case the reader will be in Interactive state and should be // positioned on xsl:stylesheet element (or any preceding whitespace) but there also can be namespaces defined on one // of the ancestor nodes. These namespace definitions have to be copied to the xsl:stylesheet element scope. Otherwise it // will not be possible to resolve them later and loading the stylesheet will end up with throwing an exception. IDictionary<string, string> namespacesInScope = null; if (_reader.ReadState == ReadState.Interactive) { // This may be an embedded stylesheet - store namespaces in scope IXmlNamespaceResolver nsResolver = _reader as IXmlNamespaceResolver; if (nsResolver != null) { namespacesInScope = nsResolver.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); } } while (MoveToNextSibling() && _nodeType == XmlNodeType.Whitespace) ; // An Element node was reached. Potentially this is xsl:stylesheet instruction. if (_nodeType == XmlNodeType.Element) { // If namespacesInScope is not null then the stylesheet being read is an embedded stylesheet that can have namespaces // defined outside of xsl:stylesheet instruction. In this case the namespace definitions collected above have to be added // to the element scope. if (namespacesInScope != null) { foreach (KeyValuePair<string, string> prefixNamespacePair in namespacesInScope) { // The namespace could be redefined on the element we just read. If this is the case scopeManager already has // namespace definition for this prefix and the old definition must not be added to the scope. if (_scopeManager.LookupNamespace(prefixNamespacePair.Key) == null) { string nsAtomizedValue = _atoms.NameTable.Add(prefixNamespacePair.Value); _scopeManager.AddNsDeclaration(prefixNamespacePair.Key, nsAtomizedValue); _ctxInfo.AddNamespace(prefixNamespacePair.Key, nsAtomizedValue); } } } // return true to indicate that we reached XmlNodeType.Element node - potentially xsl:stylesheet element. return true; } // return false to indicate that we did not reach XmlNodeType.Element node so it is not a valid stylesheet. return false; } public void Finish() { _scopeManager.CheckEmpty(); if (_topLevelReader) { while (_reader.ReadState == ReadState.Interactive) { _reader.Skip(); } } } private void FillupRecord(ref Record rec) { rec.localName = _reader.LocalName; rec.nsUri = _reader.NamespaceURI; rec.prefix = _reader.Prefix; rec.value = _reader.Value; rec.baseUri = _reader.BaseURI; if (_reatomize) { rec.localName = _atoms.NameTable.Add(rec.localName); rec.nsUri = _atoms.NameTable.Add(rec.nsUri); rec.prefix = _atoms.NameTable.Add(rec.prefix); } if (_readerLineInfo != null) { rec.start = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - PositionAdjustment(_reader.NodeType)); } } private void SetRecordEnd(ref Record rec) { if (_readerLineInfo != null) { rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - PositionAdjustment(_reader.NodeType)); if (_reader.BaseURI != rec.baseUri || rec.end.LessOrEqual(rec.start)) { rec.end = new Location(rec.start.Line, int.MaxValue); } } } private void FillupTextRecord(ref Record rec) { Debug.Assert( _reader.NodeType == XmlNodeType.Whitespace || _reader.NodeType == XmlNodeType.SignificantWhitespace || _reader.NodeType == XmlNodeType.Text || _reader.NodeType == XmlNodeType.CDATA ); rec.localName = string.Empty; rec.nsUri = string.Empty; rec.prefix = string.Empty; rec.value = _reader.Value; rec.baseUri = _reader.BaseURI; if (_readerLineInfo != null) { bool isCDATA = (_reader.NodeType == XmlNodeType.CDATA); int line = _readerLineInfo.LineNumber; int pos = _readerLineInfo.LinePosition; rec.start = new Location(line, pos - (isCDATA ? 9 : 0)); char prevChar = ' '; foreach (char ch in rec.value) { switch (ch) { case '\n': if (prevChar != '\r') { goto case '\r'; } break; case '\r': line++; pos = 1; break; default: pos++; break; } prevChar = ch; } rec.end = new Location(line, pos + (isCDATA ? 3 : 0)); } } private void FillupCharacterEntityRecord(ref Record rec) { Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference); string local = _reader.LocalName; Debug.Assert(local[0] == '#' || local == "lt" || local == "gt" || local == "quot" || local == "apos"); rec.localName = string.Empty; rec.nsUri = string.Empty; rec.prefix = string.Empty; rec.baseUri = _reader.BaseURI; if (_readerLineInfo != null) { rec.start = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition - 1); } _reader.ResolveEntity(); _reader.Read(); Debug.Assert(_reader.NodeType == XmlNodeType.Text || _reader.NodeType == XmlNodeType.Whitespace || _reader.NodeType == XmlNodeType.SignificantWhitespace); rec.value = _reader.Value; _reader.Read(); Debug.Assert(_reader.NodeType == XmlNodeType.EndEntity); if (_readerLineInfo != null) { int line = _readerLineInfo.LineNumber; int pos = _readerLineInfo.LinePosition; rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + 1); } } private StringConcat _strConcat = new StringConcat(); // returns false if attribute is actualy namespace private bool ReadAttribute(ref Record rec) { Debug.Assert(_reader.NodeType == XmlNodeType.Attribute, "reader.NodeType == XmlNodeType.Attribute"); FillupRecord(ref rec); if (Ref.Equal(rec.prefix, _atoms.Xmlns)) { // xmlns:foo="NS_FOO" string atomizedValue = _atoms.NameTable.Add(_reader.Value); if (!Ref.Equal(rec.localName, _atoms.Xml)) { _scopeManager.AddNsDeclaration(rec.localName, atomizedValue); _ctxInfo.AddNamespace(rec.localName, atomizedValue); } return false; } else if (rec.prefix.Length == 0 && Ref.Equal(rec.localName, _atoms.Xmlns)) { // xmlns="NS_FOO" string atomizedValue = _atoms.NameTable.Add(_reader.Value); _scopeManager.AddNsDeclaration(string.Empty, atomizedValue); _ctxInfo.AddNamespace(string.Empty, atomizedValue); return false; } /* Read Attribute Value */ { if (!_reader.ReadAttributeValue()) { // XmlTextReader never returns false from first call to ReadAttributeValue() rec.value = string.Empty; SetRecordEnd(ref rec); return true; } if (_readerLineInfo != null) { int correction = (_reader.NodeType == XmlNodeType.EntityReference) ? -2 : -1; rec.valueStart = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + correction); if (_reader.BaseURI != rec.baseUri || rec.valueStart.LessOrEqual(rec.start)) { int nameLength = ((rec.prefix.Length != 0) ? rec.prefix.Length + 1 : 0) + rec.localName.Length; rec.end = new Location(rec.start.Line, rec.start.Pos + nameLength + 1); } } string lastText = string.Empty; _strConcat.Clear(); do { switch (_reader.NodeType) { case XmlNodeType.EntityReference: _reader.ResolveEntity(); break; case XmlNodeType.EndEntity: break; default: Debug.Assert(_reader.NodeType == XmlNodeType.Text, "Unexpected node type inside attribute value"); lastText = _reader.Value; _strConcat.Concat(lastText); break; } } while (_reader.ReadAttributeValue()); rec.value = _strConcat.GetResult(); if (_readerLineInfo != null) { Debug.Assert(_reader.NodeType != XmlNodeType.EntityReference); int correction = ((_reader.NodeType == XmlNodeType.EndEntity) ? 1 : lastText.Length) + 1; rec.end = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition + correction); if (_reader.BaseURI != rec.baseUri || rec.end.LessOrEqual(rec.valueStart)) { rec.end = new Location(rec.start.Line, int.MaxValue); } } } return true; } // -------------------- public bool MoveToFirstChild() { Debug.Assert(_nodeType == XmlNodeType.Element, "To call MoveToFirstChild() XsltInut should be positioned on an Element."); if (IsEmptyElement) { return false; } return ReadNextSibling(); } public bool MoveToNextSibling() { Debug.Assert(_nodeType != XmlNodeType.Element || IsEmptyElement, "On non-empty elements we should call MoveToFirstChild()"); if (_nodeType == XmlNodeType.Element || _nodeType == XmlNodeType.EndElement) { _scopeManager.ExitScope(); } return ReadNextSibling(); } public void SkipNode() { if (_nodeType == XmlNodeType.Element && MoveToFirstChild()) { do { SkipNode(); } while (MoveToNextSibling()); } } private int ReadTextNodes() { bool textPreserveWS = _reader.XmlSpace == XmlSpace.Preserve; bool textIsWhite = true; int curTextNode = 0; do { switch (_reader.NodeType) { case XmlNodeType.Text: // XLinq reports WS nodes as Text so we need to analyze them here case XmlNodeType.CDATA: if (textIsWhite && !XmlCharType.Instance.IsOnlyWhitespace(_reader.Value)) { textIsWhite = false; } goto case XmlNodeType.SignificantWhitespace; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: ExtendRecordBuffer(curTextNode); FillupTextRecord(ref _records[curTextNode]); _reader.Read(); curTextNode++; break; case XmlNodeType.EntityReference: string local = _reader.LocalName; if (local.Length > 0 && ( local[0] == '#' || local == "lt" || local == "gt" || local == "quot" || local == "apos" )) { // Special treatment for character and built-in entities ExtendRecordBuffer(curTextNode); FillupCharacterEntityRecord(ref _records[curTextNode]); if (textIsWhite && !XmlCharType.Instance.IsOnlyWhitespace(_records[curTextNode].value)) { textIsWhite = false; } curTextNode++; } else { _reader.ResolveEntity(); _reader.Read(); } break; case XmlNodeType.EndEntity: _reader.Read(); break; default: _nodeType = ( !textIsWhite ? XmlNodeType.Text : textPreserveWS ? XmlNodeType.SignificantWhitespace : /*default: */ XmlNodeType.Whitespace ); return curTextNode; } } while (true); } private bool ReadNextSibling() { if (_currentRecord < _lastTextNode) { Debug.Assert(_nodeType == XmlNodeType.Text || _nodeType == XmlNodeType.Whitespace || _nodeType == XmlNodeType.SignificantWhitespace); _currentRecord++; if (_currentRecord == _lastTextNode) { _lastTextNode = 0; // we are done with text nodes. Reset this counter } return true; } _currentRecord = 0; while (!_reader.EOF) { switch (_reader.NodeType) { case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.EntityReference: int numTextNodes = ReadTextNodes(); if (numTextNodes == 0) { // Most likely this was Entity that starts from non-text node continue; } _lastTextNode = numTextNodes - 1; return true; case XmlNodeType.Element: _scopeManager.EnterScope(); _numAttributes = ReadElement(); return true; case XmlNodeType.EndElement: _nodeType = XmlNodeType.EndElement; _isEmptyElement = false; FillupRecord(ref _records[0]); _reader.Read(); SetRecordEnd(ref _records[0]); return false; default: _reader.Read(); break; } } return false; } private int ReadElement() { Debug.Assert(_reader.NodeType == XmlNodeType.Element); _attributesRead = false; FillupRecord(ref _records[0]); _nodeType = XmlNodeType.Element; _isEmptyElement = _reader.IsEmptyElement; _ctxInfo = new ContextInfo(this); int record = 1; if (_reader.MoveToFirstAttribute()) { do { ExtendRecordBuffer(record); if (ReadAttribute(ref _records[record])) { record++; } } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); } _reader.Read(); SetRecordEnd(ref _records[0]); _ctxInfo.lineInfo = BuildLineInfo(); _attributes = null; return record - 1; } public void MoveToElement() { Debug.Assert(_nodeType == XmlNodeType.Element, "For MoveToElement() we should be positioned on Element or Attribute"); _currentRecord = 0; } private bool MoveToAttributeBase(int attNum) { Debug.Assert(_nodeType == XmlNodeType.Element, "For MoveToLiteralAttribute() we should be positioned on Element or Attribute"); if (0 < attNum && attNum <= _numAttributes) { _currentRecord = attNum; return true; } else { _currentRecord = 0; return false; } } public bool MoveToLiteralAttribute(int attNum) { Debug.Assert(_nodeType == XmlNodeType.Element, "For MoveToLiteralAttribute() we should be positioned on Element or Attribute"); if (0 < attNum && attNum <= _numAttributes) { _currentRecord = attNum; return true; } else { _currentRecord = 0; return false; } } public bool MoveToXsltAttribute(int attNum, string attName) { Debug.Assert(_attributes != null && _attributes[attNum].name == attName, "Attribute numbering error."); _currentRecord = _xsltAttributeNumber[attNum]; return _currentRecord != 0; } public bool IsRequiredAttribute(int attNum) { return (_attributes[attNum].flags & (_compiler.Version == 2 ? XsltLoader.V2Req : XsltLoader.V1Req)) != 0; } public bool AttributeExists(int attNum, string attName) { Debug.Assert(_attributes != null && _attributes[attNum].name == attName, "Attribute numbering error."); return _xsltAttributeNumber[attNum] != 0; } public struct DelayedQName { private string _prefix; private string _localName; public DelayedQName(ref Record rec) { _prefix = rec.prefix; _localName = rec.localName; } public static implicit operator string (DelayedQName qn) { return qn._prefix.Length == 0 ? qn._localName : (qn._prefix + ':' + qn._localName); } } public DelayedQName ElementName { get { Debug.Assert(_nodeType == XmlNodeType.Element || _nodeType == XmlNodeType.EndElement, "Input is positioned on element or attribute"); return new DelayedQName(ref _records[0]); } } // -------------------- Keywords testing -------------------- public bool IsNs(string ns) { return Ref.Equal(ns, NamespaceUri); } public bool IsKeyword(string kwd) { return Ref.Equal(kwd, LocalName); } public bool IsXsltNamespace() { return IsNs(_atoms.UriXsl); } public bool IsNullNamespace() { return IsNs(string.Empty); } public bool IsXsltAttribute(string kwd) { return IsKeyword(kwd) && IsNullNamespace(); } public bool IsXsltKeyword(string kwd) { return IsKeyword(kwd) && IsXsltNamespace(); } // -------------------- Scope Management -------------------- // See private class InputScopeManager bellow. // InputScopeManager handles some flags and values with respect of scope level where they as defined. // To parse XSLT style sheet we need the folloing values: // BackwardCompatibility -- this flag is set when compiler.version==2 && xsl:version<2. // ForwardCompatibility -- this flag is set when compiler.version==2 && xsl:version>1 or compiler.version==1 && xsl:version!=1 // CanHaveApplyImports -- we allow xsl:apply-templates instruction to apear in any template with match!=null, but not inside xsl:for-each // so it can't be inside global variable and has initial value = false // ExtentionNamespace -- is defined by extension-element-prefixes attribute on LRE or xsl:stylesheet public bool CanHaveApplyImports { get { return _scopeManager.CanHaveApplyImports; } set { _scopeManager.CanHaveApplyImports = value; } } public bool IsExtensionNamespace(string uri) { Debug.Assert(_nodeType != XmlNodeType.Element || _attributesRead, "Should first read attributes"); return _scopeManager.IsExNamespace(uri); } public bool ForwardCompatibility { get { Debug.Assert(_nodeType != XmlNodeType.Element || _attributesRead, "Should first read attributes"); return _scopeManager.ForwardCompatibility; } } public bool BackwardCompatibility { get { Debug.Assert(_nodeType != XmlNodeType.Element || _attributesRead, "Should first read attributes"); return _scopeManager.BackwardCompatibility; } } public XslVersion XslVersion { get { return _scopeManager.ForwardCompatibility ? XslVersion.ForwardsCompatible : XslVersion.Current; } } private void SetVersion(int attVersion) { MoveToLiteralAttribute(attVersion); Debug.Assert(IsKeyword(_atoms.Version)); double version = XPathConvert.StringToDouble(Value); if (double.IsNaN(version)) { ReportError(/*[XT0110]*/SR.Xslt_InvalidAttrValue, _atoms.Version, Value); #if XSLT2 version = 2.0; #else version = 1.0; #endif } SetVersion(version); } private void SetVersion(double version) { if (_compiler.Version == 0) { #if XSLT2 compiler.Version = version < 2.0 ? 1 : 2; #else _compiler.Version = 1; #endif } if (_compiler.Version == 1) { _scopeManager.BackwardCompatibility = false; _scopeManager.ForwardCompatibility = (version != 1.0); } else { _scopeManager.BackwardCompatibility = version < 2; _scopeManager.ForwardCompatibility = 2 < version; } } // --------------- GetAtributes(...) ------------------------- // All Xslt Instructions allows fixed set of attributes in null-ns, no in XSLT-ns and any in other ns. // In ForwardCompatibility mode we should ignore any of this problems. // We not use these functions for parseing LiteralResultElement and xsl:stylesheet public struct XsltAttribute { public string name; public int flags; public XsltAttribute(string name, int flags) { this.name = name; this.flags = flags; } } private XsltAttribute[] _attributes = null; // Mapping of attribute names as they ordered in 'attributes' array // to there's numbers in actual stylesheet as they ordered in 'records' array private int[] _xsltAttributeNumber = new int[21]; static private XsltAttribute[] s_noAttributes = new XsltAttribute[] { }; public ContextInfo GetAttributes() { return GetAttributes(s_noAttributes); } public ContextInfo GetAttributes(XsltAttribute[] attributes) { Debug.Assert(NodeType == XmlNodeType.Element); Debug.Assert(attributes.Length <= _xsltAttributeNumber.Length); _attributes = attributes; // temp hack to fix value? = new AttValue(records[values[?]].value); _records[0].value = null; // Standard Attributes: int attExtension = 0; int attExclude = 0; int attNamespace = 0; int attCollation = 0; int attUseWhen = 0; bool isXslOutput = IsXsltNamespace() && IsKeyword(_atoms.Output); bool SS = IsXsltNamespace() && (IsKeyword(_atoms.Stylesheet) || IsKeyword(_atoms.Transform)); bool V2 = _compiler.Version == 2; for (int i = 0; i < attributes.Length; i++) { _xsltAttributeNumber[i] = 0; } _compiler.EnterForwardsCompatible(); if (SS || V2 && !isXslOutput) { for (int i = 1; MoveToAttributeBase(i); i++) { if (IsNullNamespace() && IsKeyword(_atoms.Version)) { SetVersion(i); break; } } } if (_compiler.Version == 0) { Debug.Assert(SS, "First we parse xsl:stylesheet element"); #if XSLT2 SetVersion(2.0); #else SetVersion(1.0); #endif } V2 = _compiler.Version == 2; int OptOrReq = V2 ? XsltLoader.V2Opt | XsltLoader.V2Req : XsltLoader.V1Opt | XsltLoader.V1Req; for (int attNum = 1; MoveToAttributeBase(attNum); attNum++) { if (IsNullNamespace()) { string localName = LocalName; int kwd; for (kwd = 0; kwd < attributes.Length; kwd++) { if (Ref.Equal(localName, attributes[kwd].name) && (attributes[kwd].flags & OptOrReq) != 0) { _xsltAttributeNumber[kwd] = attNum; break; } } if (kwd == attributes.Length) { if (Ref.Equal(localName, _atoms.ExcludeResultPrefixes) && (SS || V2)) { attExclude = attNum; } else if (Ref.Equal(localName, _atoms.ExtensionElementPrefixes) && (SS || V2)) { attExtension = attNum; } else if (Ref.Equal(localName, _atoms.XPathDefaultNamespace) && (V2)) { attNamespace = attNum; } else if (Ref.Equal(localName, _atoms.DefaultCollation) && (V2)) { attCollation = attNum; } else if (Ref.Equal(localName, _atoms.UseWhen) && (V2)) { attUseWhen = attNum; } else { ReportError(/*[XT0090]*/SR.Xslt_InvalidAttribute, QualifiedName, _records[0].QualifiedName); } } } else if (IsXsltNamespace()) { ReportError(/*[XT0090]*/SR.Xslt_InvalidAttribute, QualifiedName, _records[0].QualifiedName); } else { // Ignore the attribute. // An element from the XSLT namespace may have any attribute not from the XSLT namespace, // provided that the expanded-name of the attribute has a non-null namespace URI. // For example, it may be 'xml:space'. } } _attributesRead = true; // Ignore invalid attributes if forwards-compatible behavior is enabled. Note that invalid // attributes may encounter before ForwardCompatibility flag is set to true. For example, // <xsl:stylesheet unknown="foo" version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"/> _compiler.ExitForwardsCompatible(ForwardCompatibility); InsertExNamespaces(attExtension, _ctxInfo, /*extensions:*/ true); InsertExNamespaces(attExclude, _ctxInfo, /*extensions:*/ false); SetXPathDefaultNamespace(attNamespace); SetDefaultCollation(attCollation); if (attUseWhen != 0) { ReportNYI(_atoms.UseWhen); } MoveToElement(); // Report missing mandatory attributes for (int i = 0; i < attributes.Length; i++) { if (_xsltAttributeNumber[i] == 0) { int flags = attributes[i].flags; if ( _compiler.Version == 2 && (flags & XsltLoader.V2Req) != 0 || _compiler.Version == 1 && (flags & XsltLoader.V1Req) != 0 && (!ForwardCompatibility || (flags & XsltLoader.V2Req) != 0) ) { ReportError(/*[XT_001]*/SR.Xslt_MissingAttribute, attributes[i].name); } } } return _ctxInfo; } public ContextInfo GetLiteralAttributes(bool asStylesheet) { Debug.Assert(NodeType == XmlNodeType.Element); // Standard Attributes: int attVersion = 0; int attExtension = 0; int attExclude = 0; int attNamespace = 0; int attCollation = 0; int attUseWhen = 0; for (int i = 1; MoveToLiteralAttribute(i); i++) { if (IsXsltNamespace()) { string localName = LocalName; if (Ref.Equal(localName, _atoms.Version)) { attVersion = i; } else if (Ref.Equal(localName, _atoms.ExtensionElementPrefixes)) { attExtension = i; } else if (Ref.Equal(localName, _atoms.ExcludeResultPrefixes)) { attExclude = i; } else if (Ref.Equal(localName, _atoms.XPathDefaultNamespace)) { attNamespace = i; } else if (Ref.Equal(localName, _atoms.DefaultCollation)) { attCollation = i; } else if (Ref.Equal(localName, _atoms.UseWhen)) { attUseWhen = i; } } } _attributesRead = true; this.MoveToElement(); if (attVersion != 0) { // Enable forwards-compatible behavior if version attribute is not "1.0" SetVersion(attVersion); } else { if (asStylesheet) { ReportError(Ref.Equal(NamespaceUri, _atoms.UriWdXsl) && Ref.Equal(LocalName, _atoms.Stylesheet) ? /*[XT_025]*/SR.Xslt_WdXslNamespace : /*[XT0150]*/SR.Xslt_WrongStylesheetElement ); #if XSLT2 SetVersion(2.0); #else SetVersion(1.0); #endif } } // Parse xsl:extension-element-prefixes attribute (now that forwards-compatible mode is known) InsertExNamespaces(attExtension, _ctxInfo, /*extensions:*/true); if (!IsExtensionNamespace(_records[0].nsUri)) { // Parse other attributes (now that it's known this is a literal result element) if (_compiler.Version == 2) { SetXPathDefaultNamespace(attNamespace); SetDefaultCollation(attCollation); if (attUseWhen != 0) { ReportNYI(_atoms.UseWhen); } } InsertExNamespaces(attExclude, _ctxInfo, /*extensions:*/false); } return _ctxInfo; } // Get just the 'version' attribute of an unknown XSLT instruction. All other attributes // are ignored since we do not want to report an error on each of them. public void GetVersionAttribute() { Debug.Assert(NodeType == XmlNodeType.Element && IsXsltNamespace()); bool V2 = _compiler.Version == 2; if (V2) { for (int i = 1; MoveToAttributeBase(i); i++) { if (IsNullNamespace() && IsKeyword(_atoms.Version)) { SetVersion(i); break; } } } _attributesRead = true; } private void InsertExNamespaces(int attExPrefixes, ContextInfo ctxInfo, bool extensions) { // List of Extension namespaces are maintaned by XsltInput's ScopeManager and is used by IsExtensionNamespace() in XsltLoader.LoadLiteralResultElement() // Both Extension and Exclusion namespaces will not be coppied by LiteralResultElement. Logic of copping namespaces are in QilGenerator.CompileLiteralElement(). // At this time we will have different scope manager and need preserve all required information from load time to compile time. // Each XslNode contains list of NsDecls (nsList) wich stores prefix+namespaces pairs for each namespace decls as well as exclusion namespaces. // In addition it also contains Exclusion namespace. They are represented as (null+namespace). Special case is Exlusion "#all" represented as (null+null). //and Exclusion namespace if (MoveToLiteralAttribute(attExPrefixes)) { Debug.Assert(extensions ? IsKeyword(_atoms.ExtensionElementPrefixes) : IsKeyword(_atoms.ExcludeResultPrefixes)); string value = Value; if (value.Length != 0) { if (!extensions && _compiler.Version != 1 && value == "#all") { ctxInfo.nsList = new NsDecl(ctxInfo.nsList, /*prefix:*/null, /*nsUri:*/null); // null, null means Exlusion #all } else { _compiler.EnterForwardsCompatible(); string[] list = XmlConvert.SplitString(value); for (int idx = 0; idx < list.Length; idx++) { if (list[idx] == "#default") { list[idx] = this.LookupXmlNamespace(string.Empty); if (list[idx].Length == 0 && _compiler.Version != 1 && !BackwardCompatibility) { ReportError(/*[XTSE0809]*/SR.Xslt_ExcludeDefault); } } else { list[idx] = this.LookupXmlNamespace(list[idx]); } } if (!_compiler.ExitForwardsCompatible(this.ForwardCompatibility)) { // There were errors in the list, ignore the whole list return; } for (int idx = 0; idx < list.Length; idx++) { if (list[idx] != null) { ctxInfo.nsList = new NsDecl(ctxInfo.nsList, /*prefix:*/null, list[idx]); // null means that this Exlusion NS if (extensions) { _scopeManager.AddExNamespace(list[idx]); // At Load time we need to know Extencion namespaces to ignore such literal elements. } } } } } } } private void SetXPathDefaultNamespace(int attNamespace) { if (MoveToLiteralAttribute(attNamespace)) { Debug.Assert(IsKeyword(_atoms.XPathDefaultNamespace)); if (Value.Length != 0) { ReportNYI(_atoms.XPathDefaultNamespace); } } } private void SetDefaultCollation(int attCollation) { if (MoveToLiteralAttribute(attCollation)) { Debug.Assert(IsKeyword(_atoms.DefaultCollation)); string[] list = XmlConvert.SplitString(Value); int col; for (col = 0; col < list.Length; col++) { if (System.Xml.Xsl.Runtime.XmlCollation.Create(list[col], /*throw:*/false) != null) { break; } } if (col == list.Length) { ReportErrorFC(/*[XTSE0125]*/SR.Xslt_CollationSyntax); } else { if (list[col] != XmlReservedNs.NsCollCodePoint) { ReportNYI(_atoms.DefaultCollation); } } } } // ----------------------- ISourceLineInfo ----------------------- private static int PositionAdjustment(XmlNodeType nt) { switch (nt) { case XmlNodeType.Element: return 1; // "<" case XmlNodeType.CDATA: return 9; // "<![CDATA[" case XmlNodeType.ProcessingInstruction: return 2; // "<?" case XmlNodeType.Comment: return 4; // "<!--" case XmlNodeType.EndElement: return 2; // "</" case XmlNodeType.EntityReference: return 1; // "&" default: return 0; } } public ISourceLineInfo BuildLineInfo() { return new SourceLineInfo(Uri, Start, End); } public ISourceLineInfo BuildNameLineInfo() { if (_readerLineInfo == null) { return BuildLineInfo(); } // LocalName is checked against null since it is used to calculate QualifiedName used in turn to // calculate end position. // LocalName (and other cached properties) can be null only if nothing has been read from the reader. // This happens for instance when a reader which has already been closed or a reader positioned // on the very last node of the document is passed to the ctor. if (LocalName == null) { // Fill up the current record to set all the properties used below. FillupRecord(ref _records[_currentRecord]); } Location start = Start; int line = start.Line; int pos = start.Pos + PositionAdjustment(NodeType); return new SourceLineInfo(Uri, new Location(line, pos), new Location(line, pos + QualifiedName.Length)); } public ISourceLineInfo BuildReaderLineInfo() { Location loc; if (_readerLineInfo != null) loc = new Location(_readerLineInfo.LineNumber, _readerLineInfo.LinePosition); else loc = new Location(0, 0); return new SourceLineInfo(_reader.BaseURI, loc, loc); } // Resolve prefix, return null and report an error if not found public string LookupXmlNamespace(string prefix) { Debug.Assert(prefix != null); string nsUri = _scopeManager.LookupNamespace(prefix); if (nsUri != null) { Debug.Assert(Ref.Equal(_atoms.NameTable.Get(nsUri), nsUri), "Namespaces must be atomized"); return nsUri; } if (prefix.Length == 0) { return string.Empty; } ReportError(/*[XT0280]*/SR.Xslt_InvalidPrefix, prefix); return null; } // ---------------------- Error Handling ---------------------- public void ReportError(string res, params string[] args) { _compiler.ReportError(BuildNameLineInfo(), res, args); } public void ReportErrorFC(string res, params string[] args) { if (!ForwardCompatibility) { _compiler.ReportError(BuildNameLineInfo(), res, args); } } public void ReportWarning(string res, params string[] args) { _compiler.ReportWarning(BuildNameLineInfo(), res, args); } private void ReportNYI(string arg) { ReportErrorFC(SR.Xslt_NotYetImplemented, arg); } // -------------------------------- ContextInfo ------------------------------------ internal class ContextInfo { public NsDecl nsList; public ISourceLineInfo lineInfo; // Line info for whole start tag public ISourceLineInfo elemNameLi; // Line info for element name public ISourceLineInfo endTagLi; // Line info for end tag or '/>' private int _elemNameLength; // Create ContextInfo based on existing line info (used during AST rewriting) internal ContextInfo(ISourceLineInfo lineinfo) { this.elemNameLi = lineinfo; this.endTagLi = lineinfo; this.lineInfo = lineinfo; } public ContextInfo(XsltInput input) { _elemNameLength = input.QualifiedName.Length; } public void AddNamespace(string prefix, string nsUri) { nsList = new NsDecl(nsList, prefix, nsUri); } public void SaveExtendedLineInfo(XsltInput input) { if (lineInfo.Start.Line == 0) { elemNameLi = endTagLi = null; return; } elemNameLi = new SourceLineInfo( lineInfo.Uri, lineInfo.Start.Line, lineInfo.Start.Pos + 1, // "<" lineInfo.Start.Line, lineInfo.Start.Pos + 1 + _elemNameLength ); if (!input.IsEmptyElement) { Debug.Assert(input.NodeType == XmlNodeType.EndElement); endTagLi = input.BuildLineInfo(); } else { Debug.Assert(input.NodeType == XmlNodeType.Element || input.NodeType == XmlNodeType.Attribute); endTagLi = new EmptyElementEndTag(lineInfo); } } // We need this wrapper class because elementTagLi is not yet calculated internal class EmptyElementEndTag : ISourceLineInfo { private ISourceLineInfo _elementTagLi; public EmptyElementEndTag(ISourceLineInfo elementTagLi) { _elementTagLi = elementTagLi; } public string Uri { get { return _elementTagLi.Uri; } } public bool IsNoSource { get { return _elementTagLi.IsNoSource; } } public Location Start { get { return new Location(_elementTagLi.End.Line, _elementTagLi.End.Pos - 2); } } public Location End { get { return _elementTagLi.End; } } } } internal struct Record { public string localName; public string nsUri; public string prefix; public string value; public string baseUri; public Location start; public Location valueStart; public Location end; public string QualifiedName { get { return prefix.Length == 0 ? localName : string.Concat(prefix, ":", localName); } } } } }
namespace Nancy { using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Nancy.ModelBinding; using Nancy.Responses.Negotiation; using Nancy.Routing; using Nancy.Session; using Nancy.Validation; using Nancy.ViewEngines; /// <summary> /// Basic class containing the functionality for defining routes and actions in Nancy. /// </summary> public abstract class NancyModule : INancyModule, IHideObjectMembers { private readonly List<Route> routes; /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> protected NancyModule() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> /// <param name="modulePath">A <see cref="string"/> containing the root relative path that all paths in the module will be a subset of.</param> protected NancyModule(string modulePath) { this.After = new AfterPipeline(); this.Before = new BeforePipeline(); this.OnError = new ErrorPipeline(); this.ModulePath = modulePath; this.routes = new List<Route>(); } /// <summary> /// Non-model specific data for rendering in the response /// </summary> public dynamic ViewBag { get { return this.Context == null ? null : this.Context.ViewBag; } } /// <summary> /// Dynamic access to text resources. /// </summary> public dynamic Text { get { return this.Context.Text; } } /// <summary> /// Declares a route for DELETE requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Delete(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null) { this.Delete<object>(path, action, condition, name); } /// <summary> /// Declares a route for DELETE requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Delete<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null) { this.Delete(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name); } /// <summary> /// Declares a route for DELETE requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Delete(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Delete<object>(path, action, condition, name); } /// <summary> /// Declares a route for DELETE requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Delete<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Delete(path, (args, ct) => action((DynamicDictionary)args), condition, name); } /// <summary> /// Declares a route for DELETE requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Delete(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Delete<object>(path, action, condition, name); } /// <summary> /// Declares a route for DELETE requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Delete<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.AddRoute("DELETE", path, action, condition, name); } /// <summary> /// Declares a route for GET requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Get(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null) { this.Get<object>(path, action, condition, name); } /// <summary> /// Declares a route for GET requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Get<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null) { this.Get(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name); } /// <summary> /// Declares a route for GET requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Get(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Get<object>(path, action, condition, name); } /// <summary> /// Declares a route for GET requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Get<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Get(path, (args, ct) => action((DynamicDictionary)args), condition, name); } /// <summary> /// Declares a route for GET requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Get(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Get<object>(path, action, condition, name); } /// <summary> /// Declares a route for GET requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Get<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.AddRoute("GET", path, action, condition, name); } /// <summary> /// Declares a route for HEAD requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Head(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null) { this.Head<object>(path, action, condition, name); } /// <summary> /// Declares a route for HEAD requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Head<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null) { this.Head(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name); } /// <summary> /// Declares a route for HEAD requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Head(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Head<object>(path, action, condition, name); } /// <summary> /// Declares a route for HEAD requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Head<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Head(path, (args, ct) => action((DynamicDictionary)args), condition, name); } /// <summary> /// Declares a route for HEAD requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Head(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Head<object>(path, action, condition, name); } /// <summary> /// Declares a route for HEAD requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Head<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.AddRoute("HEAD", path, action, condition, name); } /// <summary> /// Declares a route for OPTIONS requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Options(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null) { this.Options<object>(path, action, condition, name); } /// <summary> /// Declares a route for OPTIONS requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Options<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null) { this.Options(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name); } /// <summary> /// Declares a route for OPTIONS requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Options(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Options<object>(path, action, condition, name); } /// <summary> /// Declares a route for OPTIONS requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Options<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Options(path, (args, ct) => action((DynamicDictionary)args), condition, name); } /// <summary> /// Declares a route for OPTIONS requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Options(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Options<object>(path, action, condition, name); } /// <summary> /// Declares a route for OPTIONS requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Options<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.AddRoute("OPTIONS", path, action, condition, name); } /// <summary> /// Declares a route for PATCH requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Patch(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null) { this.Patch<object>(path, action, condition, name); } /// <summary> /// Declares a route for PATCH requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Patch<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null) { this.Patch(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name); } /// <summary> /// Declares a route for PATCH requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Patch(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Patch<object>(path, action, condition, name); } /// <summary> /// Declares a route for PATCH requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Patch<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Patch(path, (args, ct) => action((DynamicDictionary)args), condition, name); } /// <summary> /// Declares a route for PATCH requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Patch(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Patch<object>(path, action, condition, name); } /// <summary> /// Declares a route for PATCH requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Patch<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.AddRoute("PATCH", path, action, condition, name); } /// <summary> /// Declares a route for POST requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Post(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null) { this.Post<object>(path, action, condition, name); } /// <summary> /// Declares a route for POST requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Post<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null) { this.Post(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name); } /// <summary> /// Declares a route for POST requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Post(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Post<object>(path, action, condition, name); } /// <summary> /// Declares a route for POST requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Post<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Post(path, (args, ct) => action((DynamicDictionary)args), condition, name); } /// <summary> /// Declares a route for POST requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Post(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Post<object>(path, action, condition, name); } /// <summary> /// Declares a route for POST requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Post<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.AddRoute("POST", path, action, condition, name); } /// <summary> /// Declares a route for PUT requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Put(string path, Func<dynamic, object> action, Func<NancyContext, bool> condition = null, string name = null) { this.Put<object>(path, action, condition, name); } /// <summary> /// Declares a route for PUT requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Put<T>(string path, Func<dynamic, T> action, Func<NancyContext, bool> condition = null, string name = null) { this.Put(path, args => Task.FromResult(action((DynamicDictionary)args)), condition, name); } /// <summary> /// Declares a route for PUT requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Put(string path, Func<dynamic, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Put<object>(path, action, condition, name); } /// <summary> /// Declares a route for PUT requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Put<T>(string path, Func<dynamic, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Put(path, (args, ct) => action((DynamicDictionary)args), condition, name); } /// <summary> /// Declares a route for PUT requests. /// </summary> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Put(string path, Func<dynamic, CancellationToken, Task<object>> action, Func<NancyContext, bool> condition = null, string name = null) { this.Put<object>(path, action, condition, name); } /// <summary> /// Declares a route for PUT requests. /// </summary> /// <typeparam name="T">The return type of the <paramref name="action"/></typeparam> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="name">Name of the route</param> /// <param name="condition">A condition to determine if the route can be hit</param> public virtual void Put<T>(string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition = null, string name = null) { this.AddRoute("PUT", path, action, condition, name); } /// <summary> /// Get the root path of the routes in the current module. /// </summary> /// <value> /// A <see cref="T:System.String" /> containing the root path of the module or <see langword="null" /> /// if no root path should be used.</value><remarks>All routes will be relative to this root path. /// </remarks> public string ModulePath { get; protected set; } /// <summary> /// Gets all declared routes by the module. /// </summary> /// <value>A <see cref="IEnumerable{T}"/> instance, containing all <see cref="Route"/> instances declared by the module.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public virtual IEnumerable<Route> Routes { get { return this.routes.AsReadOnly(); } } /// <summary> /// Gets the current session. /// </summary> public ISession Session { get { return this.Request.Session; } } /// <summary> /// Renders a view from inside a route handler. /// </summary> /// <value>A <see cref="ViewRenderer"/> instance that is used to determine which view that should be rendered.</value> public ViewRenderer View { get { return new ViewRenderer(this); } } /// <summary> /// Used to negotiate the content returned based on Accepts header. /// </summary> /// <value>A <see cref="Negotiator"/> instance that is used to negotiate the content returned.</value> public Negotiator Negotiate { get { return new Negotiator(this.Context); } } /// <summary> /// Gets or sets the validator locator. /// </summary> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IModelValidatorLocator ValidatorLocator { get; set; } /// <summary> /// Gets or sets an <see cref="Request"/> instance that represents the current request. /// </summary> /// <value>An <see cref="Request"/> instance.</value> public virtual Request Request { get { return this.Context.Request; } set { this.Context.Request = value; } } /// <summary> /// The extension point for accessing the view engines in Nancy. /// </summary><value>An <see cref="IViewFactory" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IViewFactory ViewFactory { get; set; } /// <summary><para> /// The post-request hook /// </para><para> /// The post-request hook is called after the response is created by the route execution. /// It can be used to rewrite the response or add/remove items from the context. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public AfterPipeline After { get; set; } /// <summary> /// <para> /// The pre-request hook /// </para> /// <para> /// The PreRequest hook is called prior to executing a route. If any item in the /// pre-request pipeline returns a response then the route is not executed and the /// response is returned. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public BeforePipeline Before { get; set; } /// <summary> /// <para> /// The error hook /// </para> /// <para> /// The error hook is called if an exception is thrown at any time during executing /// the PreRequest hook, a route and the PostRequest hook. It can be used to set /// the response and/or finish any ongoing tasks (close database session, etc). /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public ErrorPipeline OnError { get; set; } /// <summary> /// Gets or sets the current Nancy context /// </summary> /// <value>A <see cref="NancyContext" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> public NancyContext Context { get; set; } /// <summary> /// An extension point for adding support for formatting response contents. /// </summary><value>This property will always return <see langword="null" /> because it acts as an extension point.</value><remarks>Extension methods to this property should always return <see cref="P:Nancy.NancyModuleBase.Response" /> or one of the types that can implicitly be types into a <see cref="P:Nancy.NancyModuleBase.Response" />.</remarks> public IResponseFormatter Response { get; set; } /// <summary> /// Gets or sets the model binder locator /// </summary> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IModelBinderLocator ModelBinderLocator { get; set; } /// <summary> /// Gets or sets the model validation result /// </summary> /// <remarks>This is automatically set by Nancy at runtime when you run validation.</remarks> public virtual ModelValidationResult ModelValidationResult { get { return this.Context == null ? null : this.Context.ModelValidationResult; } set { if (this.Context != null) { this.Context.ModelValidationResult = value; } } } /// <summary> /// Declares a route for the module /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name">Name of the route</param> /// <param name="method">The HTTP method that the route will response to</param> /// <param name="path">The path that the route will respond to</param> /// <param name="action">Action that will be invoked when the route it hit</param> /// <param name="condition">A condition to determine if the route can be hit</param> protected void AddRoute<T>(string method, string path, Func<dynamic, CancellationToken, Task<T>> action, Func<NancyContext, bool> condition, string name) { this.routes.Add(new Route<T>(name ?? string.Empty, method, this.GetFullPath(path), condition, action)); } private string GetFullPath(string path) { var relativePath = (path ?? string.Empty).Trim('/'); var parentPath = (this.ModulePath ?? string.Empty).Trim('/'); if (string.IsNullOrEmpty(parentPath)) { return string.Concat("/", relativePath); } if (string.IsNullOrEmpty(relativePath)) { return string.Concat("/", parentPath); } return string.Concat("/", parentPath, "/", relativePath); } } }
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2020 Tim Stair // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Reflection; using System.Windows.Forms; namespace Support.UI { public class QueryPanel { // Critical Note: It is important that the user of a QueryPanel set the auto scroll option after all controls are added! protected const int X_CONTROL_BUFFER = 8; protected const int X_BUTTON_WIDTH = 24; protected const int Y_CONTROL_BUFFER = 4; protected const int Y_CONTROL_HEIGHT = 20; // default textbox height protected const int X_NUMERIC_WIDTH = 100; protected int X_LABEL_SIZE = 80; // this one varies based on the overall width private readonly Dictionary<object, QueryItem> m_dictionaryItems; private Control m_zCurrentLayoutControl; // the current panel / tab page to add controls to private bool m_bTabbed; private int m_nTabIndex; // the tab index value of a control protected Dictionary<Control, List<Control>> m_dictionaryLayoutControlControls = new Dictionary<Control, List<Control>>(); protected int m_nButtonHeight; protected TabControl m_zTabControl; protected Panel m_zPanel; public enum ControlType { TextBox, ComboBox, PullDownBox, CheckBox, NumBox, NumBoxSlider, BrowseBox, Label, Button, ListBox, DateTimePicker, None } /// <summary> /// /// </summary> /// <param name="zPanel">Empty Panel to add controls to</param> /// <param name="bTabbed">Flag indicating whether to use a tab control</param> public QueryPanel(Panel zPanel, bool bTabbed) { m_dictionaryItems = new Dictionary<object,QueryItem>(); InitPanel(zPanel, bTabbed); X_LABEL_SIZE = (int)((float)m_zPanel.Width * 0.25); } /// <summary> /// /// </summary> /// <param name="zPanel">Empty Panel to add controls to</param> /// <param name="nLabelWidth">Desired with of labels</param> /// <param name="bTabbed">Flag indicating whether to use a tab control</param> public QueryPanel(Panel zPanel, int nLabelWidth, bool bTabbed) { m_dictionaryItems = new Dictionary<object, QueryItem>(); InitPanel(zPanel, bTabbed); if(0 < nLabelWidth && nLabelWidth < m_zPanel.Width) { X_LABEL_SIZE = nLabelWidth; } } /// <summary> /// /// </summary> /// <param name="zPanel">Panel to setup and configure</param> /// <param name="bTabbed">Flag indicating whether to use a tab control</param> private void InitPanel(Panel zPanel, bool bTabbed) { m_nButtonHeight = new Button().Height; // setup the panel to contain the controls m_zPanel = zPanel ?? new Panel(); m_zPanel.AutoScroll = false; m_zCurrentLayoutControl = m_zPanel; // default to this as the main item if (bTabbed) { m_bTabbed = true; m_zTabControl = new TabControl { Dock = DockStyle.Fill, ClientSize = new Size(0, 0) }; m_zPanel.Controls.Add(m_zTabControl); // The SwitchToTab method is used to add items } // initialize m_zCurrentLayoutControl.Tag = Y_CONTROL_BUFFER; } /// <summary> /// Performs any finalization process related to the controls (intended for use before showing!) /// </summary> public void FinalizeControls() { // add the panel controls after the client size has been set (adding them before displayed an odd issue with control anchor/size) foreach (var zLayoutControl in m_dictionaryLayoutControlControls.Keys) { m_dictionaryLayoutControlControls[zLayoutControl].ForEach(zControl => zLayoutControl.Controls.Add(zControl)); } } /// <summary> /// Adds the control in a pending state to be placed on the panel by FinalizeControls /// </summary> /// <param name="zControl">The control to add</param> private void AddPendingControl(Control zControl) { List<Control> listControls; if (!m_dictionaryLayoutControlControls.TryGetValue(m_zCurrentLayoutControl, out listControls)) { listControls = new List<Control>(); m_dictionaryLayoutControlControls.Add(m_zCurrentLayoutControl, listControls); } listControls.Add(zControl); } /// <summary> /// Adds a label /// </summary> /// <param name="sLabel">Label string</param> /// <param name="nHeight">Label height</param> public Label AddLabel(string sLabel, int nHeight) { Label zLabel = CreateLabel(sLabel); zLabel.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top; zLabel.TextAlign = ContentAlignment.MiddleLeft; zLabel.Size = new Size(m_zCurrentLayoutControl.ClientSize.Width - (X_CONTROL_BUFFER * 2), nHeight); AddToYPosition(zLabel.Height + Y_CONTROL_BUFFER); AddPendingControl(zLabel); return zLabel; } /// <summary> /// Adds vertical spacing /// </summary> /// <param name="nHeight">The amount of space to add.</param> public void AddVerticalSpace(int nHeight) { AddToYPosition(nHeight); } /// <summary> /// Adds a check box with an associated label. /// </summary> /// <param name="sLabel">Label seting</param> /// <param name="bCheckDefault">Default check box state</param> /// <param name="zQueryKey">The query key for requesting the value</param> public CheckBox AddCheckBox(string sLabel, bool bCheckDefault, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zCheck = new CheckBox { Checked = bCheckDefault }; SetupControl(zCheck, zLabel, ControlType.CheckBox, true, zQueryKey); return zCheck; } /// <summary> /// Adds a button /// </summary> /// <param name="sLabel">Text label of the button</param> /// <param name="nDesiredWidth">The desired width of the button</param> /// <param name="eHandler">The event handler to associated with the button</param> /// <param name="zQueryKey">The query key for requesting the value</param> public Button AddButton(string sLabel, int nDesiredWidth, EventHandler eHandler, object zQueryKey) { var zButton = new Button { Text = sLabel }; zButton.Size = new Size(nDesiredWidth, zButton.Height); if (null != eHandler) { zButton.Click += eHandler; } SetupControl(zButton, null, ControlType.Button, false, zQueryKey); return zButton; } /// <summary> /// Adds a NumericUpDown /// </summary> /// <param name="sLabel">Label string</param> /// <param name="dDefault">Default value</param> /// <param name="dMin">Minimum value</param> /// <param name="dMax">Maximum value</param> /// <param name="dIncrement">Increment amout</param> /// <param name="nDecimalPlaces">decimal places</param> /// <param name="zQueryKey">The query key for requesting the value</param> public NumericUpDown AddNumericBox(string sLabel, decimal dDefault, decimal dMin, decimal dMax, decimal dIncrement, int nDecimalPlaces, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zNumeric = new NumericUpDown { Minimum = dMin, Maximum = dMax, Increment = dIncrement, DecimalPlaces = nDecimalPlaces }; if (dMin <= dDefault && dMax >= dDefault) { zNumeric.Value = dDefault; } SetupControl(zNumeric, zLabel, ControlType.NumBox, true, zQueryKey); return zNumeric; } /// <summary> /// Adds a NumericUpDown /// </summary> /// <param name="sLabel">Label string</param> /// <param name="dDefault">Default value</param> /// <param name="dMin">Minimum value</param> /// <param name="dMax">Maximum value</param> /// <param name="zQueryKey">The query key for requesting the value</param> public NumericUpDown AddNumericBox(string sLabel, decimal dDefault, decimal dMin, decimal dMax, object zQueryKey) { return AddNumericBox(sLabel, dDefault, dMin, dMax, 1, 0, zQueryKey); } /// <summary> /// Adds a NumericUpDown with associated slider /// </summary> /// <param name="sLabel">Label string</param> /// <param name="bFloat">Flag indicating whether the values associated are floating point</param> /// <param name="dDefault">Default value</param> /// <param name="dMin">Minimum value</param> /// <param name="dMax">Maximum value</param> /// <param name="zQueryKey">The query key for requesting the value</param> public NumericUpDown AddNumericBoxSlider(string sLabel, bool bFloat, decimal dDefault, decimal dMin, decimal dMax, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zNumeric = new NumericUpDown(); var zTrackBar = new TrackBar(); zNumeric.Minimum = dMin; zNumeric.Maximum = dMax; zNumeric.Increment = 1; zNumeric.Value = dMin; // default this to a valid number... if (bFloat) { int nZeroDecimalPlaces = 3 - (int)Math.Log10(Math.Max(Math.Abs((double)dMin), Math.Abs((double)dMax))); // note the trackbar value is set below using the numeric change event if (0 <= nZeroDecimalPlaces) { zNumeric.Increment = new Decimal( float.Parse("0." + "1".PadLeft(1 + nZeroDecimalPlaces, '0'), NumberStyles.Any, CultureInfo.InvariantCulture)); zNumeric.DecimalPlaces = nZeroDecimalPlaces + 1; } else { zNumeric.Increment = 1; zNumeric.DecimalPlaces = 0; } zTrackBar.Minimum = 0; zTrackBar.Maximum = ((int)(dMax / zNumeric.Increment)) - ((int)(dMin / zNumeric.Increment)); } else { zTrackBar.Minimum = (int)dMin; zTrackBar.Maximum = (int)dMax; zTrackBar.Value = (int)dDefault; } if (dDefault >= dMin && dDefault <= dMax) { zNumeric.Value = dDefault; } zNumeric.Location = new Point(GetLabelWidth(zLabel) + (X_CONTROL_BUFFER), GetYPosition()); zNumeric.Size = new Size(X_NUMERIC_WIDTH, Y_CONTROL_HEIGHT); zNumeric.Tag = zTrackBar; // the tag of the numeric is the trackbar zNumeric.Anchor = AnchorStyles.Left | AnchorStyles.Top; zNumeric.ValueChanged += numeric_ValueChanged; zLabel.Height = zNumeric.Height; // adjust the height of the label to match the control to its right zTrackBar.Location = new Point(zNumeric.Width + zNumeric.Location.X + X_CONTROL_BUFFER, GetYPosition()); zTrackBar.Size = new Size(m_zPanel.ClientSize.Width - (zTrackBar.Location.X + X_CONTROL_BUFFER), Y_CONTROL_HEIGHT); zTrackBar.Tag = zNumeric; // the tag of the trackbar is the numeric (value changes will affect the numeric) zTrackBar.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; zTrackBar.ValueChanged += numericSlider_ValueChanged; if (bFloat) { // set the trackbar value using the change event numeric_ValueChanged(zNumeric, new EventArgs()); } AddPendingControl(zLabel); AddPendingControl(zNumeric); AddPendingControl(zTrackBar); AddToYPosition(zTrackBar.Size.Height + Y_CONTROL_BUFFER); var qItem = new QueryItem(ControlType.NumBoxSlider, zNumeric, zTrackBar, ref m_nTabIndex); // the tag of the QueryItem is the trackbar (used when disabling the QueryItem) m_dictionaryItems.Add(zQueryKey, qItem); return zNumeric; } /// <summary> /// Adds a TextBox /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefaultValue">Default text</param> /// <param name="bPassword">Flag indicating that this is a password textbox</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddTextBox(string sLabel, string sDefaultValue, bool bPassword, object zQueryKey) { return AddTextBox(sLabel, sDefaultValue, false, bPassword, 0, zQueryKey); } /// <summary> /// Adds a multiline TextBox /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefaultValue">Default text</param> /// <param name="nHeight">Height of the TextBox</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddMultiLineTextBox(string sLabel, string sDefaultValue, int nHeight, object zQueryKey) { return AddTextBox(sLabel, sDefaultValue, true, false, nHeight, zQueryKey); } /// <summary> /// Adds a TextBox /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefaultValue">Default text</param> /// <param name="bMultiLine">Flag indicating whether this is a multi line textbox</param> /// <param name="bPassword">Flag indicating that this is a password textbox</param> /// <param name="nHeight">Height of the text box. This only applies to those with bMultiLine set to true</param> /// <param name="zQueryKey">The query key for requesting the value</param> private TextBox AddTextBox(string sLabel, string sDefaultValue, bool bMultiLine, bool bPassword, int nHeight, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zText = new TextBox(); if (bPassword) { zText.PasswordChar = 'x'; } zText.Multiline = bMultiLine; zText.Text = sDefaultValue; if(bMultiLine) { zText.AcceptsReturn = true; zText.Size = new Size(m_zCurrentLayoutControl.ClientSize.Width - ((X_CONTROL_BUFFER * 2) + GetLabelWidth(zLabel)), nHeight); zText.ScrollBars = ScrollBars.Both; zText.WordWrap = false; } else { zText.Size = new Size(m_zCurrentLayoutControl.ClientSize.Width - ((X_CONTROL_BUFFER * 2) + GetLabelWidth(zLabel)), Y_CONTROL_HEIGHT); } SetupControl(zText, zLabel, ControlType.TextBox, false, zQueryKey); return zText; } /// <summary> /// Adds a ComboBox /// </summary> /// <param name="sLabel">Label string</param> /// <param name="arrayEntries">Array of strings to be used in the combo box</param> /// <param name="nDefaultIndex">Default index of the combo box</param> /// <param name="zQueryKey">The query key for requesting the value</param> public ComboBox AddComboBox(string sLabel, string[] arrayEntries, int nDefaultIndex, object zQueryKey) { return AddComboBox(sLabel, arrayEntries, nDefaultIndex, false, zQueryKey); } /// <summary> /// Adds a ComboBox with the pulldownlist style. /// </summary> /// <param name="sLabel">Label string</param> /// <param name="arrayEntries">Array of strings to be used in the combo box</param> /// <param name="nDefaultIndex">Default index of the combo box</param> /// <param name="zQueryKey">The query key for requesting the value</param> public ComboBox AddPullDownBox(string sLabel, string[] arrayEntries, int nDefaultIndex, object zQueryKey) { return AddComboBox(sLabel, arrayEntries, nDefaultIndex, true, zQueryKey); } /// <summary> /// Adds a combo box with the items specified (based on the type specified) /// </summary> /// <param name="sLabel">Label string</param> /// <param name="arrayEntries">Array of strings to be used in the combo box</param> /// <param name="nDefaultIndex">Default index of the combo box</param> /// <param name="bPulldown">Flag indicating whether this is a pulldownlist or not</param> /// <param name="zQueryKey">The query key for requesting the value</param> private ComboBox AddComboBox(string sLabel, string[] arrayEntries, int nDefaultIndex, bool bPulldown, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zCombo = new ComboBox(); if (null != arrayEntries) { foreach (var entry in arrayEntries) { zCombo.Items.Add(entry); } if (zCombo.Items.Count > nDefaultIndex) { zCombo.SelectedIndex = nDefaultIndex; } else if (0 < zCombo.Items.Count) { zCombo.SelectedIndex = 0; } } if(bPulldown) { zCombo.DropDownStyle = ComboBoxStyle.DropDownList; SetupControl(zCombo, zLabel, ControlType.PullDownBox, true, zQueryKey); } else { zCombo.DropDownStyle = ComboBoxStyle.DropDown; SetupControl(zCombo, zLabel, ControlType.ComboBox, true, zQueryKey); } return zCombo; } /// <summary> /// Adds a ListBox with the specified items and selected items /// </summary> /// <param name="sLabel">Label string</param> /// <param name="arrayEntries">Array of strings as entries</param> /// <param name="arraySelected">Array of indicies to select</param> /// <param name="bMultiSelect">Flag indicating whether multiple items can be selected</param> /// <param name="nHeight">The desired height of the ListBox</param> /// <param name="zQueryKey">The query key for requesting the value</param> public ListBox AddListBox(string sLabel, string[] arrayEntries, int[] arraySelected, bool bMultiSelect, int nHeight, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zListBox = new ListBox { SelectionMode = bMultiSelect ? SelectionMode.MultiSimple : SelectionMode.One }; if (null != arrayEntries) { foreach (var sEntry in arrayEntries) { zListBox.Items.Add(sEntry); } if (null != arraySelected) { foreach (var nIndex in arraySelected) { if ((-1 < nIndex) && (nIndex < zListBox.Items.Count)) { zListBox.SelectedIndex = nIndex; } } } } zListBox.Height = nHeight; SetupControl(zListBox, zLabel, ControlType.ListBox, true, zQueryKey); return zListBox; } /// <summary> /// Adds a DateTime picker field /// </summary> /// <param name="sLabel">Label string</param> /// <param name="eFormat">DateTimePickerFormat to control the visual component</param> /// <param name="dtValue">The default date time value</param> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public DateTimePicker AddDateTimePicker(string sLabel, DateTimePickerFormat eFormat, DateTime dtValue, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zPicker = new DateTimePicker { Format = eFormat, Value = dtValue }; switch (eFormat) { case DateTimePickerFormat.Time: zPicker.ShowUpDown = true; break; } SetupControl(zPicker, zLabel, ControlType.DateTimePicker, true, zQueryKey); return zPicker; } /// <summary> /// Support method to setup the control location/size. This method also adds the control to the form. /// </summary> /// <param name="zControl">Control to configure</param> /// <param name="zLabel">Label Control associated with the Control</param> /// <param name="eType">ControlType</param> /// <param name="bApplySize">Apply size based on form flag</param> /// <param name="zQueryKey">The query key for requesting the value</param> private void SetupControl(Control zControl, Label zLabel, ControlType eType, bool bApplySize, object zQueryKey) { if (null != zLabel) { if (bApplySize) { zControl.Size = new Size((m_zCurrentLayoutControl.ClientSize.Width - GetLabelWidth(zLabel)) - (X_CONTROL_BUFFER * 2), zControl.Size.Height); } zControl.Location = new Point(zLabel.Location.X + GetLabelWidth(zLabel), GetYPosition()); zLabel.Height = zControl.Height; AddPendingControl(zLabel); AddToYPosition(Math.Max(zLabel.Height, zControl.Height) + Y_CONTROL_BUFFER); } else { zControl.Location = new Point((m_zCurrentLayoutControl.ClientSize.Width - zControl.Width) - X_CONTROL_BUFFER, GetYPosition()); AddToYPosition(zControl.Height + Y_CONTROL_BUFFER); } zControl.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top; AddPendingControl(zControl); var qItem = new QueryItem(eType, zControl, ref m_nTabIndex); m_dictionaryItems.Add(zQueryKey, qItem); } /// <summary> /// Adds a folder browser component /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefault">Default string</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddFolderBrowseBox(string sLabel, string sDefault, object zQueryKey) { return AddBrowseBox(sLabel, sDefault, null, zQueryKey); } /// <summary> /// Adds a file browser component. /// </summary> /// <param name="sLabel">Label string</param> /// <param name="sDefault">Default string</param> /// <param name="sFilter">File filter (standard format for OpenFileDialog), string.empty for default *.*</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddFileBrowseBox(string sLabel, string sDefault, string sFilter, object zQueryKey) { return AddBrowseBox(sLabel, sDefault, sFilter, zQueryKey); } /// <summary> /// Adds a browse component (button/textbox/label) /// </summary> /// <param name="sLabel">Label for the component</param> /// <param name="sDefault">Default value</param> /// <param name="sFilter">File filter (applies to file browsing only)</param> /// <param name="zQueryKey">The query key for requesting the value</param> private TextBox AddBrowseBox(string sLabel, string sDefault, string sFilter, object zQueryKey) { var zLabel = CreateLabel(sLabel); var zButton = new Button(); var zTextLocation = new Point(GetLabelWidth(zLabel) + (X_CONTROL_BUFFER), GetYPosition()); var zText = new TextBox { Text = sDefault, Location = zTextLocation, Size = new Size( m_zCurrentLayoutControl.ClientSize.Width - (zTextLocation.X + X_BUTTON_WIDTH + (X_CONTROL_BUFFER * 2)), Y_CONTROL_HEIGHT), Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top }; if (null != sFilter) { zText.Tag = 0 != sFilter.Length ? sFilter : "All files (*.*)|*.*"; } zLabel.Height = zText.Height; // adjust the height of the label to match the control to its right zButton.Text = "..."; zButton.Size = new Size(X_BUTTON_WIDTH, Y_CONTROL_HEIGHT); zButton.Location = new Point(m_zCurrentLayoutControl.ClientSize.Width - (zButton.Size.Width + X_CONTROL_BUFFER), GetYPosition()); zButton.Tag = zText; // the tag of the button is the textbox zButton.Anchor = AnchorStyles.Right | AnchorStyles.Top; zButton.Click += zButton_Click; AddPendingControl(zLabel); AddPendingControl(zText); AddPendingControl(zButton); AddToYPosition(zText.Size.Height + Y_CONTROL_BUFFER); var qItem = new QueryItem(ControlType.BrowseBox, zText, zButton, ref m_nTabIndex); // the tag of the QueryItem is the button (used when disabling the QueryItem) m_dictionaryItems.Add(zQueryKey, qItem); return zText; } /// <summary> /// Adds a browse component (button/textbox/label) /// </summary> /// <param name="sLabel">Label for the component</param> /// <param name="sDefault">Default value</param> /// <param name="actionBrowseClicked">Function that returns the form to show (or null if it should not)</param> /// <param name="actionSelect">Action to take with the dialog and TextBox (if the result is OK)</param> /// <param name="zQueryKey">The query key for requesting the value</param> public TextBox AddSelectorBox<T>(string sLabel, string sDefault, Func<T> actionBrowseClicked, Action<T, TextBox> actionSelect, object zQueryKey) where T : Form { var zLabel = CreateLabel(sLabel); var zButton = new Button(); var zTextLocation = new Point(GetLabelWidth(zLabel) + (X_CONTROL_BUFFER), GetYPosition()); var zText = new TextBox { Text = sDefault, Location = zTextLocation, Size = new Size( m_zCurrentLayoutControl.ClientSize.Width - (zTextLocation.X + X_BUTTON_WIDTH + (X_CONTROL_BUFFER * 2)), Y_CONTROL_HEIGHT), Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top }; zLabel.Height = zText.Height; // adjust the height of the label to match the control to its right zButton.Text = "..."; zButton.Size = new Size(X_BUTTON_WIDTH, Y_CONTROL_HEIGHT); zButton.Location = new Point(m_zCurrentLayoutControl.ClientSize.Width - (zButton.Size.Width + X_CONTROL_BUFFER), GetYPosition()); zButton.Tag = zText; // the tag of the button is the textbox zButton.Anchor = AnchorStyles.Right | AnchorStyles.Top; zButton.Click += (sender, args) => { var zDialog = actionBrowseClicked(); if (null == zDialog) { return; } if (DialogResult.OK == zDialog.ShowDialog(this.m_zPanel)) { actionSelect(zDialog, zText); } }; AddPendingControl(zLabel); AddPendingControl(zText); AddPendingControl(zButton); AddToYPosition(zText.Size.Height + Y_CONTROL_BUFFER); var qItem = new QueryItem(ControlType.BrowseBox, zText, zButton, ref m_nTabIndex); // the tag of the QueryItem is the button (used when disabling the QueryItem) m_dictionaryItems.Add(zQueryKey, qItem); return zText; } /// <summary> /// Created a label based on the current y position /// </summary> /// <param name="sLabel">The Label string</param> /// <returns></returns> private Label CreateLabel(string sLabel) { var zLabel = new Label(); if(null != sLabel) { zLabel.Text = sLabel; zLabel.TextAlign = ContentAlignment.MiddleRight; zLabel.Location = new Point(X_CONTROL_BUFFER, GetYPosition()); zLabel.Size = new Size(X_LABEL_SIZE, Y_CONTROL_HEIGHT); } else { zLabel.Location = new Point(X_CONTROL_BUFFER, GetYPosition()); zLabel.Size = new Size(0, Y_CONTROL_HEIGHT); } return zLabel; } /// <summary> /// Changes to the tab specified and creates it if necessary /// </summary> /// <param name="sTabName">Name of the tab to change to</param> public void ChangeToTab(string sTabName) { AddTab(sTabName); } /// <summary> /// Creates a Tab /// </summary> /// <param name="sTabName">Name of the tab to create</param> /// <returns></returns> public TabPage AddTab(string sTabName) { if (!m_bTabbed) { throw new Exception("QueryPanel: Attempted to add tab on non-tabbed QueryPanel."); } if (m_zTabControl.TabPages.ContainsKey(sTabName)) { TabPage zPage = m_zTabControl.TabPages[sTabName]; m_zCurrentLayoutControl = zPage; return zPage; } else { m_zTabControl.TabPages.Add(sTabName, sTabName); var zPage = m_zTabControl.TabPages[sTabName]; zPage.Tag = Y_CONTROL_BUFFER; // stores the current Y Position zPage.AutoScroll = true; zPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; zPage.Dock = DockStyle.Fill; m_zCurrentLayoutControl = zPage; return zPage; } } /// <summary> /// Adds the specified control to be enabled when the given control is enabled. /// </summary> /// <param name="zQueryKey">The parent control to base the enable state on</param> /// <param name="zQueryKeyEnable">The control to enable/disable based on the parent control state</param> /// <returns>true on success, false otherwise</returns> public bool AddEnableControl(object zQueryKey, object zQueryKeyEnable) { QueryItem zQueryItem, zQueryItemEnable; if (m_dictionaryItems.TryGetValue(zQueryKey, out zQueryItem) && m_dictionaryItems.TryGetValue(zQueryKeyEnable, out zQueryItemEnable)) { (zQueryItem).AddEnableControl(zQueryItemEnable); return true; } return false; } /// <summary> /// Adds the specified controls to be enabled when the given control is enabled. /// </summary> /// <param name="zQueryKey">The parent control to base the enable state on</param> /// <param name="arrayQueryKeyEnable">string[] of controls to enable/disable based on the parent control state</param> /// <returns>true on success, false otherwise</returns> public bool AddEnableControls(object zQueryKey, object[] arrayQueryKeyEnable) { var bRet = true; foreach(var zKey in arrayQueryKeyEnable) { bRet &= AddEnableControl(zQueryKey, zKey); } return bRet; } /// <summary> /// This gets the width of the label + the control buffer (or 0 if the label is empty) /// </summary> /// <param name="zLabel"></param> /// <returns></returns> private int GetLabelWidth(Label zLabel) { return (zLabel.Width == 0) ? 0 : zLabel.Width + X_CONTROL_BUFFER; } public static void SetupScrollState(ScrollableControl scrollableControl) { Type scrollableControlType = typeof(ScrollableControl); MethodInfo setScrollStateMethod = scrollableControlType.GetMethod("SetScrollState", BindingFlags.NonPublic | BindingFlags.Instance); setScrollStateMethod.Invoke(scrollableControl, new object[] { 0x10 /*ScrollableControl.ScrollStateFullDrag*/, true }); } #region Value Getters /// <summary> /// Gets the control associated with the query key /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns>The control associated with the query key</returns> public Control GetControl(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { return zItem.QueryControl; } ThrowBadQueryException(); return null; } /// <summary> /// Gets the state of the specified check box /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public bool GetBool(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { if(ControlType.CheckBox == zItem.Type) { return ((CheckBox)zItem.QueryControl).Checked; } ThrowWrongTypeException(); } return false; } /// <summary> /// Gets the index of the specified combo box /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public int GetIndex(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { switch(zItem.Type) { case ControlType.PullDownBox: case ControlType.ComboBox: return ((ComboBox)zItem.QueryControl).SelectedIndex; case ControlType.ListBox: return ((ListBox)zItem.QueryControl).SelectedIndex; } ThrowWrongTypeException(); } return 0; } /// <summary> /// Gets the selected indices of the given control /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns>Array of selected indices, NULL if none are selected</returns> public int[] GetIndices(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if (null != zItem) { switch (zItem.Type) { case ControlType.ListBox: var zListBox = (ListBox)zItem.QueryControl; var arrayItems = new int[zListBox.SelectedIndices.Count]; for (var nIdx = 0; nIdx < arrayItems.Length; nIdx++) { arrayItems[nIdx] = zListBox.SelectedIndices[nIdx]; } return arrayItems; } ThrowWrongTypeException(); } return null; } /// <summary> /// Gets the string value of the specified control /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public string GetString(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { switch(zItem.Type) { case ControlType.BrowseBox: case ControlType.PullDownBox: case ControlType.ComboBox: case ControlType.TextBox: return zItem.QueryControl.Text; case ControlType.ListBox: return (string)((ListBox)zItem.QueryControl).SelectedItem; case ControlType.NumBox: return ((NumericUpDown)zItem.QueryControl).Value.ToString(CultureInfo.CurrentCulture); } ThrowWrongTypeException(); } return string.Empty; } /// <summary> /// Gets the selected strings of the control /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns>Array of selected strings, or NULL if none are selected</returns> public string[] GetStrings(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if (null != zItem) { switch (zItem.Type) { case ControlType.ListBox: var zListBox = (ListBox)zItem.QueryControl; var arrayItems = new string[zListBox.SelectedItems.Count]; for (var nIdx = 0; nIdx < arrayItems.Length; nIdx++) { arrayItems[nIdx] = (string)zListBox.SelectedItems[nIdx]; } return arrayItems; } ThrowWrongTypeException(); } return null; } /// <summary> /// /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public decimal GetDecimal(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if(null != zItem) { switch(zItem.Type) { case ControlType.NumBox: case ControlType.NumBoxSlider: return ((NumericUpDown)zItem.QueryControl).Value; } ThrowWrongTypeException(); } return 0; } /// <summary> /// Returns the DateTime of the specified control. /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> public DateTime GetDateTime(object zQueryKey) { var zItem = GetQueryItem(zQueryKey); if (null != zItem) { switch (zItem.Type) { case ControlType.DateTimePicker: return ((DateTimePicker)zItem.QueryControl).Value; } ThrowWrongTypeException(); } return DateTime.Now; } /// <summary> /// /// </summary> /// <param name="zQueryKey">The query key for requesting the value</param> /// <returns></returns> private QueryItem GetQueryItem(object zQueryKey) { QueryItem zQueryItem; if (!m_dictionaryItems.TryGetValue(zQueryKey, out zQueryItem)) { ThrowBadQueryException(); } return zQueryItem; } /// <summary> /// Used to throw a general exception when the wrong type is queried /// </summary> private void ThrowWrongTypeException() { throw new Exception("QueryDialog: Incorrect type for specified return."); } /// <summary> /// Used to throw a general exception when the query key specified is wrong /// </summary> private void ThrowBadQueryException() { throw new Exception("QueryDialog: Invalid Query Key."); } /// <summary> /// Class representing an entry/item on the dialog /// </summary> protected class QueryItem { private ControlType m_eControlType = ControlType.None; private Control m_zControl; private readonly List<QueryItem> m_listEnableControls = new List<QueryItem>(); public object Tag; // always good to have an extra object reference just in case... public ControlType Type => m_eControlType; public Control QueryControl => m_zControl; /// <summary> /// Constructor /// </summary> /// <param name="eControlType">The ControlType to create</param> /// <param name="zControl">The associated control</param> /// <param name="nTabIndex"></param> public QueryItem(ControlType eControlType, Control zControl, ref int nTabIndex) { ConfigureQueryItem(eControlType, zControl, null, ref nTabIndex); } /// <summary> /// Constructor /// </summary> /// <param name="eControlType">The ControlType to create</param> /// <param name="zControl">The associated control</param> /// <param name="zTagControl">The Tag control of the query item</param> /// <param name="nTabIndex"></param> public QueryItem(ControlType eControlType, Control zControl, Control zTagControl, ref int nTabIndex) { ConfigureQueryItem(eControlType, zControl, zTagControl, ref nTabIndex); } private void ConfigureQueryItem(ControlType eControlType, Control zControl, Control zTagControl, ref int nTabIndex) { Tag = zTagControl; m_eControlType = eControlType; m_zControl = zControl; m_zControl.TabIndex = nTabIndex++; switch (eControlType) { case ControlType.TextBox: case ControlType.ComboBox: zControl.TextChanged += QueryItem_TextChanged; break; case ControlType.CheckBox: ((CheckBox)zControl).CheckedChanged += QueryItem_CheckedChanged; break; case ControlType.BrowseBox: zControl.TextChanged += QueryItem_TextChanged; zTagControl.TabIndex = nTabIndex++; break; case ControlType.NumBoxSlider: zTagControl.TabIndex = nTabIndex++; break; } } /// <summary> /// Adds an enable control state for the specified item /// </summary> /// <param name="zItem"></param> public void AddEnableControl(QueryItem zItem) { if (!m_listEnableControls.Contains(zItem)) { m_listEnableControls.Add(zItem); } } private void QueryItem_TextChanged(object sender, EventArgs e) { UpdateEnableStates(); } private void QueryItem_CheckedChanged(object sender, EventArgs e) { UpdateEnableStates(); } /// <summary> /// Updates all of the enable states for the controls (based on the current state of this control) /// </summary> public void UpdateEnableStates() { bool bEnabled; switch(m_eControlType) { case ControlType.TextBox: case ControlType.BrowseBox: case ControlType.ComboBox: bEnabled = 0 < m_zControl.Text.Length; break; case ControlType.CheckBox: bEnabled = ((CheckBox)m_zControl).Checked; break; default: return; } foreach (QueryItem zItem in m_listEnableControls) { zItem.m_zControl.Enabled = bEnabled; switch (zItem.m_eControlType) { case ControlType.BrowseBox: case ControlType.NumBoxSlider: ((Control)zItem.Tag).Enabled = bEnabled; break; } } } } #endregion #region Events /// <summary> /// Generic button press (used for the browse file/folder box) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void zButton_Click(object sender, EventArgs e) { var zButton = (Button)sender; var zText = (TextBox)zButton.Tag; var sFilter = (string)zText.Tag; if(!string.IsNullOrEmpty(sFilter)) // file browse { var ofn = new OpenFileDialog { Filter = sFilter, CheckFileExists = false, FileName = zText.Text }; if(DialogResult.OK == ofn.ShowDialog()) { zText.Text = ofn.FileName; } } else // folder browse { var fbd = new FolderBrowserDialog { ShowNewFolderButton = true, SelectedPath = zText.Text }; if(DialogResult.OK == fbd.ShowDialog()) { zText.Text = fbd.SelectedPath; } } } /// <summary> /// Handles generic numeric slider change /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void numericSlider_ValueChanged(object sender, EventArgs e) { var zTrackBar = (TrackBar)sender; var zNumeric = (NumericUpDown)zTrackBar.Tag; if (1 > zNumeric.Increment) { zNumeric.Value = zNumeric.Minimum + ((decimal)zTrackBar.Value * zNumeric.Increment); } else { zNumeric.Value = zTrackBar.Value; } } /// <summary> /// Handles generic numeric change /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void numeric_ValueChanged(object sender, EventArgs e) { var zNumeric = (NumericUpDown)sender; var zTrackBar = (TrackBar)zNumeric.Tag; if (1 > zNumeric.Increment) { zTrackBar.Value = (int)((zNumeric.Value - zNumeric.Minimum) * ((decimal)1 / zNumeric.Increment)); } else { zTrackBar.Value = (int)zNumeric.Value; } } /// <summary> /// Sets the Y position for the current layout control (panel, tab etc.) /// </summary> /// <param name="nYAmount">Amount to add</param> private void AddToYPosition(int nYAmount) { var nCurrentY = (int)m_zCurrentLayoutControl.Tag; nCurrentY += nYAmount; m_zCurrentLayoutControl.Tag = nCurrentY; } /// <summary> /// Gets the current y position (based on the current layout control) /// </summary> /// <returns></returns> protected int GetYPosition() { return (int)m_zCurrentLayoutControl.Tag; } public void UpdateEnableStates() { // Update enable states foreach (var zItem in m_dictionaryItems.Values) { zItem.UpdateEnableStates(); } } #endregion } }
namespace Microsoft.Protocols.TestSuites.MS_WOPI { using System; /// <summary> /// This class is used to perform the discovery process between the shared test case part and the pure WOPI test cases part. /// </summary> public class DiscoveryProcessHelper : HelperBase { /// <summary> /// A bool value is used to indicating whether the discovery process has been executed successfully. /// </summary> private static bool hasPerformDiscoveryProcessSucceed = false; /// <summary> /// A bool value is used to indicating whether the discovery record has been cleaned up successfully. /// </summary> private static bool hasPerformCleanUpForDiscovery = false; /// <summary> /// An object instance is used for lock blocks which is used for multiple threads. This instance is used to keep asynchronous process for visiting the "hasPerformDiscoveryProcessSucceed" field in different threads. /// </summary> private static object lockObjectOfVisitDiscoveryProcessStatus = new object(); /// <summary> /// An DiscoveryRequestListener instance represents the listener which is listening discovery request. The test suite will use only one listener instance to listen. /// </summary> private static DiscoveryRequestListener discoveryListenerInstance = null; /// <summary> /// A string value represents the progId which is used in discovery process in order to make the WOPI server enable folder level visit ability when it receive the progId from the discovery response. /// </summary> private static string progIdValue = string.Empty; /// <summary> /// Prevents a default instance of the DiscoveryProcessHelper class from being created /// </summary> private DiscoveryProcessHelper() { } /// <summary> /// Gets a value indicating whether the helper need to perform a clean up action for discovery record. /// </summary> public static bool NeedToCleanUpDiscoveryRecord { get { lock (lockObjectOfVisitDiscoveryProcessStatus) { return hasPerformDiscoveryProcessSucceed && !hasPerformCleanUpForDiscovery; } } } /// <summary> /// Gets a value indicating whether the discovery process has been executed successfully /// </summary> public static bool HasPerformDiscoveryProcessSucceed { get { lock (lockObjectOfVisitDiscoveryProcessStatus) { return hasPerformDiscoveryProcessSucceed; } } } /// <summary> /// A method is used to perform the WOPI discovery process for the WOPI server. /// </summary> /// <param name="hostNameOfDiscoveryListener">A parameter represents the machine name which is hosting the discovery listener feature. It should be the test client name which is running the test suite.</param> /// <param name="sutControllerInstance">A parameter represents the IMS_WOPISUTControlAdapter instance which is used to make the WOPI server perform sending discovery request to the discovery listener.</param> public static void PerformDiscoveryProcess(string hostNameOfDiscoveryListener, IMS_WOPISUTControlAdapter sutControllerInstance) { if (HasPerformDiscoveryProcessSucceed) { return; } if (null == sutControllerInstance) { throw new ArgumentNullException("sutControllerInstance"); } if (string.IsNullOrEmpty(hostNameOfDiscoveryListener)) { throw new ArgumentNullException("hostNameOfDiscoveryListener"); } // Call the "TriggerWOPIDiscovery" method of IMS_WOPISUTControlAdapter interface bool isDiscoverySuccessful = sutControllerInstance.TriggerWOPIDiscovery(hostNameOfDiscoveryListener); if (!isDiscoverySuccessful) { throw new InvalidOperationException("Could not perform the discovery process successfully."); } lock (lockObjectOfVisitDiscoveryProcessStatus) { hasPerformDiscoveryProcessSucceed = true; } DiscoveryProcessHelper.AppendLogs(typeof(DiscoveryProcessHelper), DateTime.Now, "Perform the trigger WOPI discovery process successfully."); } /// <summary> /// A method is used to clean up the WOPI discovery record for the WOPI server. For removing the record successfully, the WOPI server can be triggered the WOPI discovery process again. /// </summary> /// <param name="wopiClientName">A parameter represents the WOPI client name which should have been discovered by WOPI server</param> /// <param name="sutControllerInstance">A parameter represents the IMS_WOPISUTControlAdapter instance which is used to make the WOPI server clean up discovery record for the specified WOPI client.</param> public static void CleanUpDiscoveryRecord(string wopiClientName, IMS_WOPISUTControlAdapter sutControllerInstance) { DiscoveryProcessHelper.CheckInputParameterNullOrEmpty<IMS_WOPISUTControlAdapter>(sutControllerInstance, "sutControllerInstance", "CleanUpDiscoveryRecord"); if (!NeedToCleanUpDiscoveryRecord) { return; } lock (lockObjectOfVisitDiscoveryProcessStatus) { if (hasPerformDiscoveryProcessSucceed && !hasPerformCleanUpForDiscovery) { bool isDiscoveryRecordRemoveSuccessful = sutControllerInstance.RemoveWOPIDiscoveryRecord(wopiClientName); if (!isDiscoveryRecordRemoveSuccessful) { throw new InvalidOperationException("Could not remove the discovery record successfully, need to remove that manually."); } hasPerformCleanUpForDiscovery = true; } } } /// <summary> /// A method is used to generate response of a WOPI discovery request. It indicates the WOPI client supports 3 types file extensions: ".txt", ".zip", ".one" /// </summary> /// <param name="currentTestClientName">A parameter represents the current test client name which is used to construct WOPI client's app name in WOPI discovery response.</param> /// <param name="progId">A parameter represents the id of program which is associated with folder level visit in discovery process. This value must be valid for WOPI server.</param> /// <returns>A return value represents the response of a WOPI discovery request.</returns> public static string GetDiscoveryResponseXmlString(string currentTestClientName, string progId) { DiscoveryProcessHelper.CheckInputParameterNullOrEmpty<string>(currentTestClientName, "currentTestClientName", "GetDiscoveryResponseXmlString"); DiscoveryProcessHelper.CheckInputParameterNullOrEmpty<string>(progId, "progId", "GetDiscoveryResponseXmlString"); wopidiscovery wopiDiscoveryInstance = new wopidiscovery(); // Pass the prog id, so that the WOPI discovery response logic will use the prog id value. progIdValue = progId; // Add http and https net zone into the wopiDiscovery wopiDiscoveryInstance.netzone = GetNetZonesForWopiDiscoveryResponse(currentTestClientName); // ProofKey element wopiDiscoveryInstance.proofkey = new ct_proofkey(); wopiDiscoveryInstance.proofkey.oldvalue = RSACryptoContext.PublicKeyStringOfOld; wopiDiscoveryInstance.proofkey.value = RSACryptoContext.PublicKeyStringOfCurrent; string xmlStringOfResponseDiscovery = WOPISerializerHelper.GetDiscoveryXmlFromDiscoveryObject(wopiDiscoveryInstance); return xmlStringOfResponseDiscovery; } /// <summary> /// A method is used to start listening the discovery request from the WOPI server. If the listen thread has existed, the DiscoverProcessHelper will not start any new listen thread. /// </summary> /// <param name="currentTestClient">A parameter represent the current test client which acts as WOPI client to listen the discovery request.</param> /// <param name="progId">A parameter represents the id of program which is associated with folder level visit in discovery process. This value must be valid for WOPI server. For Microsoft products, this value can be "OneNote.Notebook". It is used to ensure the WOPI server can support folder level visit ability in WOPI mode when receive the value from the discovery response.</param> public static void StartDiscoveryListen(string currentTestClient, string progId) { DiscoveryProcessHelper.CheckInputParameterNullOrEmpty<string>(currentTestClient, "currentTestClient", "StartDiscoveryListen"); DiscoveryProcessHelper.CheckInputParameterNullOrEmpty<string>(progId, "progId", "StartDiscoveryListen"); if (null == discoveryListenerInstance) { string discoveryXmlResponse = GetDiscoveryResponseXmlString(currentTestClient, progId); discoveryListenerInstance = new DiscoveryRequestListener(currentTestClient, discoveryXmlResponse); discoveryListenerInstance.StartListen(); } } /// <summary> /// A method is used to dispose the discovery request listener. /// </summary> public static void DisposeDiscoveryListener() { if (discoveryListenerInstance != null) { discoveryListenerInstance.Dispose(); discoveryListenerInstance = null; } } /// <summary> /// A method is used to get necessary internal http and internal https ct_netzone instances. This values is used to response to the WOPI server so that the WOPI server can use this test client as a WOPI client. /// </summary> /// <param name="currentTestClientName">A parameter represents the current test client name which run the test suite. This value is used to generated the WOPI client's app name.</param> /// <returns>A return value represents an array of ct_netzone type instances.</returns> private static ct_netzone[] GetNetZonesForWopiDiscoveryResponse(string currentTestClientName) { #region validate the parameter HelperBase.CheckInputParameterNullOrEmpty<string>(currentTestClientName, "currentTestClientName", "GetNetZoneForWopiDiscoveryResponse"); #endregion string fakedWOPIClientActionHostName = string.Format(@"{0}.com", Guid.NewGuid().ToString("N")); // Http Net zone ct_netzone httpNetZone = GetSingleNetZoneForWopiDiscoveryResponse(st_wopizone.internalhttp, currentTestClientName, fakedWOPIClientActionHostName); // Https Net zone ct_netzone httpsNetZone = GetSingleNetZoneForWopiDiscoveryResponse(st_wopizone.internalhttps, currentTestClientName, fakedWOPIClientActionHostName); return new ct_netzone[] { httpNetZone, httpsNetZone }; } /// <summary> /// A method is used to generate a single ct_netzone type instance for current test client according to the netZoneType. /// </summary> /// <param name="netZoneType">A parameter represents the netZone type, it can only be set to "st_wopizone.internalhttp" or "st_wopizone.internalhttps"</param> /// <param name="currentTestClientName">A parameter represents the current test client name which run the test suite. This value is used to generated the WOPI client's app name.</param> /// <param name="fakedWOPIClientActionHostName">A parameter represents the host name for the action of the WOPI client support.</param> /// <returns>A return value represents the ct_netzone type instance.</returns> private static ct_netzone GetSingleNetZoneForWopiDiscoveryResponse(st_wopizone netZoneType, string currentTestClientName, string fakedWOPIClientActionHostName) { string transportValue = st_wopizone.internalhttp == netZoneType ? Uri.UriSchemeHttp : Uri.UriSchemeHttps; Random radomInstance = new Random((int)DateTime.UtcNow.Ticks & 0x0000FFFF); string appName = string.Format( @"MSWOPITESTAPP {0} _for {1} WOPIServer_{2}", radomInstance.Next(), currentTestClientName, netZoneType); Uri favIconUrlValue = new Uri( string.Format(@"{0}://{1}/wv/resources/1033/FavIcon_Word.ico", transportValue, fakedWOPIClientActionHostName), UriKind.Absolute); Uri urlsrcValueOfTextFile = new Uri( string.Format(@"{0}://{1}/wv/wordviewerframe.aspx?&lt;ui=UI_LLCC&amp;&gt;&lt;rs=DC_LLCC&amp;&gt;&lt;showpagestats=PERFSTATS&amp;&gt;", transportValue, fakedWOPIClientActionHostName), UriKind.Absolute); Uri urlsrcValueOfZipFile = new Uri( string.Format(@"{0}://{1}/wv/zipviewerframe.aspx?&lt;ui=UI_LLCC&amp;&gt;&lt;rs=DC_LLCC&amp;&gt;&lt;showpagestats=PERFSTATS&amp;&gt;", transportValue, fakedWOPIClientActionHostName), UriKind.Absolute); Uri urlsrcValueOfUsingprogid = new Uri( string.Format(@"{0}://{1}/o/onenoteframe.aspx?edit=0&amp;&lt;ui=UI_LLCC&amp;&gt;&lt;rs=DC_LLCC&amp;&gt;&lt;showpagestats=PERFSTATS&amp;&gt;", transportValue, fakedWOPIClientActionHostName), UriKind.Absolute); // Setting netZone's sub element's values ct_appname appElement = new ct_appname(); appElement.name = appName; appElement.favIconUrl = favIconUrlValue.OriginalString; appElement.checkLicense = true; // Action element for txt file ct_wopiaction actionForTextFile = new ct_wopiaction(); actionForTextFile.name = st_wopiactionvalues.view; actionForTextFile.ext = "txt"; actionForTextFile.requires = "containers"; actionForTextFile.@default = true; actionForTextFile.urlsrc = urlsrcValueOfTextFile.OriginalString; // Action element for txt file ct_wopiaction formeditactionForTextFile = new ct_wopiaction(); formeditactionForTextFile.name = st_wopiactionvalues.formedit; formeditactionForTextFile.ext = "txt"; formeditactionForTextFile.@default = true; formeditactionForTextFile.urlsrc = urlsrcValueOfTextFile.OriginalString; ct_wopiaction formViewactionForTextFile = new ct_wopiaction(); formViewactionForTextFile.name = st_wopiactionvalues.formsubmit; formViewactionForTextFile.ext = "txt"; formViewactionForTextFile.@default = true; formViewactionForTextFile.urlsrc = urlsrcValueOfTextFile.OriginalString; // Action element for zip file ct_wopiaction actionForZipFile = new ct_wopiaction(); actionForZipFile.name = st_wopiactionvalues.view; actionForZipFile.ext = "zip"; actionForZipFile.@default = true; actionForZipFile.urlsrc = urlsrcValueOfZipFile.OriginalString; // Action elements for one note. ct_wopiaction actionForOneNote = new ct_wopiaction(); actionForOneNote.name = st_wopiactionvalues.view; actionForOneNote.ext = "one"; actionForOneNote.requires = "cobalt"; actionForOneNote.@default = true; actionForOneNote.urlsrc = urlsrcValueOfUsingprogid.OriginalString; // Action elements for one note. ct_wopiaction actionForOneNoteProg = new ct_wopiaction(); actionForOneNoteProg.name = st_wopiactionvalues.view; actionForOneNoteProg.progid = progIdValue; actionForOneNoteProg.requires = "cobalt,containers"; actionForOneNoteProg.@default = true; actionForOneNoteProg.urlsrc = urlsrcValueOfUsingprogid.OriginalString; // Add action elements into the app element. appElement.action = new ct_wopiaction[] { actionForTextFile, actionForOneNote, actionForZipFile, formeditactionForTextFile, formViewactionForTextFile, actionForOneNoteProg }; // Add app element into the netzone element. ct_netzone netZoneInstance = new ct_netzone(); netZoneInstance.app = new ct_appname[] { appElement }; netZoneInstance.name = netZoneType; netZoneInstance.nameSpecified = true; return netZoneInstance; } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Runtime.Serialization; namespace XenAPI { public partial class HTTP { [Serializable] public class TooManyRedirectsException : Exception { private readonly int redirect; private readonly Uri uri; public TooManyRedirectsException(int redirect, Uri uri) { this.redirect = redirect; this.uri = uri; } public TooManyRedirectsException() : base() { } public TooManyRedirectsException(string message) : base(message) { } public TooManyRedirectsException(string message, Exception exception) : base(message, exception) { } protected TooManyRedirectsException(SerializationInfo info, StreamingContext context) : base(info, context) { redirect = info.GetInt32("redirect"); uri = (Uri)info.GetValue("uri", typeof(Uri)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("redirect", redirect); info.AddValue("uri", uri, typeof(Uri)); base.GetObjectData(info, context); } } [Serializable] public class BadServerResponseException : Exception { public BadServerResponseException() : base() { } public BadServerResponseException(string message) : base(message) { } public BadServerResponseException(string message, Exception exception) : base(message, exception) { } protected BadServerResponseException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class CancelledException : Exception { public CancelledException() : base() { } public CancelledException(string message) : base(message) { } public CancelledException(string message, Exception exception) : base(message, exception) { } protected CancelledException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class ProxyServerAuthenticationException : Exception { public ProxyServerAuthenticationException() : base() { } public ProxyServerAuthenticationException(string message) : base(message) { } public ProxyServerAuthenticationException(string message, Exception exception) : base(message, exception) { } protected ProxyServerAuthenticationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public delegate bool FuncBool(); public delegate void UpdateProgressDelegate(int percent); public delegate void DataCopiedDelegate(long bytes); // Size of byte buffer used for GETs and PUTs // (not the socket rx buffer) public const int BUFFER_SIZE = 32 * 1024; public const int MAX_REDIRECTS = 10; public const int DEFAULT_HTTPS_PORT = 443; public enum ProxyAuthenticationMethod { Basic = 0, Digest = 1 } /// <summary> /// The authentication scheme to use for authenticating to a proxy server. /// Defaults to Digest. /// </summary> public static ProxyAuthenticationMethod CurrentProxyAuthenticationMethod = ProxyAuthenticationMethod.Digest; #region Helper functions private static void WriteLine(String txt, Stream stream) { byte[] bytes = System.Text.Encoding.ASCII.GetBytes(String.Format("{0}\r\n", txt)); stream.Write(bytes, 0, bytes.Length); } private static void WriteLine(Stream stream) { WriteLine("", stream); } // Stream.ReadByte() is used because using StreamReader in its place causes the reading to become stuck, // as it seems the Stream object has trouble recognizing the end of the stream. This seems to be a common // problem, of which a common solution is to read each byte until an EndOfStreamException is thrown, as is // done here. private static string ReadLine(Stream stream) { System.Text.StringBuilder result = new StringBuilder(); while (true) { int b = stream.ReadByte(); if (b == -1) throw new EndOfStreamException(); char c = Convert.ToChar(b); result.Append(c); if (c == '\n') return result.ToString(); } } /// <summary> /// Read HTTP headers, doing any redirects as necessary /// </summary> /// <param name="stream"></param> /// <returns>True if a redirect has occurred - headers will need to be resent.</returns> private static bool ReadHttpHeaders(ref Stream stream, IWebProxy proxy, bool nodelay, int timeout_ms, List<string> headers = null) { // read headers/fields string line = ReadLine(stream), initialLine = line, transferEncodingField = null; if (string.IsNullOrEmpty(initialLine)) // sanity check return false; if (headers == null) headers = new List<string>(); while (!string.IsNullOrWhiteSpace(line)) // IsNullOrWhiteSpace also checks for empty string { line = line.TrimEnd('\r', '\n'); headers.Add(line); if (line == "Transfer-Encoding: Chunked") transferEncodingField = line; line = ReadLine(stream); } // read chunks string entityBody = ""; if (!string.IsNullOrEmpty(transferEncodingField)) { int lastChunkSize = -1; do { // read chunk size string chunkSizeStr = ReadLine(stream); chunkSizeStr = chunkSizeStr.TrimEnd('\r', '\n'); int chunkSize = 0; int.TryParse(chunkSizeStr, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture, out chunkSize); // read <chunkSize> number of bytes from the stream int totalNumberOfBytesRead = 0; int numberOfBytesRead; byte[] bytes = new byte[chunkSize]; do { numberOfBytesRead = stream.Read(bytes, totalNumberOfBytesRead, chunkSize - totalNumberOfBytesRead); totalNumberOfBytesRead += numberOfBytesRead; } while (numberOfBytesRead > 0 && totalNumberOfBytesRead < chunkSize); string str = System.Text.Encoding.ASCII.GetString(bytes); string[] split = str.Split(new string[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries); headers.AddRange(split); entityBody += str; line = ReadLine(stream); // empty line in the end of chunk lastChunkSize = chunkSize; } while (lastChunkSize != 0); entityBody = entityBody.TrimEnd('\r', '\n'); headers.Add(entityBody); // keep entityBody if it's needed for Digest authentication (when qop="auth-int") } else { // todo: handle other transfer types, in case "Transfer-Encoding: Chunked" isn't used } // handle server response int code = getResultCode(initialLine); switch (code) { case 407: // authentication error; caller must handle this case case 200: break; case 302: string url = ""; foreach (string header in headers) { if (header.StartsWith("Location: ")) { url = header.Substring(10); break; } } Uri redirect = new Uri(url.Trim()); stream.Close(); stream = ConnectStream(redirect, proxy, nodelay, timeout_ms); return true; // headers need to be sent again default: stream.Close(); throw new BadServerResponseException(string.Format("Received error code {0} from the server", initialLine)); } return false; } private static int getResultCode(string line) { string[] bits = line.Split(new char[] { ' ' }); return (bits.Length < 2 ? 0 : Int32.Parse(bits[1])); } public static bool UseSSL(Uri uri) { return uri.Scheme == "https" || uri.Port == DEFAULT_HTTPS_PORT; } private static bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } /// <summary> /// Returns a secure MD5 hash of the given input string. /// </summary> /// <param name="str">The string to hash.</param> /// <returns>The secure hash as a hex string.</returns> public static string MD5Hash(string str) { MD5 hasher = MD5.Create(); ASCIIEncoding enc = new ASCIIEncoding(); byte[] bytes = enc.GetBytes(str); byte[] hash = hasher.ComputeHash(bytes); return BitConverter.ToString(hash).Replace("-", "").ToLower(); } public static long CopyStream(Stream inStream, Stream outStream, DataCopiedDelegate progressDelegate, FuncBool cancellingDelegate) { long bytesWritten = 0; byte[] buffer = new byte[BUFFER_SIZE]; DateTime lastUpdate = DateTime.Now; while (cancellingDelegate == null || !cancellingDelegate()) { int bytesRead = inStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) break; outStream.Write(buffer, 0, bytesRead); bytesWritten += bytesRead; if (progressDelegate != null && DateTime.Now - lastUpdate > TimeSpan.FromMilliseconds(500)) { progressDelegate(bytesWritten); lastUpdate = DateTime.Now; } } if (cancellingDelegate != null && cancellingDelegate()) throw new CancelledException(); if (progressDelegate != null) progressDelegate(bytesWritten); return bytesWritten; } /// <summary> /// Build a URI from a hostname, a path, and some query arguments /// </summary> /// <param name="args">An even-length array, alternating argument names and values</param> /// <returns></returns> public static Uri BuildUri(string hostname, string path, params object[] args) { // The last argument may be an object[] in its own right, in which case we need // to flatten the array. List<object> flatargs = new List<object>(); foreach (object arg in args) { if (arg is IEnumerable<object>) flatargs.AddRange((IEnumerable<object>)arg); else flatargs.Add(arg); } UriBuilder uri = new UriBuilder(); uri.Scheme = "https"; uri.Port = DEFAULT_HTTPS_PORT; uri.Host = hostname; uri.Path = path; StringBuilder query = new StringBuilder(); for (int i = 0; i < flatargs.Count - 1; i += 2) { string kv; // If the argument is null, don't include it in the URL if (flatargs[i + 1] == null) continue; // bools are special because some xapi calls use presence/absence and some // use "b=true" (not "True") and "b=false". But all accept "b=true" or absent. if (flatargs[i + 1] is bool) { if (!((bool)flatargs[i + 1])) continue; kv = flatargs[i] + "=true"; } else kv = flatargs[i] + "=" + Uri.EscapeDataString(flatargs[i + 1].ToString()); if (query.Length != 0) query.Append('&'); query.Append(kv); } uri.Query = query.ToString(); return uri.Uri; } private static string GetPartOrNull(string str, int partIndex) { string[] parts = str.Split(new char[] { ' ' }, partIndex + 2, StringSplitOptions.RemoveEmptyEntries); return partIndex < parts.Length - 1 ? parts[partIndex] : null; } #endregion private static NetworkStream ConnectSocket(Uri uri, bool nodelay, int timeout_ms) { AddressFamily addressFamily = uri.HostNameType == UriHostNameType.IPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; Socket socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); socket.NoDelay = nodelay; //socket.ReceiveBufferSize = 64 * 1024; socket.ReceiveTimeout = timeout_ms; socket.SendTimeout = timeout_ms; socket.Connect(uri.Host, uri.Port); return new NetworkStream(socket, true); } /// <summary> /// This function will connect a stream to a uri (host and port), /// negotiating proxies and SSL /// </summary> /// <param name="uri"></param> /// <param name="timeout_ms">Timeout, in ms. 0 for no timeout.</param> /// <returns></returns> public static Stream ConnectStream(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms) { IMockWebProxy mockProxy = proxy != null ? proxy as IMockWebProxy : null; if (mockProxy != null) return mockProxy.GetStream(uri); Stream stream; bool useProxy = proxy != null && !proxy.IsBypassed(uri); if (useProxy) { Uri proxyURI = proxy.GetProxy(uri); stream = ConnectSocket(proxyURI, nodelay, timeout_ms); } else { stream = ConnectSocket(uri, nodelay, timeout_ms); } try { if (useProxy) { string line = String.Format("CONNECT {0}:{1} HTTP/1.0", uri.Host, uri.Port); WriteLine(line, stream); WriteLine(stream); List<string> initialResponse = new List<string>(); ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms, initialResponse); AuthenticateProxy(ref stream, uri, proxy, nodelay, timeout_ms, initialResponse, line); } if (UseSSL(uri)) { SslStream sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient("", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, true); stream = sslStream; } return stream; } catch { stream.Close(); throw; } } private static void AuthenticateProxy(ref Stream stream, Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms, List<string> initialResponse, string header) { // perform authentication only if proxy requires it List<string> fields = initialResponse.FindAll(str => str.StartsWith("Proxy-Authenticate:")); if (fields.Count > 0) { // clean up (if initial server response specifies "Proxy-Connection: Close" then stream cannot be re-used) string field = initialResponse.Find(str => str.StartsWith("Proxy-Connection: Close", StringComparison.CurrentCultureIgnoreCase)); if (!string.IsNullOrEmpty(field)) { stream.Close(); Uri proxyURI = proxy.GetProxy(uri); stream = ConnectSocket(proxyURI, nodelay, timeout_ms); } if (proxy.Credentials == null) throw new BadServerResponseException(string.Format("Received error code {0} from the server", initialResponse[0])); NetworkCredential credentials = proxy.Credentials.GetCredential(uri, null); string basicField = fields.Find(str => str.StartsWith("Proxy-Authenticate: Basic")); string digestField = fields.Find(str => str.StartsWith("Proxy-Authenticate: Digest")); if (CurrentProxyAuthenticationMethod == ProxyAuthenticationMethod.Basic) { if (string.IsNullOrEmpty(basicField)) throw new ProxyServerAuthenticationException("Basic authentication scheme is not supported/enabled by the proxy server."); string authenticationFieldReply = string.Format("Proxy-Authorization: Basic {0}", Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials.UserName + ":" + credentials.Password))); WriteLine(header, stream); WriteLine(authenticationFieldReply, stream); WriteLine(stream); } else if (CurrentProxyAuthenticationMethod == ProxyAuthenticationMethod.Digest) { if (string.IsNullOrEmpty(digestField)) throw new ProxyServerAuthenticationException("Digest authentication scheme is not supported/enabled by the proxy server."); string authenticationFieldReply = string.Format( "Proxy-Authorization: Digest username=\"{0}\", uri=\"{1}:{2}\"", credentials.UserName, uri.Host, uri.Port); string directiveString = digestField.Substring(27, digestField.Length - 27); string[] directives = directiveString.Split(new string[] { ", ", "\"" }, StringSplitOptions.RemoveEmptyEntries); string algorithm = null; // optional string opaque = null; // optional string qop = null; // optional string realm = null; string nonce = null; for (int i = 0; i < directives.Length; ++i) { switch (directives[i]) { case "stale=": if (directives[++i].ToLower() == "true") throw new ProxyServerAuthenticationException("Stale nonce in Digest authentication attempt."); break; case "realm=": authenticationFieldReply += string.Format(", {0}\"{1}\"", directives[i], directives[++i]); realm = directives[i]; break; case "nonce=": authenticationFieldReply += string.Format(", {0}\"{1}\"", directives[i], directives[++i]); nonce = directives[i]; break; case "opaque=": authenticationFieldReply += string.Format(", {0}\"{1}\"", directives[i], directives[++i]); opaque = directives[i]; break; case "algorithm=": authenticationFieldReply += string.Format(", {0}\"{1}\"", directives[i], directives[++i]); algorithm = directives[i]; break; case "qop=": List<string> qops = new List<string>(directives[++i].Split(new char[] { ',' })); if (qops.Count > 0) { if (qops.Contains("auth")) qop = "auth"; else if (qops.Contains("auth-int")) qop = "auth-int"; else throw new ProxyServerAuthenticationException( "Digest authentication's quality-of-protection directive of is not supported."); authenticationFieldReply += string.Format(", qop=\"{0}\"", qop); } break; default: break; } } string clientNonce = "X3nC3nt3r"; // todo: generate random string if (qop != null) authenticationFieldReply += string.Format(", cnonce=\"{0}\"", clientNonce); string nonceCount = "00000001"; // todo: track nonces and their corresponding nonce counts if (qop != null) authenticationFieldReply += string.Format(", nc={0}", nonceCount); string HA1 = ""; string scratch = string.Format("{0}:{1}:{2}", credentials.UserName, realm, credentials.Password); if (algorithm == null || algorithm == "MD5") HA1 = MD5Hash(scratch); else HA1 = MD5Hash(string.Format("{0}:{1}:{2}", MD5Hash(scratch), nonce, clientNonce)); string HA2 = ""; scratch = GetPartOrNull(header, 0); scratch = string.Format("{0}:{1}:{2}", scratch ?? "CONNECT", uri.Host, uri.Port); if (qop == null || qop == "auth") HA2 = MD5Hash(scratch); else { string entityBody = initialResponse[initialResponse.Count - 1]; // entity body should have been stored as last element of initialResponse string str = string.Format("{0}:{1}", scratch, MD5Hash(entityBody)); HA2 = MD5Hash(str); } string response = ""; if (qop == null) response = MD5Hash(string.Format("{0}:{1}:{2}", HA1, nonce, HA2)); else response = MD5Hash(string.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, nonce, nonceCount, clientNonce, qop, HA2)); authenticationFieldReply += string.Format(", response=\"{0}\"", response); WriteLine(header, stream); WriteLine(authenticationFieldReply, stream); WriteLine(stream); } else { string authType = GetPartOrNull(fields[0], 1); throw new ProxyServerAuthenticationException( string.Format("Proxy server's {0} authentication method is not supported.", authType ?? "chosen")); } // handle authentication attempt response List<string> authenticatedResponse = new List<string>(); ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms, authenticatedResponse); if (authenticatedResponse.Count == 0) throw new BadServerResponseException("No response from the proxy server after authentication attempt."); switch (getResultCode(authenticatedResponse[0])) { case 200: break; case 407: throw new ProxyServerAuthenticationException("Proxy server denied access due to wrong credentials."); default: throw new BadServerResponseException(string.Format( "Received error code {0} from the server", authenticatedResponse[0])); } } } private static Stream DO_HTTP(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms, params string[] headers) { Stream stream = ConnectStream(uri, proxy, nodelay, timeout_ms); int redirects = 0; do { if (redirects > MAX_REDIRECTS) throw new TooManyRedirectsException(redirects, uri); redirects++; foreach (string header in headers) WriteLine(header, stream); WriteLine(stream); stream.Flush(); } while (ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms)); return stream; } // // The following functions do all the HTTP headers related stuff // returning the stream ready for use // public static Stream CONNECT(Uri uri, IWebProxy proxy, String session, int timeout_ms) { return DO_HTTP(uri, proxy, true, timeout_ms, string.Format("CONNECT {0} HTTP/1.0", uri.PathAndQuery), string.Format("Host: {0}", uri.Host), string.Format("Cookie: session_id={0}", session)); } public static Stream PUT(Uri uri, IWebProxy proxy, long ContentLength, int timeout_ms) { return DO_HTTP(uri, proxy, false, timeout_ms, string.Format("PUT {0} HTTP/1.0", uri.PathAndQuery), string.Format("Host: {0}", uri.Host), string.Format("Content-Length: {0}", ContentLength)); } public static Stream GET(Uri uri, IWebProxy proxy, int timeout_ms) { return DO_HTTP(uri, proxy, false, timeout_ms, string.Format("GET {0} HTTP/1.0", uri.PathAndQuery), string.Format("Host: {0}", uri.Host)); } /// <summary> /// A general HTTP PUT method, with delegates for progress and cancelling. May throw various exceptions. /// </summary> /// <param name="progressDelegate">Delegate called periodically (500ms) with percent complete</param> /// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param> /// <param name="uri">URI to PUT to</param> /// <param name="proxy">A proxy to handle the HTTP connection</param> /// <param name="path">Path to file to put</param> /// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param> public static void Put(UpdateProgressDelegate progressDelegate, FuncBool cancellingDelegate, Uri uri, IWebProxy proxy, string path, int timeout_ms) { using (Stream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read), requestStream = PUT(uri, proxy, fileStream.Length, timeout_ms)) { long len = fileStream.Length; DataCopiedDelegate dataCopiedDelegate = delegate(long bytes) { if (progressDelegate != null && len > 0) progressDelegate((int)((bytes * 100) / len)); }; CopyStream(fileStream, requestStream, dataCopiedDelegate, cancellingDelegate); } } /// <summary> /// A general HTTP GET method, with delegates for progress and cancelling. May throw various exceptions. /// </summary> /// <param name="dataRxDelegate">Delegate called periodically (500 ms) with the number of bytes transferred</param> /// <param name="cancellingDelegate">Delegate called periodically to see if need to cancel</param> /// <param name="uri">URI to GET from</param> /// <param name="proxy">A proxy to handle the HTTP connection</param> /// <param name="path">Path to file to receive the data</param> /// <param name="timeout_ms">Timeout for the connection in ms. 0 for no timeout.</param> public static void Get(DataCopiedDelegate dataCopiedDelegate, FuncBool cancellingDelegate, Uri uri, IWebProxy proxy, string path, int timeout_ms) { string tmpFile = Path.GetTempFileName(); try { using (Stream fileStream = new FileStream(tmpFile, FileMode.Create, FileAccess.Write, FileShare.None), downloadStream = GET(uri, proxy, timeout_ms)) { CopyStream(downloadStream, fileStream, dataCopiedDelegate, cancellingDelegate); fileStream.Flush(); } File.Delete(path); File.Move(tmpFile, path); } finally { File.Delete(tmpFile); } } } }
using System.Linq; using System.Threading.Tasks; using OmniSharp.Models; using OmniSharp.Roslyn.CSharp.Services.Signatures; using OmniSharp.Tests; using Xunit; namespace OmniSharp.Roslyn.CSharp.Tests { public class SignatureHelpFacts { [Fact] public async Task NoInvocationNoHelp() { var source = @"class Program { public static void Ma$in(){ System.Guid.NoSuchMethod(); } }"; var actual = await GetSignatureHelp(source); Assert.Null(actual); source = @"class Program { public static void Main(){ System.Gu$id.NoSuchMethod(); } }"; actual = await GetSignatureHelp(source); Assert.Null(actual); source = @"class Program { public static void Main(){ System.Guid.NoSuchMethod()$; } }"; actual = await GetSignatureHelp(source); Assert.Null(actual); } [Fact] public async Task NoTypeNoHelp() { var source = @"class Program { public static void Main(){ System.Guid.Foo$Bar(); } }"; var actual = await GetSignatureHelp(source); Assert.Null(actual); } [Fact] public async Task NoMethodNoHelp() { var source = @"class Program { public static void Main(){ System.Gu$id; } }"; var actual = await GetSignatureHelp(source); Assert.Null(actual); } [Fact] public async Task SimpleSignatureHelp() { var source = @"class Program { public static void Main(){ System.Guid.NewGuid($); } }"; var actual = await GetSignatureHelp(source); Assert.Equal(1, actual.Signatures.Count()); Assert.Equal(0, actual.ActiveParameter); Assert.Equal(0, actual.ActiveSignature); Assert.Equal("NewGuid", actual.Signatures.ElementAt(0).Name); Assert.Equal(0, actual.Signatures.ElementAt(0).Parameters.Count()); } [Fact] public async Task TestForParameterLabels() { var source = @"class Program { public static void Main(){ Foo($); } pubic static Foo(bool b, int n = 1234) { } }"; var actual = await GetSignatureHelp(source); Assert.Equal(1, actual.Signatures.Count()); Assert.Equal(0, actual.ActiveParameter); Assert.Equal(0, actual.ActiveSignature); var signature = actual.Signatures.ElementAt(0); Assert.Equal(2, signature.Parameters.Count()); Assert.Equal("b", signature.Parameters.ElementAt(0).Name); Assert.Equal("bool b", signature.Parameters.ElementAt(0).Label); Assert.Equal("n", signature.Parameters.ElementAt(1).Name); Assert.Equal("int n = 1234", signature.Parameters.ElementAt(1).Label); } [Fact] public async Task ActiveParameterIsBasedOnComma() { // 1st position, a var source = @"class Program { public static void Main(){ new Program().Foo(1$2, } /// foo1 private int Foo(int one, int two, int three) { return 3; } }"; var actual = await GetSignatureHelp(source); Assert.Equal(0, actual.ActiveParameter); // 1st position, b source = @"class Program { public static void Main(){ new Program().Foo(12 $) } /// foo1 private int Foo(int one, int two, int three) { return 3; } }"; actual = await GetSignatureHelp(source); Assert.Equal(0, actual.ActiveParameter); // 2nd position, a source = @"class Program { public static void Main(){ new Program().Foo(12, $ } /// foo1 private int Foo(int one, int two, int three) { return 3; } }"; actual = await GetSignatureHelp(source); Assert.Equal(1, actual.ActiveParameter); // 2nd position, b source = @"class Program { public static void Main(){ new Program().Foo(12, 1$ } /// foo1 private int Foo(int one, int two, int three) { return 3; } }"; actual = await GetSignatureHelp(source); Assert.Equal(1, actual.ActiveParameter); // 3rd position, a source = @"class Program { public static void Main(){ new Program().Foo(12, 1, $ } /// foo1 private int Foo(int one, int two, int three) { return 3; } }"; actual = await GetSignatureHelp(source); Assert.Equal(2, actual.ActiveParameter); } [Fact] public async Task ActiveSignatureIsBasedOnTypes() { var source = @"class Program { public static void Main(){ new Program().Foo(12, $ } /// foo1 private int Foo() { return 3; } /// foo2 private int Foo(int m, int n) { return m * Foo() * n; } /// foo3 private int Foo(string m, int n) { return Foo(m.length, n); } }"; var actual = await GetSignatureHelp(source); Assert.Equal(3, actual.Signatures.Count()); Assert.True(actual.Signatures.ElementAt(actual.ActiveSignature).Documentation.Contains("foo2")); source = @"class Program { public static void Main(){ new Program().Foo(""d"", $ } /// foo1 private int Foo() { return 3; } /// foo2 private int Foo(int m, int n) { return m * Foo() * n; } /// foo3 private int Foo(string m, int n) { return Foo(m.length, n); } }"; actual = await GetSignatureHelp(source); Assert.Equal(3, actual.Signatures.Count()); Assert.True(actual.Signatures.ElementAt(actual.ActiveSignature).Documentation.Contains("foo3")); source = @"class Program { public static void Main(){ new Program().Foo($) } /// foo1 private int Foo() { return 3; } /// foo2 private int Foo(int m, int n) { return m * Foo() * n; } /// foo3 private int Foo(string m, int n) { return Foo(m.length, n); } }"; actual = await GetSignatureHelp(source); Assert.Equal(3, actual.Signatures.Count()); Assert.True(actual.Signatures.ElementAt(actual.ActiveSignature).Documentation.Contains("foo1")); } [Fact] public async Task SigantureHelpForCtor() { var source = @"class Program { public static void Main() { new Program($) } public Program() { } public Program(bool b) { } public Program(Program p) { } }"; var actual = await GetSignatureHelp(source); Assert.Equal(3, actual.Signatures.Count()); } [Fact] public async Task SigantureHelpForCtorWithOverloads() { var source = @"class Program { public static void Main() { new Program(true, 12$3) } public Program() { } /// ctor2 public Program(bool b, int n) { } public Program(Program p, int n) { } }"; var actual = await GetSignatureHelp(source); Assert.Equal(3, actual.Signatures.Count()); Assert.Equal(1, actual.ActiveParameter); Assert.True(actual.Signatures.ElementAt(actual.ActiveSignature).Documentation.Contains("ctor2")); } [Fact] public async Task SkipReceiverOfExtensionMethods() { var source = @"class Program { public static void Main() { new Program().B($); } public Program() { } public bool B(this Program p, int n) { return p.Foo() > n; } }"; var actual = await GetSignatureHelp(source); Assert.Equal(1, actual.Signatures.Count()); Assert.Equal(1, actual.Signatures.ElementAt(actual.ActiveSignature).Parameters.Count()); Assert.Equal("n", actual.Signatures.ElementAt(actual.ActiveSignature).Parameters.ElementAt(0).Name); } private async Task<SignatureHelp> GetSignatureHelp(string source) { var lineColumn = TestHelpers.GetLineAndColumnFromDollar(source); source = source.Replace("$", string.Empty); var request = new SignatureHelpRequest() { FileName = "dummy.cs", Line = lineColumn.Line, Column = lineColumn.Column, Buffer = source }; var workspace = await TestHelpers.CreateSimpleWorkspace(source); var controller = new SignatureHelpService(workspace); return await controller.Handle(request); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Caching; using osu.Framework.Layout; using osuTK; namespace osu.Framework.Graphics.Containers { /// <summary> /// A container which allows laying out <see cref="Drawable"/>s in a grid. /// </summary> public class GridContainer : CompositeDrawable { public GridContainer() { AddLayout(cellLayout); AddLayout(cellChildLayout); } [BackgroundDependencyLoader] private void load() { layoutContent(); } private GridContainerContent content; /// <summary> /// The content of this <see cref="GridContainer"/>, arranged in a 2D grid array, where each array /// of <see cref="Drawable"/>s represents a row and each element of that array represents a column. /// <para> /// Null elements are allowed to represent blank rows/cells. /// </para> /// </summary> public GridContainerContent Content { get => content; set { if (content?.Equals(value) == true) return; if (content != null) content.ArrayElementChanged -= onContentChange; content = value; onContentChange(); if (content != null) content.ArrayElementChanged += onContentChange; } } private void onContentChange() { cellContent.Invalidate(); } private Dimension[] rowDimensions = Array.Empty<Dimension>(); /// <summary> /// Explicit dimensions for rows. Each index of this array applies to the respective row index inside <see cref="Content"/>. /// </summary> public Dimension[] RowDimensions { set { if (value == null) throw new ArgumentNullException(nameof(RowDimensions)); if (rowDimensions == value) return; rowDimensions = value; cellLayout.Invalidate(); } } private Dimension[] columnDimensions = Array.Empty<Dimension>(); /// <summary> /// Explicit dimensions for columns. Each index of this array applies to the respective column index inside <see cref="Content"/>. /// </summary> public Dimension[] ColumnDimensions { set { if (value == null) throw new ArgumentNullException(nameof(ColumnDimensions)); if (columnDimensions == value) return; columnDimensions = value; cellLayout.Invalidate(); } } /// <summary> /// Controls which <see cref="Axes"/> are automatically sized w.r.t. <see cref="CompositeDrawable.InternalChildren"/>. /// Children's <see cref="Drawable.BypassAutoSizeAxes"/> are ignored for automatic sizing. /// Most notably, <see cref="Drawable.RelativePositionAxes"/> and <see cref="Drawable.RelativeSizeAxes"/> of children /// do not affect automatic sizing to avoid circular size dependencies. /// It is not allowed to manually set <see cref="Drawable.Size"/> (or <see cref="Drawable.Width"/> / <see cref="Drawable.Height"/>) /// on any <see cref="Axes"/> which are automatically sized. /// </summary> public new Axes AutoSizeAxes { get => base.AutoSizeAxes; set => base.AutoSizeAxes = value; } protected override void Update() { base.Update(); layoutContent(); layoutCells(); } private readonly Cached cellContent = new Cached(); private readonly LayoutValue cellLayout = new LayoutValue(Invalidation.DrawInfo | Invalidation.RequiredParentSizeToFit); private readonly LayoutValue cellChildLayout = new LayoutValue(Invalidation.RequiredParentSizeToFit | Invalidation.Presence, InvalidationSource.Child); private CellContainer[,] cells = new CellContainer[0, 0]; private int cellRows => cells.GetLength(0); private int cellColumns => cells.GetLength(1); /// <summary> /// Moves content from <see cref="Content"/> into cells. /// </summary> private void layoutContent() { if (cellContent.IsValid) return; int requiredRows = Content?.Count ?? 0; int requiredColumns = requiredRows == 0 ? 0 : Content?.Max(c => c?.Count ?? 0) ?? 0; // Clear cell containers without disposing, as the content might be reused foreach (var cell in cells) cell.Clear(false); // It's easier to just re-construct the cell containers instead of resizing // If this becomes a bottleneck we can transition to using lists, but this keeps the structure clean... ClearInternal(); cellLayout.Invalidate(); // Create the new cell containers and add content cells = new CellContainer[requiredRows, requiredColumns]; for (int r = 0; r < cellRows; r++) { for (int c = 0; c < cellColumns; c++) { // Add cell cells[r, c] = new CellContainer(); // Allow empty rows if (Content[r] == null) continue; // Allow non-square grids if (c >= Content[r].Count) continue; // Allow empty cells if (Content[r][c] == null) continue; // Add content cells[r, c].Add(Content[r][c]); cells[r, c].Depth = Content[r][c].Depth; AddInternal(cells[r, c]); } } cellContent.Validate(); } /// <summary> /// Repositions/resizes cells. /// </summary> private void layoutCells() { if (!cellChildLayout.IsValid) { cellLayout.Invalidate(); cellChildLayout.Validate(); } if (cellLayout.IsValid) return; var widths = distribute(columnDimensions, DrawWidth, getCellSizesAlongAxis(Axes.X, DrawWidth)); var heights = distribute(rowDimensions, DrawHeight, getCellSizesAlongAxis(Axes.Y, DrawHeight)); for (int col = 0; col < cellColumns; col++) { for (int row = 0; row < cellRows; row++) { cells[row, col].Size = new Vector2(widths[col], heights[row]); if (col > 0) cells[row, col].X = cells[row, col - 1].X + cells[row, col - 1].Width; if (row > 0) cells[row, col].Y = cells[row - 1, col].Y + cells[row - 1, col].Height; } } cellLayout.Validate(); } /// <summary> /// Retrieves the size of all cells along the span of an axis. /// For the X-axis, this retrieves the size of all columns. /// For the Y-axis, this retrieves the size of all rows. /// </summary> /// <param name="axis">The axis span.</param> /// <param name="spanLength">The absolute length of the span.</param> /// <returns>The size of all cells along the span of <paramref name="axis"/>.</returns> /// <exception cref="InvalidOperationException">If the <see cref="Dimension"/> for a cell is unsupported.</exception> private float[] getCellSizesAlongAxis(Axes axis, float spanLength) { var spanDimensions = axis == Axes.X ? columnDimensions : rowDimensions; int spanCount = axis == Axes.X ? cellColumns : cellRows; var sizes = new float[spanCount]; for (int i = 0; i < spanCount; i++) { if (i >= spanDimensions.Length) break; var dimension = spanDimensions[i]; switch (dimension.Mode) { default: throw new InvalidOperationException($"Unsupported dimension: {dimension.Mode}."); case GridSizeMode.Distributed: break; case GridSizeMode.Relative: sizes[i] = dimension.Size * spanLength; break; case GridSizeMode.Absolute: sizes[i] = dimension.Size; break; case GridSizeMode.AutoSize: float size = 0; if (axis == Axes.X) { // Go through each row and get the width of the cell at the indexed column for (int r = 0; r < cellRows; r++) size = Math.Max(size, getCellWidth(Content[r]?[i])); } else { // Go through each column and get the height of the cell at the indexed row for (int c = 0; c < cellColumns; c++) size = Math.Max(size, getCellHeight(Content[i]?[c])); } sizes[i] = size; break; } sizes[i] = Math.Clamp(sizes[i], dimension.MinSize, dimension.MaxSize); } return sizes; } private static bool shouldConsiderCell(Drawable cell) => cell != null && cell.IsAlive && cell.IsPresent; private static float getCellWidth(Drawable cell) => shouldConsiderCell(cell) ? cell.BoundingBox.Width : 0; private static float getCellHeight(Drawable cell) => shouldConsiderCell(cell) ? cell.BoundingBox.Height : 0; /// <summary> /// Distributes any available length along all distributed dimensions, if required. /// </summary> /// <param name="dimensions">The full dimensions of the row or column.</param> /// <param name="spanLength">The total available length.</param> /// <param name="cellSizes">An array containing pre-filled sizes of any non-distributed cells. This array will be mutated.</param> /// <returns><paramref name="cellSizes"/>.</returns> private float[] distribute(Dimension[] dimensions, float spanLength, float[] cellSizes) { // Indices of all distributed cells int[] distributedIndices = Enumerable.Range(0, cellSizes.Length).Where(i => i >= dimensions.Length || dimensions[i].Mode == GridSizeMode.Distributed).ToArray(); // The dimensions corresponding to all distributed cells IEnumerable<(int i, Dimension dim)> distributedDimensions = distributedIndices.Select(i => (i, i >= dimensions.Length ? new Dimension() : dimensions[i])); // Total number of distributed cells int distributionCount = distributedIndices.Length; // Non-distributed size float requiredSize = cellSizes.Sum(); // Distribution size for _each_ distributed cell float distributionSize = Math.Max(0, spanLength - requiredSize) / distributionCount; // Write the sizes of distributed cells. Ordering is important to maximize excess at every step foreach (var (i, dim) in distributedDimensions.OrderBy(d => d.dim.Range)) { // Cells start off at their minimum size, and the total size should not exceed their maximum size cellSizes[i] = Math.Min(dim.MaxSize, dim.MinSize + distributionSize); // If there's no excess, any further distributions are guaranteed to also have no excess, so this becomes a null-op // If there is an excess, the excess should be re-distributed among all other n-1 distributed cells if (--distributionCount > 0) distributionSize += Math.Max(0, distributionSize - dim.Range) / distributionCount; } return cellSizes; } /// <summary> /// Represents one cell of the <see cref="GridContainer"/>. /// </summary> private class CellContainer : Container { protected override bool OnInvalidate(Invalidation invalidation, InvalidationSource source) { var result = base.OnInvalidate(invalidation, source); if (source == InvalidationSource.Child && (invalidation & (Invalidation.RequiredParentSizeToFit | Invalidation.Presence)) > 0) result |= Parent?.Invalidate(invalidation, InvalidationSource.Child) ?? false; return result; } } } /// <summary> /// Defines the size of a row or column in a <see cref="GridContainer"/>. /// </summary> public class Dimension { /// <summary> /// The mode in which this row or column <see cref="GridContainer"/> is sized. /// </summary> public readonly GridSizeMode Mode; /// <summary> /// The size of the row or column which this <see cref="Dimension"/> applies to. /// Only has an effect if <see cref="Mode"/> is not <see cref="GridSizeMode.Distributed"/>. /// </summary> public readonly float Size; /// <summary> /// The minimum size of the row or column which this <see cref="Dimension"/> applies to. /// </summary> public readonly float MinSize; /// <summary> /// The maximum size of the row or column which this <see cref="Dimension"/> applies to. /// </summary> public readonly float MaxSize; /// <summary> /// Constructs a new <see cref="Dimension"/>. /// </summary> /// <param name="mode">The sizing mode to use.</param> /// <param name="size">The size of this row or column. This only has an effect if <paramref name="mode"/> is not <see cref="GridSizeMode.Distributed"/>.</param> /// <param name="minSize">The minimum size of this row or column.</param> /// <param name="maxSize">The maximum size of this row or column.</param> public Dimension(GridSizeMode mode = GridSizeMode.Distributed, float size = 0, float minSize = 0, float maxSize = float.MaxValue) { if (minSize < 0) throw new ArgumentOutOfRangeException(nameof(minSize), "Must be greater than 0."); if (minSize > maxSize) throw new ArgumentOutOfRangeException(nameof(minSize), $"Must be less than {nameof(maxSize)}."); Mode = mode; Size = size; MinSize = minSize; MaxSize = maxSize; } /// <summary> /// The range of the size of this <see cref="Dimension"/>. /// </summary> internal float Range => MaxSize - MinSize; } public enum GridSizeMode { /// <summary> /// Any remaining area of the <see cref="GridContainer"/> will be divided amongst this and all /// other elements which use <see cref="GridSizeMode.Distributed"/>. /// </summary> Distributed, /// <summary> /// This element should be sized relative to the dimensions of the <see cref="GridContainer"/>. /// </summary> Relative, /// <summary> /// This element has a size independent of the <see cref="GridContainer"/>. /// </summary> Absolute, /// <summary> /// This element will be sized to the maximum size along its span. /// </summary> AutoSize } }
// 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 gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="FeedPlaceholderViewServiceClient"/> instances.</summary> public sealed partial class FeedPlaceholderViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="FeedPlaceholderViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="FeedPlaceholderViewServiceSettings"/>.</returns> public static FeedPlaceholderViewServiceSettings GetDefault() => new FeedPlaceholderViewServiceSettings(); /// <summary> /// Constructs a new <see cref="FeedPlaceholderViewServiceSettings"/> object with default settings. /// </summary> public FeedPlaceholderViewServiceSettings() { } private FeedPlaceholderViewServiceSettings(FeedPlaceholderViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetFeedPlaceholderViewSettings = existing.GetFeedPlaceholderViewSettings; OnCopy(existing); } partial void OnCopy(FeedPlaceholderViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeedPlaceholderViewServiceClient.GetFeedPlaceholderView</c> and /// <c>FeedPlaceholderViewServiceClient.GetFeedPlaceholderViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetFeedPlaceholderViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="FeedPlaceholderViewServiceSettings"/> object.</returns> public FeedPlaceholderViewServiceSettings Clone() => new FeedPlaceholderViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="FeedPlaceholderViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class FeedPlaceholderViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeedPlaceholderViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public FeedPlaceholderViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public FeedPlaceholderViewServiceClientBuilder() { UseJwtAccessWithScopes = FeedPlaceholderViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref FeedPlaceholderViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeedPlaceholderViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override FeedPlaceholderViewServiceClient Build() { FeedPlaceholderViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<FeedPlaceholderViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<FeedPlaceholderViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private FeedPlaceholderViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return FeedPlaceholderViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<FeedPlaceholderViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return FeedPlaceholderViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => FeedPlaceholderViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeedPlaceholderViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => FeedPlaceholderViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>FeedPlaceholderViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch feed placeholder views. /// </remarks> public abstract partial class FeedPlaceholderViewServiceClient { /// <summary> /// The default endpoint for the FeedPlaceholderViewService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default FeedPlaceholderViewService scopes.</summary> /// <remarks> /// The default FeedPlaceholderViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="FeedPlaceholderViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="FeedPlaceholderViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="FeedPlaceholderViewServiceClient"/>.</returns> public static stt::Task<FeedPlaceholderViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new FeedPlaceholderViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="FeedPlaceholderViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="FeedPlaceholderViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="FeedPlaceholderViewServiceClient"/>.</returns> public static FeedPlaceholderViewServiceClient Create() => new FeedPlaceholderViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="FeedPlaceholderViewServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="FeedPlaceholderViewServiceSettings"/>.</param> /// <returns>The created <see cref="FeedPlaceholderViewServiceClient"/>.</returns> internal static FeedPlaceholderViewServiceClient Create(grpccore::CallInvoker callInvoker, FeedPlaceholderViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } FeedPlaceholderViewService.FeedPlaceholderViewServiceClient grpcClient = new FeedPlaceholderViewService.FeedPlaceholderViewServiceClient(callInvoker); return new FeedPlaceholderViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC FeedPlaceholderViewService client</summary> public virtual FeedPlaceholderViewService.FeedPlaceholderViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedPlaceholderView GetFeedPlaceholderView(GetFeedPlaceholderViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedPlaceholderView> GetFeedPlaceholderViewAsync(GetFeedPlaceholderViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedPlaceholderView> GetFeedPlaceholderViewAsync(GetFeedPlaceholderViewRequest request, st::CancellationToken cancellationToken) => GetFeedPlaceholderViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed placeholder view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedPlaceholderView GetFeedPlaceholderView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedPlaceholderView(new GetFeedPlaceholderViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed placeholder view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedPlaceholderView> GetFeedPlaceholderViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedPlaceholderViewAsync(new GetFeedPlaceholderViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed placeholder view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedPlaceholderView> GetFeedPlaceholderViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetFeedPlaceholderViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed placeholder view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedPlaceholderView GetFeedPlaceholderView(gagvr::FeedPlaceholderViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedPlaceholderView(new GetFeedPlaceholderViewRequest { ResourceNameAsFeedPlaceholderViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed placeholder view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedPlaceholderView> GetFeedPlaceholderViewAsync(gagvr::FeedPlaceholderViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedPlaceholderViewAsync(new GetFeedPlaceholderViewRequest { ResourceNameAsFeedPlaceholderViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed placeholder view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedPlaceholderView> GetFeedPlaceholderViewAsync(gagvr::FeedPlaceholderViewName resourceName, st::CancellationToken cancellationToken) => GetFeedPlaceholderViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>FeedPlaceholderViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch feed placeholder views. /// </remarks> public sealed partial class FeedPlaceholderViewServiceClientImpl : FeedPlaceholderViewServiceClient { private readonly gaxgrpc::ApiCall<GetFeedPlaceholderViewRequest, gagvr::FeedPlaceholderView> _callGetFeedPlaceholderView; /// <summary> /// Constructs a client wrapper for the FeedPlaceholderViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="FeedPlaceholderViewServiceSettings"/> used within this client. /// </param> public FeedPlaceholderViewServiceClientImpl(FeedPlaceholderViewService.FeedPlaceholderViewServiceClient grpcClient, FeedPlaceholderViewServiceSettings settings) { GrpcClient = grpcClient; FeedPlaceholderViewServiceSettings effectiveSettings = settings ?? FeedPlaceholderViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetFeedPlaceholderView = clientHelper.BuildApiCall<GetFeedPlaceholderViewRequest, gagvr::FeedPlaceholderView>(grpcClient.GetFeedPlaceholderViewAsync, grpcClient.GetFeedPlaceholderView, effectiveSettings.GetFeedPlaceholderViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetFeedPlaceholderView); Modify_GetFeedPlaceholderViewApiCall(ref _callGetFeedPlaceholderView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetFeedPlaceholderViewApiCall(ref gaxgrpc::ApiCall<GetFeedPlaceholderViewRequest, gagvr::FeedPlaceholderView> call); partial void OnConstruction(FeedPlaceholderViewService.FeedPlaceholderViewServiceClient grpcClient, FeedPlaceholderViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC FeedPlaceholderViewService client</summary> public override FeedPlaceholderViewService.FeedPlaceholderViewServiceClient GrpcClient { get; } partial void Modify_GetFeedPlaceholderViewRequest(ref GetFeedPlaceholderViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::FeedPlaceholderView GetFeedPlaceholderView(GetFeedPlaceholderViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedPlaceholderViewRequest(ref request, ref callSettings); return _callGetFeedPlaceholderView.Sync(request, callSettings); } /// <summary> /// Returns the requested feed placeholder view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::FeedPlaceholderView> GetFeedPlaceholderViewAsync(GetFeedPlaceholderViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedPlaceholderViewRequest(ref request, ref callSettings); return _callGetFeedPlaceholderView.Async(request, callSettings); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // zlib.h -- interface of the 'zlib' general purpose compression library // version 1.2.1, November 17th, 2003 // // Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // // ==--== namespace Mapbox.IO.Compression { using System; using System.Diagnostics; internal class Inflater { // const tables used in decoding: // Extra bits for length code 257 - 285. private static readonly byte[] extraLengthBits = { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; // The base length for length code 257 - 285. // The formula to get the real length for a length code is lengthBase[code - 257] + (value stored in extraBits) private static readonly int[] lengthBase = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258}; // The base distance for distance code 0 - 29 // The real distance for a distance code is distanceBasePosition[code] + (value stored in extraBits) private static readonly int[] distanceBasePosition= { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; // code lengths for code length alphabet is stored in following order private static readonly byte[] codeOrder = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; private static readonly byte[] staticDistanceTreeTable = { 0x00,0x10,0x08,0x18,0x04,0x14,0x0c,0x1c,0x02,0x12,0x0a,0x1a, 0x06,0x16,0x0e,0x1e,0x01,0x11,0x09,0x19,0x05,0x15,0x0d,0x1d, 0x03,0x13,0x0b,0x1b,0x07,0x17,0x0f,0x1f, }; private OutputWindow output; private InputBuffer input; HuffmanTree literalLengthTree; HuffmanTree distanceTree; InflaterState state; bool hasFormatReader; int bfinal; BlockType blockType; // uncompressed block byte[] blockLengthBuffer = new byte[4]; int blockLength; // compressed block private int length; private int distanceCode; private int extraBits; private int loopCounter; private int literalLengthCodeCount; private int distanceCodeCount; private int codeLengthCodeCount; private int codeArraySize; private int lengthCode; private byte[] codeList; // temporary array to store the code length for literal/Length and distance private byte[] codeLengthTreeCodeLength; HuffmanTree codeLengthTree; IFileFormatReader formatReader; // class to decode header and footer (e.g. gzip) public Inflater() { output = new OutputWindow(); input = new InputBuffer(); codeList = new byte[HuffmanTree.MaxLiteralTreeElements + HuffmanTree.MaxDistTreeElements]; codeLengthTreeCodeLength = new byte[HuffmanTree.NumberOfCodeLengthTreeElements]; Reset(); } internal void SetFileFormatReader(IFileFormatReader reader) { formatReader = reader; hasFormatReader = true; Reset(); } private void Reset() { if ( hasFormatReader) { state = InflaterState.ReadingHeader; // start by reading Header info } else { state = InflaterState.ReadingBFinal; // start by reading BFinal bit } } public void SetInput(byte[] inputBytes, int offset, int length) { input.SetInput(inputBytes, offset, length); // append the bytes } public bool Finished() { return (state == InflaterState.Done || state== InflaterState.VerifyingFooter); } public int AvailableOutput{ get { return output.AvailableBytes; } } public bool NeedsInput(){ return input.NeedsInput(); } public int Inflate(byte[] bytes, int offset, int length) { // copy bytes from output to outputbytes if we have aviable bytes // if buffer is not filled up. keep decoding until no input are available // if decodeBlock returns false. Throw an exception. int count = 0; do { int copied = output.CopyTo(bytes, offset, length); if( copied > 0) { if( hasFormatReader) { formatReader.UpdateWithBytesRead(bytes, offset, copied); } offset += copied; count += copied; length -= copied; } if (length == 0) { // filled in the bytes array break; } // Decode will return false when more input is needed } while ( !Finished() && Decode()); if( state == InflaterState.VerifyingFooter) { // finished reading CRC // In this case finished is true and output window has all the data. // But some data in output window might not be copied out. if( output.AvailableBytes == 0) { formatReader.Validate(); } } return count; } //Each block of compressed data begins with 3 header bits // containing the following data: // first bit BFINAL // next 2 bits BTYPE // Note that the header bits do not necessarily begin on a byte // boundary, since a block does not necessarily occupy an integral // number of bytes. // BFINAL is set if and only if this is the last block of the data // set. // BTYPE specifies how the data are compressed, as follows: // 00 - no compression // 01 - compressed with fixed Huffman codes // 10 - compressed with dynamic Huffman codes // 11 - reserved (error) // The only difference between the two compressed cases is how the // Huffman codes for the literal/length and distance alphabets are // defined. // // This function returns true for success (end of block or output window is full,) // false if we are short of input // private bool Decode() { bool eob = false; bool result = false; if( Finished()) { return true; } if (hasFormatReader) { if (state == InflaterState.ReadingHeader) { if (!formatReader.ReadHeader(input)) { return false; } state = InflaterState.ReadingBFinal; } else if (state == InflaterState.StartReadingFooter || state == InflaterState.ReadingFooter) { if (!formatReader.ReadFooter(input)) return false; state = InflaterState.VerifyingFooter; return true; } } if( state == InflaterState.ReadingBFinal) { // reading bfinal bit // Need 1 bit if (!input.EnsureBitsAvailable(1)) return false; bfinal = input.GetBits(1); state = InflaterState.ReadingBType; } if( state == InflaterState.ReadingBType) { // Need 2 bits if (!input.EnsureBitsAvailable(2)) { state = InflaterState.ReadingBType; return false; } blockType = (BlockType)input.GetBits(2); if (blockType == BlockType.Dynamic) { //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "Decoding Dynamic Block", "Compression"); state = InflaterState.ReadingNumLitCodes; } else if (blockType == BlockType.Static) { //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "Decoding Static Block", "Compression"); literalLengthTree = HuffmanTree.StaticLiteralLengthTree; distanceTree = HuffmanTree.StaticDistanceTree; state = InflaterState.DecodeTop; } else if (blockType == BlockType.Uncompressed) { //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "Decoding UnCompressed Block", "Compression"); state = InflaterState.UncompressedAligning; } else { throw new InvalidDataException(SR.GetString(SR.UnknownBlockType)); } } if (blockType == BlockType.Dynamic) { if (state < InflaterState.DecodeTop) { // we are reading the header result = DecodeDynamicBlockHeader(); } else { result = DecodeBlock(out eob); // this can returns true when output is full } } else if (blockType == BlockType.Static) { result = DecodeBlock(out eob); } else if (blockType == BlockType.Uncompressed) { result = DecodeUncompressedBlock(out eob); } else { throw new InvalidDataException(SR.GetString(SR.UnknownBlockType)); } // // If we reached the end of the block and the block we were decoding had // bfinal=1 (final block) // if (eob && (bfinal != 0)) { if (hasFormatReader) state = InflaterState.StartReadingFooter; else state = InflaterState.Done; } return result; } // Format of Non-compressed blocks (BTYPE=00): // // Any bits of input up to the next byte boundary are ignored. // The rest of the block consists of the following information: // // 0 1 2 3 4... // +---+---+---+---+================================+ // | LEN | NLEN |... LEN bytes of literal data...| // +---+---+---+---+================================+ // // LEN is the number of data bytes in the block. NLEN is the // one's complement of LEN. bool DecodeUncompressedBlock(out bool end_of_block) { end_of_block = false; while(true) { switch( state) { case InflaterState.UncompressedAligning: // intial state when calling this function // we must skip to a byte boundary input.SkipToByteBoundary(); state = InflaterState.UncompressedByte1; goto case InflaterState.UncompressedByte1; case InflaterState.UncompressedByte1: // decoding block length case InflaterState.UncompressedByte2: case InflaterState.UncompressedByte3: case InflaterState.UncompressedByte4: int bits = input.GetBits(8); if( bits < 0) { return false; } blockLengthBuffer[state - InflaterState.UncompressedByte1] = (byte)bits; if( state == InflaterState.UncompressedByte4) { blockLength = blockLengthBuffer[0] + ((int)blockLengthBuffer[1]) * 256; int blockLengthComplement= blockLengthBuffer[2] + ((int)blockLengthBuffer[3]) * 256; // make sure complement matches if ((ushort) blockLength != (ushort)(~blockLengthComplement)) { throw new InvalidDataException(SR.GetString(SR.InvalidBlockLength)); } } state += 1; break; case InflaterState.DecodingUncompressed: // copying block data // Directly copy bytes from input to output. int bytesCopied = output.CopyFrom(input, blockLength); blockLength -= bytesCopied; if (blockLength == 0) { // Done with this block, need to re-init bit buffer for next block state = InflaterState.ReadingBFinal; end_of_block = true; //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "End of Block", "Compression"); return true; } // We can fail to copy all bytes for two reasons: // Running out of Input // running out of free space in output window if(output.FreeBytes == 0) { return true; } return false; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.GetString(SR.UnknownState)); } } } bool DecodeBlock(out bool end_of_block_code_seen) { end_of_block_code_seen = false; int freeBytes = output.FreeBytes; // it is a little bit faster than frequently accessing the property while(freeBytes > 258) { // 258 means we can safely do decoding since maximum repeat length is 258 int symbol; switch (state) { case InflaterState.DecodeTop: // decode an element from the literal tree // symbol = literalLengthTree.GetNextSymbol(input); if( symbol < 0) { // running out of input return false; } if (symbol < 256) { // literal output.Write((byte)symbol); --freeBytes; } else if( symbol == 256) { // end of block end_of_block_code_seen = true; //Debug.WriteLineIf(CompressionTracingSwitch.Informational, "End of Block", "Compression"); // Reset state state = InflaterState.ReadingBFinal; return true; // *********** } else { // length/distance pair symbol -= 257; // length code started at 257 if( symbol < 8) { symbol += 3; // match length = 3,4,5,6,7,8,9,10 extraBits = 0; } else if( symbol == 28) { // extra bits for code 285 is 0 symbol = 258; // code 285 means length 258 extraBits = 0; } else { if( symbol < 0 || symbol >= extraLengthBits.Length ) { throw new InvalidDataException(SR.GetString(SR.GenericInvalidData)); } extraBits = extraLengthBits[symbol]; Debug.Assert(extraBits != 0, "We handle other cases seperately!"); } length = symbol; goto case InflaterState.HaveInitialLength; } break; case InflaterState.HaveInitialLength: if( extraBits > 0) { state = InflaterState.HaveInitialLength; int bits = input.GetBits(extraBits); if( bits < 0) { return false; } if( length < 0 || length >= lengthBase.Length ) { throw new InvalidDataException(SR.GetString(SR.GenericInvalidData)); } length = lengthBase[length] + bits; } state = InflaterState.HaveFullLength; goto case InflaterState.HaveFullLength; case InflaterState.HaveFullLength: if( blockType == BlockType.Dynamic) { distanceCode = distanceTree.GetNextSymbol(input); } else { // get distance code directly for static block distanceCode = input.GetBits(5); if( distanceCode >= 0 ) { distanceCode = staticDistanceTreeTable[distanceCode]; } } if( distanceCode < 0) { // running out input return false; } state = InflaterState.HaveDistCode; goto case InflaterState.HaveDistCode; case InflaterState.HaveDistCode: // To avoid a table lookup we note that for distanceCode >= 2, // extra_bits = (distanceCode-2) >> 1 int offset; if( distanceCode > 3) { extraBits = (distanceCode-2) >> 1; int bits = input.GetBits(extraBits); if( bits < 0 ) { return false; } offset = distanceBasePosition[distanceCode] + bits; } else { offset = distanceCode + 1; } Debug.Assert(freeBytes>= 258, "following operation is not safe!"); output.WriteLengthDistance(length, offset); freeBytes -= length; state = InflaterState.DecodeTop; break; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.GetString(SR.UnknownState)); } } return true; } // Format of the dynamic block header: // 5 Bits: HLIT, # of Literal/Length codes - 257 (257 - 286) // 5 Bits: HDIST, # of Distance codes - 1 (1 - 32) // 4 Bits: HCLEN, # of Code Length codes - 4 (4 - 19) // // (HCLEN + 4) x 3 bits: code lengths for the code length // alphabet given just above, in the order: 16, 17, 18, // 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 // // These code lengths are interpreted as 3-bit integers // (0-7); as above, a code length of 0 means the // corresponding symbol (literal/length or distance code // length) is not used. // // HLIT + 257 code lengths for the literal/length alphabet, // encoded using the code length Huffman code // // HDIST + 1 code lengths for the distance alphabet, // encoded using the code length Huffman code // // The code length repeat codes can cross from HLIT + 257 to the // HDIST + 1 code lengths. In other words, all code lengths form // a single sequence of HLIT + HDIST + 258 values. bool DecodeDynamicBlockHeader() { switch (state) { case InflaterState.ReadingNumLitCodes: literalLengthCodeCount = input.GetBits(5); if( literalLengthCodeCount < 0) { return false; } literalLengthCodeCount += 257; state = InflaterState.ReadingNumDistCodes; goto case InflaterState.ReadingNumDistCodes; case InflaterState.ReadingNumDistCodes: distanceCodeCount = input.GetBits(5); if( distanceCodeCount < 0) { return false; } distanceCodeCount += 1; state = InflaterState.ReadingNumCodeLengthCodes; goto case InflaterState.ReadingNumCodeLengthCodes; case InflaterState.ReadingNumCodeLengthCodes: codeLengthCodeCount = input.GetBits(4); if( codeLengthCodeCount < 0) { return false; } codeLengthCodeCount += 4; loopCounter = 0; state = InflaterState.ReadingCodeLengthCodes; goto case InflaterState.ReadingCodeLengthCodes; case InflaterState.ReadingCodeLengthCodes: while(loopCounter < codeLengthCodeCount) { int bits = input.GetBits(3); if( bits < 0) { return false; } codeLengthTreeCodeLength[codeOrder[loopCounter]] = (byte)bits; ++loopCounter; } for (int i = codeLengthCodeCount; i < codeOrder.Length; i++) { codeLengthTreeCodeLength[ codeOrder[i] ] = 0; } // create huffman tree for code length codeLengthTree = new HuffmanTree(codeLengthTreeCodeLength); codeArraySize = literalLengthCodeCount + distanceCodeCount; loopCounter = 0; // reset loop count state = InflaterState.ReadingTreeCodesBefore; goto case InflaterState.ReadingTreeCodesBefore; case InflaterState.ReadingTreeCodesBefore: case InflaterState.ReadingTreeCodesAfter: while (loopCounter < codeArraySize) { if( state == InflaterState.ReadingTreeCodesBefore) { if( (lengthCode = codeLengthTree.GetNextSymbol(input)) < 0) { return false; } } // The alphabet for code lengths is as follows: // 0 - 15: Represent code lengths of 0 - 15 // 16: Copy the previous code length 3 - 6 times. // The next 2 bits indicate repeat length // (0 = 3, ... , 3 = 6) // Example: Codes 8, 16 (+2 bits 11), // 16 (+2 bits 10) will expand to // 12 code lengths of 8 (1 + 6 + 5) // 17: Repeat a code length of 0 for 3 - 10 times. // (3 bits of length) // 18: Repeat a code length of 0 for 11 - 138 times // (7 bits of length) if (lengthCode <= 15) { codeList[loopCounter++] = (byte)lengthCode; } else { if( !input.EnsureBitsAvailable(7)) { // it doesn't matter if we require more bits here state = InflaterState.ReadingTreeCodesAfter; return false; } int repeatCount; if (lengthCode == 16) { if (loopCounter == 0) { // can't have "prev code" on first code throw new InvalidDataException(); } byte previousCode = codeList[loopCounter-1]; repeatCount = input.GetBits(2) + 3; if (loopCounter + repeatCount > codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { codeList[loopCounter++] = previousCode; } } else if (lengthCode == 17) { repeatCount = input.GetBits(3) + 3; if (loopCounter + repeatCount > codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { codeList[loopCounter++] = 0; } } else { // code == 18 repeatCount = input.GetBits(7) + 11; if (loopCounter + repeatCount > codeArraySize) { throw new InvalidDataException(); } for (int j = 0; j < repeatCount; j++) { codeList[loopCounter++] = 0; } } } state = InflaterState.ReadingTreeCodesBefore; // we want to read the next code. } break; default: Debug.Assert(false, "check why we are here!"); throw new InvalidDataException(SR.GetString(SR.UnknownState)); } byte[] literalTreeCodeLength = new byte[HuffmanTree.MaxLiteralTreeElements]; byte[] distanceTreeCodeLength = new byte[HuffmanTree.MaxDistTreeElements]; // Create literal and distance tables Array.Copy(codeList, literalTreeCodeLength, literalLengthCodeCount); Array.Copy(codeList, literalLengthCodeCount, distanceTreeCodeLength, 0, distanceCodeCount); // Make sure there is an end-of-block code, otherwise how could we ever end? if (literalTreeCodeLength[HuffmanTree.EndOfBlockCode] == 0) { throw new InvalidDataException(); } literalLengthTree = new HuffmanTree(literalTreeCodeLength); distanceTree = new HuffmanTree(distanceTreeCodeLength); state = InflaterState.DecodeTop; return true; } } }
namespace org.apache.http.entity { [global::MonoJavaBridge.JavaClass(typeof(global::org.apache.http.entity.AbstractHttpEntity_))] public abstract partial class AbstractHttpEntity : java.lang.Object, HttpEntity { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static AbstractHttpEntity() { InitJNI(); } protected AbstractHttpEntity(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getContent16439; public abstract global::java.io.InputStream getContent(); internal static global::MonoJavaBridge.MethodId _writeTo16440; public abstract void writeTo(java.io.OutputStream arg0); internal static global::MonoJavaBridge.MethodId _getContentLength16441; public abstract long getContentLength(); internal static global::MonoJavaBridge.MethodId _isRepeatable16442; public abstract bool isRepeatable(); internal static global::MonoJavaBridge.MethodId _isStreaming16443; public abstract bool isStreaming(); internal static global::MonoJavaBridge.MethodId _getContentType16444; public virtual global::org.apache.http.Header getContentType() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity._getContentType16444)) as org.apache.http.Header; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._getContentType16444)) as org.apache.http.Header; } internal static global::MonoJavaBridge.MethodId _setContentType16445; public virtual void setContentType(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity._setContentType16445, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._setContentType16445, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setContentType16446; public virtual void setContentType(org.apache.http.Header arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity._setContentType16446, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._setContentType16446, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getContentEncoding16447; public virtual global::org.apache.http.Header getContentEncoding() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity._getContentEncoding16447)) as org.apache.http.Header; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._getContentEncoding16447)) as org.apache.http.Header; } internal static global::MonoJavaBridge.MethodId _isChunked16448; public virtual bool isChunked() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity._isChunked16448); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._isChunked16448); } internal static global::MonoJavaBridge.MethodId _consumeContent16449; public virtual void consumeContent() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity._consumeContent16449); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._consumeContent16449); } internal static global::MonoJavaBridge.MethodId _setContentEncoding16450; public virtual void setContentEncoding(org.apache.http.Header arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity._setContentEncoding16450, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._setContentEncoding16450, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setContentEncoding16451; public virtual void setContentEncoding(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity._setContentEncoding16451, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._setContentEncoding16451, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setChunked16452; public virtual void setChunked(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity._setChunked16452, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._setChunked16452, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _AbstractHttpEntity16453; protected AbstractHttpEntity() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(org.apache.http.entity.AbstractHttpEntity.staticClass, global::org.apache.http.entity.AbstractHttpEntity._AbstractHttpEntity16453); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::org.apache.http.entity.AbstractHttpEntity.staticClass = @__env.NewGlobalRef(@__env.FindClass("org/apache/http/entity/AbstractHttpEntity")); global::org.apache.http.entity.AbstractHttpEntity._getContent16439 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "getContent", "()Ljava/io/InputStream;"); global::org.apache.http.entity.AbstractHttpEntity._writeTo16440 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "writeTo", "(Ljava/io/OutputStream;)V"); global::org.apache.http.entity.AbstractHttpEntity._getContentLength16441 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "getContentLength", "()J"); global::org.apache.http.entity.AbstractHttpEntity._isRepeatable16442 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "isRepeatable", "()Z"); global::org.apache.http.entity.AbstractHttpEntity._isStreaming16443 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "isStreaming", "()Z"); global::org.apache.http.entity.AbstractHttpEntity._getContentType16444 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "getContentType", "()Lorg/apache/http/Header;"); global::org.apache.http.entity.AbstractHttpEntity._setContentType16445 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "setContentType", "(Ljava/lang/String;)V"); global::org.apache.http.entity.AbstractHttpEntity._setContentType16446 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "setContentType", "(Lorg/apache/http/Header;)V"); global::org.apache.http.entity.AbstractHttpEntity._getContentEncoding16447 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "getContentEncoding", "()Lorg/apache/http/Header;"); global::org.apache.http.entity.AbstractHttpEntity._isChunked16448 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "isChunked", "()Z"); global::org.apache.http.entity.AbstractHttpEntity._consumeContent16449 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "consumeContent", "()V"); global::org.apache.http.entity.AbstractHttpEntity._setContentEncoding16450 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "setContentEncoding", "(Lorg/apache/http/Header;)V"); global::org.apache.http.entity.AbstractHttpEntity._setContentEncoding16451 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "setContentEncoding", "(Ljava/lang/String;)V"); global::org.apache.http.entity.AbstractHttpEntity._setChunked16452 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "setChunked", "(Z)V"); global::org.apache.http.entity.AbstractHttpEntity._AbstractHttpEntity16453 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity.staticClass, "<init>", "()V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::org.apache.http.entity.AbstractHttpEntity))] public sealed partial class AbstractHttpEntity_ : org.apache.http.entity.AbstractHttpEntity { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static AbstractHttpEntity_() { InitJNI(); } internal AbstractHttpEntity_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getContent16454; public override global::java.io.InputStream getContent() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_._getContent16454)) as java.io.InputStream; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_.staticClass, global::org.apache.http.entity.AbstractHttpEntity_._getContent16454)) as java.io.InputStream; } internal static global::MonoJavaBridge.MethodId _writeTo16455; public override void writeTo(java.io.OutputStream arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_._writeTo16455, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_.staticClass, global::org.apache.http.entity.AbstractHttpEntity_._writeTo16455, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getContentLength16456; public override long getContentLength() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_._getContentLength16456); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_.staticClass, global::org.apache.http.entity.AbstractHttpEntity_._getContentLength16456); } internal static global::MonoJavaBridge.MethodId _isRepeatable16457; public override bool isRepeatable() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_._isRepeatable16457); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_.staticClass, global::org.apache.http.entity.AbstractHttpEntity_._isRepeatable16457); } internal static global::MonoJavaBridge.MethodId _isStreaming16458; public override bool isStreaming() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_._isStreaming16458); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.entity.AbstractHttpEntity_.staticClass, global::org.apache.http.entity.AbstractHttpEntity_._isStreaming16458); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::org.apache.http.entity.AbstractHttpEntity_.staticClass = @__env.NewGlobalRef(@__env.FindClass("org/apache/http/entity/AbstractHttpEntity")); global::org.apache.http.entity.AbstractHttpEntity_._getContent16454 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity_.staticClass, "getContent", "()Ljava/io/InputStream;"); global::org.apache.http.entity.AbstractHttpEntity_._writeTo16455 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity_.staticClass, "writeTo", "(Ljava/io/OutputStream;)V"); global::org.apache.http.entity.AbstractHttpEntity_._getContentLength16456 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity_.staticClass, "getContentLength", "()J"); global::org.apache.http.entity.AbstractHttpEntity_._isRepeatable16457 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity_.staticClass, "isRepeatable", "()Z"); global::org.apache.http.entity.AbstractHttpEntity_._isStreaming16458 = @__env.GetMethodIDNoThrow(global::org.apache.http.entity.AbstractHttpEntity_.staticClass, "isStreaming", "()Z"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using LamarCodeGeneration; using Marten.Events; using Marten.Exceptions; using Marten.Internal.CodeGeneration; using Marten.Internal.DirtyTracking; using Marten.Internal.Storage; using Marten.Linq; using Marten.Linq.QueryHandlers; using Marten.Schema; using Marten.Services; using Marten.Services.BatchQuerying; using Marten.Storage; using Marten.Storage.Metadata; using Marten.Util; using Npgsql; #nullable enable namespace Marten.Internal.Sessions { public class QuerySession : IMartenSession, IQuerySession { private readonly IProviderGraph _providers; private bool _disposed; public VersionTracker Versions { get; internal set; } = new VersionTracker(); public IManagedConnection Database { get; } public ISerializer Serializer { get; } public Dictionary<Type, object> ItemMap { get; internal set; } = new Dictionary<Type, object>(); public ITenant Tenant { get; } public StoreOptions Options { get; } public void MarkAsAddedForStorage(object id, object document) { foreach (var listener in Listeners) { listener.DocumentAddedForStorage(id, document); } } public void MarkAsDocumentLoaded(object id, object? document) { if (document == null) return; foreach (var listener in Listeners) { listener.DocumentLoaded(id, document); } } public IList<IChangeTracker> ChangeTrackers { get; } = new List<IChangeTracker>(); public IList<IDocumentSessionListener> Listeners { get; } = new List<IDocumentSessionListener>(); internal SessionOptions? SessionOptions { get; } public QuerySession(DocumentStore store, SessionOptions? sessionOptions, IManagedConnection database, ITenant tenant) { DocumentStore = store; SessionOptions = sessionOptions; Listeners.AddRange(store.Options.Listeners); if (sessionOptions != null) { if (sessionOptions.Timeout is < 0) { throw new ArgumentOutOfRangeException(nameof(sessionOptions.Timeout),"CommandTimeout can't be less than zero"); } Listeners.AddRange(sessionOptions.Listeners); } _providers = tenant.Providers ?? throw new ArgumentNullException(nameof(ITenant.Providers)); Database = database; Serializer = store.Serializer; Tenant = tenant; Options = store.Options; } protected internal virtual IDocumentStorage<T> selectStorage<T>(DocumentProvider<T> provider) where T : notnull { return provider.QueryOnly; } public IDocumentStorage StorageFor(Type documentType) { // TODO -- possible optimization opportunity return typeof(StorageFinder<>).CloseAndBuildAs<IStorageFinder>(documentType).Find(this); } private interface IStorageFinder { IDocumentStorage Find(QuerySession session); } private class StorageFinder<T>: IStorageFinder where T : notnull { public IDocumentStorage Find(QuerySession session) { return session.StorageFor<T>(); } } internal IDocumentStorage<T, TId> StorageFor<T, TId>() where T : notnull where TId : notnull { var storage = StorageFor<T>(); if (storage is IDocumentStorage<T, TId> s) return s; throw new DocumentIdTypeMismatchException(storage, typeof(TId)); } /// <summary> /// This returns the query-only version of the document storage /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TId"></typeparam> /// <returns></returns> /// <exception cref="DocumentIdTypeMismatchException"></exception> internal IDocumentStorage<T, TId> QueryStorageFor<T, TId>() where T : notnull where TId : notnull { var storage = _providers.StorageFor<T>().QueryOnly; if (storage is IDocumentStorage<T, TId> s) return s; throw new DocumentIdTypeMismatchException(storage, typeof(TId)); } public IDocumentStorage<T> StorageFor<T>() where T : notnull { return selectStorage(_providers.StorageFor<T>()); } public IEventStorage EventStorage() { return (IEventStorage) selectStorage(_providers.StorageFor<IEvent>()); } public ConcurrencyChecks Concurrency { get; protected set; } = ConcurrencyChecks.Enabled; private int _tableNumber; public string NextTempTableName() { return LinqConstants.IdListTableName + ++_tableNumber; } public string? CausationId { get; set; } public string? CorrelationId { get; set; } public string? LastModifiedBy { get; set; } /// <summary> /// This is meant to be lazy created, and can be null /// </summary> public Dictionary<string, object>? Headers { get; protected set; } public void Dispose() { if (_disposed) return; _disposed = true; Database?.Dispose(); GC.SuppressFinalize(this); } public async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; if (Database != null) { await Database.DisposeAsync(); } GC.SuppressFinalize(this); } protected void assertNotDisposed() { if (_disposed) throw new ObjectDisposedException("This session has been disposed"); } public T? Load<T>(string id) where T : notnull { assertNotDisposed(); var document = StorageFor<T, string>().Load(id, this); return document; } public async Task<T?> LoadAsync<T>(string id, CancellationToken token = default) where T : notnull { assertNotDisposed(); var document = await StorageFor<T, string>().LoadAsync(id, this, token); return document; } public T? Load<T>(int id) where T : notnull { assertNotDisposed(); var storage = StorageFor<T>(); var document = storage switch { IDocumentStorage<T, int> i => i.Load(id, this), IDocumentStorage<T, long> l => l.Load(id, this), _ => throw new DocumentIdTypeMismatchException( $"The identity type for document type {typeof(T).FullNameInCode()} is not numeric") }; return document; } public async Task<T?> LoadAsync<T>(int id, CancellationToken token = default) where T : notnull { assertNotDisposed(); var storage = StorageFor<T>(); var document = storage switch { IDocumentStorage<T, int> i => await i.LoadAsync(id, this, token), IDocumentStorage<T, long> l => await l.LoadAsync(id, this, token), _ => throw new DocumentIdTypeMismatchException( $"The identity type for document type {typeof(T).FullNameInCode()} is not numeric") }; return document; } public T? Load<T>(long id) where T : notnull { assertNotDisposed(); var document = StorageFor<T, long>().Load(id, this); return document; } public async Task<T?> LoadAsync<T>(long id, CancellationToken token = default) where T : notnull { assertNotDisposed(); var document = await StorageFor<T, long>().LoadAsync(id, this, token); return document; } public T? Load<T>(Guid id) where T : notnull { assertNotDisposed(); var document = StorageFor<T, Guid>().Load(id, this); return document; } public async Task<T?> LoadAsync<T>(Guid id, CancellationToken token = default) where T : notnull { assertNotDisposed(); var document = await StorageFor<T, Guid>().LoadAsync(id, this, token); return document; } public IMartenQueryable<T> Query<T>() { return new MartenLinqQueryable<T>(this); } public IReadOnlyList<T> Query<T>(string sql, params object[] parameters) { assertNotDisposed(); var handler = new UserSuppliedQueryHandler<T>(this, sql, parameters); var provider = new MartenLinqQueryProvider(this); return provider.ExecuteHandler(handler); } public Task<IReadOnlyList<T>> QueryAsync<T>(string sql, CancellationToken token = default, params object[] parameters) { assertNotDisposed(); var handler = new UserSuppliedQueryHandler<T>(this, sql, parameters); var provider = new MartenLinqQueryProvider(this); return provider.ExecuteHandlerAsync(handler, token); } public IBatchedQuery CreateBatchQuery() { return new BatchedQuery(Database, this); } public NpgsqlConnection Connection => Database.Connection; public IMartenSessionLogger Logger { get { return Database.Logger; } set { Database.Logger = value; } } public int RequestCount => Database.RequestCount; public IDocumentStore DocumentStore { get; } public TOut Query<TDoc, TOut>(ICompiledQuery<TDoc, TOut> query) { var source = Options.GetCompiledQuerySourceFor(query, this); var handler = (IQueryHandler<TOut>)source.Build(query, this); return ExecuteHandler(handler); } public Task<TOut> QueryAsync<TDoc, TOut>(ICompiledQuery<TDoc, TOut> query, CancellationToken token = default) { var source = Options.GetCompiledQuerySourceFor(query, this); var handler = (IQueryHandler<TOut>)source.Build(query, this); return ExecuteHandlerAsync(handler, token); } public IReadOnlyList<T> LoadMany<T>(params string[] ids) where T : notnull { assertNotDisposed(); return StorageFor<T, string>().LoadMany(ids, this); } public IReadOnlyList<T> LoadMany<T>(IEnumerable<string> ids) where T : notnull { assertNotDisposed(); return StorageFor<T, string>().LoadMany(ids.ToArray(), this); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(params string[] ids) where T : notnull { assertNotDisposed(); return StorageFor<T, string>().LoadManyAsync(ids, this, default); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(IEnumerable<string> ids) where T : notnull { assertNotDisposed(); return StorageFor<T, string>().LoadManyAsync(ids.ToArray(), this, default); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(CancellationToken token, params string[] ids) where T : notnull { assertNotDisposed(); return StorageFor<T, string>().LoadManyAsync(ids, this, token); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(CancellationToken token, IEnumerable<string> ids) where T : notnull { assertNotDisposed(); return StorageFor<T, string>().LoadManyAsync(ids.ToArray(), this, token); } public IReadOnlyList<T> LoadMany<T>(params int[] ids) where T : notnull { assertNotDisposed(); var storage = StorageFor<T>(); if (storage is IDocumentStorage<T, int> i) { return i.LoadMany(ids, this); } else if (storage is IDocumentStorage<T, long> l) { return l.LoadMany(ids.Select(x => (long)x).ToArray(), this); } throw new DocumentIdTypeMismatchException($"The identity type for document type {typeof(T).FullNameInCode()} is not numeric"); } public IReadOnlyList<T> LoadMany<T>(IEnumerable<int> ids) where T : notnull { return LoadMany<T>(ids.ToArray()); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(params int[] ids) where T : notnull { return LoadManyAsync<T>(CancellationToken.None, ids); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(IEnumerable<int> ids) where T : notnull { return LoadManyAsync<T>(ids.ToArray()); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(CancellationToken token, params int[] ids) where T : notnull { assertNotDisposed(); var storage = StorageFor<T>(); if (storage is IDocumentStorage<T, int> i) { return i.LoadManyAsync(ids, this, token); } else if (storage is IDocumentStorage<T, long> l) { return l.LoadManyAsync(ids.Select(x => (long)x).ToArray(), this, token); } throw new DocumentIdTypeMismatchException($"The identity type for document type {typeof(T).FullNameInCode()} is not numeric"); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(CancellationToken token, IEnumerable<int> ids) where T : notnull { return LoadManyAsync<T>(token, ids.ToArray()); } public IReadOnlyList<T> LoadMany<T>(params long[] ids) where T : notnull { assertNotDisposed(); return StorageFor<T, long>().LoadMany(ids, this); } public IReadOnlyList<T> LoadMany<T>(IEnumerable<long> ids) where T : notnull { assertNotDisposed(); return StorageFor<T, long>().LoadMany(ids.ToArray(), this); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(params long[] ids) where T : notnull { assertNotDisposed(); return StorageFor<T, long>().LoadManyAsync(ids, this, default); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(IEnumerable<long> ids) where T : notnull { assertNotDisposed(); return StorageFor<T, long>().LoadManyAsync(ids.ToArray(), this, default); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(CancellationToken token, params long[] ids) where T : notnull { assertNotDisposed(); return StorageFor<T, long>().LoadManyAsync(ids, this, token); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(CancellationToken token, IEnumerable<long> ids) where T : notnull { assertNotDisposed(); return StorageFor<T, long>().LoadManyAsync(ids.ToArray(), this, token); } public IReadOnlyList<T> LoadMany<T>(params Guid[] ids) where T: notnull { assertNotDisposed(); return StorageFor<T, Guid>().LoadMany(ids, this); } public IReadOnlyList<T> LoadMany<T>(IEnumerable<Guid> ids) where T : notnull { assertNotDisposed(); return StorageFor<T, Guid>().LoadMany(ids.ToArray(), this); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(params Guid[] ids) where T : notnull { assertNotDisposed(); return StorageFor<T, Guid>().LoadManyAsync(ids, this, default); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(IEnumerable<Guid> ids) where T : notnull { assertNotDisposed(); return StorageFor<T, Guid>().LoadManyAsync(ids.ToArray(), this, default); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(CancellationToken token, params Guid[] ids) where T : notnull { assertNotDisposed(); return StorageFor<T, Guid>().LoadManyAsync(ids, this, token); } public Task<IReadOnlyList<T>> LoadManyAsync<T>(CancellationToken token, IEnumerable<Guid> ids) where T : notnull { assertNotDisposed(); return StorageFor<T, Guid>().LoadManyAsync(ids.ToArray(), this, token); } public IJsonLoader Json => new JsonLoader(this); public Guid? VersionFor<TDoc>(TDoc entity) where TDoc : notnull { return StorageFor<TDoc>().VersionFor(entity, this); } public IReadOnlyList<TDoc> Search<TDoc>(string searchTerm, string regConfig = FullTextIndex.DefaultRegConfig) { return Query<TDoc>().Where(d => d.Search(searchTerm, regConfig)).ToList(); } public Task<IReadOnlyList<TDoc>> SearchAsync<TDoc>(string searchTerm, string regConfig = FullTextIndex.DefaultRegConfig, CancellationToken token = default) { return Query<TDoc>().Where(d => d.Search(searchTerm, regConfig)).ToListAsync(token: token); } public IReadOnlyList<TDoc> PlainTextSearch<TDoc>(string searchTerm, string regConfig = FullTextIndex.DefaultRegConfig) { return Query<TDoc>().Where(d => d.PlainTextSearch(searchTerm, regConfig)).ToList(); } public Task<IReadOnlyList<TDoc>> PlainTextSearchAsync<TDoc>(string searchTerm, string regConfig = FullTextIndex.DefaultRegConfig, CancellationToken token = default) { return Query<TDoc>().Where(d => d.PlainTextSearch(searchTerm, regConfig)).ToListAsync(token: token); } public IReadOnlyList<TDoc> PhraseSearch<TDoc>(string searchTerm, string regConfig = FullTextIndex.DefaultRegConfig) { return Query<TDoc>().Where(d => d.PhraseSearch(searchTerm, regConfig)).ToList(); } public Task<IReadOnlyList<TDoc>> PhraseSearchAsync<TDoc>(string searchTerm, string regConfig = FullTextIndex.DefaultRegConfig, CancellationToken token = default) { return Query<TDoc>().Where(d => d.PhraseSearch(searchTerm, regConfig)).ToListAsync(token: token); } public IReadOnlyList<TDoc> WebStyleSearch<TDoc>(string searchTerm, string regConfig = FullTextIndex.DefaultRegConfig) { return Query<TDoc>().Where(d => d.WebStyleSearch(searchTerm, regConfig)).ToList(); } public Task<IReadOnlyList<TDoc>> WebStyleSearchAsync<TDoc>(string searchTerm, string regConfig = FullTextIndex.DefaultRegConfig, CancellationToken token = default) { return Query<TDoc>().Where(d => d.WebStyleSearch(searchTerm, regConfig)).ToListAsync(token: token); } public DocumentMetadata MetadataFor<T>(T entity) where T: notnull { assertNotDisposed(); if (entity == null) throw new ArgumentNullException(nameof(entity)); var storage = StorageFor<T>(); var id = storage.IdentityFor(entity); var handler = new EntityMetadataQueryHandler(id, storage); return ExecuteHandler(handler); } public Task<DocumentMetadata> MetadataForAsync<T>(T entity, CancellationToken token = default) where T : notnull { assertNotDisposed(); if (entity == null) throw new ArgumentNullException(nameof(entity)); var storage = StorageFor<T>(); var id = storage.IdentityFor(entity); var handler = new EntityMetadataQueryHandler(id, storage); return ExecuteHandlerAsync(handler, token); } public async Task<T> ExecuteHandlerAsync<T>(IQueryHandler<T> handler, CancellationToken token) { var cmd = this.BuildCommand(handler); using (var reader = await Database.ExecuteReaderAsync(cmd, token)) { return await handler.HandleAsync(reader, this, token); } } public T ExecuteHandler<T>(IQueryHandler<T> handler) { var cmd = this.BuildCommand(handler); using var reader = Database.ExecuteReader(cmd); return handler.Handle(reader, this); } } }
namespace Lex { /* * Class: Utility */ using System; using System.Text; public class Utility { #if DUMMY /* * Constants */ public const bool DEBUG = true; public const bool SLOW_DEBUG = true; public const bool DUMP_DEBUG = true; /*public const bool DEBUG = false; public const bool SLOW_DEBUG = false; public const bool DUMP_DEBUG = false;*/ public const bool DESCENT_DEBUG = false; public const bool OLD_DEBUG = false; public const bool OLD_DUMP_DEBUG = false; public const bool FOODEBUG = false; public const bool DO_DEBUG = false; #endif /* * Constants: Integer Bounds */ public const int INT_MAX = 2147483647; /* UNDONE: What about other character values??? */ public const int MAX_SEVEN_BIT = 127; public const int MAX_EIGHT_BIT = 256; /* * Function: enter * Description: Debugging routine. */ public static void enter(String descent, char lexeme, int token) { StringBuilder sb = new StringBuilder(); sb.Append("Entering "); sb.Append(descent); sb.Append(" [lexeme: '"); if (lexeme < ' ') { lexeme += (char) 64; sb.Append("^"); } sb.Append(lexeme); sb.Append("'] [token: "); sb.Append(token); sb.Append("]"); Console.WriteLine(sb.ToString()); } /* * Function: leave * Description: Debugging routine. */ public static void leave(String descent, char lexeme, int token) { StringBuilder sb = new StringBuilder(); sb.Append("Leaving "); sb.Append(descent); sb.Append(" [lexeme: '"); if (lexeme < ' ') { lexeme += (char) 64; sb.Append("^"); } sb.Append(lexeme); sb.Append("'] [token: "); sb.Append(token); sb.Append("]"); Console.WriteLine(sb.ToString()); } /* * Function: assert * Description: Debugging routine. */ public static void assert(bool expr) { if (false == expr) { Console.WriteLine("Assertion Failed"); throw new ApplicationException("Assertion Failed."); } } /* * Function: doubleSize */ public static char[] doubleSize(char[] oldBuffer) { char[] newBuffer = new char[2 * oldBuffer.Length]; int elem; for (elem = 0; elem < oldBuffer.Length; ++elem) { newBuffer[elem] = oldBuffer[elem]; } return newBuffer; } /* * Function: doubleSize */ public static byte[] doubleSize(byte[] oldBuffer) { byte[] newBuffer = new byte[2 * oldBuffer.Length]; int elem; for (elem = 0; elem < oldBuffer.Length; elem++) { newBuffer[elem] = oldBuffer[elem]; } return newBuffer; } /* * Function: hex2bin */ public static char hex2bin(char c) { if ('0' <= c && '9' >= c) { return (char) (c - '0'); } else if ('a' <= c && 'f' >= c) { return (char) (c - 'a' + 10); } else if ('A' <= c && 'F' >= c) { return (char) (c - 'A' + 10); } Error.impos("Bad hexidecimal digit" + Char.ToString(c)); return (char) 0; } /* * Function: ishexdigit */ public static bool ishexdigit(char c) { if (('0' <= c && '9' >= c) || ('a' <= c && 'f' >= c) || ('A' <= c && 'F' >= c)) { return true; } return false; } /* * Function: oct2bin */ public static char oct2bin(char c) { if ('0' <= c && '7' >= c) { return (char) (c - '0'); } Error.impos("Bad octal digit " + Char.ToString(c)); return (char) 0; } /* * Function: isoctdigit */ public static bool isoctdigit(char c) { if ('0' <= c && '7' >= c) { return true; } return false; } /* * Function: isspace */ public static bool IsSpace(char c) { if ('\b' == c || '\t' == c || '\n' == c || '\f' == c || '\r' == c || ' ' == c) { return true; } return false; } /* * Function: IsNewline */ public static bool IsNewline(char c) { if ('\n' == c || '\r' == c) { return true; } return false; } /* * Function: isalpha */ public static bool isalpha(char c) { if (('a' <= c && 'z' >= c) || ('A' <= c && 'Z' >= c)) { return true; } return false; } /* * Function: toupper */ public static char toupper(char c) { if (('a' <= c && 'z' >= c)) { return (char) (c - 'a' + 'A'); } return c; } /* * Function: bytencmp * Description: Compares up to n elements of * byte array a[] against byte array b[]. * The first byte comparison is made between * a[a_first] and b[b_first]. Comparisons continue * until the null terminating byte '\0' is reached * or until n bytes are compared. * Return Value: Returns 0 if arrays are the * same up to and including the null terminating byte * or up to and including the first n bytes, * whichever comes first. */ public static int bytencmp(byte[] a, int a_first, byte[] b, int b_first, int n) { int elem; for (elem = 0; elem < n; ++elem) { /*System.out.print((char) a[a_first + elem]); System.out.print((char) b[b_first + elem]);*/ if ('\0' == a[a_first + elem] && '\0' == b[b_first + elem]) { /*Console.WriteLine("return 0");*/ return 0; } if (a[a_first + elem] < b[b_first + elem]) { /*Console.WriteLine("return 1");*/ return 1; } else if (a[a_first + elem] > b[b_first + elem]) { /*Console.WriteLine("return -1");*/ return -1; } } /*Console.WriteLine("return 0");*/ return 0; } /* * Function: charncmp */ public static int charncmp(char[] a, int a_first, char[] b, int b_first, int n) { int elem; for (elem = 0; elem < n; ++elem) { if ('\0' == a[a_first + elem] && '\0' == b[b_first + elem]) { return 0; } if (a[a_first + elem] < b[b_first + elem]) { return 1; } else if (a[a_first + elem] > b[b_first + elem]) { return -1; } } return 0; } public static int Compare(char[] c, String s) { char[] x = s.ToCharArray(); for (int i = 0; i < x.Length; i++) { if (c[i] < x[i]) return 1; if (c[i] > x[i]) return -1; } return 0; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Reflection; namespace OpenSim.Region.CoreModules.Asset { /// <summary> /// Cenome memory asset cache. /// </summary> /// <remarks> /// <para> /// Cache is enabled by setting "AssetCaching" configuration to value "CenomeMemoryAssetCache". /// When cache is successfully enable log should have message /// "[ASSET CACHE]: Cenome asset cache enabled (MaxSize = XXX bytes, MaxCount = XXX, ExpirationTime = XXX)". /// </para> /// <para> /// Cache's size is limited by two parameters: /// maximal allowed size in bytes and maximal allowed asset count. When new asset /// is added to cache that have achieved either size or count limitation, cache /// will automatically remove less recently used assets from cache. Additionally /// asset's lifetime is controlled by expiration time. /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Configuration</term> /// <description>Description</description> /// </listheader> /// <item> /// <term>MaxSize</term> /// <description>Maximal size of the cache in bytes. Default value: 128MB (134 217 728 bytes).</description> /// </item> /// <item> /// <term>MaxCount</term> /// <description>Maximal count of assets stored to cache. Default value: 4096 assets.</description> /// </item> /// <item> /// <term>ExpirationTime</term> /// <description>Asset's expiration time in minutes. Default value: 30 minutes.</description> /// </item> /// </list> /// </para> /// </remarks> /// <example> /// Enabling Cenome Asset Cache: /// <code> /// [Modules] /// AssetCaching = "CenomeMemoryAssetCache" /// </code> /// Setting size and expiration time limitations: /// <code> /// [AssetCache] /// ; 256 MB (default: 134217728) /// MaxSize = 268435456 /// ; How many assets it is possible to store cache (default: 4096) /// MaxCount = 16384 /// ; Expiration time - 1 hour (default: 30 minutes) /// ExpirationTime = 60 /// </code> /// </example> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CenomeMemoryAssetCache")] public class CenomeMemoryAssetCache : IImprovedAssetCache, ISharedRegionModule { /// <summary> /// Cache's default maximal asset count. /// </summary> /// <remarks> /// <para> /// Assuming that average asset size is about 32768 bytes. /// </para> /// </remarks> public const int DefaultMaxCount = 4096; /// <summary> /// Default maximal size of the cache in bytes /// </summary> /// <remarks> /// <para> /// 128MB = 128 * 1024^2 = 134 217 728 bytes. /// </para> /// </remarks> public const long DefaultMaxSize = 134217728; /// <summary> /// Asset's default expiration time in the cache. /// </summary> public static readonly TimeSpan DefaultExpirationTime = TimeSpan.FromMinutes(30.0); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Cache object. /// </summary> private ICnmCache<string, AssetBase> m_cache; /// <summary> /// Count of cache commands /// </summary> private int m_cachedCount; /// <summary> /// How many gets before dumping statistics /// </summary> /// <remarks> /// If 0 or less, then disabled. /// </remarks> private int m_debugEpoch; /// <summary> /// Is Cenome asset cache enabled. /// </summary> private bool m_enabled; /// <summary> /// Count of get requests /// </summary> private int m_getCount; /// <summary> /// How many hits /// </summary> private int m_hitCount; /// <summary> /// Initialize asset cache module, with custom parameters. /// </summary> /// <param name="maximalSize"> /// Cache's maximal size in bytes. /// </param> /// <param name="maximalCount"> /// Cache's maximal count of assets. /// </param> /// <param name="expirationTime"> /// Asset's expiration time. /// </param> protected void Initialize(long maximalSize, int maximalCount, TimeSpan expirationTime) { if (maximalSize <= 0 || maximalCount <= 0) { //m_log.Debug("[ASSET CACHE]: Cenome asset cache is not enabled."); m_enabled = false; return; } if (expirationTime <= TimeSpan.Zero) { // Disable expiration time expirationTime = TimeSpan.MaxValue; } // Create cache and add synchronization wrapper over it m_cache = CnmSynchronizedCache<string, AssetBase>.Synchronized(new CnmMemoryCache<string, AssetBase>( maximalSize, maximalCount, expirationTime)); m_enabled = true; m_log.DebugFormat( "[ASSET CACHE]: Cenome asset cache enabled (MaxSize = {0} bytes, MaxCount = {1}, ExpirationTime = {2})", maximalSize, maximalCount, expirationTime); } #region IImprovedAssetCache Members /// <summary> /// Cache asset. /// </summary> /// <param name="asset"> /// The asset that is being cached. /// </param> public void Cache(AssetBase asset) { if (asset != null) { // m_log.DebugFormat("[CENOME ASSET CACHE]: Caching asset {0}", asset.ID); long size = asset.Data != null ? asset.Data.Length : 1; m_cache.Set(asset.ID, asset, size); m_cachedCount++; } } public bool Check(string id) { AssetBase asset; // XXX:This is probably not an efficient implementation. return m_cache.TryGetValue(id, out asset); } /// <summary> /// Clear asset cache. /// </summary> public void Clear() { m_cache.Clear(); } /// <summary> /// Expire (remove) asset stored to cache. /// </summary> /// <param name="id"> /// The expired asset's id. /// </param> public void Expire(string id) { m_cache.Remove(id); } /// <summary> /// Get asset stored /// </summary> /// <param name="id"> /// The asset's id. /// </param> /// <returns> /// Asset if it is found from cache; otherwise <see langword="null"/>. /// </returns> /// <remarks> /// <para> /// Caller should always check that is return value <see langword="null"/>. /// Cache doesn't guarantee in any situation that asset is stored to it. /// </para> /// </remarks> public AssetBase Get(string id) { m_getCount++; AssetBase assetBase; if (m_cache.TryGetValue(id, out assetBase)) m_hitCount++; if (m_getCount == m_debugEpoch) { m_log.DebugFormat( "[ASSET CACHE]: Cached = {0}, Get = {1}, Hits = {2}%, Size = {3} bytes, Avg. A. Size = {4} bytes", m_cachedCount, m_getCount, ((double)m_hitCount / m_getCount) * 100.0, m_cache.Size, m_cache.Size / m_cache.Count); m_getCount = 0; m_hitCount = 0; m_cachedCount = 0; } // if (null == assetBase) // m_log.DebugFormat("[CENOME ASSET CACHE]: Asset {0} not in cache", id); return assetBase; } #endregion IImprovedAssetCache Members #region ISharedRegionModule Members /// <summary> /// Gets region module's name. /// </summary> public string Name { get { return "CenomeMemoryAssetCache"; } } public Type ReplaceableInterface { get { return null; } } /// <summary> /// New region is being added to server. /// </summary> /// <param name="scene"> /// Region's scene. /// </param> public void AddRegion(Scene scene) { if (m_enabled) scene.RegisterModuleInterface<IImprovedAssetCache>(this); } /// <summary> /// Close region module. /// </summary> public void Close() { m_enabled = false; m_cache.Clear(); m_cache = null; } /// <summary> /// Initialize region module. /// </summary> /// <param name="source"> /// Configuration source. /// </param> public void Initialise(IConfigSource source) { m_cache = null; m_enabled = false; IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig == null) return; string name = moduleConfig.GetString("AssetCaching"); //m_log.DebugFormat("[XXX] name = {0} (this module's name: {1}", name, Name); if (name != Name) return; long maxSize = DefaultMaxSize; int maxCount = DefaultMaxCount; TimeSpan expirationTime = DefaultExpirationTime; IConfig assetConfig = source.Configs["AssetCache"]; if (assetConfig != null) { // Get optional configurations maxSize = assetConfig.GetLong("MaxSize", DefaultMaxSize); maxCount = assetConfig.GetInt("MaxCount", DefaultMaxCount); expirationTime = TimeSpan.FromMinutes(assetConfig.GetInt("ExpirationTime", (int)DefaultExpirationTime.TotalMinutes)); // Debugging purposes only m_debugEpoch = assetConfig.GetInt("DebugEpoch", 0); } Initialize(maxSize, maxCount, expirationTime); } /// <summary> /// Initialization post handling. /// </summary> /// <remarks> /// <para> /// Modules can use this to initialize connection with other modules. /// </para> /// </remarks> public void PostInitialise() { } /// <summary> /// Region has been loaded. /// </summary> /// <param name="scene"> /// Region's scene. /// </param> /// <remarks> /// <para> /// This is needed for all module types. Modules will register /// Interfaces with scene in AddScene, and will also need a means /// to access interfaces registered by other modules. Without /// this extra method, a module attempting to use another modules' /// interface would be successful only depending on load order, /// which can't be depended upon, or modules would need to resort /// to ugly kludges to attempt to request interfaces when needed /// and unnecessary caching logic repeated in all modules. /// The extra function stub is just that much cleaner. /// </para> /// </remarks> public void RegionLoaded(Scene scene) { } /// <summary> /// Region is being removed. /// </summary> /// <param name="scene"> /// Region scene that is being removed. /// </param> public void RemoveRegion(Scene scene) { } #endregion ISharedRegionModule Members } }
// 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, // MERCHANTABILITY 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.CodeAnalysis; using System.IO; using System.Linq; using System.Xml.Serialization; namespace Microsoft.PythonTools.Profiling { // XmlSerializer requires these types to be public [Serializable] public sealed class ProfilingTarget { internal static XmlSerializer Serializer = new XmlSerializer(typeof(ProfilingTarget)); [XmlElement("ProjectTarget")] public ProjectTarget ProjectTarget { get; set; } [XmlElement("StandaloneTarget")] public StandaloneTarget StandaloneTarget { get; set; } [XmlElement("Reports")] public Reports Reports { get; set; } [XmlElement()] public bool UseVTune { get; set; } internal string GetProfilingName(IServiceProvider serviceProvider, out bool save) { string baseName = null; if (ProjectTarget != null) { if (!String.IsNullOrEmpty(ProjectTarget.FriendlyName)) { baseName = ProjectTarget.FriendlyName; } } else if (StandaloneTarget != null) { if (!String.IsNullOrEmpty(StandaloneTarget.Script)) { baseName = Path.GetFileNameWithoutExtension(StandaloneTarget.Script); } } if (baseName == null) { baseName = Strings.PerformanceBaseFileName; } baseName = baseName + ".pyperf"; var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE)); if (dte.Solution.IsOpen && !String.IsNullOrEmpty(dte.Solution.FullName)) { save = true; return Path.Combine(Path.GetDirectoryName(dte.Solution.FullName), baseName); } save = false; return baseName; } internal ProfilingTarget Clone() { var res = new ProfilingTarget(); if (ProjectTarget != null) { res.ProjectTarget = ProjectTarget.Clone(); } if (StandaloneTarget != null) { res.StandaloneTarget = StandaloneTarget.Clone(); } if (Reports != null) { res.Reports = Reports.Clone(); } return res; } internal static bool IsSame(ProfilingTarget self, ProfilingTarget other) { if (self == null) { return other == null; } else if (other != null) { return ProjectTarget.IsSame(self.ProjectTarget, other.ProjectTarget) && StandaloneTarget.IsSame(self.StandaloneTarget, other.StandaloneTarget); } return false; } } [Serializable] public sealed class ProjectTarget { [XmlElement("TargetProject")] public Guid TargetProject { get; set; } [XmlElement("FriendlyName")] public string FriendlyName { get; set; } internal ProjectTarget Clone() { var res = new ProjectTarget(); res.TargetProject = TargetProject; res.FriendlyName = FriendlyName; return res; } internal static bool IsSame(ProjectTarget self, ProjectTarget other) { if (self == null) { return other == null; } else if (other != null) { return self.TargetProject == other.TargetProject; } return false; } } [Serializable] public sealed class StandaloneTarget { [XmlElement(ElementName = "PythonInterpreter")] public PythonInterpreter PythonInterpreter { get; set; } [XmlElement(ElementName = "InterpreterPath")] public string InterpreterPath { get; set; } [XmlElement("WorkingDirectory")] public string WorkingDirectory { get; set; } [XmlElement("Script")] public string Script { get; set; } [XmlElement("Arguments")] public string Arguments { get; set; } internal StandaloneTarget Clone() { var res = new StandaloneTarget(); if (PythonInterpreter != null) { res.PythonInterpreter = PythonInterpreter.Clone(); } res.InterpreterPath = InterpreterPath; res.WorkingDirectory = WorkingDirectory; res.Script = Script; res.Arguments = Arguments; return res; } internal static bool IsSame(StandaloneTarget self, StandaloneTarget other) { if (self == null) { return other == null; } else if (other != null) { return PythonInterpreter.IsSame(self.PythonInterpreter, other.PythonInterpreter) && self.InterpreterPath == other.InterpreterPath && self.WorkingDirectory == other.WorkingDirectory && self.Script == other.Script && self.Arguments == other.Arguments; } return false; } } public sealed class PythonInterpreter { [XmlElement("Id")] public string Id { get; set; } internal PythonInterpreter Clone() { var res = new PythonInterpreter(); res.Id = Id; return res; } internal static bool IsSame(PythonInterpreter self, PythonInterpreter other) { if (self == null) { return other == null; } else if (other != null) { return self.Id == other.Id; } return false; } } public sealed class Reports { public Reports() { } public Reports(Profiling.Report[] reports) { Report = reports; } [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [XmlElement("Report")] public Report[] Report { get { return AllReports.Values.ToArray(); } set { AllReports = new SortedDictionary<uint, Report>(); for (uint i = 0; i < value.Length; i++) { AllReports[i + SessionNode.StartingReportId] = value[i]; } } } internal SortedDictionary<uint, Report> AllReports { get; set; } internal Reports Clone() { var res = new Reports(); if (Report != null) { res.Report = new Report[Report.Length]; for (int i = 0; i < res.Report.Length; i++) { res.Report[i] = Report[i].Clone(); } } return res; } } public sealed class Report { public Report() { } public Report(string filename) { Filename = filename; } [XmlElement("Filename")] public string Filename { get; set; } internal Report Clone() { var res = new Report(); res.Filename = Filename; return res; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Serialization; using OpenSim.Region.CoreModules.World.Terrain; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Ionic.Zlib; using GZipStream = Ionic.Zlib.GZipStream; using CompressionMode = Ionic.Zlib.CompressionMode; using CompressionLevel = Ionic.Zlib.CompressionLevel; using OpenSim.Framework.Serialization.External; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// Prepare to write out an archive. /// </summary> public class ArchiveWriteRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The minimum major version of OAR that we can write. /// </summary> public static int MIN_MAJOR_VERSION = 0; /// <summary> /// The maximum major version of OAR that we can write. /// </summary> public static int MAX_MAJOR_VERSION = 1; /// <summary> /// Whether we're saving a multi-region archive. /// </summary> public bool MultiRegionFormat { get; set; } /// <summary> /// Determine whether this archive will save assets. Default is true. /// </summary> public bool SaveAssets { get; set; } /// <summary> /// Determines which objects will be included in the archive, according to their permissions. /// Default is null, meaning no permission checks. /// </summary> public string FilterContent { get; set; } protected Scene m_rootScene; protected Stream m_saveStream; protected TarArchiveWriter m_archiveWriter; protected Guid m_requestId; protected Dictionary<string, object> m_options; /// <summary> /// Constructor /// </summary> /// <param name="module">Calling module</param> /// <param name="savePath">The path to which to save data.</param> /// <param name="requestId">The id associated with this request</param> /// <exception cref="System.IO.IOException"> /// If there was a problem opening a stream for the file specified by the savePath /// </exception> public ArchiveWriteRequest(Scene scene, string savePath, Guid requestId) : this(scene, requestId) { try { m_saveStream = new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress, CompressionLevel.BestCompression); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.ErrorFormat("{0} {1}", e.Message, e.StackTrace); } } /// <summary> /// Constructor. /// </summary> /// <param name="scene">The root scene to archive</param> /// <param name="saveStream">The stream to which to save data.</param> /// <param name="requestId">The id associated with this request</param> public ArchiveWriteRequest(Scene scene, Stream saveStream, Guid requestId) : this(scene, requestId) { m_saveStream = saveStream; } protected ArchiveWriteRequest(Scene scene, Guid requestId) { m_rootScene = scene; m_requestId = requestId; m_archiveWriter = null; MultiRegionFormat = false; SaveAssets = true; FilterContent = null; } /// <summary> /// Archive the region requested. /// </summary> /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception> public void ArchiveRegion(Dictionary<string, object> options) { m_options = options; if (options.ContainsKey("all") && (bool)options["all"]) MultiRegionFormat = true; if (options.ContainsKey("noassets") && (bool)options["noassets"]) SaveAssets = false; Object temp; if (options.TryGetValue("checkPermissions", out temp)) FilterContent = (string)temp; // Find the regions to archive ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup(); if (MultiRegionFormat) { m_log.InfoFormat("[ARCHIVER]: Saving {0} regions", SceneManager.Instance.Scenes.Count); SceneManager.Instance.ForEachScene(delegate(Scene scene) { scenesGroup.AddScene(scene); }); } else { scenesGroup.AddScene(m_rootScene); } scenesGroup.CalcSceneLocations(); m_archiveWriter = new TarArchiveWriter(m_saveStream); try { // Write out control file. It should be first so that it will be found ASAP when loading the file. m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(scenesGroup)); m_log.InfoFormat("[ARCHIVER]: Added control file to archive."); // Archive the regions Dictionary<UUID, sbyte> assetUuids = new Dictionary<UUID, sbyte>(); scenesGroup.ForEachScene(delegate(Scene scene) { string regionDir = MultiRegionFormat ? scenesGroup.GetRegionDir(scene.RegionInfo.RegionID) : ""; ArchiveOneRegion(scene, regionDir, assetUuids); }); // Archive the assets if (SaveAssets) { m_log.DebugFormat("[ARCHIVER]: Saving {0} assets", assetUuids.Count); // Asynchronously request all the assets required to perform this archive operation AssetsRequest ar = new AssetsRequest( new AssetsArchiver(m_archiveWriter), assetUuids, m_rootScene.AssetService, m_rootScene.UserAccountService, m_rootScene.RegionInfo.ScopeID, options, ReceivedAllAssets); WorkManager.RunInThread(o => ar.Execute(), null, "Archive Assets Request"); // CloseArchive() will be called from ReceivedAllAssets() } else { m_log.DebugFormat("[ARCHIVER]: Not saving assets since --noassets was specified"); CloseArchive(string.Empty); } } catch (Exception e) { CloseArchive(e.Message); throw; } } private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary<UUID, sbyte> assetUuids) { m_log.InfoFormat("[ARCHIVER]: Writing region {0}", scene.Name); EntityBase[] entities = scene.GetEntities(); List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); int numObjectsSkippedPermissions = 0; // Filter entities so that we only have scene objects. // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods // end up having to do this IPermissionsModule permissionsModule = scene.RequestModuleInterface<IPermissionsModule>(); foreach (EntityBase entity in entities) { if (entity is SceneObjectGroup) { SceneObjectGroup sceneObject = (SceneObjectGroup)entity; if (!sceneObject.IsDeleted && !sceneObject.IsAttachment) { if (!CanUserArchiveObject(scene.RegionInfo.EstateSettings.EstateOwner, sceneObject, FilterContent, permissionsModule)) { // The user isn't allowed to copy/transfer this object, so it will not be included in the OAR. ++numObjectsSkippedPermissions; } else { sceneObjects.Add(sceneObject); } } } } if (SaveAssets) { UuidGatherer assetGatherer = new UuidGatherer(scene.AssetService, assetUuids); int prevAssets = assetUuids.Count; foreach (SceneObjectGroup sceneObject in sceneObjects) assetGatherer.AddForInspection(sceneObject); assetGatherer.GatherAll(); m_log.DebugFormat( "[ARCHIVER]: {0} scene objects to serialize requiring save of {1} assets", sceneObjects.Count, assetUuids.Count - prevAssets); } if (numObjectsSkippedPermissions > 0) { m_log.DebugFormat( "[ARCHIVER]: {0} scene objects skipped due to lack of permissions", numObjectsSkippedPermissions); } // Make sure that we also request terrain texture assets RegionSettings regionSettings = scene.RegionInfo.RegionSettings; if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1) assetUuids[regionSettings.TerrainTexture1] = (sbyte)AssetType.Texture; if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2) assetUuids[regionSettings.TerrainTexture2] = (sbyte)AssetType.Texture; if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3) assetUuids[regionSettings.TerrainTexture3] = (sbyte)AssetType.Texture; if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4) assetUuids[regionSettings.TerrainTexture4] = (sbyte)AssetType.Texture; Save(scene, sceneObjects, regionDir); } /// <summary> /// Checks whether the user has permission to export an object group to an OAR. /// </summary> /// <param name="user">The user</param> /// <param name="objGroup">The object group</param> /// <param name="filterContent">Which permissions to check: "C" = Copy, "T" = Transfer</param> /// <param name="permissionsModule">The scene's permissions module</param> /// <returns>Whether the user is allowed to export the object to an OAR</returns> private bool CanUserArchiveObject(UUID user, SceneObjectGroup objGroup, string filterContent, IPermissionsModule permissionsModule) { if (filterContent == null) return true; if (permissionsModule == null) return true; // this shouldn't happen // Check whether the user is permitted to export all of the parts in the SOG. If any // part can't be exported then the entire SOG can't be exported. bool permitted = true; //int primNumber = 1; foreach (SceneObjectPart obj in objGroup.Parts) { uint perm; PermissionClass permissionClass = permissionsModule.GetPermissionClass(user, obj); switch (permissionClass) { case PermissionClass.Owner: perm = obj.BaseMask; break; case PermissionClass.Group: perm = obj.GroupMask | obj.EveryoneMask; break; case PermissionClass.Everyone: default: perm = obj.EveryoneMask; break; } bool canCopy = (perm & (uint)PermissionMask.Copy) != 0; bool canTransfer = (perm & (uint)PermissionMask.Transfer) != 0; // Special case: if Everyone can copy the object then this implies it can also be // Transferred. // However, if the user is the Owner then we don't check EveryoneMask, because it seems that the mask // always (incorrectly) includes the Copy bit set in this case. But that's a mistake: the viewer // does NOT show that the object has Everyone-Copy permissions, and doesn't allow it to be copied. if (permissionClass != PermissionClass.Owner) canTransfer |= (obj.EveryoneMask & (uint)PermissionMask.Copy) != 0; bool partPermitted = true; if (filterContent.Contains("C") && !canCopy) partPermitted = false; if (filterContent.Contains("T") && !canTransfer) partPermitted = false; // If the user is the Creator of the object then it can always be included in the OAR bool creator = (obj.CreatorID.Guid == user.Guid); if (creator) partPermitted = true; //string name = (objGroup.PrimCount == 1) ? objGroup.Name : string.Format("{0} ({1}/{2})", obj.Name, primNumber, objGroup.PrimCount); //m_log.DebugFormat("[ARCHIVER]: Object permissions: {0}: Base={1:X4}, Owner={2:X4}, Everyone={3:X4}, permissionClass={4}, checkPermissions={5}, canCopy={6}, canTransfer={7}, creator={8}, permitted={9}", // name, obj.BaseMask, obj.OwnerMask, obj.EveryoneMask, // permissionClass, checkPermissions, canCopy, canTransfer, creator, partPermitted); if (!partPermitted) { permitted = false; break; } //++primNumber; } return permitted; } /// <summary> /// Create the control file. /// </summary> /// <returns></returns> public string CreateControlFile(ArchiveScenesGroup scenesGroup) { int majorVersion; int minorVersion; if (MultiRegionFormat) { majorVersion = MAX_MAJOR_VERSION; minorVersion = 0; } else { // To support older versions of OpenSim, we continue to create single-region OARs // using the old file format. In the future this format will be discontinued. majorVersion = 0; minorVersion = 8; } // // if (m_options.ContainsKey("version")) // { // string[] parts = m_options["version"].ToString().Split('.'); // if (parts.Length >= 1) // { // majorVersion = Int32.Parse(parts[0]); // // if (parts.Length >= 2) // minorVersion = Int32.Parse(parts[1]); // } // } // // if (majorVersion < MIN_MAJOR_VERSION || majorVersion > MAX_MAJOR_VERSION) // { // throw new Exception( // string.Format( // "OAR version number for save must be between {0} and {1}", // MIN_MAJOR_VERSION, MAX_MAJOR_VERSION)); // } // else if (majorVersion == MAX_MAJOR_VERSION) // { // // Force 1.0 // minorVersion = 0; // } // else if (majorVersion == MIN_MAJOR_VERSION) // { // // Force 0.4 // minorVersion = 4; // } m_log.InfoFormat("[ARCHIVER]: Creating version {0}.{1} OAR", majorVersion, minorVersion); if (majorVersion == 1) { m_log.WarnFormat("[ARCHIVER]: Please be aware that version 1.0 OARs are not compatible with OpenSim versions prior to 0.7.4. Do not use the --all option if you want to produce a compatible OAR"); } String s; using (StringWriter sw = new StringWriter()) { using (XmlTextWriter xtw = new XmlTextWriter(sw)) { xtw.Formatting = Formatting.Indented; xtw.WriteStartDocument(); xtw.WriteStartElement("archive"); xtw.WriteAttributeString("major_version", majorVersion.ToString()); xtw.WriteAttributeString("minor_version", minorVersion.ToString()); xtw.WriteStartElement("creation_info"); DateTime now = DateTime.UtcNow; TimeSpan t = now - new DateTime(1970, 1, 1); xtw.WriteElementString("datetime", ((int)t.TotalSeconds).ToString()); if (!MultiRegionFormat) xtw.WriteElementString("id", m_rootScene.RegionInfo.RegionID.ToString()); xtw.WriteEndElement(); xtw.WriteElementString("assets_included", SaveAssets.ToString()); if (MultiRegionFormat) { WriteRegionsManifest(scenesGroup, xtw); } else { xtw.WriteStartElement("region_info"); WriteRegionInfo(m_rootScene, xtw); xtw.WriteEndElement(); } xtw.WriteEndElement(); xtw.Flush(); } s = sw.ToString(); } return s; } /// <summary> /// Writes the list of regions included in a multi-region OAR. /// </summary> private static void WriteRegionsManifest(ArchiveScenesGroup scenesGroup, XmlTextWriter xtw) { xtw.WriteStartElement("regions"); // Write the regions in order: rows from South to North, then regions from West to East. // The list of regions can have "holes"; we write empty elements in their position. for (uint y = (uint)scenesGroup.Rect.Top; y < scenesGroup.Rect.Bottom; ++y) { SortedDictionary<uint, Scene> row; if (scenesGroup.Regions.TryGetValue(y, out row)) { xtw.WriteStartElement("row"); for (uint x = (uint)scenesGroup.Rect.Left; x < scenesGroup.Rect.Right; ++x) { Scene scene; if (row.TryGetValue(x, out scene)) { xtw.WriteStartElement("region"); xtw.WriteElementString("id", scene.RegionInfo.RegionID.ToString()); xtw.WriteElementString("dir", scenesGroup.GetRegionDir(scene.RegionInfo.RegionID)); WriteRegionInfo(scene, xtw); xtw.WriteEndElement(); } else { // Write a placeholder for a missing region xtw.WriteElementString("region", ""); } } xtw.WriteEndElement(); } else { // Write a placeholder for a missing row xtw.WriteElementString("row", ""); } } xtw.WriteEndElement(); // "regions" } protected static void WriteRegionInfo(Scene scene, XmlTextWriter xtw) { Vector2 size; size = new Vector2((float)scene.RegionInfo.RegionSizeX, (float)scene.RegionInfo.RegionSizeY); xtw.WriteElementString("size_in_meters", string.Format("{0},{1}", size.X, size.Y)); } protected void Save(Scene scene, List<SceneObjectGroup> sceneObjects, string regionDir) { if (regionDir != string.Empty) regionDir = ArchiveConstants.REGIONS_PATH + regionDir + "/"; m_log.InfoFormat("[ARCHIVER]: Adding region settings to archive."); // Write out region settings string settingsPath = String.Format("{0}{1}{2}.xml", regionDir, ArchiveConstants.SETTINGS_PATH, scene.RegionInfo.RegionName); m_archiveWriter.WriteFile(settingsPath, RegionSettingsSerializer.Serialize(scene.RegionInfo.RegionSettings)); m_log.InfoFormat("[ARCHIVER]: Adding parcel settings to archive."); // Write out land data (aka parcel) settings List<ILandObject> landObjects = scene.LandChannel.AllParcels(); foreach (ILandObject lo in landObjects) { LandData landData = lo.LandData; string landDataPath = String.Format("{0}{1}", regionDir, ArchiveConstants.CreateOarLandDataPath(landData)); m_archiveWriter.WriteFile(landDataPath, LandDataSerializer.Serialize(landData, m_options)); } m_log.InfoFormat("[ARCHIVER]: Adding terrain information to archive."); // Write out terrain string terrainPath = String.Format("{0}{1}{2}.r32", regionDir, ArchiveConstants.TERRAINS_PATH, scene.RegionInfo.RegionName); using (MemoryStream ms = new MemoryStream()) { scene.RequestModuleInterface<ITerrainModule>().SaveToStream(terrainPath, ms); m_archiveWriter.WriteFile(terrainPath, ms.ToArray()); } m_log.InfoFormat("[ARCHIVER]: Adding scene objects to archive."); // Write out scene object metadata IRegionSerialiserModule serializer = scene.RequestModuleInterface<IRegionSerialiserModule>(); foreach (SceneObjectGroup sceneObject in sceneObjects) { //m_log.DebugFormat("[ARCHIVER]: Saving {0} {1}, {2}", entity.Name, entity.UUID, entity.GetType()); string serializedObject = serializer.SerializeGroupToXml2(sceneObject, m_options); string objectPath = string.Format("{0}{1}", regionDir, ArchiveHelpers.CreateObjectPath(sceneObject)); m_archiveWriter.WriteFile(objectPath, serializedObject); } } protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut) { string errorMessage; if (timedOut) { errorMessage = "Loading assets timed out"; } else { foreach (UUID uuid in assetsNotFoundUuids) { m_log.DebugFormat("[ARCHIVER]: Could not find asset {0}", uuid); } // m_log.InfoFormat( // "[ARCHIVER]: Received {0} of {1} assets requested", // assetsFoundUuids.Count, assetsFoundUuids.Count + assetsNotFoundUuids.Count); errorMessage = String.Empty; } CloseArchive(errorMessage); } /// <summary> /// Closes the archive and notifies that we're done. /// </summary> /// <param name="errorMessage">The error that occurred, or empty for success</param> protected void CloseArchive(string errorMessage) { try { if (m_archiveWriter != null) m_archiveWriter.Close(); m_saveStream.Close(); } catch (Exception e) { m_log.Error(string.Format("[ARCHIVER]: Error closing archive: {0} ", e.Message), e); if (errorMessage == string.Empty) errorMessage = e.Message; } m_log.InfoFormat("[ARCHIVER]: Finished writing out OAR for {0}", m_rootScene.RegionInfo.RegionName); m_rootScene.EventManager.TriggerOarFileSaved(m_requestId, errorMessage); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.DocumentationCommentFormatting; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic.DocumentationCommentFormatting; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocCommentFormatting { public class DocCommentFormattingTests { private CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string xmlFragment, string expectedCSharp, string expectedVB) { var csharpFormattedText = _csharpService.Format(xmlFragment); var vbFormattedText = _vbService.Format(xmlFragment); Assert.Equal(expectedCSharp, csharpFormattedText); Assert.Equal(expectedVB, vbFormattedText); } private void TestFormat(string xmlFragment, string expected) { TestFormat(xmlFragment, expected, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void CTag() { var comment = "Class <c>Point</c> models a point in a two-dimensional plane."; var expected = "Class Point models a point in a two-dimensional plane."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ExampleAndCodeTags() { var comment = @"This method changes the point's location by the given x- and y-offsets. <example>For example: <code> Point p = new Point(3,5); p.Translate(-1,3); </code> results in <c>p</c>'s having the value (2,8). </example>"; var expected = "This method changes the point's location by the given x- and y-offsets. For example: Point p = new Point(3,5); p.Translate(-1,3); results in p's having the value (2,8)."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ListTag() { var comment = @"Here is an example of a bulleted list: <list type=""bullet""> <item> <description>Item 1.</description> </item> <item> <description>Item 2.</description> </item> </list>"; var expected = @"Here is an example of a bulleted list: Item 1. Item 2."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ParaTag() { var comment = @"This is the entry point of the Point class testing program. <para>This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class.</para>"; var expected = @"This is the entry point of the Point class testing program. This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestPermissionTag() { var comment = @"<permission cref=""System.Security.PermissionSet"">Everyone can access this method.</permission>"; var expected = @"Everyone can access this method."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeTag() { var comment = @"<see cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlsoTag() { var comment = @"<seealso cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ValueTag() { var comment = @"<value>Property <c>X</c> represents the point's x-coordinate.</value>"; var expected = @"Property X represents the point's x-coordinate."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestParamRefTag() { var comment = @"This constructor initializes the new Point to (<paramref name=""xor""/>,<paramref name=""yor""/>)."; var expected = "This constructor initializes the new Point to (xor,yor)."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestTypeParamRefTag() { var comment = @"This method fetches data and returns a list of <typeparamref name=""Z""/>."; var expected = @"This method fetches data and returns a list of Z."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace1() { var comment = " This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace2() { var comment = @" This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace3() { var comment = "This has extra whitespace."; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs1() { var comment = @" <para>This is part of a paragraph.</para> "; var expected = "This is part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs2() { var comment = @" <para>This is part of a paragraph.</para> <para>This is also part of a paragraph.</para> "; var expected = @"This is part of a paragraph. This is also part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs3() { var comment = @" This is a summary. <para>This is part of a paragraph.</para> "; var expected = @"This is a summary. This is part of a paragraph."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs4() { var comment = @" <para>This is part of a paragraph.</para> This is part of the summary, too. "; var expected = @"This is part of a paragraph. This is part of the summary, too."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See1() { var comment = @"See <see cref=""T:System.Object"" />"; var expected = "See System.Object"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See2() { var comment = @"See <see />"; var expected = @"See"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso1() { var comment = @"See also <seealso cref=""T:System.Object"" />"; var expected = @"See also System.Object"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso2() { var comment = @"See also <seealso />"; var expected = @"See also"; TestFormat(comment, expected); } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace Dynastream.Fit { /// <summary> /// Implements the DeviceInfo profile message. /// </summary> public class DeviceInfoMesg : Mesg { #region Fields static class DeviceTypeSubfield { public static ushort AntplusDeviceType = 0; public static ushort AntDeviceType = 1; public static ushort Subfields = 2; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } static class ProductSubfield { public static ushort GarminProduct = 0; public static ushort Subfields = 1; public static ushort Active = Fit.SubfieldIndexActiveSubfield; public static ushort MainField = Fit.SubfieldIndexMainField; } #endregion #region Constructors public DeviceInfoMesg() : base(Profile.mesgs[Profile.DeviceInfoIndex]) { } public DeviceInfoMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the Timestamp field /// Units: s</summary> /// <returns>Returns DateTime representing the Timestamp field</returns> public DateTime GetTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set Timestamp field /// Units: s</summary> /// <param name="timestamp_">Nullable field value to be set</param> public void SetTimestamp(DateTime timestamp_) { SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the DeviceIndex field</summary> /// <returns>Returns nullable byte representing the DeviceIndex field</returns> public byte? GetDeviceIndex() { return (byte?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set DeviceIndex field</summary> /// <param name="deviceIndex_">Nullable field value to be set</param> public void SetDeviceIndex(byte? deviceIndex_) { SetFieldValue(0, 0, deviceIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the DeviceType field</summary> /// <returns>Returns nullable byte representing the DeviceType field</returns> public byte? GetDeviceType() { return (byte?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set DeviceType field</summary> /// <param name="deviceType_">Nullable field value to be set</param> public void SetDeviceType(byte? deviceType_) { SetFieldValue(1, 0, deviceType_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the AntplusDeviceType subfield</summary> /// <returns>Nullable byte representing the AntplusDeviceType subfield</returns> public byte? GetAntplusDeviceType() { return (byte?)GetFieldValue(1, 0, DeviceTypeSubfield.AntplusDeviceType); } /// <summary> /// /// Set AntplusDeviceType subfield</summary> /// <param name="antplusDeviceType">Subfield value to be set</param> public void SetAntplusDeviceType(byte? antplusDeviceType) { SetFieldValue(1, 0, antplusDeviceType, DeviceTypeSubfield.AntplusDeviceType); } /// <summary> /// Retrieves the AntDeviceType subfield</summary> /// <returns>Nullable byte representing the AntDeviceType subfield</returns> public byte? GetAntDeviceType() { return (byte?)GetFieldValue(1, 0, DeviceTypeSubfield.AntDeviceType); } /// <summary> /// /// Set AntDeviceType subfield</summary> /// <param name="antDeviceType">Subfield value to be set</param> public void SetAntDeviceType(byte? antDeviceType) { SetFieldValue(1, 0, antDeviceType, DeviceTypeSubfield.AntDeviceType); } ///<summary> /// Retrieves the Manufacturer field</summary> /// <returns>Returns nullable ushort representing the Manufacturer field</returns> public ushort? GetManufacturer() { return (ushort?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Manufacturer field</summary> /// <param name="manufacturer_">Nullable field value to be set</param> public void SetManufacturer(ushort? manufacturer_) { SetFieldValue(2, 0, manufacturer_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SerialNumber field</summary> /// <returns>Returns nullable uint representing the SerialNumber field</returns> public uint? GetSerialNumber() { return (uint?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set SerialNumber field</summary> /// <param name="serialNumber_">Nullable field value to be set</param> public void SetSerialNumber(uint? serialNumber_) { SetFieldValue(3, 0, serialNumber_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Product field</summary> /// <returns>Returns nullable ushort representing the Product field</returns> public ushort? GetProduct() { return (ushort?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Product field</summary> /// <param name="product_">Nullable field value to be set</param> public void SetProduct(ushort? product_) { SetFieldValue(4, 0, product_, Fit.SubfieldIndexMainField); } /// <summary> /// Retrieves the GarminProduct subfield</summary> /// <returns>Nullable ushort representing the GarminProduct subfield</returns> public ushort? GetGarminProduct() { return (ushort?)GetFieldValue(4, 0, ProductSubfield.GarminProduct); } /// <summary> /// /// Set GarminProduct subfield</summary> /// <param name="garminProduct">Subfield value to be set</param> public void SetGarminProduct(ushort? garminProduct) { SetFieldValue(4, 0, garminProduct, ProductSubfield.GarminProduct); } ///<summary> /// Retrieves the SoftwareVersion field</summary> /// <returns>Returns nullable float representing the SoftwareVersion field</returns> public float? GetSoftwareVersion() { return (float?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set SoftwareVersion field</summary> /// <param name="softwareVersion_">Nullable field value to be set</param> public void SetSoftwareVersion(float? softwareVersion_) { SetFieldValue(5, 0, softwareVersion_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the HardwareVersion field</summary> /// <returns>Returns nullable byte representing the HardwareVersion field</returns> public byte? GetHardwareVersion() { return (byte?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set HardwareVersion field</summary> /// <param name="hardwareVersion_">Nullable field value to be set</param> public void SetHardwareVersion(byte? hardwareVersion_) { SetFieldValue(6, 0, hardwareVersion_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the CumOperatingTime field /// Units: s /// Comment: Reset by new battery or charge.</summary> /// <returns>Returns nullable uint representing the CumOperatingTime field</returns> public uint? GetCumOperatingTime() { return (uint?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set CumOperatingTime field /// Units: s /// Comment: Reset by new battery or charge.</summary> /// <param name="cumOperatingTime_">Nullable field value to be set</param> public void SetCumOperatingTime(uint? cumOperatingTime_) { SetFieldValue(7, 0, cumOperatingTime_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BatteryVoltage field /// Units: V</summary> /// <returns>Returns nullable float representing the BatteryVoltage field</returns> public float? GetBatteryVoltage() { return (float?)GetFieldValue(10, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BatteryVoltage field /// Units: V</summary> /// <param name="batteryVoltage_">Nullable field value to be set</param> public void SetBatteryVoltage(float? batteryVoltage_) { SetFieldValue(10, 0, batteryVoltage_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the BatteryStatus field</summary> /// <returns>Returns nullable byte representing the BatteryStatus field</returns> public byte? GetBatteryStatus() { return (byte?)GetFieldValue(11, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set BatteryStatus field</summary> /// <param name="batteryStatus_">Nullable field value to be set</param> public void SetBatteryStatus(byte? batteryStatus_) { SetFieldValue(11, 0, batteryStatus_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SensorPosition field /// Comment: Indicates the location of the sensor</summary> /// <returns>Returns nullable BodyLocation enum representing the SensorPosition field</returns> public BodyLocation? GetSensorPosition() { object obj = GetFieldValue(18, 0, Fit.SubfieldIndexMainField); BodyLocation? value = obj == null ? (BodyLocation?)null : (BodyLocation)obj; return value; } /// <summary> /// Set SensorPosition field /// Comment: Indicates the location of the sensor</summary> /// <param name="sensorPosition_">Nullable field value to be set</param> public void SetSensorPosition(BodyLocation? sensorPosition_) { SetFieldValue(18, 0, sensorPosition_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Descriptor field /// Comment: Used to describe the sensor or location</summary> /// <returns>Returns byte[] representing the Descriptor field</returns> public byte[] GetDescriptor() { return (byte[])GetFieldValue(19, 0, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Descriptor field /// Comment: Used to describe the sensor or location</summary> /// <returns>Returns String representing the Descriptor field</returns> public String GetDescriptorAsString() { return Encoding.UTF8.GetString((byte[])GetFieldValue(19, 0, Fit.SubfieldIndexMainField)); } ///<summary> /// Set Descriptor field /// Comment: Used to describe the sensor or location</summary> /// <returns>Returns String representing the Descriptor field</returns> public void SetDescriptor(String descriptor_) { SetFieldValue(19, 0, System.Text.Encoding.UTF8.GetBytes(descriptor_), Fit.SubfieldIndexMainField); } /// <summary> /// Set Descriptor field /// Comment: Used to describe the sensor or location</summary> /// <param name="descriptor_">field value to be set</param> public void SetDescriptor(byte[] descriptor_) { SetFieldValue(19, 0, descriptor_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AntTransmissionType field</summary> /// <returns>Returns nullable byte representing the AntTransmissionType field</returns> public byte? GetAntTransmissionType() { return (byte?)GetFieldValue(20, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set AntTransmissionType field</summary> /// <param name="antTransmissionType_">Nullable field value to be set</param> public void SetAntTransmissionType(byte? antTransmissionType_) { SetFieldValue(20, 0, antTransmissionType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AntDeviceNumber field</summary> /// <returns>Returns nullable ushort representing the AntDeviceNumber field</returns> public ushort? GetAntDeviceNumber() { return (ushort?)GetFieldValue(21, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set AntDeviceNumber field</summary> /// <param name="antDeviceNumber_">Nullable field value to be set</param> public void SetAntDeviceNumber(ushort? antDeviceNumber_) { SetFieldValue(21, 0, antDeviceNumber_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the AntNetwork field</summary> /// <returns>Returns nullable AntNetwork enum representing the AntNetwork field</returns> public AntNetwork? GetAntNetwork() { object obj = GetFieldValue(22, 0, Fit.SubfieldIndexMainField); AntNetwork? value = obj == null ? (AntNetwork?)null : (AntNetwork)obj; return value; } /// <summary> /// Set AntNetwork field</summary> /// <param name="antNetwork_">Nullable field value to be set</param> public void SetAntNetwork(AntNetwork? antNetwork_) { SetFieldValue(22, 0, antNetwork_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SourceType field</summary> /// <returns>Returns nullable SourceType enum representing the SourceType field</returns> public SourceType? GetSourceType() { object obj = GetFieldValue(25, 0, Fit.SubfieldIndexMainField); SourceType? value = obj == null ? (SourceType?)null : (SourceType)obj; return value; } /// <summary> /// Set SourceType field</summary> /// <param name="sourceType_">Nullable field value to be set</param> public void SetSourceType(SourceType? sourceType_) { SetFieldValue(25, 0, sourceType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ProductName field /// Comment: Optional free form string to indicate the devices name or model</summary> /// <returns>Returns byte[] representing the ProductName field</returns> public byte[] GetProductName() { return (byte[])GetFieldValue(27, 0, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the ProductName field /// Comment: Optional free form string to indicate the devices name or model</summary> /// <returns>Returns String representing the ProductName field</returns> public String GetProductNameAsString() { return Encoding.UTF8.GetString((byte[])GetFieldValue(27, 0, Fit.SubfieldIndexMainField)); } ///<summary> /// Set ProductName field /// Comment: Optional free form string to indicate the devices name or model</summary> /// <returns>Returns String representing the ProductName field</returns> public void SetProductName(String productName_) { SetFieldValue(27, 0, System.Text.Encoding.UTF8.GetBytes(productName_), Fit.SubfieldIndexMainField); } /// <summary> /// Set ProductName field /// Comment: Optional free form string to indicate the devices name or model</summary> /// <param name="productName_">field value to be set</param> public void SetProductName(byte[] productName_) { SetFieldValue(27, 0, productName_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
using Android.App; using Android.Content; using Android.OS; using Java.Security; using Java.Security.Spec; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Xamarin.InAppPurchasing.Droid { public class GooglePlayPurchaseService : PurchaseService { private BillingConnection _connection; private TaskCompletionSource<Order> _purchaseSource; private IPublicKey _publicKey; private sealed class Product { public string Title { get; set; } public string Price { get; set; } public string Type { get; set; } public string Description { get; set; } public string ProductId { get; set; } } private sealed class Order { public string PackageName { get; set; } public string OrderId { get; set; } public string ProductId { get; set; } public string DeveloperPayload { get; set; } public long PurchaseTime { get; set; } public int PurchaseState { get; set; } public string PurchaseToken { get; set; } public byte[] Signature { get; set; } } private async Task Connect() { if (_connection == null) { _connection = new BillingConnection(); await _connection.Connect(); } } public void Disconnect() { if (_connection != null) { _connection.Disconnect(); _connection.Dispose(); _connection = null; } } public string PublicKey { get; set; } public async override Task<Purchase[]> GetPrices(params string[] ids) { await Connect(); var querySku = new Bundle(); querySku.PutStringArrayList(BillingConstants.SkuDetailsItemList, ids); var skuDetails = await Task.Factory.StartNew(() => _connection.Service.GetSkuDetails(BillingConstants.ApiVersion, Application.Context.PackageName, BillingConstants.ItemTypeInApp, querySku)); int response = skuDetails.GetInt(BillingConstants.ResponseCode); if (response != BillingConstants.ResultOk) { throw new Exception("GetSkuDetails failed, code: " + response); } var productsAsJson = skuDetails.GetStringArrayList(BillingConstants.SkuDetailsList); var products = new List<Purchase>(productsAsJson.Count); foreach (string json in productsAsJson) { var nativeProduct = JsonConvert.DeserializeObject<Product>(json); products.Add(new Purchase { Id = nativeProduct.ProductId, Price = nativeProduct.Price, NativeObject = nativeProduct, }); } return products.ToArray(); } protected async override Task<Receipt> BuyNative(Purchase purchase) { var context = (Activity)Xamarin.Forms.Forms.Context; string developerPayload = Guid.NewGuid().ToString("N"); var buyIntent = _connection.Service.GetBuyIntent(BillingConstants.ApiVersion, context.PackageName, purchase.Id, BillingConstants.ItemTypeInApp, developerPayload); int response = buyIntent.GetInt(BillingConstants.ResponseCode); if (response == BillingConstants.ResultItemAlreadyOwned) { var ownedItems = await Task.Factory.StartNew(() => _connection.Service.GetPurchases(BillingConstants.ApiVersion, context.PackageName, BillingConstants.ItemTypeInApp, null)); response = ownedItems.GetInt(BillingConstants.ResponseCode); if (response != BillingConstants.ResultOk) { throw new Exception("GetPurchases failed, code: " + response); } var ordersJson = ownedItems.GetStringArrayList(BillingConstants.InAppDataList); var signatures = ownedItems.GetStringArrayList(BillingConstants.InAppSignatureList); if (ordersJson == null || ordersJson.Count == 0) { throw new Exception("GetPurchases failed, missing: " + BillingConstants.InAppDataList); } if (signatures == null || signatures.Count == 0) { throw new Exception("GetPurchases failed, missing: " + BillingConstants.InAppSignatureList); } for (int i = 0; i < ordersJson.Count; i++) { string json = ordersJson[i]; var pastOrder = JsonConvert.DeserializeObject<Order>(json); if (pastOrder.ProductId != purchase.Id) continue; pastOrder.Signature = Convert.FromBase64String(signatures[i]); if (!IsSignatureValid(pastOrder, json)) throw new Exception("Signature not valid!"); return await ConsumePurchase(pastOrder); } throw new Exception("GetPurchases failed, no product found for: " + purchase.Id); } else if (response != BillingConstants.ResultOk) { throw new Exception("GetBuyIntent failed, code: " + response); } var source = _purchaseSource = new TaskCompletionSource<Order>(); var pendingIntent = (PendingIntent)buyIntent.GetParcelable(BillingConstants.BuyIntent); context.StartIntentSenderForResult(pendingIntent.IntentSender, BillingConstants.PurchaseRequestCode, new Intent(), 0, 0, 0); var order = await source.Task; if (order.DeveloperPayload != developerPayload) { throw new Exception($"DeveloperPayload did not match {developerPayload} != {order.DeveloperPayload}"); } return await ConsumePurchase(order); } private bool IsSignatureValid(Order order, string orderJson) { if (string.IsNullOrEmpty(PublicKey)) throw new Exception("PublicKey not set!"); if (_publicKey == null) { var bytes = Convert.FromBase64String(PublicKey); var keyFactory = KeyFactory.GetInstance("RSA"); _publicKey = keyFactory.GeneratePublic(new X509EncodedKeySpec(bytes)); } var signature = Signature.GetInstance("SHA1withRSA"); signature.InitVerify(_publicKey); signature.Update(Encoding.Default.GetBytes(orderJson)); return signature.Verify(order.Signature); } private async Task<Receipt> ConsumePurchase(Order order) { if (string.IsNullOrEmpty(order.PurchaseToken)) { throw new Exception("PurchaseToken not found, cannot consume purchase!"); } int response = await Task.Factory.StartNew(() => _connection.Service.ConsumePurchase(BillingConstants.ApiVersion, Application.Context.PackageName, order.PurchaseToken)); if (response != BillingConstants.ResultOk) { throw new Exception("ConsumePurchase failed, code: " + response); } return new GoogleReceipt { Id = order.ProductId, BundleId = Application.Context.PackageName, TransactionId = order.OrderId ?? "TEST", //NOTE: if null, it is a test purchase PurchaseToken = order.PurchaseToken, DeveloperPayload = order.DeveloperPayload, }; } public bool HandleActivityResult(int requestCode, Result resultCode, Intent data) { if (requestCode == BillingConstants.PurchaseRequestCode) { var source = _purchaseSource; if (source != null) { try { int responseCode = data.GetIntExtra(BillingConstants.ResponseCode, BillingConstants.ResultOk); if (responseCode != BillingConstants.ResultOk) { source.TrySetException(new Exception($"OnActivityResult {BillingConstants.ResponseCode} failed: {responseCode}")); return true; } if (resultCode != Result.Ok) { source.TrySetException(new Exception($"OnActivityResult {nameof(resultCode)} failed: {resultCode}")); return true; } string orderJson = data.GetStringExtra(BillingConstants.InAppPurchaseData); if (string.IsNullOrEmpty(orderJson)) { source.TrySetException(new Exception(BillingConstants.InAppPurchaseData + " not found!")); return true; } string signature = data.GetStringExtra(BillingConstants.InAppDataSignature); if (string.IsNullOrEmpty(signature)) { source.TrySetException(new Exception(BillingConstants.InAppDataSignature + " not found!")); return true; } var order = JsonConvert.DeserializeObject<Order>(orderJson); order.Signature = Convert.FromBase64String(signature); if (IsSignatureValid(order, orderJson)) { source.TrySetResult(order); } else { source.TrySetException(new Exception("Signature not valid!")); } } catch (Exception exc) { source.TrySetException(exc); return true; } } return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; namespace structinreg { public class Program { public static int Main() { try { int ret = Program0.Main1(); if (ret != 100) { return ret; } ret = Program1.Main1(); if (ret != 100) { return ret; } ret = Program2.Main1(); if (ret != 100) { return ret; } ret = Program3.Main1(); if (ret != 100) { return ret; } } catch(Exception e) { Console.WriteLine(e.ToString()); } return 100; } } struct Test20 { public int i1; public int i2; public int i3; public int i4; public int i5; public int i6; public int i7; public int i8; } struct Test21 { public int i1; public double d1; } struct Test22 { public object o1; public object o2; public object o3; public object o4; } struct Test23 { public int i1; public int i2; public int i3; public int i4; public int i5; public int i6; public int i7; public int i8; public int i9; public int i10; public int i11; public int i12; public int i13; public int i14; public int i15; public int i16; public int i17; public int i18; public int i19; public int i20; public int i21; public int i22; public int i23; public int i24; } public class Foo1 { public int iFoo; } public class Program2 { [MethodImplAttribute(MethodImplOptions.NoInlining)] static int test20(Test20 t1) { Console.WriteLine("test1Res: {0}", t1.i1 + t1.i2 + t1.i3 + t1.i4 + t1.i5 + t1.i6 + t1.i7 + t1.i8); return t1.i1 + t1.i2 + t1.i3 + t1.i4 + t1.i5 + t1.i6 + t1.i7 + t1.i8; } [MethodImplAttribute(MethodImplOptions.NoInlining)] static int test21(Test21 t2) { Console.WriteLine("test2Res: {0}", t2.i1 + t2.d1); return (int)(t2.i1 + t2.d1); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static int test22(Test22 t3) { Console.WriteLine("test3Res: {0} {1} {2} {3}", t3.o1, t3.o2, t3.o3, t3.o4); return (int)(t3.o1.GetHashCode() + t3.o2.GetHashCode() + t3.o3.GetHashCode() + t3.o4.GetHashCode()); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static int test23(Test23 t4) { Console.WriteLine("test4Res: {0}", t4.i1 + t4.i2, +t4.i3 + t4.i4 + t4.i5 + t4.i6 + t4.i7 + t4.i8 + t4.i9 + t4.i10 + t4.i11 + t4.i12 + t4.i13 + t4.i14 + t4.i15 + t4.i16 + t4.i17 + t4.i18 + t4.i19 + t4.i20 + t4.i21 + t4.i22 + t4.i23 + t4.i24); return t4.i1 + t4.i2 + t4.i3 + t4.i4 + t4.i5 + t4.i6 + t4.i7 + t4.i8 + t4.i9 + t4.i10 + t4.i11 + t4.i12 + t4.i13 + t4.i14 + t4.i15 + t4.i16 + t4.i17 + t4.i18 + t4.i19 + t4.i20 + t4.i21 + t4.i22 + t4.i23 + t4.i24; } [MethodImplAttribute(MethodImplOptions.NoInlining)] static int test24(int i1, int i2, int i3, int i4, int i5, int i6, int i7, Foo1 foo) { Console.WriteLine("test5Res: {0}", i1 + i2 + i3 + i4 + i5 + i6 + i7 + foo.iFoo); return (i1 + i2 + i3 + i4 + i5 + i6 + i7 + foo.iFoo); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static int Main1() { Test20 t1 = default(Test20); t1.i1 = 1; t1.i2 = 2; t1.i3 = 3; t1.i4 = 4; t1.i5 = 5; t1.i6 = 6; t1.i7 = 7; t1.i8 = 8; Test21 t2 = default(Test21); t2.i1 = 9; t2.d1 = 10; Test22 t3 = default(Test22); t3.o1 = new object(); t3.o2 = new object(); t3.o3 = new object(); t3.o4 = new object(); Test23 t4 = default(Test23); t4.i1 = 1; t4.i2 = 2; t4.i3 = 3; t4.i4 = 4; t4.i5 = 5; t4.i6 = 6; t4.i7 = 7; t4.i8 = 8; t4.i9 = 9; t4.i10 = 10; t4.i11 = 11; t4.i12 = 12; t4.i13 = 13; t4.i14 = 14; t4.i15 = 15; t4.i16 = 16; t4.i17 = 17; t4.i18 = 18; t4.i19 = 19; t4.i20 = 20; t4.i21 = 21; t4.i22 = 22; t4.i23 = 23; t4.i24 = 24; Foo1 foo = new Foo1(); foo.iFoo = 8; int t1Res = test20(t1); Console.WriteLine("test1 Result: {0}", t1Res); if (t1Res != 36) { throw new Exception("Failed test1 test!"); } int t2Res = test21(t2); Console.WriteLine("test2 Result: {0}", t2Res); if (t2Res != 19) { throw new Exception("Failed test2 test!"); } int t3Res = test22(t3); Console.WriteLine("test3 Result: {0}", t3Res); if (t3Res == 0) // Adding HashCodes should be != 0. { throw new Exception("Failed test3 test!"); } int t4Res = test23(t4); Console.WriteLine("test4 Result: {0}", t4Res); if (t4Res != 300) { throw new Exception("Failed test4 test!"); } int t5Res = test24(1, 2, 3, 4, 5, 6, 7, foo); if (t5Res != 36) { throw new Exception("Failed test5 test!"); } return 100; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Scriban.Functions; using Scriban.Helpers; using Scriban.Parsing; using Scriban.Syntax; namespace Scriban.Runtime { /// <summary> /// Base runtime object for arrays. /// </summary> /// <seealso cref="object" /> /// <seealso cref="System.Collections.IList" /> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ScriptArray<>.DebugListView))] #if SCRIBAN_PUBLIC public #else internal #endif class ScriptArray<T> : IList<T>, IList, IScriptObject, IScriptCustomBinaryOperation, IScriptTransformable { private List<T> _values; private bool _isReadOnly; // Attached ScriptObject is only created if needed private ScriptObject _script; /// <summary> /// Initializes a new instance of the <see cref="ScriptArray"/> class. /// </summary> public ScriptArray() { _values = new List<T>(); } /// <summary> /// Initializes a new instance of the <see cref="ScriptArray"/> class. /// </summary> /// <param name="capacity">The capacity.</param> public ScriptArray(int capacity) { _values = new List<T>(capacity); } public ScriptArray(T[] array) { if (array == null) throw new ArgumentNullException(nameof(array)); _values = new List<T>(array.Length); for (int i = 0; i < array.Length; i++) { _values.Add(array[i]); } } /// <summary> /// Initializes a new instance of the <see cref="ScriptArray"/> class. /// </summary> /// <param name="values">The values.</param> public ScriptArray(IEnumerable<T> values) { this._values = new List<T>(values); } public ScriptArray(IEnumerable values) { this._values = new List<T>(); foreach (var value in values) { _values.Add((T)value); } } public int Capacity { get => _values.Capacity; set => _values.Capacity = value; } public virtual bool IsReadOnly { get => _isReadOnly; set { if (_script != null) { _script.IsReadOnly = value; } _isReadOnly = value; } } public virtual IScriptObject Clone(bool deep) { var array = (ScriptArray<T>) MemberwiseClone(); array._values = new List<T>(_values.Count); array._script = null; if (deep) { foreach (var value in _values) { var fromValue = value; if (value is IScriptObject) { var fromObject = (IScriptObject)value; fromValue = (T)fromObject.Clone(true); } array._values.Add(fromValue); } if (_script != null) { array._script = (ScriptObject)_script.Clone(true); } } else { foreach (var value in _values) { array._values.Add(value); } if (_script != null) { array._script = (ScriptObject)_script.Clone(false); } } return array; } public ScriptObject ScriptObject => _script ?? (_script = new ScriptObject() { IsReadOnly = IsReadOnly}); public int Count => _values.Count; public virtual T this[int index] { get => index < 0 || index >= _values.Count ? default : _values[index]; set { if (index < 0) { return; } this.AssertNotReadOnly(); // Auto-expand the array in case of accessing a range outside the current value for (int i = _values.Count; i <= index; i++) { _values.Add(default); } _values[index] = value; } } public virtual void Add(T item) { this.AssertNotReadOnly(); _values.Add(item); } public void AddRange(IEnumerable<T> items) { if (items == null) throw new ArgumentNullException(nameof(items)); foreach (var item in items) { Add(item); } } int IList.Add(object value) { Add((T) value); return 0; } bool IList.Contains(object value) { return ((IList) _values).Contains(value); } public virtual void Clear() { this.AssertNotReadOnly(); _values.Clear(); } int IList.IndexOf(object value) { return ((IList)_values).IndexOf(value); } void IList.Insert(int index, object value) { Insert(index, (T)value); } public virtual bool Contains(T item) { return _values.Contains(item); } public virtual void CopyTo(T[] array, int arrayIndex) { _values.CopyTo(array, arrayIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(int index, T[] array, int arrayIndex, int count) { _values.CopyTo(index, array, arrayIndex, count); } public virtual int IndexOf(T item) { return _values.IndexOf(item); } public virtual void Insert(int index, T item) { this.AssertNotReadOnly(); // Auto-expand the array in case of accessing a range outside the current value for (int i = _values.Count; i < index; i++) { _values.Add(default); } _values.Insert(index, item); } void IList.Remove(object value) { Remove((T) value); } public virtual void RemoveAt(int index) { this.AssertNotReadOnly(); if (index < 0 || index >= _values.Count) { return; } _values.RemoveAt(index); } object IList.this[int index] { get => this[index]; set { if (typeof(T) == typeof(object)) { this[index] = (T)value; } else { if (value is T tValue) { this[index] = tValue; } else { this[index] = (T)Convert.ChangeType(value, typeof(T)); } } } } public virtual bool Remove(T item) { this.AssertNotReadOnly(); return _values.Remove(item); } public List<T>.Enumerator GetEnumerator() { return _values.GetEnumerator(); } bool IList.IsFixedSize => ((IList)_values).IsFixedSize; bool ICollection.IsSynchronized => ((ICollection)_values).IsSynchronized; object ICollection.SyncRoot => ((ICollection)_values).SyncRoot; bool IList.IsReadOnly => IsReadOnly; IEnumerator<T> IEnumerable<T>.GetEnumerator() { return _values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _values.GetEnumerator(); } bool ICollection<T>.IsReadOnly => IsReadOnly; void ICollection.CopyTo(Array array, int index) { ((ICollection)_values).CopyTo(array, index); } public IEnumerable<string> GetMembers() { yield return "size"; if (_script != null) { foreach (var member in _script.GetMembers()) { yield return member; } } } public virtual bool Contains(string member) { return ScriptObject.Contains(member); } public virtual bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value) { if (member == "size") { value = Count; return true; } return ScriptObject.TryGetValue(context, span, member, out value); } public virtual bool CanWrite(string member) { if (member == "size") { return false; } return ScriptObject.CanWrite(member); } public virtual bool TrySetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly) { return ScriptObject.TrySetValue(context, span, member, value, readOnly); } public virtual bool Remove(string member) { return ScriptObject.Remove(member); } public virtual void SetReadOnly(string member, bool readOnly) { ScriptObject.SetReadOnly(member, readOnly); } public bool TryEvaluate(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, SourceSpan leftSpan, object leftValue, SourceSpan rightSpan, object rightValue, out object result) { result = null; var leftArray = TryGetArray(leftValue); var rightArray = TryGetArray(rightValue); int intModifier = 0; var intSpan = leftSpan; var errorSpan = span; string reason = null; switch (op) { case ScriptBinaryOperator.BinaryOr: case ScriptBinaryOperator.BinaryAnd: case ScriptBinaryOperator.CompareEqual: case ScriptBinaryOperator.CompareNotEqual: case ScriptBinaryOperator.CompareLessOrEqual: case ScriptBinaryOperator.CompareGreaterOrEqual: case ScriptBinaryOperator.CompareLess: case ScriptBinaryOperator.CompareGreater: case ScriptBinaryOperator.Add: if (leftArray == null) { errorSpan = leftSpan; reason = " Expecting an array for the left argument."; } if (rightArray == null) { errorSpan = rightSpan; reason = " Expecting an array for the right argument."; } break; case ScriptBinaryOperator.Multiply: if (leftArray == null && rightArray == null || leftArray != null && rightArray != null) { reason = " Expecting only one array for the left or right argument."; } else { intModifier = context.ToInt(span, leftArray == null ? leftValue : rightValue); if (rightArray == null) intSpan = rightSpan; } break; case ScriptBinaryOperator.Divide: case ScriptBinaryOperator.DivideRound: case ScriptBinaryOperator.Modulus: if (leftArray == null) { errorSpan = leftSpan; reason = " Expecting an array for the left argument."; } else { intModifier = context.ToInt(span, rightValue); intSpan = rightSpan; } break; case ScriptBinaryOperator.ShiftLeft: if (leftArray == null) { errorSpan = leftSpan; reason = " Expecting an array for the left argument."; } break; case ScriptBinaryOperator.ShiftRight: if (rightArray == null) { errorSpan = rightSpan; reason = " Expecting an array for the right argument."; } break; default: reason = string.Empty; break; } if (intModifier < 0) { errorSpan = intSpan; reason = $" Integer {intModifier} cannot be negative when multiplying"; } if (reason != null) { throw new ScriptRuntimeException(errorSpan, $"The operator `{op.ToText()}` is not supported between {context.GetTypeName(leftValue)} and {context.GetTypeName(rightValue)}.{reason}"); } switch (op) { case ScriptBinaryOperator.BinaryOr: result = new ScriptArray<T>(leftArray.Union(rightArray)); return true; case ScriptBinaryOperator.BinaryAnd: result = new ScriptArray<T>(leftArray.Intersect(rightArray)); return true; case ScriptBinaryOperator.Add: result = ArrayFunctions.Concat(leftArray, rightArray); return true; case ScriptBinaryOperator.CompareEqual: case ScriptBinaryOperator.CompareNotEqual: case ScriptBinaryOperator.CompareLessOrEqual: case ScriptBinaryOperator.CompareGreaterOrEqual: case ScriptBinaryOperator.CompareLess: case ScriptBinaryOperator.CompareGreater: result = CompareTo(context, span, op, leftArray, rightArray); return true; case ScriptBinaryOperator.Multiply: { // array with integer var array = leftArray ?? rightArray; if (intModifier == 0) { result = new ScriptArray<T>(); return true; } var newArray = new ScriptArray<T>(intModifier * array.Count); for (int i = 0; i < intModifier; i++) { newArray.AddRange(array); } result = newArray; return true; } case ScriptBinaryOperator.Divide: case ScriptBinaryOperator.DivideRound: { // array with integer var array = leftArray ?? rightArray; if (intModifier == 0) throw new ScriptRuntimeException(intSpan, "Cannot divide by 0"); var newLength = array.Count / intModifier; var newArray = new ScriptArray<T>(newLength); for (int i = 0; i < newLength; i++) { newArray.Add(array[i]); } result = newArray; return true; } case ScriptBinaryOperator.Modulus: { // array with integer var array = leftArray ?? rightArray; if (intModifier == 0) throw new ScriptRuntimeException(intSpan, "Cannot divide by 0"); var newArray = new ScriptArray<T>(array.Count); for (int i = 0; i < array.Count; i++) { if ((i % intModifier) == 0) { newArray.Add(array[i]); } } result = newArray; return true; } case ScriptBinaryOperator.ShiftLeft: var newLeft = new ScriptArray<T>(leftArray); newLeft.Add(typeof(T) == typeof(object) ? (T)rightValue : context.ToObject<T>(rightSpan, rightValue)); result = newLeft; return true; case ScriptBinaryOperator.ShiftRight: var newRight = new ScriptArray<T>(rightArray); newRight.Insert(0, typeof(T) == typeof(object) ? (T)leftValue : context.ToObject<T>(leftSpan, leftValue)); result = newRight; return true; } return false; } private static ScriptArray<T> TryGetArray(object rightValue) { var rightArray = rightValue as ScriptArray<T>; if (rightArray == null) { var list = rightValue as IList; if (list != null) { rightArray = new ScriptArray<T>(list); } else if (rightValue is IEnumerable enumerable && !(rightValue is string)) { rightArray = new ScriptArray<T>(enumerable); } } return rightArray; } private static bool CompareTo(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, ScriptArray<T> left, ScriptArray<T> right) { // Compare the length first var compare = left.Count.CompareTo(right.Count); switch (op) { case ScriptBinaryOperator.CompareEqual: if (compare != 0) return false; break; case ScriptBinaryOperator.CompareNotEqual: if (compare != 0) return true; if (left.Count == 0) return false; break; case ScriptBinaryOperator.CompareLessOrEqual: case ScriptBinaryOperator.CompareLess: if (compare < 0) return true; if (compare > 0) return false; if (left.Count == 0 && op == ScriptBinaryOperator.CompareLess) return false; break; case ScriptBinaryOperator.CompareGreaterOrEqual: case ScriptBinaryOperator.CompareGreater: if (compare < 0) return false; if (compare > 0) return true; if (left.Count == 0 && op == ScriptBinaryOperator.CompareGreater) return false; break; default: throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not supported between {context.GetTypeName(left)} and {context.GetTypeName(right)}."); } // Otherwise we need to compare each element for (int i = 0; i < left.Count; i++) { var result = (bool) ScriptBinaryExpression.Evaluate(context, span, op, left[i], right[i]); if (!result) { return false; } } return true; } public Type ElementType => typeof(object); public virtual bool CanTransform(Type transformType) { return true; } public virtual bool Visit(TemplateContext context, SourceSpan span, Func<object, bool> visit) { foreach (var item in this) { if (!visit(item)) return false; } return true; } public virtual object Transform(TemplateContext context, SourceSpan span, Func<object, object> apply, Type destType) { if (apply == null) throw new ArgumentNullException(nameof(apply)); var clone = (ScriptArray<T>)Clone(true); var values = clone._values; if (typeof(T) == typeof(object)) { for (int i = 0; i < values.Count; i++) { values[i] = (T)apply(values[i]); } } else { for (int i = 0; i < values.Count; i++) { values[i] = context.ToObject<T>(span, apply(values[i])); } } return clone; } internal class DebugListView { private readonly ScriptArray<T> _collection; public DebugListView(ScriptArray<T> collection) { this._collection = collection; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object[] Items => _collection._values.Cast<object>().ToArray(); } } #if SCRIBAN_PUBLIC public #else internal #endif class ScriptArray : ScriptArray<object> { public ScriptArray() { } public ScriptArray(int capacity) : base(capacity) { } public ScriptArray(IEnumerable<object> values) : base(values) { } public ScriptArray(IEnumerable values) : base(values) { } } }
// *********************************************************************** // Copyright (c) 2008-2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Reflection; #if NETCF using System.Linq; #endif using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Builders { /// <summary> /// NUnitTestCaseBuilder is a utility class used by attributes /// that build test cases. /// </summary> public class NUnitTestCaseBuilder { private readonly Randomizer randomizer = Randomizer.CreateRandomizer(); /// <summary> /// Builds a single NUnitTestMethod, either as a child of the fixture /// or as one of a set of test cases under a ParameterizedTestMethodSuite. /// </summary> /// <param name="method">The MethodInfo from which to construct the TestMethod</param> /// <param name="parentSuite">The suite or fixture to which the new test will be added</param> /// <param name="parms">The ParameterSet to be used, or null</param> /// <returns></returns> public TestMethod BuildTestMethod(MethodInfo method, Test parentSuite, TestCaseParameters parms) { var testMethod = new TestMethod(method, parentSuite) { Seed = randomizer.Next() }; string prefix = method.ReflectedType.FullName; // Needed to give proper fullname to test in a parameterized fixture. // Without this, the arguments to the fixture are not included. if (parentSuite != null) prefix = parentSuite.FullName; CheckTestMethodSignature(testMethod, parms); if (parms == null || parms.Arguments == null) testMethod.ApplyAttributesToTest(method); if (parms != null) { // NOTE: After the call to CheckTestMethodSignature, the Method // property of testMethod may no longer be the same as the // original MethodInfo, so we reassign it here. method = testMethod.Method; if (parms.TestName != null) { testMethod.Name = parms.TestName; testMethod.FullName = prefix + "." + parms.TestName; } else if (parms.OriginalArguments != null) { string name = MethodHelper.GetDisplayName(method, parms.OriginalArguments); testMethod.Name = name; testMethod.FullName = prefix + "." + name; } parms.ApplyToTest(testMethod); } return testMethod; } #region Helper Methods /// <summary> /// Helper method that checks the signature of a TestMethod and /// any supplied parameters to determine if the test is valid. /// /// Currently, NUnitTestMethods are required to be public, /// non-abstract methods, either static or instance, /// returning void. They may take arguments but the _values must /// be provided or the TestMethod is not considered runnable. /// /// Methods not meeting these criteria will be marked as /// non-runnable and the method will return false in that case. /// </summary> /// <param name="testMethod">The TestMethod to be checked. If it /// is found to be non-runnable, it will be modified.</param> /// <param name="parms">Parameters to be used for this test, or null</param> /// <returns>True if the method signature is valid, false if not</returns> /// <remarks> /// The return value is no longer used internally, but is retained /// for testing purposes. /// </remarks> private static bool CheckTestMethodSignature(TestMethod testMethod, TestCaseParameters parms) { if (testMethod.Method.IsAbstract) return MarkAsNotRunnable(testMethod, "Method is abstract"); if (!testMethod.Method.IsPublic) return MarkAsNotRunnable(testMethod, "Method is not public"); ParameterInfo[] parameters; #if NETCF if (testMethod.Method.IsGenericMethodDefinition) { if (parms != null && parms.Arguments != null) { testMethod.Method = testMethod.Method.MakeGenericMethodEx(parms.Arguments); if (testMethod.Method == null) return MarkAsNotRunnable(testMethod, "Cannot determine generic types by probing"); parameters = testMethod.Method.GetParameters(); } else parameters = new ParameterInfo[0]; } else #endif parameters = testMethod.Method.GetParameters(); #if !NETCF int minArgsNeeded = 0; foreach (var parameter in parameters) { // IsOptional is supported since .NET 1.1 if (!parameter.IsOptional) minArgsNeeded++; } #else int minArgsNeeded = parameters.Length; #endif int maxArgsNeeded = parameters.Length; object[] arglist = null; int argsProvided = 0; if (parms != null) { testMethod.parms = parms; testMethod.RunState = parms.RunState; arglist = parms.Arguments; if (arglist != null) argsProvided = arglist.Length; if (testMethod.RunState != RunState.Runnable) return false; } #if NETCF Type returnType = testMethod.Method.IsGenericMethodDefinition && (parms == null || parms.Arguments == null) ? typeof(void) : (Type)testMethod.Method.ReturnType; #else Type returnType = testMethod.Method.ReturnType; #endif #if NET_4_0 || NET_4_5 || PORTABLE if (AsyncInvocationRegion.IsAsyncOperation(testMethod.Method)) { if (returnType == typeof(void)) return MarkAsNotRunnable(testMethod, "Async test method must have non-void return type"); var returnsGenericTask = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>); if (returnsGenericTask && (parms == null || !parms.HasExpectedResult)) return MarkAsNotRunnable(testMethod, "Async test method must have non-generic Task return type when no result is expected"); if (!returnsGenericTask && parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Async test method must have Task<T> return type when a result is expected"); } else #endif if (returnType == typeof(void)) { if (parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result"); } else if (parms == null || !parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected"); if (argsProvided > 0 && maxArgsNeeded == 0) return MarkAsNotRunnable(testMethod, "Arguments provided for method not taking any"); if (argsProvided == 0 && minArgsNeeded > 0) return MarkAsNotRunnable(testMethod, "No arguments were provided"); if (argsProvided < minArgsNeeded) return MarkAsNotRunnable(testMethod, string.Format("Not enough arguments provided, provide at least {0} arguments.", minArgsNeeded)); if (argsProvided > maxArgsNeeded) return MarkAsNotRunnable(testMethod, string.Format("Too many arguments provided, provide at most {0} arguments.", maxArgsNeeded)); if (testMethod.Method.IsGenericMethodDefinition && arglist != null) { var typeArguments = new GenericMethodHelper(testMethod.Method).GetTypeArguments(arglist); foreach (Type o in typeArguments) if (o == null || o == TypeHelper.NonmatchingType) return MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method"); testMethod.Method = testMethod.Method.MakeGenericMethod(typeArguments); parameters = testMethod.Method.GetParameters(); } if (arglist != null && parameters != null) TypeHelper.ConvertArgumentList(arglist, parameters); return true; } private static bool MarkAsNotRunnable(TestMethod testMethod, string reason) { testMethod.RunState = RunState.NotRunnable; testMethod.Properties.Set(PropertyNames.SkipReason, reason); return false; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.List.LastIndexOf(T item, Int32) /// </summary> public class ListLastIndexOf2 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The generic type is int"); try { int[] iArray = new int[1000]; for (int i = 0; i < 1000; i++) { iArray[i] = i; } List<int> listObject = new List<int>(iArray); int ob = this.GetInt32(0, 1000); int result = listObject.LastIndexOf(ob, 999); if (result != ob) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The generic type is type of string"); try { string[] strArray = { "apple", "dog", "banana", "chocolate", "dog", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.LastIndexOf("dog", 3); if (result != 1) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type"); try { MyClass myclass1 = new MyClass(); MyClass myclass2 = new MyClass(); MyClass myclass3 = new MyClass(); MyClass[] mc = new MyClass[3] { myclass1, myclass2, myclass3 }; List<MyClass> listObject = new List<MyClass>(mc); int result = listObject.LastIndexOf(myclass3, 2); if (result != 2) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: There are many element in the list with the same value"); try { string[] strArray = { "apple", "banana", "chocolate", "banana", "banana", "dog", "banana", "food" }; List<string> listObject = new List<string>(strArray); int result = listObject.LastIndexOf("banana", 5); if (result != 4) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Do not find the element "); try { int[] iArray = { 1, 9, -15, 3, 6, -1, 8, 7, -11, 2, 4 }; List<int> listObject = new List<int>(iArray); int result = listObject.LastIndexOf(-11, 6); if (result != -1) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,result is: " + result); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The index is negative"); try { int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); int result = listObject.LastIndexOf(-11, -4); TestLibrary.TestFramework.LogError("101", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The index is greater than the last index of the list"); try { int[] iArray = { 1, 9, -11, 3, 6, -1, 8, 7, 1, 2, 4 }; List<int> listObject = new List<int>(iArray); int result = listObject.LastIndexOf(-11, 12); TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ListLastIndexOf2 test = new ListLastIndexOf2(); TestLibrary.TestFramework.BeginTestCase("ListLastIndexOf2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } } public class MyClass { }
namespace More.ComponentModel { using FluentAssertions; using Moq; using More.Collections.Generic; using More.Windows.Input; using System; using System.Collections.Generic; using System.ComponentModel; using Xunit; using static Moq.Times; public class HierarchicalItemTTest { public static IEnumerable<object[]> ConstructorData { get { var command = new Command<string>( DefaultAction.None ); yield return new object[] { new Func<HierarchicalItem<string>>( () => new HierarchicalItem<string>( "test", command ) ), default( bool? ) }; yield return new object[] { new Func<HierarchicalItem<string>>( () => new HierarchicalItem<string>( "test", command, EqualityComparer<string>.Default ) ), default( bool? ) }; yield return new object[] { new Func<HierarchicalItem<string>>( () => new HierarchicalItem<string>( "test", true, command ) ), new bool?( true ) }; yield return new object[] { new Func<HierarchicalItem<string>>( () => new HierarchicalItem<string>( "test", true, command, EqualityComparer<string>.Default ) ), new bool?( true ) }; } } [Theory] [MemberData( nameof( ConstructorData ) )] public void new_hierarchical_item_should_set_expected_properties( Func<HierarchicalItem<string>> @new, bool? selected ) { // arrange // act var item = @new(); // assert item.Value.Should().Be( "test" ); item.IsSelected.Should().Be( selected ); item.Click.Should().BeOfType<CommandInterceptor<object>>(); } [Fact] public void perform_click_should_execute_command() { // arrange var click = new Mock<Action<string>>(); var command = new Command<string>( click.Object ); var item = new HierarchicalItem<string>( "test", command ); click.Setup( f => f( It.IsAny<string>() ) ); item.MonitorEvents(); // act item.PerformClick(); // assert click.Verify( f => f( null ), Once() ); item.ShouldRaise( nameof( item.Clicked ) ); } [Fact] public void perform_click_should_execute_command_with_parameter() { // arrange var click = new Mock<Action<string>>(); var command = new Command<string>( click.Object ); var item = new HierarchicalItem<string>( "test", command ); click.Setup( f => f( It.IsAny<string>() ) ); item.MonitorEvents(); // act item.PerformClick( "param" ); // assert click.Verify( f => f( "param" ), Once() ); item.ShouldRaise( nameof( item.Clicked ) ); } [Fact] public void item_selection_state_should_be_indeterminate_by_default() { // arrange var item = new HierarchicalItem<string>( "test", new Command<string>( DefaultAction.None ) ); // act // assert item.IsSelected.Should().BeNull(); } [Fact] public void item_should_be_selected_using_property() { // arrange var item = new HierarchicalItem<string>( "test", new Command<string>( DefaultAction.None ) ); item.MonitorEvents(); ( (INotifyPropertyChanged) item ).MonitorEvents<INotifyPropertyChanged>(); // act item.IsSelected = true; // assert item.ShouldRaisePropertyChangeFor( i => i.IsSelected ); item.ShouldRaise( nameof( item.Selected ) ); } [Fact] public void item_should_be_selected_using_command() { // arrange var item = new HierarchicalItem<string>( "test", new Command<string>( DefaultAction.None ) ); item.MonitorEvents(); ( (INotifyPropertyChanged) item ).MonitorEvents<INotifyPropertyChanged>(); // act item.Select.Execute( null ); // assert item.ShouldRaisePropertyChangeFor( i => i.IsSelected ); item.ShouldRaise( nameof( item.Selected ) ); } [Fact] public void item_should_be_unselected_using_property() { // arrange var item = new HierarchicalItem<string>( "test", true, new Command<string>( DefaultAction.None ) ); item.MonitorEvents(); ( (INotifyPropertyChanged) item ).MonitorEvents<INotifyPropertyChanged>(); // act item.IsSelected = false; // assert item.ShouldRaisePropertyChangeFor( i => i.IsSelected ); item.ShouldRaise( nameof( item.Unselected ) ); } [Fact] public void item_should_be_unselected_using_command() { // arrange var item = new HierarchicalItem<string>( "test", true, new Command<string>( DefaultAction.None ) ); item.MonitorEvents(); ( (INotifyPropertyChanged) item ).MonitorEvents<INotifyPropertyChanged>(); // act item.Unselect.Execute( null ); // assert item.ShouldRaisePropertyChangeFor( i => i.IsSelected ); item.ShouldRaise( nameof( item.Unselected ) ); } [Theory] [InlineData( 0 )] [InlineData( 1 )] [InlineData( 2 )] [InlineData( 3 )] public void item_depth_should_return_correct_level( int depth ) { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); // act for ( var i = 0; i < depth; i++ ) { var value = ( i + 1 ).ToString(); var newItem = new HierarchicalItem<string>( value, command ); item.Add( newItem ); item = newItem; } // assert item.Depth.Should().Be( depth ); } [Theory] [InlineData( 0 )] [InlineData( 1 )] [InlineData( 2 )] [InlineData( 3 )] public void parent_should_return_correct_object( int depth ) { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var parent = default( HierarchicalItem<string> ); // act for ( var i = 0; i < depth; i++ ) { var value = ( i + 1 ).ToString(); var newItem = new HierarchicalItem<string>( value, command ); item.Add( newItem ); parent = newItem.Parent; item = newItem; } // assert item.Parent.Should().BeSameAs( parent ); } [Fact] public void items_with_equal_values_at_different_depths_should_yield_different_hash_codes() { // arrange var comparer = new DynamicComparer<Tuple<int, string>>( tuple => tuple.Item1.GetHashCode() ); var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<Tuple<int, string>>( Tuple.Create( 1, "0" ), command, comparer ) { new HierarchicalItem<Tuple<int, string>>( Tuple.Create( 1, "1" ), command, comparer ) }; var other = new HierarchicalItem<Tuple<int, string>>( Tuple.Create( 1, "2" ), command, comparer ); // act item[0].Add( other ); // assert item.Depth.Should().NotBe( other.Depth ); item.GetHashCode().Should().NotBe( other.GetHashCode() ); } [Fact] public void items_with_different_values_and_depths_should_yield_different_hash_codes() { // arrange var comparer = new DynamicComparer<Tuple<int, string>>( tuple => tuple.Item1.GetHashCode() ); var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<Tuple<int, string>>( Tuple.Create( 2, "0" ), command, comparer ) { new HierarchicalItem<Tuple<int, string>>( Tuple.Create( 1, "1" ), command, comparer ) }; var other = new HierarchicalItem<Tuple<int, string>>( Tuple.Create( 0, "2" ), command, comparer ); // act item[0].Add( other ); // assert item.Depth.Should().NotBe( other.Depth ); item.GetHashCode().Should().NotBe( other.GetHashCode() ); } [Fact] public void X3DX3D_should_equate_equal_items() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var other = new HierarchicalItem<string>( "test", command ); // act var result = item == other; // assert result.Should().BeTrue(); } [Fact] public void X3DX3D_should_equate_equal_caseX2Dinsensitive_items() { // arrange var command = new Command<string>( DefaultAction.None ); var comparer = StringComparer.OrdinalIgnoreCase; var item = new HierarchicalItem<string>( "test", command, comparer ); var other = new HierarchicalItem<string>( "TEST", command, comparer ); // act var result = item == other; // assert result.Should().BeTrue(); } [Fact] public void X3DX3D_should_not_equate_unequal_items() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var other = new HierarchicalItem<string>( "abc", command ); // act var result = item == other; // assert result.Should().BeFalse(); } [Fact] public void X3DX3D_should_not_equate_equal_values_for_items_at_different_depths() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var other = new HierarchicalItem<string>( "test", command ); item.Add( other ); // act var result = item == other; // assert result.Should().BeFalse(); } [Fact] public void ne_should_not_equate_equal_items() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var other = new HierarchicalItem<string>( "test", command ); // act var result = item != other; // assert result.Should().BeFalse(); } [Fact] public void ne_should_not_equate_equal_caseX2Dinsensitive_items() { // arrange var command = new Command<string>( DefaultAction.None ); var comparer = StringComparer.OrdinalIgnoreCase; var item = new HierarchicalItem<string>( "test", command, comparer ); var other = new HierarchicalItem<string>( "TEST", command, comparer ); // act var result = item != other; // assert result.Should().BeFalse(); } [Fact] public void ne_should_equate_unequal_items() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var other = new HierarchicalItem<string>( "abc", command ); // act var result = item != other; // assert result.Should().BeTrue(); } [Fact] public void ne_should_not_equate_equal_values_for_items_at_different_depths() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var other = new HierarchicalItem<string>( "test", command ); item.Add( other ); // act var result = item != other; // assert result.Should().BeTrue(); } [Fact] public void equals_should_equate_equal_items() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var other = new HierarchicalItem<string>( "test", command ); // act var result = item.Equals( other ); // assert result.Should().BeTrue(); } [Fact] public void equals_should_equate_equal_caseX2Dinsensitive_items() { // arrange var command = new Command<string>( DefaultAction.None ); var comparer = StringComparer.OrdinalIgnoreCase; var item = new HierarchicalItem<string>( "test", command, comparer ); var other = new HierarchicalItem<string>( "TEST", command, comparer ); // act var result = item.Equals( other ); // assert result.Should().BeTrue(); } [Fact] public void equals_should_not_equate_unequal_items() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var other = new HierarchicalItem<string>( "abc", command ); // act var result = item.Equals( other ); // assert result.Should().BeFalse(); } [Fact] public void equals_should_not_equate_equal_values_for_items_at_different_depths() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var other = new HierarchicalItem<string>( "test", command ); item.Add( other ); // act var result = item.Equals( other ); // assert result.Should().BeFalse(); } [Fact] public void equals_should_equate_equal_objects() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); object other = new HierarchicalItem<string>( "test", command ); // act var result = item.Equals( other ); // assert result.Should().BeTrue(); } [Fact] public void equals_should_equate_equal_caseX2Dinsensitive_objects() { // arrange var command = new Command<string>( DefaultAction.None ); var comparer = StringComparer.OrdinalIgnoreCase; var item = new HierarchicalItem<string>( "test", command, comparer ); object other = new HierarchicalItem<string>( "TEST", command, comparer ); // act var result = item.Equals( other ); // assert result.Should().BeTrue(); } [Fact] public void equals_should_not_equate_unequal_objects() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); object other = new HierarchicalItem<string>( "abc", command ); // act var result = item.Equals( other ); // assert result.Should().BeFalse(); } [Fact] public void equals_should_not_equate_equal_values_for_objects_at_different_depths() { // arrange var command = new Command<string>( DefaultAction.None ); var item = new HierarchicalItem<string>( "test", command ); var child = new HierarchicalItem<string>( "test", command ); object other = child; item.Add( child ); // act var result = item.Equals( other ); // assert result.Should().BeFalse(); } } }