context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // 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 Microsoft.Azure; using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; namespace Microsoft.Azure.Commands.Compute.Automation { //[Cmdlet(VerbsLifecycle.Invoke, "AzureComputeMethod", DefaultParameterSetName = "InvokeByDynamicParameters")] [OutputType(typeof(object))] public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet, IDynamicParameters { protected RuntimeDefinedParameterDictionary dynamicParameters; protected object[] argumentList; protected static object[] ConvertDynamicParameters(RuntimeDefinedParameterDictionary parameters) { List<object> paramList = new List<object>(); foreach (var param in parameters) { paramList.Add(param.Value.Value); } return paramList.ToArray(); } [Parameter(Mandatory = true, ParameterSetName = "InvokeByDynamicParameters", Position = 0)] [Parameter(Mandatory = true, ParameterSetName = "InvokeByStaticParameters", Position = 0)] [ValidateSet( "ContainerServiceCreateOrUpdate", "ContainerServiceDelete", "ContainerServiceGet", "ContainerServiceList", "VirtualMachineScaleSetCreateOrUpdate", "VirtualMachineScaleSetDeallocate", "VirtualMachineScaleSetDelete", "VirtualMachineScaleSetDeleteInstances", "VirtualMachineScaleSetGet", "VirtualMachineScaleSetGetInstanceView", "VirtualMachineScaleSetList", "VirtualMachineScaleSetListAll", "VirtualMachineScaleSetListAllNext", "VirtualMachineScaleSetListNext", "VirtualMachineScaleSetListSkus", "VirtualMachineScaleSetListSkusNext", "VirtualMachineScaleSetPowerOff", "VirtualMachineScaleSetReimage", "VirtualMachineScaleSetRestart", "VirtualMachineScaleSetStart", "VirtualMachineScaleSetUpdateInstances", "VirtualMachineScaleSetVMDeallocate", "VirtualMachineScaleSetVMDelete", "VirtualMachineScaleSetVMGet", "VirtualMachineScaleSetVMGetInstanceView", "VirtualMachineScaleSetVMList", "VirtualMachineScaleSetVMListNext", "VirtualMachineScaleSetVMPowerOff", "VirtualMachineScaleSetVMReimage", "VirtualMachineScaleSetVMRestart", "VirtualMachineScaleSetVMStart" )] public virtual string MethodName { get; set; } protected object ParseParameter(object input) { if (input is PSObject) { return (input as PSObject).BaseObject; } else { return input; } } protected override void ProcessRecord() { base.ProcessRecord(); ExecuteClientAction(() => { if (ParameterSetName.StartsWith("InvokeByDynamicParameters")) { argumentList = ConvertDynamicParameters(dynamicParameters); } else { argumentList = ConvertFromArgumentsToObjects((object[])dynamicParameters["ArgumentList"].Value); } switch (MethodName) { case "ContainerServiceCreateOrUpdate": ExecuteContainerServiceCreateOrUpdateMethod(argumentList); break; case "ContainerServiceDelete": ExecuteContainerServiceDeleteMethod(argumentList); break; case "ContainerServiceGet": ExecuteContainerServiceGetMethod(argumentList); break; case "ContainerServiceList": ExecuteContainerServiceListMethod(argumentList); break; case "VirtualMachineScaleSetCreateOrUpdate": ExecuteVirtualMachineScaleSetCreateOrUpdateMethod(argumentList); break; case "VirtualMachineScaleSetDeallocate": ExecuteVirtualMachineScaleSetDeallocateMethod(argumentList); break; case "VirtualMachineScaleSetDelete": ExecuteVirtualMachineScaleSetDeleteMethod(argumentList); break; case "VirtualMachineScaleSetDeleteInstances": ExecuteVirtualMachineScaleSetDeleteInstancesMethod(argumentList); break; case "VirtualMachineScaleSetGet": ExecuteVirtualMachineScaleSetGetMethod(argumentList); break; case "VirtualMachineScaleSetGetInstanceView": ExecuteVirtualMachineScaleSetGetInstanceViewMethod(argumentList); break; case "VirtualMachineScaleSetList": ExecuteVirtualMachineScaleSetListMethod(argumentList); break; case "VirtualMachineScaleSetListAll": ExecuteVirtualMachineScaleSetListAllMethod(argumentList); break; case "VirtualMachineScaleSetListAllNext": ExecuteVirtualMachineScaleSetListAllNextMethod(argumentList); break; case "VirtualMachineScaleSetListNext": ExecuteVirtualMachineScaleSetListNextMethod(argumentList); break; case "VirtualMachineScaleSetListSkus": ExecuteVirtualMachineScaleSetListSkusMethod(argumentList); break; case "VirtualMachineScaleSetListSkusNext": ExecuteVirtualMachineScaleSetListSkusNextMethod(argumentList); break; case "VirtualMachineScaleSetPowerOff": ExecuteVirtualMachineScaleSetPowerOffMethod(argumentList); break; case "VirtualMachineScaleSetReimage": ExecuteVirtualMachineScaleSetReimageMethod(argumentList); break; case "VirtualMachineScaleSetRestart": ExecuteVirtualMachineScaleSetRestartMethod(argumentList); break; case "VirtualMachineScaleSetStart": ExecuteVirtualMachineScaleSetStartMethod(argumentList); break; case "VirtualMachineScaleSetUpdateInstances": ExecuteVirtualMachineScaleSetUpdateInstancesMethod(argumentList); break; case "VirtualMachineScaleSetVMDeallocate": ExecuteVirtualMachineScaleSetVMDeallocateMethod(argumentList); break; case "VirtualMachineScaleSetVMDelete": ExecuteVirtualMachineScaleSetVMDeleteMethod(argumentList); break; case "VirtualMachineScaleSetVMGet": ExecuteVirtualMachineScaleSetVMGetMethod(argumentList); break; case "VirtualMachineScaleSetVMGetInstanceView": ExecuteVirtualMachineScaleSetVMGetInstanceViewMethod(argumentList); break; case "VirtualMachineScaleSetVMList": ExecuteVirtualMachineScaleSetVMListMethod(argumentList); break; case "VirtualMachineScaleSetVMListNext": ExecuteVirtualMachineScaleSetVMListNextMethod(argumentList); break; case "VirtualMachineScaleSetVMPowerOff": ExecuteVirtualMachineScaleSetVMPowerOffMethod(argumentList); break; case "VirtualMachineScaleSetVMReimage": ExecuteVirtualMachineScaleSetVMReimageMethod(argumentList); break; case "VirtualMachineScaleSetVMRestart": ExecuteVirtualMachineScaleSetVMRestartMethod(argumentList); break; case "VirtualMachineScaleSetVMStart": ExecuteVirtualMachineScaleSetVMStartMethod(argumentList); break; default: WriteWarning("Cannot find the method by name = '" + MethodName + "'."); break; } }); } public virtual object GetDynamicParameters() { switch (MethodName) { case "ContainerServiceCreateOrUpdate": return CreateContainerServiceCreateOrUpdateDynamicParameters(); case "ContainerServiceDelete": return CreateContainerServiceDeleteDynamicParameters(); case "ContainerServiceGet": return CreateContainerServiceGetDynamicParameters(); case "ContainerServiceList": return CreateContainerServiceListDynamicParameters(); case "VirtualMachineScaleSetCreateOrUpdate": return CreateVirtualMachineScaleSetCreateOrUpdateDynamicParameters(); case "VirtualMachineScaleSetDeallocate": return CreateVirtualMachineScaleSetDeallocateDynamicParameters(); case "VirtualMachineScaleSetDelete": return CreateVirtualMachineScaleSetDeleteDynamicParameters(); case "VirtualMachineScaleSetDeleteInstances": return CreateVirtualMachineScaleSetDeleteInstancesDynamicParameters(); case "VirtualMachineScaleSetGet": return CreateVirtualMachineScaleSetGetDynamicParameters(); case "VirtualMachineScaleSetGetInstanceView": return CreateVirtualMachineScaleSetGetInstanceViewDynamicParameters(); case "VirtualMachineScaleSetList": return CreateVirtualMachineScaleSetListDynamicParameters(); case "VirtualMachineScaleSetListAll": return CreateVirtualMachineScaleSetListAllDynamicParameters(); case "VirtualMachineScaleSetListAllNext": return CreateVirtualMachineScaleSetListAllNextDynamicParameters(); case "VirtualMachineScaleSetListNext": return CreateVirtualMachineScaleSetListNextDynamicParameters(); case "VirtualMachineScaleSetListSkus": return CreateVirtualMachineScaleSetListSkusDynamicParameters(); case "VirtualMachineScaleSetListSkusNext": return CreateVirtualMachineScaleSetListSkusNextDynamicParameters(); case "VirtualMachineScaleSetPowerOff": return CreateVirtualMachineScaleSetPowerOffDynamicParameters(); case "VirtualMachineScaleSetReimage": return CreateVirtualMachineScaleSetReimageDynamicParameters(); case "VirtualMachineScaleSetRestart": return CreateVirtualMachineScaleSetRestartDynamicParameters(); case "VirtualMachineScaleSetStart": return CreateVirtualMachineScaleSetStartDynamicParameters(); case "VirtualMachineScaleSetUpdateInstances": return CreateVirtualMachineScaleSetUpdateInstancesDynamicParameters(); case "VirtualMachineScaleSetVMDeallocate": return CreateVirtualMachineScaleSetVMDeallocateDynamicParameters(); case "VirtualMachineScaleSetVMDelete": return CreateVirtualMachineScaleSetVMDeleteDynamicParameters(); case "VirtualMachineScaleSetVMGet": return CreateVirtualMachineScaleSetVMGetDynamicParameters(); case "VirtualMachineScaleSetVMGetInstanceView": return CreateVirtualMachineScaleSetVMGetInstanceViewDynamicParameters(); case "VirtualMachineScaleSetVMList": return CreateVirtualMachineScaleSetVMListDynamicParameters(); case "VirtualMachineScaleSetVMListNext": return CreateVirtualMachineScaleSetVMListNextDynamicParameters(); case "VirtualMachineScaleSetVMPowerOff": return CreateVirtualMachineScaleSetVMPowerOffDynamicParameters(); case "VirtualMachineScaleSetVMReimage": return CreateVirtualMachineScaleSetVMReimageDynamicParameters(); case "VirtualMachineScaleSetVMRestart": return CreateVirtualMachineScaleSetVMRestartDynamicParameters(); case "VirtualMachineScaleSetVMStart": return CreateVirtualMachineScaleSetVMStartDynamicParameters(); default: break; } return null; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.CortexM.Drivers { using System; using System.Runtime.CompilerServices; using RT = Microsoft.Zelig.Runtime; [Flags] public enum InterruptSettings { Normal = 0x00000000, Fast = 0x00000001, LevelSensitive = 0x00000000, EdgeSensitive = 0x00000002, ActiveLowOrFalling = 0x00000000, ActiveHighOrRising = 0x00000004, ActiveLow = LevelSensitive | ActiveLowOrFalling, ActiveHigh = LevelSensitive | ActiveHighOrRising, FallingEdge = EdgeSensitive | ActiveLowOrFalling, RisingEdge = EdgeSensitive | ActiveHighOrRising, } public enum InterruptPriority { Lowest = 255, BelowNormal = 200, Normal = 127, AboveNormal = 50, Highest = 0, } public abstract class InterruptController { public delegate void Callback( InterruptData data ); /// <summary> /// This structure contains the interrupt handler and any data associated with the interrupt. /// Context and Subcontext is interrupt dependent data and is not required to be set. /// </summary> public struct InterruptData { public ulong Context; public Handler Handler; } public class Handler { // // State // private readonly int m_index; internal readonly InterruptPriority m_priority; private readonly InterruptSettings m_settings; private readonly Callback m_callback; internal readonly RT.KernelNode< Handler > m_node; // // Constructor Methods // private Handler( int index , InterruptPriority priority , InterruptSettings settings , Callback callback ) { m_index = index; m_priority = priority; m_settings = settings; m_callback = callback; m_node = new RT.KernelNode< Handler >( this ); } // // Helper Methods // public static Handler Create( int index , InterruptPriority priority , InterruptSettings settings , Callback callback ) { return new Handler( index, priority, settings, callback ); } public void Enable() { NVIC.EnableInterrupt( m_index ); } public void Disable() { NVIC.DisableInterrupt( m_index ); } public void Invoke( InterruptData interruptData ) { m_callback( interruptData ); } // // Access Methods // public int Index { get { return m_index; } } public bool IsFastHandler { [RT.Inline] get { return (m_settings & InterruptSettings.Fast) != 0; } } public bool IsEdgeSensitive { [RT.Inline] get { return (m_settings & InterruptSettings.EdgeSensitive) != 0; } } public bool IsActiveHighOrRising { [RT.Inline] get { return (m_settings & InterruptSettings.ActiveHighOrRising) != 0;; } } } //--// static private readonly int c_Invalid = 0xFFFF; // ProcessorARMv[7|6]M.IRQn_Type.Invalid // // State // private RT.KernelList< Handler > m_handlers; private System.Threading.Thread m_interruptThread; private RT.KernelCircularBuffer<InterruptData> m_interrupts; // // Helper Methods // public void Initialize() { m_handlers = new RT.KernelList< Handler >(); m_interrupts = new RT.KernelCircularBuffer<InterruptData>(32); m_interruptThread = new System.Threading.Thread(DispatchInterrupts); m_interruptThread.Priority = System.Threading.ThreadPriority.Highest; } public void Activate() { m_interruptThread.Start(); } //--// public void RegisterAndEnable( Handler hnd ) { Register( hnd ); hnd.Enable(); } public void Register( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); var newPriority = hnd.m_priority; int priorityIdx = 0; // // Insert the handler in priority order and rebuild the Interrupt Priority Registers table. // for(RT.KernelNode<Handler> node = m_handlers.StartOfForwardWalk; ; node = node.Next) { if(hnd != null) { if(node.IsValidForForwardMove == false || node.Target.m_priority < newPriority) { var newNode = hnd.m_node; newNode.InsertBefore( node ); node = newNode; hnd = null; } } if(node.IsValidForForwardMove == false) { break; } NVIC.SetPriority( node.Target.Index, (uint)priorityIdx++ ); } } //--// public void DeregisterAndDisable( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.Disable(); Deregister( hnd ); } public void Deregister( Handler hnd ) { RT.BugCheck.AssertInterruptsOff(); hnd.m_node.RemoveFromList(); } //--// public void ProcessInterrupt() { ProcessInterrupt( false ); } public void ProcessFastInterrupt() { ProcessInterrupt( true ); } public void ProcessInterrupt( bool fFastOnly ) { InterruptData data; int activeInterrupt = GetNextActiveInterrupt(); data.Context = 0; while (activeInterrupt != c_Invalid) { RT.KernelNode<Handler> node = m_handlers.StartOfForwardWalk; while (true) { if (node.IsValidForForwardMove == false) { break; } Handler hnd = node.Target; if (hnd.Index == activeInterrupt) { data.Handler = hnd; if ( hnd.IsFastHandler ) { hnd.Invoke(data); } else { PostInterrupt(data); } } node = node.Next; } ClearInterrupt(activeInterrupt); activeInterrupt = GetNextActiveInterrupt(); } } public virtual int GetNextActiveInterrupt() { return c_Invalid; } public virtual void ClearInterrupt( int interrupt ) { } public void CauseInterrupt() { NVIC.SetPending( Board.Instance.GetSystemTimerIRQ() ); } public void ContinueUnderNormalInterrupt( RT.Peripherals.Continuation dlg ) { } public void PostInterrupt(InterruptData interruptData) { RT.BugCheck.AssertInterruptsOff(); m_interrupts.EnqueueNonblocking(interruptData); } private void DispatchInterrupts() { while (true) { InterruptData intr = m_interrupts.DequeueBlocking(); if (intr.Handler != null) { intr.Handler.Invoke( intr ); } } } // // Access Methods // public static extern InterruptController Instance { [RT.SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Diagnostics; using System.Data; using System.Data.SqlTypes; using System.Globalization; namespace Microsoft.SqlServer.Server { // DESIGN NOTES // // The following classes are a tight inheritance heirarchy, and are not designed for // being inherited outside of this file. Instances are guaranteed to be immutable, and // outside classes rely on this fact. // // The various levels may not all be used outside of this file, but for clarity of purpose // they are all usefull distinctions to make. // // In general, moving lower in the type heirarchy exposes less portable values. Thus, // the root metadata can be readily shared across different (MSSQL) servers and clients, // while QueryMetaData has attributes tied to a specific query, running against specific // data storage on a specific server. // // The SmiMetaData heirarchy does not do data validation on retail builds! It will assert // that the values passed to it have been validated externally, however. // // SmiMetaData // // Root of the heirarchy. // Represents the minimal amount of metadata required to represent any Sql Server datum // without any references to any particular server or schema (thus, no server-specific multi-part names). // It could be used to communicate solely between two disconnected clients, for instance. // // NOTE: It currently does not contain sufficient information to describe typed XML, since we // don't have a good server-independent mechanism for such. // // This class is also used as implementation for the public SqlMetaData class. internal class SmiMetaData { private SqlDbType _databaseType; // Main enum that determines what is valid for other attributes. private long _maxLength; // Varies for variable-length types, others are fixed value per type private byte _precision; // Varies for SqlDbType.Decimal, others are fixed value per type private byte _scale; // Varies for SqlDbType.Decimal, others are fixed value per type private long _localeId; // Valid only for character types, others are 0 private SqlCompareOptions _compareOptions; // Valid only for character types, others are SqlCompareOptions.Default private bool _isMultiValued; // Multiple instances per value? (I.e. tables, arrays) private IList<SmiExtendedMetaData> _fieldMetaData; // Metadata of fields for structured types private SmiMetaDataPropertyCollection _extendedProperties; // Extended properties, Key columns, sort order, etc. // DevNote: For now, since the list of extended property types is small, we can handle them in a simple list. // In the future, we may need to create a more performant storage & lookup mechanism, such as a hash table // of lists indexed by type of property or an array of lists with a well-known index for each type. // Limits for attributes (SmiMetaData will assert that these limits as applicable in constructor) internal const long UnlimitedMaxLengthIndicator = -1; // unlimited (except by implementation) max-length. internal const long MaxUnicodeCharacters = 4000; // Maximum for limited type internal const long MaxANSICharacters = 8000; // Maximum for limited type internal const long MaxBinaryLength = 8000; // Maximum for limited type internal const int MinPrecision = 1; // SqlDecimal defines max precision internal const int MinScale = 0; // SqlDecimal defines max scale internal const int MaxTimeScale = 7; // Max scale for time, datetime2, and datetimeoffset internal static readonly DateTime MaxSmallDateTime = new DateTime(2079, 06, 06, 23, 59, 29, 998); internal static readonly DateTime MinSmallDateTime = new DateTime(1899, 12, 31, 23, 59, 29, 999); internal static readonly SqlMoney MaxSmallMoney = new SqlMoney(((Decimal)Int32.MaxValue) / 10000); internal static readonly SqlMoney MinSmallMoney = new SqlMoney(((Decimal)Int32.MinValue) / 10000); internal const SqlCompareOptions DefaultStringCompareOptions = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth; internal const long MaxNameLength = 128; // maximum length in the server is 128. private static readonly IList<SmiExtendedMetaData> s_emptyFieldList = new SmiExtendedMetaData[0]; // Precision to max length lookup table private static byte[] s_maxLenFromPrecision = new byte[] {5,5,5,5,5,5,5,5,5,9,9,9,9,9, 9,9,9,9,9,13,13,13,13,13,13,13,13,13,17,17,17,17,17,17,17,17,17,17}; // Scale offset to max length lookup table private static byte[] s_maxVarTimeLenOffsetFromScale = new byte[] { 2, 2, 2, 1, 1, 0, 0, 0 }; // Defaults // SmiMetaData(SqlDbType, MaxLen, Prec, Scale, CompareOptions) internal static readonly SmiMetaData DefaultBigInt = new SmiMetaData(SqlDbType.BigInt, 8, 19, 0, SqlCompareOptions.None); // SqlDbType.BigInt internal static readonly SmiMetaData DefaultBinary = new SmiMetaData(SqlDbType.Binary, 1, 0, 0, SqlCompareOptions.None); // SqlDbType.Binary internal static readonly SmiMetaData DefaultBit = new SmiMetaData(SqlDbType.Bit, 1, 1, 0, SqlCompareOptions.None); // SqlDbType.Bit internal static readonly SmiMetaData DefaultChar_NoCollation = new SmiMetaData(SqlDbType.Char, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.Char internal static readonly SmiMetaData DefaultDateTime = new SmiMetaData(SqlDbType.DateTime, 8, 23, 3, SqlCompareOptions.None); // SqlDbType.DateTime internal static readonly SmiMetaData DefaultDecimal = new SmiMetaData(SqlDbType.Decimal, 9, 18, 0, SqlCompareOptions.None); // SqlDbType.Decimal internal static readonly SmiMetaData DefaultFloat = new SmiMetaData(SqlDbType.Float, 8, 53, 0, SqlCompareOptions.None); // SqlDbType.Float internal static readonly SmiMetaData DefaultImage = new SmiMetaData(SqlDbType.Image, UnlimitedMaxLengthIndicator, 0, 0, SqlCompareOptions.None); // SqlDbType.Image internal static readonly SmiMetaData DefaultInt = new SmiMetaData(SqlDbType.Int, 4, 10, 0, SqlCompareOptions.None); // SqlDbType.Int internal static readonly SmiMetaData DefaultMoney = new SmiMetaData(SqlDbType.Money, 8, 19, 4, SqlCompareOptions.None); // SqlDbType.Money internal static readonly SmiMetaData DefaultNChar_NoCollation = new SmiMetaData(SqlDbType.NChar, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.NChar internal static readonly SmiMetaData DefaultNText_NoCollation = new SmiMetaData(SqlDbType.NText, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.NText internal static readonly SmiMetaData DefaultNVarChar_NoCollation = new SmiMetaData(SqlDbType.NVarChar, MaxUnicodeCharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.NVarChar internal static readonly SmiMetaData DefaultReal = new SmiMetaData(SqlDbType.Real, 4, 24, 0, SqlCompareOptions.None); // SqlDbType.Real internal static readonly SmiMetaData DefaultUniqueIdentifier = new SmiMetaData(SqlDbType.UniqueIdentifier, 16, 0, 0, SqlCompareOptions.None); // SqlDbType.UniqueIdentifier internal static readonly SmiMetaData DefaultSmallDateTime = new SmiMetaData(SqlDbType.SmallDateTime, 4, 16, 0, SqlCompareOptions.None); // SqlDbType.SmallDateTime internal static readonly SmiMetaData DefaultSmallInt = new SmiMetaData(SqlDbType.SmallInt, 2, 5, 0, SqlCompareOptions.None); // SqlDbType.SmallInt internal static readonly SmiMetaData DefaultSmallMoney = new SmiMetaData(SqlDbType.SmallMoney, 4, 10, 4, SqlCompareOptions.None); // SqlDbType.SmallMoney internal static readonly SmiMetaData DefaultText_NoCollation = new SmiMetaData(SqlDbType.Text, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.Text internal static readonly SmiMetaData DefaultTimestamp = new SmiMetaData(SqlDbType.Timestamp, 8, 0, 0, SqlCompareOptions.None); // SqlDbType.Timestamp internal static readonly SmiMetaData DefaultTinyInt = new SmiMetaData(SqlDbType.TinyInt, 1, 3, 0, SqlCompareOptions.None); // SqlDbType.TinyInt internal static readonly SmiMetaData DefaultVarBinary = new SmiMetaData(SqlDbType.VarBinary, MaxBinaryLength, 0, 0, SqlCompareOptions.None); // SqlDbType.VarBinary internal static readonly SmiMetaData DefaultVarChar_NoCollation = new SmiMetaData(SqlDbType.VarChar, MaxANSICharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.VarChar internal static readonly SmiMetaData DefaultVariant = new SmiMetaData(SqlDbType.Variant, 8016, 0, 0, SqlCompareOptions.None); // SqlDbType.Variant internal static readonly SmiMetaData DefaultXml = new SmiMetaData(SqlDbType.Xml, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.Xml internal static readonly SmiMetaData DefaultStructured = new SmiMetaData(SqlDbType.Structured, 0, 0, 0, SqlCompareOptions.None); // SqlDbType.Structured internal static readonly SmiMetaData DefaultDate = new SmiMetaData(SqlDbType.Date, 3, 10, 0, SqlCompareOptions.None); // SqlDbType.Date internal static readonly SmiMetaData DefaultTime = new SmiMetaData(SqlDbType.Time, 5, 0, 7, SqlCompareOptions.None); // SqlDbType.Time internal static readonly SmiMetaData DefaultDateTime2 = new SmiMetaData(SqlDbType.DateTime2, 8, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTime2 internal static readonly SmiMetaData DefaultDateTimeOffset = new SmiMetaData(SqlDbType.DateTimeOffset, 10, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTimeOffset // No default for generic UDT internal static SmiMetaData DefaultNVarChar { get { return new SmiMetaData( DefaultNVarChar_NoCollation.SqlDbType, DefaultNVarChar_NoCollation.MaxLength, DefaultNVarChar_NoCollation.Precision, DefaultNVarChar_NoCollation.Scale, LocaleInterop.GetCurrentCultureLcid(), SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth ); } } // SMI V100 (aka V3) constructor. Superceded in V200. internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions ) : this(dbType, maxLength, precision, scale, localeId, compareOptions, false, null, null) { } // SMI V200 ctor. internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldTypes, SmiMetaDataPropertyCollection extendedProperties) : this(dbType, maxLength, precision, scale, localeId, compareOptions, null, isMultiValued, fieldTypes, extendedProperties) { } // SMI V220 ctor. internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldTypes, SmiMetaDataPropertyCollection extendedProperties) { Debug.Assert(IsSupportedDbType(dbType), "Invalid SqlDbType: " + dbType); SetDefaultsForType(dbType); switch (dbType) { case SqlDbType.BigInt: case SqlDbType.Bit: case SqlDbType.DateTime: case SqlDbType.Float: case SqlDbType.Image: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.Real: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.Timestamp: case SqlDbType.TinyInt: case SqlDbType.UniqueIdentifier: case SqlDbType.Variant: case SqlDbType.Xml: case SqlDbType.Date: break; case SqlDbType.Binary: case SqlDbType.VarBinary: _maxLength = maxLength; break; case SqlDbType.Char: case SqlDbType.NChar: case SqlDbType.NVarChar: case SqlDbType.VarChar: // locale and compare options are not validated until they get to the server _maxLength = maxLength; _localeId = localeId; _compareOptions = compareOptions; break; case SqlDbType.NText: case SqlDbType.Text: _localeId = localeId; _compareOptions = compareOptions; break; case SqlDbType.Decimal: Debug.Assert(MinPrecision <= precision && SqlDecimal.MaxPrecision >= precision, "Invalid precision: " + precision); Debug.Assert(MinScale <= scale && SqlDecimal.MaxScale >= scale, "Invalid scale: " + scale); Debug.Assert(scale <= precision, "Precision: " + precision + " greater than scale: " + scale); _precision = precision; _scale = scale; _maxLength = s_maxLenFromPrecision[precision - 1]; break; case SqlDbType.Udt: throw System.Data.Common.ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); case SqlDbType.Structured: if (null != fieldTypes) { _fieldMetaData = new System.Collections.ObjectModel.ReadOnlyCollection<SmiExtendedMetaData>(fieldTypes); } _isMultiValued = isMultiValued; _maxLength = _fieldMetaData.Count; break; case SqlDbType.Time: Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale); _scale = scale; _maxLength = 5 - s_maxVarTimeLenOffsetFromScale[scale]; break; case SqlDbType.DateTime2: Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale); _scale = scale; _maxLength = 8 - s_maxVarTimeLenOffsetFromScale[scale]; break; case SqlDbType.DateTimeOffset: Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale); _scale = scale; _maxLength = 10 - s_maxVarTimeLenOffsetFromScale[scale]; break; default: Debug.Assert(false, "How in the world did we get here? :" + dbType); break; } if (null != extendedProperties) { extendedProperties.SetReadOnly(); _extendedProperties = extendedProperties; } // properties and fields must meet the following conditions at this point: // 1) not null // 2) read only // 3) same number of columns in each list (0 count acceptable for properties that are "unused") Debug.Assert(null != _extendedProperties && _extendedProperties.IsReadOnly, "SmiMetaData.ctor: _extendedProperties is " + (null != _extendedProperties ? "writeable" : "null")); Debug.Assert(null != _fieldMetaData && _fieldMetaData.IsReadOnly, "SmiMetaData.ctor: _fieldMetaData is " + (null != _fieldMetaData ? "writeable" : "null")); #if DEBUG ((SmiDefaultFieldsProperty)_extendedProperties[SmiPropertySelector.DefaultFields]).CheckCount(_fieldMetaData.Count); ((SmiUniqueKeyProperty)_extendedProperties[SmiPropertySelector.UniqueKey]).CheckCount(_fieldMetaData.Count); #endif } // Sql-style compare options for character types. internal SqlCompareOptions CompareOptions { get { return _compareOptions; } } // LCID for type. 0 for non-character types. internal long LocaleId { get { return _localeId; } } // Units of length depend on type. // NVarChar, NChar, NText: # of unicode characters // Everything else: # of bytes internal long MaxLength { get { return _maxLength; } } internal byte Precision { get { return _precision; } } internal byte Scale { get { return _scale; } } internal SqlDbType SqlDbType { get { return _databaseType; } } internal bool IsMultiValued { get { return _isMultiValued; } } // Returns read-only list of field metadata internal IList<SmiExtendedMetaData> FieldMetaData { get { return _fieldMetaData; } } // Returns read-only list of extended properties internal SmiMetaDataPropertyCollection ExtendedProperties { get { return _extendedProperties; } } internal static bool IsSupportedDbType(SqlDbType dbType) { // Hole in SqlDbTypes between Xml and Udt for non-WinFS scenarios. return (SqlDbType.BigInt <= dbType && SqlDbType.Xml >= dbType) || (SqlDbType.Udt <= dbType && SqlDbType.DateTimeOffset >= dbType); } // Only correct access point for defaults per SqlDbType. internal static SmiMetaData GetDefaultForType(SqlDbType dbType) { Debug.Assert(IsSupportedDbType(dbType), "Unsupported SqlDbtype: " + dbType); Debug.Assert(dbType != SqlDbType.Udt, "UDT not supported"); return s_defaultValues[(int)dbType]; } // Private constructor used only to initialize default instance array elements. // DO NOT EXPOSE OUTSIDE THIS CLASS! private SmiMetaData( SqlDbType sqlDbType, long maxLength, byte precision, byte scale, SqlCompareOptions compareOptions) { _databaseType = sqlDbType; _maxLength = maxLength; _precision = precision; _scale = scale; _compareOptions = compareOptions; // defaults are the same for all types for the following attributes. _localeId = 0; _isMultiValued = false; _fieldMetaData = s_emptyFieldList; _extendedProperties = SmiMetaDataPropertyCollection.EmptyInstance; } // static array of default-valued metadata ordered by corresponding SqlDbType. // NOTE: INDEXED BY SqlDbType ENUM! MUST UPDATE THIS ARRAY WHEN UPDATING SqlDbType! // ONLY ACCESS THIS GLOBAL FROM GetDefaultForType! private static SmiMetaData[] s_defaultValues = { DefaultBigInt, // SqlDbType.BigInt DefaultBinary, // SqlDbType.Binary DefaultBit, // SqlDbType.Bit DefaultChar_NoCollation, // SqlDbType.Char DefaultDateTime, // SqlDbType.DateTime DefaultDecimal, // SqlDbType.Decimal DefaultFloat, // SqlDbType.Float DefaultImage, // SqlDbType.Image DefaultInt, // SqlDbType.Int DefaultMoney, // SqlDbType.Money DefaultNChar_NoCollation, // SqlDbType.NChar DefaultNText_NoCollation, // SqlDbType.NText DefaultNVarChar_NoCollation, // SqlDbType.NVarChar DefaultReal, // SqlDbType.Real DefaultUniqueIdentifier, // SqlDbType.UniqueIdentifier DefaultSmallDateTime, // SqlDbType.SmallDateTime DefaultSmallInt, // SqlDbType.SmallInt DefaultSmallMoney, // SqlDbType.SmallMoney DefaultText_NoCollation, // SqlDbType.Text DefaultTimestamp, // SqlDbType.Timestamp DefaultTinyInt, // SqlDbType.TinyInt DefaultVarBinary, // SqlDbType.VarBinary DefaultVarChar_NoCollation, // SqlDbType.VarChar DefaultVariant, // SqlDbType.Variant DefaultNVarChar_NoCollation, // Placeholder for value 24 DefaultXml, // SqlDbType.Xml DefaultNVarChar_NoCollation, // Placeholder for value 26 DefaultNVarChar_NoCollation, // Placeholder for value 27 DefaultNVarChar_NoCollation, // Placeholder for value 28 null, DefaultStructured, // Generic structured type DefaultDate, // SqlDbType.Date DefaultTime, // SqlDbType.Time DefaultDateTime2, // SqlDbType.DateTime2 DefaultDateTimeOffset, // SqlDbType.DateTimeOffset }; // static array of type names ordered by corresponding SqlDbType. // NOTE: INDEXED BY SqlDbType ENUM! MUST UPDATE THIS ARRAY WHEN UPDATING SqlDbType! // ONLY ACCESS THIS GLOBAL FROM get_TypeName! private static string[] s_typeNameByDatabaseType = { "bigint", // SqlDbType.BigInt "binary", // SqlDbType.Binary "bit", // SqlDbType.Bit "char", // SqlDbType.Char "datetime", // SqlDbType.DateTime "decimal", // SqlDbType.Decimal "float", // SqlDbType.Float "image", // SqlDbType.Image "int", // SqlDbType.Int "money", // SqlDbType.Money "nchar", // SqlDbType.NChar "ntext", // SqlDbType.NText "nvarchar", // SqlDbType.NVarChar "real", // SqlDbType.Real "uniqueidentifier", // SqlDbType.UniqueIdentifier "smalldatetime", // SqlDbType.SmallDateTime "smallint", // SqlDbType.SmallInt "smallmoney", // SqlDbType.SmallMoney "text", // SqlDbType.Text "timestamp", // SqlDbType.Timestamp "tinyint", // SqlDbType.TinyInt "varbinary", // SqlDbType.VarBinary "varchar", // SqlDbType.VarChar "sql_variant", // SqlDbType.Variant null, // placeholder for 24 "xml", // SqlDbType.Xml null, // placeholder for 26 null, // placeholder for 27 null, // placeholder for 28 String.Empty, // SqlDbType.Udt -- get type name from Type.FullName instead. String.Empty, // Structured types have user-defined type names. "date", // SqlDbType.Date "time", // SqlDbType.Time "datetime2", // SqlDbType.DateTime2 "datetimeoffset", // SqlDbType.DateTimeOffset }; // Internal setter to be used by constructors only! Modifies state! private void SetDefaultsForType(SqlDbType dbType) { SmiMetaData smdDflt = GetDefaultForType(dbType); _databaseType = dbType; _maxLength = smdDflt.MaxLength; _precision = smdDflt.Precision; _scale = smdDflt.Scale; _localeId = smdDflt.LocaleId; _compareOptions = smdDflt.CompareOptions; _isMultiValued = smdDflt._isMultiValued; _fieldMetaData = smdDflt._fieldMetaData; // This is ok due to immutability _extendedProperties = smdDflt._extendedProperties; // This is ok due to immutability } } // SmiExtendedMetaData // // Adds server-specific type extension information to base metadata, but still portable across a specific server. // internal class SmiExtendedMetaData : SmiMetaData { private string _name; // context-dependant identifier, ie. parameter name for parameters, column name for columns, etc. // three-part name for typed xml schema and for udt names private string _typeSpecificNamePart1; private string _typeSpecificNamePart2; private string _typeSpecificNamePart3; internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3) : this( dbType, maxLength, precision, scale, localeId, compareOptions, false, null, null, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { } // SMI V200 ctor. internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3) : this(dbType, maxLength, precision, scale, localeId, compareOptions, null, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { } // SMI V220 ctor. internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3) : base(dbType, maxLength, precision, scale, localeId, compareOptions, udtAssemblyQualifiedName, isMultiValued, fieldMetaData, extendedProperties) { Debug.Assert(null == name || MaxNameLength >= name.Length, "Name is too long"); _name = name; _typeSpecificNamePart1 = typeSpecificNamePart1; _typeSpecificNamePart2 = typeSpecificNamePart2; _typeSpecificNamePart3 = typeSpecificNamePart3; } internal string Name { get { return _name; } } internal string TypeSpecificNamePart1 { get { return _typeSpecificNamePart1; } } internal string TypeSpecificNamePart2 { get { return _typeSpecificNamePart2; } } internal string TypeSpecificNamePart3 { get { return _typeSpecificNamePart3; } } } // SmiParameterMetaData // // MetaData class to send parameter definitions to server. // Sealed because we don't need to derive from it yet. internal sealed class SmiParameterMetaData : SmiExtendedMetaData { private ParameterDirection _direction; // SMI V200 ctor. internal SmiParameterMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, ParameterDirection direction) : this(dbType, maxLength, precision, scale, localeId, compareOptions, null, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, direction) { } // SMI V220 ctor. internal SmiParameterMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, ParameterDirection direction) : base(dbType, maxLength, precision, scale, localeId, compareOptions, udtAssemblyQualifiedName, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { Debug.Assert(ParameterDirection.Input == direction || ParameterDirection.Output == direction || ParameterDirection.InputOutput == direction || ParameterDirection.ReturnValue == direction, "Invalid direction: " + direction); _direction = direction; } internal ParameterDirection Direction { get { return _direction; } } } // SmiStorageMetaData // // This class represents the addition of storage-level attributes to the heirarchy (i.e. attributes from // underlying table, source variables, or whatever). // // Most values use Null (either IsNullable == true or CLR null) to indicate "Not specified" state. Selection // of which values allow "not specified" determined by backward compatibility. // // Maps approximately to TDS' COLMETADATA token with TABNAME and part of COLINFO thrown in. internal class SmiStorageMetaData : SmiExtendedMetaData { private SqlBoolean _isKey; // Is this one of a set of key columns that uniquely identify an underlying table? // SMI V220 ctor. internal SmiStorageMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, SqlBoolean isKey ) : base(dbType, maxLength, precision, scale, localeId, compareOptions, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { _isKey = isKey; } internal SqlBoolean IsKey { get { return _isKey; } } } // SmiQueryMetaData // // Adds Query-specific attributes. // Sealed since we don't need to extend it for now. // Maps to full COLMETADATA + COLINFO + TABNAME tokens on TDS. internal class SmiQueryMetaData : SmiStorageMetaData { // SMI V220 ctor. internal SmiQueryMetaData(SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, SqlBoolean isKey ) : base(dbType, maxLength, precision, scale, localeId, compareOptions, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, isKey ) { } } }
// 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.IO; using System.Linq; using System.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public abstract class SslStreamStreamToStreamTest { private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message"); protected abstract Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream); [Fact] public async Task SslStream_StreamToStream_Authentication_Success() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var server = new SslStream(serverStream)) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { await DoHandshake(client, server); Assert.True(client.IsAuthenticated); Assert.True(server.IsAuthenticated); } } [Fact] public async Task SslStream_StreamToStream_Authentication_IncorrectServerName_Fail() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new SslStream(clientStream)) using (var server = new SslStream(serverStream)) using (var certificate = Configuration.Certificates.GetServerCertificate()) { Task t1 = client.AuthenticateAsClientAsync("incorrectServer"); Task t2 = server.AuthenticateAsServerAsync(certificate); await Assert.ThrowsAsync<AuthenticationException>(() => t1); await t2; } } [Fact] public async Task SslStream_StreamToStream_Successive_ClientWrite_Sync_Success() { byte[] recvBuf = new byte[_sampleMsg.Length]; VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { await DoHandshake(clientSslStream, serverSslStream); clientSslStream.Write(_sampleMsg); int bytesRead = 0; while (bytesRead < _sampleMsg.Length) { bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead); } Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected."); clientSslStream.Write(_sampleMsg); bytesRead = 0; while (bytesRead < _sampleMsg.Length) { bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead); } Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected."); } } [Fact] public async Task SslStream_StreamToStream_Successive_ClientWrite_WithZeroBytes_Success() { byte[] recvBuf = new byte[_sampleMsg.Length]; VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { await DoHandshake(clientSslStream, serverSslStream); clientSslStream.Write(Array.Empty<byte>()); await clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0); clientSslStream.Write(_sampleMsg); int bytesRead = 0; while (bytesRead < _sampleMsg.Length) { bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead); } Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected."); clientSslStream.Write(_sampleMsg); await clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0); clientSslStream.Write(Array.Empty<byte>()); bytesRead = 0; while (bytesRead < _sampleMsg.Length) { bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead); } Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected."); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task SslStream_StreamToStream_LargeWrites_Sync_Success(bool randomizedData) { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { await DoHandshake(clientSslStream, serverSslStream); byte[] largeMsg = new byte[4096 * 5]; // length longer than max read chunk size (16K + headers) if (randomizedData) { new Random().NextBytes(largeMsg); // not very compressible } else { for (int i = 0; i < largeMsg.Length; i++) { largeMsg[i] = unchecked((byte)i); // very compressible } } byte[] receivedLargeMsg = new byte[largeMsg.Length]; // First do a large write and read blocks at a time clientSslStream.Write(largeMsg); int bytesRead = 0, totalRead = 0; while (totalRead < largeMsg.Length && (bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0) { totalRead += bytesRead; } Assert.Equal(receivedLargeMsg.Length, totalRead); Assert.Equal(largeMsg, receivedLargeMsg); // Then write again and read bytes at a time clientSslStream.Write(largeMsg); foreach (byte b in largeMsg) { Assert.Equal(b, serverSslStream.ReadByte()); } } } [Fact] public async Task SslStream_StreamToStream_Successive_ClientWrite_Async_Success() { byte[] recvBuf = new byte[_sampleMsg.Length]; VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { await DoHandshake(clientSslStream, serverSslStream); await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length) .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds); int bytesRead = 0; while (bytesRead < _sampleMsg.Length) { bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead) .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds); } Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected."); await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length) .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds); bytesRead = 0; while (bytesRead < _sampleMsg.Length) { bytesRead += await serverSslStream.ReadAsync(recvBuf, bytesRead, _sampleMsg.Length - bytesRead) .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds); } Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected."); } } [Fact] public async Task SslStream_StreamToStream_Write_ReadByte_Success() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { await DoHandshake(clientSslStream, serverSslStream); for (int i = 0; i < 3; i++) { clientSslStream.Write(_sampleMsg); foreach (byte b in _sampleMsg) { Assert.Equal(b, serverSslStream.ReadByte()); } } } } [Fact] public async Task SslStream_StreamToStream_WriteAsync_ReadByte_Success() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { await DoHandshake(clientSslStream, serverSslStream); for (int i = 0; i < 3; i++) { await clientSslStream.WriteAsync(_sampleMsg, 0, _sampleMsg.Length).ConfigureAwait(false); foreach (byte b in _sampleMsg) { Assert.Equal(b, serverSslStream.ReadByte()); } } } } [Fact] public async Task SslStream_StreamToStream_WriteAsync_ReadAsync_Pending_Success() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new NotifyReadVirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { await DoHandshake(clientSslStream, serverSslStream); var serverBuffer = new byte[1]; var tcs = new TaskCompletionSource<object>(); serverStream.OnRead += (buffer, offset, count) => { tcs.TrySetResult(null); }; Task readTask = serverSslStream.ReadAsync(serverBuffer, 0, serverBuffer.Length); // Since the sequence of calls that ends in serverStream.Read() is sync, by now // the read task will have acquired the semaphore shared by Stream.BeginReadInternal() // and Stream.BeginWriteInternal(). // But to be sure, we wait until we know we're inside Read(). await tcs.Task.TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds); // Should not hang await serverSslStream.WriteAsync(new byte[] { 1 }, 0, 1) .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds); // Read in client var clientBuffer = new byte[1]; await clientSslStream.ReadAsync(clientBuffer, 0, clientBuffer.Length); Assert.Equal(1, clientBuffer[0]); // Complete server read task await clientSslStream.WriteAsync(new byte[] { 2 }, 0, 1); await readTask; Assert.Equal(2, serverBuffer[0]); } } [Fact] public async Task SslStream_StreamToStream_Dispose_Throws() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) { var serverSslStream = new SslStream(serverStream); await DoHandshake(clientSslStream, serverSslStream); var serverBuffer = new byte[1]; Task serverReadTask = serverSslStream.ReadAsync(serverBuffer, 0, serverBuffer.Length); await serverSslStream.WriteAsync(new byte[] { 1 }, 0, 1) .TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds); // Shouldn't throw, the context is diposed now. // Since the server read task is in progress, the read buffer is not returned to ArrayPool. serverSslStream.Dispose(); // Read in client var clientBuffer = new byte[1]; await clientSslStream.ReadAsync(clientBuffer, 0, clientBuffer.Length); Assert.Equal(1, clientBuffer[0]); await clientSslStream.WriteAsync(new byte[] { 2 }, 0, 1); if (PlatformDetection.IsFullFramework) { await Assert.ThrowsAsync<ObjectDisposedException>(() => serverReadTask); } else { IOException serverException = await Assert.ThrowsAsync<IOException>(() => serverReadTask); Assert.IsType<ObjectDisposedException>(serverException.InnerException); } await Assert.ThrowsAsync<ObjectDisposedException>(() => serverSslStream.ReadAsync(serverBuffer, 0, serverBuffer.Length)); // Now, there is no pending read, so the internal buffer will be returned to ArrayPool. serverSslStream.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(() => serverSslStream.ReadAsync(serverBuffer, 0, serverBuffer.Length)); } } [Fact] public void SslStream_StreamToStream_Flush_Propagated() { VirtualNetwork network = new VirtualNetwork(); using (var stream = new VirtualNetworkStream(network, isServer: false)) using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate)) { Assert.False(stream.HasBeenSyncFlushed); sslStream.Flush(); Assert.True(stream.HasBeenSyncFlushed); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Relies on FlushAsync override not available in desktop")] public void SslStream_StreamToStream_FlushAsync_Propagated() { VirtualNetwork network = new VirtualNetwork(); using (var stream = new VirtualNetworkStream(network, isServer: false)) using (var sslStream = new SslStream(stream, false, AllowAnyServerCertificate)) { Task task = sslStream.FlushAsync(); Assert.False(task.IsCompleted); stream.CompleteAsyncFlush(); Assert.True(task.IsCompleted); } } private bool VerifyOutput(byte[] actualBuffer, byte[] expectedBuffer) { return expectedBuffer.SequenceEqual(actualBuffer); } protected bool AllowAnyServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None; if (!Capability.IsTrustedRootCertificateInstalled()) { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors; } Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors); if (sslPolicyErrors == expectedSslPolicyErrors) { return true; } else { return false; } } } public sealed class SslStreamStreamToStreamTest_Async : SslStreamStreamToStreamTest { protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream) { using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { Task t1 = clientSslStream.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false)); Task t2 = serverSslStream.AuthenticateAsServerAsync(certificate); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); } } } public sealed class SslStreamStreamToStreamTest_BeginEnd : SslStreamStreamToStreamTest { protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream) { using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { Task t1 = Task.Factory.FromAsync(clientSslStream.BeginAuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false), null, null), clientSslStream.EndAuthenticateAsClient); Task t2 = Task.Factory.FromAsync(serverSslStream.BeginAuthenticateAsServer(certificate, null, null), serverSslStream.EndAuthenticateAsServer); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); } } } public sealed class SslStreamStreamToStreamTest_Sync : SslStreamStreamToStreamTest { protected override async Task DoHandshake(SslStream clientSslStream, SslStream serverSslStream) { using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { Task t1 = Task.Run(() => clientSslStream.AuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false))); Task t2 = Task.Run(() => serverSslStream.AuthenticateAsServer(certificate)); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); } } } }
// 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.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.Unicode; using Xunit; namespace System.Text.Encodings.Web.Tests { public class UrlEncoderTests { private static UTF8Encoding _utf8EncodingThrowOnInvalidBytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); [Fact] public void TestSurrogate() { Assert.Equal("%F0%9F%92%A9", System.Text.Encodings.Web.UrlEncoder.Default.Encode("\U0001f4a9")); using (var writer = new StringWriter()) { System.Text.Encodings.Web.UrlEncoder.Default.Encode(writer, "\U0001f4a9"); Assert.Equal("%F0%9F%92%A9", writer.GetStringBuilder().ToString()); } } [Fact] public void Ctor_WithTextEncoderSettings() { // Arrange var filter = new TextEncoderSettings(); filter.AllowCharacters('a', 'b'); filter.AllowCharacters('\0', '&', '\uFFFF', 'd'); UrlEncoder encoder = new UrlEncoder(filter); // Act & assert Assert.Equal("a", encoder.UrlEncode("a")); Assert.Equal("b", encoder.UrlEncode("b")); Assert.Equal("%63", encoder.UrlEncode("c")); Assert.Equal("d", encoder.UrlEncode("d")); Assert.Equal("%00", encoder.UrlEncode("\0")); // we still always encode control chars Assert.Equal("%26", encoder.UrlEncode("&")); // we still always encode HTML-special chars Assert.Equal("%EF%BF%BF", encoder.UrlEncode("\uFFFF")); // we still always encode non-chars and other forbidden chars } [Fact] public void Ctor_WithUnicodeRanges() { // Arrange UrlEncoder encoder = new UrlEncoder(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols); // Act & assert Assert.Equal("%61", encoder.UrlEncode("a")); Assert.Equal("\u00E9", encoder.UrlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */)); Assert.Equal("\u2601", encoder.UrlEncode("\u2601" /* CLOUD */)); } [Fact] public void Ctor_WithNoParameters_DefaultsToBasicLatin() { // Arrange UrlEncoder encoder = new UrlEncoder(); // Act & assert Assert.Equal("a", encoder.UrlEncode("a")); Assert.Equal("%C3%A9", encoder.UrlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */)); Assert.Equal("%E2%98%81", encoder.UrlEncode("\u2601" /* CLOUD */)); } [Fact] public void Default_EquivalentToBasicLatin() { // Arrange UrlEncoder controlEncoder = new UrlEncoder(UnicodeRanges.BasicLatin); UrlEncoder testEncoder = UrlEncoder.Default; // Act & assert for (int i = 0; i <= char.MaxValue; i++) { if (!IsSurrogateCodePoint(i)) { string input = new string((char)i, 1); Assert.Equal(controlEncoder.UrlEncode(input), testEncoder.UrlEncode(input)); } } } [Fact] public void UrlEncode_AllRangesAllowed_StillEncodesForbiddenChars() { // Arrange UrlEncoder encoder = new UrlEncoder(UnicodeRanges.All); // Act & assert - BMP chars for (int i = 0; i <= 0xFFFF; i++) { string input = new string((char)i, 1); string expected; if (IsSurrogateCodePoint(i)) { expected = "%EF%BF%BD"; // unpaired surrogate -> Unicode replacement char } else { bool mustEncode = true; // RFC 3987, Sec. 2.2 gives the list of allowed chars // (We allow 'ipchar' except for "'", "&", "+", "%", and "=" if (('a' <= i && i <= 'z') || ('A' <= i && i <= 'Z') || ('0' <= i && i <= '9')) { mustEncode = false; // ALPHA / DIGIT } else if ((0x00A0 <= i && i <= 0xD7FF) | (0xF900 <= i && i <= 0xFDCF) | (0xFDF0 <= i && i <= 0xFFEF)) { mustEncode = !UnicodeHelpers.IsCharacterDefined((char)i); // 'ucschar' } else { switch (i) { // iunreserved case '-': case '.': case '_': case '~': // isegment-nz-nc case '@': // sub-delims case '!': case '$': case '(': case ')': case '*': case ',': case ';': mustEncode = false; break; } } if (mustEncode) { expected = GetKnownGoodPercentEncodedValue(i); } else { expected = input; // no encoding } } string retVal = encoder.UrlEncode(input); Assert.Equal(expected, retVal); } // Act & assert - astral chars for (int i = 0x10000; i <= 0x10FFFF; i++) { string input = char.ConvertFromUtf32(i); string expected = GetKnownGoodPercentEncodedValue(i); string retVal = encoder.UrlEncode(input); Assert.Equal(expected, retVal); } } [Fact] public void UrlEncode_BadSurrogates_ReturnsUnicodeReplacementChar() { // Arrange UrlEncoder encoder = new UrlEncoder(UnicodeRanges.All); // allow all codepoints // "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>" const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800"; const string expected = "a%EF%BF%BDb%EF%BF%BDc%EF%BF%BD%EF%BF%BDd%EF%BF%BD%F0%90%8F%BFe%EF%BF%BD"; // 'D800' 'DFFF' was preserved since it's valid // Act string retVal = encoder.UrlEncode(input); // Assert Assert.Equal(expected, retVal); } [Fact] public void UrlEncode_EmptyStringInput_ReturnsEmptyString() { // Arrange UrlEncoder encoder = new UrlEncoder(); // Act & assert Assert.Equal("", encoder.UrlEncode("")); } [Fact] public void UrlEncode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance() { // Arrange UrlEncoder encoder = new UrlEncoder(); string input = "Hello,there!"; // Act & assert Assert.Same(input, encoder.UrlEncode(input)); } [Fact] public void UrlEncode_NullInput_ReturnsNull() { // Arrange UrlEncoder encoder = new UrlEncoder(); Assert.Throws<ArgumentNullException>(() => { encoder.UrlEncode(null); }); } [Fact] public void UrlEncode_WithCharsRequiringEncodingAtBeginning() { Assert.Equal(@"%26Hello,there!", new UrlEncoder().UrlEncode("&Hello,there!")); } [Fact] public void UrlEncode_WithCharsRequiringEncodingAtEnd() { Assert.Equal(@"Hello,there!%26", new UrlEncoder().UrlEncode("Hello,there!&")); } [Fact] public void UrlEncode_WithCharsRequiringEncodingInMiddle() { Assert.Equal(@"Hello,%20%26there!", new UrlEncoder().UrlEncode("Hello, &there!")); } [Fact] public void UrlEncode_WithCharsRequiringEncodingInterspersed() { Assert.Equal(@"Hello,%20%3Cthere%3E!", new UrlEncoder().UrlEncode("Hello, <there>!")); } [Fact] public void UrlEncode_CharArray() { // Arrange UrlEncoder encoder = new UrlEncoder(); var output = new StringWriter(); // Act encoder.UrlEncode("Hello+world!".ToCharArray(), 3, 5, output); // Assert Assert.Equal("lo%2Bwo", output.ToString()); } [Fact] public void UrlEncode_StringSubstring() { // Arrange UrlEncoder encoder = new UrlEncoder(); var output = new StringWriter(); // Act encoder.UrlEncode("Hello+world!", 3, 5, output); // Assert Assert.Equal("lo%2Bwo", output.ToString()); } [Fact] public void UrlEncode_DoesNotOutputHtmlSensitiveCharacters() { // Per the design document, we provide additional defense-in-depth // by never emitting HTML-sensitive characters unescaped. // Arrange UrlEncoder urlEncoder = new UrlEncoder(UnicodeRanges.All); HtmlEncoder htmlEncoder = new HtmlEncoder(UnicodeRanges.All); // Act & assert for (int i = 0; i <= 0x10FFFF; i++) { if (IsSurrogateCodePoint(i)) { continue; // surrogates don't matter here } string urlEncoded = urlEncoder.UrlEncode(char.ConvertFromUtf32(i)); string thenHtmlEncoded = htmlEncoder.HtmlEncode(urlEncoded); Assert.Equal(urlEncoded, thenHtmlEncoded); // should have contained no HTML-sensitive characters } } private static string GetKnownGoodPercentEncodedValue(int codePoint) { // Convert the code point to UTF16, then call Encoding.UTF8.GetBytes, then hex-encode everything return string.Concat(_utf8EncodingThrowOnInvalidBytes.GetBytes(char.ConvertFromUtf32(codePoint)).Select(b => string.Format(CultureInfo.InvariantCulture, "%{0:X2}", b))); } private static bool IsSurrogateCodePoint(int codePoint) { return (0xD800 <= codePoint && codePoint <= 0xDFFF); } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace WeifenLuo.WinFormsUI.Docking { using WeifenLuo.WinFormsUI.ThemeVS2012Light; /// <summary> /// Visual Studio 2012 Light theme. /// </summary> public class VS2012LightTheme : ThemeBase { /// <summary> /// Applies the specified theme to the dock panel. /// </summary> /// <param name="dockPanel">The dock panel.</param> public override void Apply(DockPanel dockPanel) { if (dockPanel == null) { throw new NullReferenceException("dockPanel"); } Measures.SplitterSize = 6; dockPanel.Extender.DockPaneCaptionFactory = new VS2012LightDockPaneCaptionFactory(); dockPanel.Extender.AutoHideStripFactory = new VS2012LightAutoHideStripFactory(); dockPanel.Extender.AutoHideWindowFactory = new VS2012LightAutoHideWindowFactory(); dockPanel.Extender.DockPaneStripFactory = new VS2012LightDockPaneStripFactory(); dockPanel.Extender.DockPaneSplitterControlFactory = new VS2012LightDockPaneSplitterControlFactory(); dockPanel.Extender.DockWindowSplitterControlFactory = new VS2012LightDockWindowSplitterControlFactory(); dockPanel.Extender.DockWindowFactory = new VS2012LightDockWindowFactory(); dockPanel.Extender.PaneIndicatorFactory = new VS2012LightPaneIndicatorFactory(); dockPanel.Extender.PanelIndicatorFactory = new VS2012LightPanelIndicatorFactory(); dockPanel.Extender.DockOutlineFactory = new VS2012LightDockOutlineFactory(); dockPanel.Skin = CreateVisualStudio2012Light(); } private class VS2012LightDockOutlineFactory : DockPanelExtender.IDockOutlineFactory { public DockOutlineBase CreateDockOutline() { return new VS2012LightDockOutline(); } private class VS2012LightDockOutline : DockOutlineBase { public VS2012LightDockOutline() { m_dragForm = new DragForm(); SetDragForm(Rectangle.Empty); DragForm.BackColor = Color.FromArgb(0xff, 91, 173, 255); DragForm.Opacity = 0.5; DragForm.Show(false); } DragForm m_dragForm; private DragForm DragForm { get { return m_dragForm; } } protected override void OnShow() { CalculateRegion(); } protected override void OnClose() { DragForm.Close(); } private void CalculateRegion() { if (SameAsOldValue) return; if (!FloatWindowBounds.IsEmpty) SetOutline(FloatWindowBounds); else if (DockTo is DockPanel) SetOutline(DockTo as DockPanel, Dock, (ContentIndex != 0)); else if (DockTo is DockPane) SetOutline(DockTo as DockPane, Dock, ContentIndex); else SetOutline(); } private void SetOutline() { SetDragForm(Rectangle.Empty); } private void SetOutline(Rectangle floatWindowBounds) { SetDragForm(floatWindowBounds); } private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) { Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); if (dock == DockStyle.Top) { int height = dockPanel.GetDockWindowSize(DockState.DockTop); rect = new Rectangle(rect.X, rect.Y, rect.Width, height); } else if (dock == DockStyle.Bottom) { int height = dockPanel.GetDockWindowSize(DockState.DockBottom); rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); } else if (dock == DockStyle.Left) { int width = dockPanel.GetDockWindowSize(DockState.DockLeft); rect = new Rectangle(rect.X, rect.Y, width, rect.Height); } else if (dock == DockStyle.Right) { int width = dockPanel.GetDockWindowSize(DockState.DockRight); rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); } else if (dock == DockStyle.Fill) { rect = dockPanel.DocumentWindowBounds; rect.Location = dockPanel.PointToScreen(rect.Location); } SetDragForm(rect); } private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) { if (dock != DockStyle.Fill) { Rectangle rect = pane.DisplayingRectangle; if (dock == DockStyle.Right) rect.X += rect.Width / 2; if (dock == DockStyle.Bottom) rect.Y += rect.Height / 2; if (dock == DockStyle.Left || dock == DockStyle.Right) rect.Width -= rect.Width / 2; if (dock == DockStyle.Top || dock == DockStyle.Bottom) rect.Height -= rect.Height / 2; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else if (contentIndex == -1) { Rectangle rect = pane.DisplayingRectangle; rect.Location = pane.PointToScreen(rect.Location); SetDragForm(rect); } else { using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) { RectangleF rectF = path.GetBounds(); Rectangle rect = new Rectangle((int)rectF.X, (int)rectF.Y, (int)rectF.Width, (int)rectF.Height); using (Matrix matrix = new Matrix(rect, new Point[] { new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height) })) { path.Transform(matrix); } Region region = new Region(path); SetDragForm(rect, region); } } } private void SetDragForm(Rectangle rect) { DragForm.Bounds = rect; if (rect == Rectangle.Empty) { if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = new Region(Rectangle.Empty); } else if (DragForm.Region != null) { DragForm.Region.Dispose(); DragForm.Region = null; } } private void SetDragForm(Rectangle rect, Region region) { DragForm.Bounds = rect; if (DragForm.Region != null) { DragForm.Region.Dispose(); } DragForm.Region = region; } } } private class VS2012LightPanelIndicatorFactory : DockPanelExtender.IPanelIndicatorFactory { public DockPanel.IPanelIndicator CreatePanelIndicator(DockStyle style) { return new VS2012LightPanelIndicator(style); } private class VS2012LightPanelIndicator : PictureBox, DockPanel.IPanelIndicator { private static Image _imagePanelLeft = Resources.DockIndicator_PanelLeft; private static Image _imagePanelRight = Resources.DockIndicator_PanelRight; private static Image _imagePanelTop = Resources.DockIndicator_PanelTop; private static Image _imagePanelBottom = Resources.DockIndicator_PanelBottom; private static Image _imagePanelFill = Resources.DockIndicator_PanelFill; private static Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft; private static Image _imagePanelRightActive = Resources.DockIndicator_PanelRight; private static Image _imagePanelTopActive = Resources.DockIndicator_PanelTop; private static Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom; private static Image _imagePanelFillActive = Resources.DockIndicator_PanelFill; public VS2012LightPanelIndicator(DockStyle dockStyle) { m_dockStyle = dockStyle; SizeMode = PictureBoxSizeMode.AutoSize; Image = ImageInactive; } private DockStyle m_dockStyle; private DockStyle DockStyle { get { return m_dockStyle; } } private DockStyle m_status; public DockStyle Status { get { return m_status; } set { if (value != DockStyle && value != DockStyle.None) throw new InvalidEnumArgumentException(); if (m_status == value) return; m_status = value; IsActivated = (m_status != DockStyle.None); } } private Image ImageInactive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeft; else if (DockStyle == DockStyle.Right) return _imagePanelRight; else if (DockStyle == DockStyle.Top) return _imagePanelTop; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottom; else if (DockStyle == DockStyle.Fill) return _imagePanelFill; else return null; } } private Image ImageActive { get { if (DockStyle == DockStyle.Left) return _imagePanelLeftActive; else if (DockStyle == DockStyle.Right) return _imagePanelRightActive; else if (DockStyle == DockStyle.Top) return _imagePanelTopActive; else if (DockStyle == DockStyle.Bottom) return _imagePanelBottomActive; else if (DockStyle == DockStyle.Fill) return _imagePanelFillActive; else return null; } } private bool m_isActivated = false; private bool IsActivated { get { return m_isActivated; } set { m_isActivated = value; Image = IsActivated ? ImageActive : ImageInactive; } } public DockStyle HitTest(Point pt) { return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; } } } private class VS2012LightPaneIndicatorFactory : DockPanelExtender.IPaneIndicatorFactory { public DockPanel.IPaneIndicator CreatePaneIndicator() { return new VS2012LightPaneIndicator(); } private class VS2012LightPaneIndicator : PictureBox, DockPanel.IPaneIndicator { private static Bitmap _bitmapPaneDiamond = Resources.Dockindicator_PaneDiamond; private static Bitmap _bitmapPaneDiamondLeft = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondRight = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondTop = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondBottom = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondFill = Resources.Dockindicator_PaneDiamond_Fill; private static Bitmap _bitmapPaneDiamondHotSpot = Resources.Dockindicator_PaneDiamond_Hotspot; private static Bitmap _bitmapPaneDiamondHotSpotIndex = Resources.DockIndicator_PaneDiamond_HotspotIndex; private static DockPanel.HotSpotIndex[] _hotSpots = new[] { new DockPanel.HotSpotIndex(1, 0, DockStyle.Top), new DockPanel.HotSpotIndex(0, 1, DockStyle.Left), new DockPanel.HotSpotIndex(1, 1, DockStyle.Fill), new DockPanel.HotSpotIndex(2, 1, DockStyle.Right), new DockPanel.HotSpotIndex(1, 2, DockStyle.Bottom) }; private GraphicsPath _displayingGraphicsPath = DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); public VS2012LightPaneIndicator() { SizeMode = PictureBoxSizeMode.AutoSize; Image = _bitmapPaneDiamond; Region = new Region(DisplayingGraphicsPath); } public GraphicsPath DisplayingGraphicsPath { get { return _displayingGraphicsPath; } } public DockStyle HitTest(Point pt) { if (!Visible) return DockStyle.None; pt = PointToClient(pt); if (!ClientRectangle.Contains(pt)) return DockStyle.None; for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) { if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) return _hotSpots[i].DockStyle; } return DockStyle.None; } private DockStyle m_status = DockStyle.None; public DockStyle Status { get { return m_status; } set { m_status = value; if (m_status == DockStyle.None) Image = _bitmapPaneDiamond; else if (m_status == DockStyle.Left) Image = _bitmapPaneDiamondLeft; else if (m_status == DockStyle.Right) Image = _bitmapPaneDiamondRight; else if (m_status == DockStyle.Top) Image = _bitmapPaneDiamondTop; else if (m_status == DockStyle.Bottom) Image = _bitmapPaneDiamondBottom; else if (m_status == DockStyle.Fill) Image = _bitmapPaneDiamondFill; } } } } private class VS2012LightAutoHideWindowFactory : DockPanelExtender.IAutoHideWindowFactory { public DockPanel.AutoHideWindowControl CreateAutoHideWindow(DockPanel panel) { return new VS2012LightAutoHideWindowControl(panel); } } private class VS2012LightDockPaneSplitterControlFactory : DockPanelExtender.IDockPaneSplitterControlFactory { public DockPane.SplitterControlBase CreateSplitterControl(DockPane pane) { return new VS2012LightSplitterControl(pane); } } private class VS2012LightDockWindowSplitterControlFactory : DockPanelExtender.IDockWindowSplitterControlFactory { public SplitterBase CreateSplitterControl() { return new VS2012LightDockWindow.VS2012LightDockWindowSplitterControl(); } } private class VS2012LightDockPaneStripFactory : DockPanelExtender.IDockPaneStripFactory { public DockPaneStripBase CreateDockPaneStrip(DockPane pane) { return new VS2012LightDockPaneStrip(pane); } } private class VS2012LightAutoHideStripFactory : DockPanelExtender.IAutoHideStripFactory { public AutoHideStripBase CreateAutoHideStrip(DockPanel panel) { return new VS2012LightAutoHideStrip(panel); } } private class VS2012LightDockPaneCaptionFactory : DockPanelExtender.IDockPaneCaptionFactory { public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane) { return new VS2012LightDockPaneCaption(pane); } } private class VS2012LightDockWindowFactory : DockPanelExtender.IDockWindowFactory { public DockWindow CreateDockWindow(DockPanel dockPanel, DockState dockState) { return new VS2012LightDockWindow(dockPanel, dockState); } } public static DockPanelSkin CreateVisualStudio2012Light() { var specialBlue = Color.FromArgb(0xFF, 0x00, 0x7A, 0xCC); var dot = Color.FromArgb(80, 170, 220); var activeTab = specialBlue; var mouseHoverTab = Color.FromArgb(0xFF, 28, 151, 234); var inactiveTab = SystemColors.Control; var lostFocusTab = Color.FromArgb(0xFF, 204, 206, 219); var skin = new DockPanelSkin(); skin.AutoHideStripSkin.DockStripGradient.StartColor = specialBlue; skin.AutoHideStripSkin.DockStripGradient.EndColor = SystemColors.ControlLight; skin.AutoHideStripSkin.TabGradient.TextColor = SystemColors.ControlDarkDark; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = activeTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = lostFocusTab; skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor = Color.White; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = inactiveTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = mouseHoverTab; skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor = Color.Black; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight; skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.GrayText; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor = specialBlue; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor = dot; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor = Color.White; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.Control; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.ControlDark; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.GrayText; return skin; } } }
/* * 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. */ // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global namespace Apache.Ignite.Core.Cache.Configuration { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Log; /// <summary> /// Query entity is a description of cache entry (composed of key and value) /// in a way of how it must be indexed and can be queried. /// </summary> public sealed class QueryEntity : IQueryEntityInternal, IBinaryRawWriteAware { /** */ private Type _keyType; /** */ private Type _valueType; /** */ private string _valueTypeName; /** */ private string _keyTypeName; /** */ private Dictionary<string, string> _aliasMap; /** */ private ICollection<QueryAlias> _aliases; /// <summary> /// Initializes a new instance of the <see cref="QueryEntity"/> class. /// </summary> public QueryEntity() { // No-op. } /// <summary> /// Initializes a new instance of the <see cref="QueryEntity"/> class. /// </summary> /// <param name="valueType">Type of the cache entry value.</param> public QueryEntity(Type valueType) { ValueType = valueType; } /// <summary> /// Initializes a new instance of the <see cref="QueryEntity"/> class. /// </summary> /// <param name="keyType">Type of the key.</param> /// <param name="valueType">Type of the value.</param> public QueryEntity(Type keyType, Type valueType) { KeyType = keyType; ValueType = valueType; } /// <summary> /// Gets or sets key Java type name. /// </summary> public string KeyTypeName { get { return _keyTypeName; } set { _keyTypeName = value; _keyType = null; } } /// <summary> /// Gets or sets the type of the key. /// <para /> /// This is a shortcut for <see cref="KeyTypeName"/>. Getter will return null for non-primitive types. /// <para /> /// Setting this property will overwrite <see cref="Fields"/> and <see cref="Indexes"/> according to /// <see cref="QuerySqlFieldAttribute"/>, if any. /// </summary> public Type KeyType { get { return _keyType ?? JavaTypes.GetDotNetType(KeyTypeName); } set { RescanAttributes(value, _valueType); // Do this first because it can throw KeyTypeName = value == null ? null : (JavaTypes.GetJavaTypeName(value) ?? BinaryUtils.GetSqlTypeName(value)); _keyType = value; } } /// <summary> /// Gets or sets value Java type name. /// </summary> public string ValueTypeName { get { return _valueTypeName; } set { _valueTypeName = value; _valueType = null; } } /// <summary> /// Gets or sets the type of the value. /// <para /> /// This is a shortcut for <see cref="ValueTypeName"/>. Getter will return null for non-primitive types. /// <para /> /// Setting this property will overwrite <see cref="Fields"/> and <see cref="Indexes"/> according to /// <see cref="QuerySqlFieldAttribute"/>, if any. /// </summary> public Type ValueType { get { return _valueType ?? JavaTypes.GetDotNetType(ValueTypeName); } set { RescanAttributes(_keyType, value); // Do this first because it can throw ValueTypeName = value == null ? null : (JavaTypes.GetJavaTypeName(value) ?? BinaryUtils.GetSqlTypeName(value)); _valueType = value; } } /// <summary> /// Gets or sets the name of the field that is used to denote the entire key. /// <para /> /// By default, entite key can be accessed with a special "_key" field name. /// </summary> public string KeyFieldName { get; set; } /// <summary> /// Gets or sets the name of the field that is used to denote the entire value. /// <para /> /// By default, entite value can be accessed with a special "_val" field name. /// </summary> public string ValueFieldName { get; set; } /// <summary> /// Gets or sets the name of the SQL table. /// When not set, value type name is used. /// </summary> public string TableName { get; set; } /// <summary> /// Gets or sets query fields, a map from field name to Java type name. /// The order of fields defines the order of columns returned by the 'select *' queries. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<QueryField> Fields { get; set; } /// <summary> /// Gets or sets field name aliases: mapping from full name in dot notation to an alias /// that will be used as SQL column name. /// Example: {"parent.name" -> "parentName"}. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<QueryAlias> Aliases { get { return _aliases; } set { _aliases = value; _aliasMap = null; } } /// <summary> /// Gets or sets the query indexes. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public ICollection<QueryIndex> Indexes { get; set; } /// <summary> /// Gets the alias by field name, or null when no match found. /// This method constructs a dictionary lazily to perform lookups. /// </summary> string IQueryEntityInternal.GetAlias(string fieldName) { if (Aliases == null || Aliases.Count == 0) { return null; } // PERF: No ToDictionary. if (_aliasMap == null) { _aliasMap = new Dictionary<string, string>(Aliases.Count, StringComparer.Ordinal); foreach (var alias in Aliases) { _aliasMap[alias.FullName] = alias.Alias; } } string res; return _aliasMap.TryGetValue(fieldName, out res) ? res : null; } /// <summary> /// Initializes a new instance of the <see cref="QueryEntity"/> class. /// </summary> /// <param name="reader">The reader.</param> internal QueryEntity(IBinaryRawReader reader) { KeyTypeName = reader.ReadString(); ValueTypeName = reader.ReadString(); TableName = reader.ReadString(); KeyFieldName = reader.ReadString(); ValueFieldName = reader.ReadString(); var count = reader.ReadInt(); Fields = count == 0 ? null : Enumerable.Range(0, count).Select(x => new QueryField(reader)).ToList(); count = reader.ReadInt(); Aliases = count == 0 ? null : Enumerable.Range(0, count) .Select(x=> new QueryAlias(reader.ReadString(), reader.ReadString())).ToList(); count = reader.ReadInt(); Indexes = count == 0 ? null : Enumerable.Range(0, count).Select(x => new QueryIndex(reader)).ToList(); } /// <summary> /// Writes this instance. /// </summary> void IBinaryRawWriteAware<IBinaryRawWriter>.Write(IBinaryRawWriter writer) { writer.WriteString(KeyTypeName); writer.WriteString(ValueTypeName); writer.WriteString(TableName); writer.WriteString(KeyFieldName); writer.WriteString(ValueFieldName); if (Fields != null) { writer.WriteInt(Fields.Count); foreach (var field in Fields) { field.Write(writer); } } else writer.WriteInt(0); if (Aliases != null) { writer.WriteInt(Aliases.Count); foreach (var queryAlias in Aliases) { writer.WriteString(queryAlias.FullName); writer.WriteString(queryAlias.Alias); } } else writer.WriteInt(0); if (Indexes != null) { writer.WriteInt(Indexes.Count); foreach (var index in Indexes) { if (index == null) throw new InvalidOperationException("Invalid cache configuration: QueryIndex can't be null."); index.Write(writer); } } else writer.WriteInt(0); } /// <summary> /// Validates this instance and outputs information to the log, if necessary. /// </summary> internal void Validate(ILogger log, string logInfo) { Debug.Assert(log != null); Debug.Assert(logInfo != null); logInfo += string.Format(", QueryEntity '{0}:{1}'", _keyTypeName ?? "", _valueTypeName ?? ""); JavaTypes.LogIndirectMappingWarning(_keyType, log, logInfo); JavaTypes.LogIndirectMappingWarning(_valueType, log, logInfo); var fields = Fields; if (fields != null) { foreach (var field in fields) field.Validate(log, logInfo); } } /// <summary> /// Copies the local properties (properties that are not written in Write method). /// </summary> internal void CopyLocalProperties(QueryEntity entity) { Debug.Assert(entity != null); if (entity._keyType != null) { _keyType = entity._keyType; } if (entity._valueType != null) { _valueType = entity._valueType; } if (Fields != null && entity.Fields != null) { var fields = entity.Fields.Where(x => x != null).ToDictionary(x => "_" + x.Name, x => x); foreach (var field in Fields) { QueryField src; if (fields.TryGetValue("_" + field.Name, out src)) { field.CopyLocalProperties(src); } } } } /// <summary> /// Rescans the attributes in <see cref="KeyType"/> and <see cref="ValueType"/>. /// </summary> private void RescanAttributes(Type keyType, Type valType) { if (keyType == null && valType == null) return; var fields = new List<QueryField>(); var indexes = new List<QueryIndexEx>(); if (keyType != null) ScanAttributes(keyType, fields, indexes, null, new HashSet<Type>(), true); if (valType != null) ScanAttributes(valType, fields, indexes, null, new HashSet<Type>(), false); if (fields.Any()) Fields = fields.OrderBy(x => x.Name).ToList(); if (indexes.Any()) Indexes = GetGroupIndexes(indexes).ToArray(); } /// <summary> /// Gets the group indexes. /// </summary> /// <param name="indexes">Ungrouped indexes with their group names.</param> /// <returns></returns> private static IEnumerable<QueryIndex> GetGroupIndexes(List<QueryIndexEx> indexes) { return indexes.Where(idx => idx.IndexGroups != null) .SelectMany(idx => idx.IndexGroups.Select(g => new {Index = idx, GroupName = g})) .GroupBy(x => x.GroupName) .Select(g => { var idxs = g.Select(pair => pair.Index).ToArray(); var first = idxs.First(); return new QueryIndex(idxs.SelectMany(i => i.Fields).ToArray()) { IndexType = first.IndexType, Name = first.Name }; }) .Concat(indexes.Where(idx => idx.IndexGroups == null)); } /// <summary> /// Scans specified type for occurences of <see cref="QuerySqlFieldAttribute" />. /// </summary> /// <param name="type">The type.</param> /// <param name="fields">The fields.</param> /// <param name="indexes">The indexes.</param> /// <param name="parentPropName">Name of the parent property.</param> /// <param name="visitedTypes">The visited types.</param> /// <param name="isKey">Whether this is a key type.</param> /// <exception cref="System.InvalidOperationException">Recursive Query Field definition detected: + type</exception> private static void ScanAttributes(Type type, List<QueryField> fields, List<QueryIndexEx> indexes, string parentPropName, ISet<Type> visitedTypes, bool isKey) { Debug.Assert(type != null); Debug.Assert(fields != null); Debug.Assert(indexes != null); if (visitedTypes.Contains(type)) throw new InvalidOperationException("Recursive Query Field definition detected: " + type); visitedTypes.Add(type); foreach (var memberInfo in ReflectionUtils.GetFieldsAndProperties(type)) { var customAttributes = memberInfo.Key.GetCustomAttributes(true); foreach (var attr in customAttributes.OfType<QuerySqlFieldAttribute>()) { var columnName = attr.Name ?? memberInfo.Key.Name; // Dot notation is required for nested SQL fields. if (parentPropName != null) { columnName = parentPropName + "." + columnName; } if (attr.IsIndexed) { indexes.Add(new QueryIndexEx(columnName, attr.IsDescending, QueryIndexType.Sorted, attr.IndexGroups) { InlineSize = attr.IndexInlineSize, }); } fields.Add(new QueryField(columnName, memberInfo.Value) { IsKeyField = isKey, NotNull = attr.NotNull, DefaultValue = attr.DefaultValue }); ScanAttributes(memberInfo.Value, fields, indexes, columnName, visitedTypes, isKey); } foreach (var attr in customAttributes.OfType<QueryTextFieldAttribute>()) { var columnName = attr.Name ?? memberInfo.Key.Name; if (parentPropName != null) { columnName = parentPropName + "." + columnName; } indexes.Add(new QueryIndexEx(columnName, false, QueryIndexType.FullText, null)); fields.Add(new QueryField(columnName, memberInfo.Value) {IsKeyField = isKey}); ScanAttributes(memberInfo.Value, fields, indexes, columnName, visitedTypes, isKey); } } visitedTypes.Remove(type); } /// <summary> /// Extended index with group names. /// </summary> private class QueryIndexEx : QueryIndex { /// <summary> /// Initializes a new instance of the <see cref="QueryIndexEx"/> class. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="isDescending">if set to <c>true</c> [is descending].</param> /// <param name="indexType">Type of the index.</param> /// <param name="groups">The groups.</param> public QueryIndexEx(string fieldName, bool isDescending, QueryIndexType indexType, ICollection<string> groups) : base(isDescending, indexType, fieldName) { IndexGroups = groups; } /// <summary> /// Gets or sets the index groups. /// </summary> public ICollection<string> IndexGroups { get; set; } } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Text; using gov.va.medora.utils; namespace gov.va.medora.mdo { public class PersonName { const String INVALID_NAME = "Invalid person name"; String lastname; String firstname; String inits; String suffix; String prefix; String degree; public PersonName() {} public PersonName(String value) { if (!StringUtils.isEmpty(value)) { splitName(value); } } public String Lastname { get { return lastname; } set { lastname = value; } } public String Firstname { get { return firstname; } set { firstname = value; } } public String Inits { get { return inits; } set { inits = value; } } public String Suffix { get { return suffix; } set { suffix = value; } } public String Prefix { get { return prefix; } set { prefix = value; } } public String Degree { get { return degree; } set { degree = value; } } private void splitName(String value) { String[] names = StringUtils.split(value,StringUtils.COMMA); if (names.Length == 1) { Lastname = value; Firstname = ""; return; } Lastname = names[0]; Firstname = names[1].Trim(); } public String LastNameFirst { get { return getLastNameFirst(); } set { if (StringUtils.isEmpty(value)) { return; } splitName(value); } } public String getFirstNameFirst() { if (StringUtils.isEmpty(Lastname)) { return ""; } String s = Firstname + ' '; if (!StringUtils.isEmpty(Inits)) { s += Inits + ' '; } s += Lastname; if (!StringUtils.isEmpty(Suffix)) { s += Suffix + ' '; } return s; } public String getLastNameFirst() { if (StringUtils.isEmpty(Lastname)) { return ""; } StringBuilder name = new StringBuilder(Lastname); if (!StringUtils.isEmpty(Firstname)) { name.Append(","); name.Append(Firstname); } if (!StringUtils.isEmpty(Inits)) { name.Append(" "); name.Append(Inits); } if (!StringUtils.isEmpty(Suffix)) { name.Append(Suffix); name.Append(" "); } return name.ToString(); } public String getFullName() { if (StringUtils.isEmpty(Lastname)) { return ""; } String s = ""; if (!StringUtils.isEmpty(Prefix)) { s += Prefix + ' '; } s += getFirstNameFirst(); if (!StringUtils.isEmpty(Degree)) { s += ", " + Degree; } return s; } public static bool isValid(string s) { if (StringUtils.isEmpty(s) || !StringUtils.isAlphaChar(s[0])) { return false; } for (int i = 1; i < s.Length; i++) { if (!StringUtils.isAlphaChar(s[i]) && s[i] != ' ' && s[i] != '\'' && s[i] != '-' && s[i] != ',' && s[i] != '.') { return false; } } return true; } public override string ToString() { return getLastNameFirst(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if ES_BUILD_STANDALONE using System; using System.Diagnostics; #endif using System.Reflection; using System.Runtime.InteropServices; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// Holds property values of any type. For common value types, we have inline storage so that we don't need /// to box the values. For all other types, we store the value in a single object reference field. /// /// To get the value of a property quickly, use a delegate produced by <see cref="PropertyValue.GetPropertyGetter(PropertyInfo)"/>. /// </summary> #if ES_BUILD_PN [CLSCompliant(false)] public #else internal #endif readonly unsafe struct PropertyValue { /// <summary> /// Union of well-known value types, to avoid boxing those types. /// </summary> [StructLayout(LayoutKind.Explicit)] public struct Scalar { [FieldOffset(0)] public bool AsBoolean; [FieldOffset(0)] public byte AsByte; [FieldOffset(0)] public sbyte AsSByte; [FieldOffset(0)] public char AsChar; [FieldOffset(0)] public short AsInt16; [FieldOffset(0)] public ushort AsUInt16; [FieldOffset(0)] public int AsInt32; [FieldOffset(0)] public uint AsUInt32; [FieldOffset(0)] public long AsInt64; [FieldOffset(0)] public ulong AsUInt64; [FieldOffset(0)] public IntPtr AsIntPtr; [FieldOffset(0)] public UIntPtr AsUIntPtr; [FieldOffset(0)] public float AsSingle; [FieldOffset(0)] public double AsDouble; [FieldOffset(0)] public Guid AsGuid; [FieldOffset(0)] public DateTime AsDateTime; [FieldOffset(0)] public DateTimeOffset AsDateTimeOffset; [FieldOffset(0)] public TimeSpan AsTimeSpan; [FieldOffset(0)] public decimal AsDecimal; } // Anything not covered by the Scalar union gets stored in this reference. private readonly object? _reference; private readonly Scalar _scalar; private readonly int _scalarLength; private PropertyValue(object? value) { _reference = value; _scalar = default; _scalarLength = 0; } private PropertyValue(Scalar scalar, int scalarLength) { _reference = null; _scalar = scalar; _scalarLength = scalarLength; } private PropertyValue(bool value) : this(new Scalar() { AsBoolean = value }, sizeof(bool)) { } private PropertyValue(byte value) : this(new Scalar() { AsByte = value }, sizeof(byte)) { } private PropertyValue(sbyte value) : this(new Scalar() { AsSByte = value }, sizeof(sbyte)) { } private PropertyValue(char value) : this(new Scalar() { AsChar = value }, sizeof(char)) { } private PropertyValue(short value) : this(new Scalar() { AsInt16 = value }, sizeof(short)) { } private PropertyValue(ushort value) : this(new Scalar() { AsUInt16 = value }, sizeof(ushort)) { } private PropertyValue(int value) : this(new Scalar() { AsInt32 = value }, sizeof(int)) { } private PropertyValue(uint value) : this(new Scalar() { AsUInt32 = value }, sizeof(uint)) { } private PropertyValue(long value) : this(new Scalar() { AsInt64 = value }, sizeof(long)) { } private PropertyValue(ulong value) : this(new Scalar() { AsUInt64 = value }, sizeof(ulong)) { } private PropertyValue(IntPtr value) : this(new Scalar() { AsIntPtr = value }, sizeof(IntPtr)) { } private PropertyValue(UIntPtr value) : this(new Scalar() { AsUIntPtr = value }, sizeof(UIntPtr)) { } private PropertyValue(float value) : this(new Scalar() { AsSingle = value }, sizeof(float)) { } private PropertyValue(double value) : this(new Scalar() { AsDouble = value }, sizeof(double)) { } private PropertyValue(Guid value) : this(new Scalar() { AsGuid = value }, sizeof(Guid)) { } private PropertyValue(DateTime value) : this(new Scalar() { AsDateTime = value }, sizeof(DateTime)) { } private PropertyValue(DateTimeOffset value) : this(new Scalar() { AsDateTimeOffset = value }, sizeof(DateTimeOffset)) { } private PropertyValue(TimeSpan value) : this(new Scalar() { AsTimeSpan = value }, sizeof(TimeSpan)) { } private PropertyValue(decimal value) : this(new Scalar() { AsDecimal = value }, sizeof(decimal)) { } public static Func<object?, PropertyValue> GetFactory(Type type) { if (type == typeof(bool)) return value => new PropertyValue((bool)value!); if (type == typeof(byte)) return value => new PropertyValue((byte)value!); if (type == typeof(sbyte)) return value => new PropertyValue((sbyte)value!); if (type == typeof(char)) return value => new PropertyValue((char)value!); if (type == typeof(short)) return value => new PropertyValue((short)value!); if (type == typeof(ushort)) return value => new PropertyValue((ushort)value!); if (type == typeof(int)) return value => new PropertyValue((int)value!); if (type == typeof(uint)) return value => new PropertyValue((uint)value!); if (type == typeof(long)) return value => new PropertyValue((long)value!); if (type == typeof(ulong)) return value => new PropertyValue((ulong)value!); if (type == typeof(IntPtr)) return value => new PropertyValue((IntPtr)value!); if (type == typeof(UIntPtr)) return value => new PropertyValue((UIntPtr)value!); if (type == typeof(float)) return value => new PropertyValue((float)value!); if (type == typeof(double)) return value => new PropertyValue((double)value!); if (type == typeof(Guid)) return value => new PropertyValue((Guid)value!); if (type == typeof(DateTime)) return value => new PropertyValue((DateTime)value!); if (type == typeof(DateTimeOffset)) return value => new PropertyValue((DateTimeOffset)value!); if (type == typeof(TimeSpan)) return value => new PropertyValue((TimeSpan)value!); if (type == typeof(decimal)) return value => new PropertyValue((decimal)value!); return value => new PropertyValue(value); } public object? ReferenceValue { get { Debug.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type."); return _reference; } } public Scalar ScalarValue { get { Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalar; } } public int ScalarLength { get { Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalarLength; } } /// <summary> /// Gets a delegate that gets the value of a given property. /// </summary> public static Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property) { if (property.DeclaringType!.GetTypeInfo().IsValueType) return GetBoxedValueTypePropertyGetter(property); else return GetReferenceTypePropertyGetter(property); } /// <summary> /// Gets a delegate that gets the value of a property of a value type. We unfortunately cannot avoid boxing the value type, /// without making this generic over the value type. That would result in a large number of generic instantiations, and furthermore /// does not work correctly on .NET Native (we cannot express the needed instantiations in an rd.xml file). We expect that user-defined /// value types will be rare, and in any case the boxing only happens for events that are actually enabled. /// </summary> private static Func<PropertyValue, PropertyValue> GetBoxedValueTypePropertyGetter(PropertyInfo property) { Type type = property.PropertyType; if (type.GetTypeInfo().IsEnum) type = Enum.GetUnderlyingType(type); Func<object?, PropertyValue> factory = GetFactory(type); return container => factory(property.GetValue(container.ReferenceValue)); } /// <summary> /// For properties of reference types, we use a generic helper class to get the value. This enables us to use MethodInfo.CreateDelegate /// to build a fast getter. We can get away with this on .NET Native, because we really only need one runtime instantiation of the /// generic type, since it's only instantiated over reference types (and thus all instances are shared). /// </summary> /// <param name="property"></param> /// <returns></returns> private static Func<PropertyValue, PropertyValue> GetReferenceTypePropertyGetter(PropertyInfo property) { var helper = (TypeHelper)Activator.CreateInstance(typeof(ReferenceTypeHelper<>).MakeGenericType(property.DeclaringType!))!; return helper.GetPropertyGetter(property); } #if ES_BUILD_PN public #else private #endif abstract class TypeHelper { public abstract Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property); protected Delegate GetGetMethod(PropertyInfo property, Type propertyType) { return property.GetMethod!.CreateDelegate(typeof(Func<,>).MakeGenericType(property.DeclaringType!, propertyType)); } } #if ES_BUILD_PN public #else private #endif sealed class ReferenceTypeHelper<TContainer> : TypeHelper where TContainer : class? { public override Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property) { Type type = property.PropertyType; if (!Statics.IsValueType(type)) { var getter = (Func<TContainer, object?>)GetGetMethod(property, type); return container => new PropertyValue(getter((TContainer)container.ReferenceValue!)); } else { if (type.GetTypeInfo().IsEnum) type = Enum.GetUnderlyingType(type); if (type == typeof(bool)) { var f = (Func<TContainer, bool>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(byte)) { var f = (Func<TContainer, byte>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(sbyte)) { var f = (Func<TContainer, sbyte>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(char)) { var f = (Func<TContainer, char>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(short)) { var f = (Func<TContainer, short>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(ushort)) { var f = (Func<TContainer, ushort>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(int)) { var f = (Func<TContainer, int>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(uint)) { var f = (Func<TContainer, uint>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(long)) { var f = (Func<TContainer, long>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(ulong)) { var f = (Func<TContainer, ulong>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(IntPtr)) { var f = (Func<TContainer, IntPtr>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(UIntPtr)) { var f = (Func<TContainer, UIntPtr>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(float)) { var f = (Func<TContainer, float>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(double)) { var f = (Func<TContainer, double>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(Guid)) { var f = (Func<TContainer, Guid>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(DateTime)) { var f = (Func<TContainer, DateTime>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(DateTimeOffset)) { var f = (Func<TContainer, DateTimeOffset>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(TimeSpan)) { var f = (Func<TContainer, TimeSpan>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } if (type == typeof(decimal)) { var f = (Func<TContainer, decimal>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue!)); } return container => new PropertyValue(property.GetValue(container.ReferenceValue)); } } } } }
// Copyright 2018 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 Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.Language.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.Language.V1.Snippets { /// <summary>Generated snippets</summary> public class GeneratedLanguageServiceClientSnippets { /// <summary>Snippet for AnalyzeSentimentAsync</summary> public async Task AnalyzeSentimentAsync() { // Snippet: AnalyzeSentimentAsync(Document,CallSettings) // Additional: AnalyzeSentimentAsync(Document,CancellationToken) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) Document document = new Document(); // Make the request AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(document); // End snippet } /// <summary>Snippet for AnalyzeSentiment</summary> public void AnalyzeSentiment() { // Snippet: AnalyzeSentiment(Document,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) Document document = new Document(); // Make the request AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(document); // End snippet } /// <summary>Snippet for AnalyzeSentimentAsync</summary> public async Task AnalyzeSentimentAsync_RequestObject() { // Snippet: AnalyzeSentimentAsync(AnalyzeSentimentRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) AnalyzeSentimentRequest request = new AnalyzeSentimentRequest { Document = new Document(), }; // Make the request AnalyzeSentimentResponse response = await languageServiceClient.AnalyzeSentimentAsync(request); // End snippet } /// <summary>Snippet for AnalyzeSentiment</summary> public void AnalyzeSentiment_RequestObject() { // Snippet: AnalyzeSentiment(AnalyzeSentimentRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) AnalyzeSentimentRequest request = new AnalyzeSentimentRequest { Document = new Document(), }; // Make the request AnalyzeSentimentResponse response = languageServiceClient.AnalyzeSentiment(request); // End snippet } /// <summary>Snippet for AnalyzeEntitiesAsync</summary> public async Task AnalyzeEntitiesAsync() { // Snippet: AnalyzeEntitiesAsync(Document,EncodingType?,CallSettings) // Additional: AnalyzeEntitiesAsync(Document,EncodingType?,CancellationToken) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) Document document = new Document(); EncodingType encodingType = EncodingType.None; // Make the request AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(document, encodingType); // End snippet } /// <summary>Snippet for AnalyzeEntities</summary> public void AnalyzeEntities() { // Snippet: AnalyzeEntities(Document,EncodingType?,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) Document document = new Document(); EncodingType encodingType = EncodingType.None; // Make the request AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(document, encodingType); // End snippet } /// <summary>Snippet for AnalyzeEntitiesAsync</summary> public async Task AnalyzeEntitiesAsync_RequestObject() { // Snippet: AnalyzeEntitiesAsync(AnalyzeEntitiesRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest { Document = new Document(), }; // Make the request AnalyzeEntitiesResponse response = await languageServiceClient.AnalyzeEntitiesAsync(request); // End snippet } /// <summary>Snippet for AnalyzeEntities</summary> public void AnalyzeEntities_RequestObject() { // Snippet: AnalyzeEntities(AnalyzeEntitiesRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest { Document = new Document(), }; // Make the request AnalyzeEntitiesResponse response = languageServiceClient.AnalyzeEntities(request); // End snippet } /// <summary>Snippet for AnalyzeEntitySentimentAsync</summary> public async Task AnalyzeEntitySentimentAsync() { // Snippet: AnalyzeEntitySentimentAsync(Document,EncodingType?,CallSettings) // Additional: AnalyzeEntitySentimentAsync(Document,EncodingType?,CancellationToken) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) Document document = new Document(); EncodingType encodingType = EncodingType.None; // Make the request AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(document, encodingType); // End snippet } /// <summary>Snippet for AnalyzeEntitySentiment</summary> public void AnalyzeEntitySentiment() { // Snippet: AnalyzeEntitySentiment(Document,EncodingType?,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) Document document = new Document(); EncodingType encodingType = EncodingType.None; // Make the request AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(document, encodingType); // End snippet } /// <summary>Snippet for AnalyzeEntitySentimentAsync</summary> public async Task AnalyzeEntitySentimentAsync_RequestObject() { // Snippet: AnalyzeEntitySentimentAsync(AnalyzeEntitySentimentRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest { Document = new Document(), }; // Make the request AnalyzeEntitySentimentResponse response = await languageServiceClient.AnalyzeEntitySentimentAsync(request); // End snippet } /// <summary>Snippet for AnalyzeEntitySentiment</summary> public void AnalyzeEntitySentiment_RequestObject() { // Snippet: AnalyzeEntitySentiment(AnalyzeEntitySentimentRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) AnalyzeEntitySentimentRequest request = new AnalyzeEntitySentimentRequest { Document = new Document(), }; // Make the request AnalyzeEntitySentimentResponse response = languageServiceClient.AnalyzeEntitySentiment(request); // End snippet } /// <summary>Snippet for AnalyzeSyntaxAsync</summary> public async Task AnalyzeSyntaxAsync() { // Snippet: AnalyzeSyntaxAsync(Document,EncodingType?,CallSettings) // Additional: AnalyzeSyntaxAsync(Document,EncodingType?,CancellationToken) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) Document document = new Document(); EncodingType encodingType = EncodingType.None; // Make the request AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(document, encodingType); // End snippet } /// <summary>Snippet for AnalyzeSyntax</summary> public void AnalyzeSyntax() { // Snippet: AnalyzeSyntax(Document,EncodingType?,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) Document document = new Document(); EncodingType encodingType = EncodingType.None; // Make the request AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(document, encodingType); // End snippet } /// <summary>Snippet for AnalyzeSyntaxAsync</summary> public async Task AnalyzeSyntaxAsync_RequestObject() { // Snippet: AnalyzeSyntaxAsync(AnalyzeSyntaxRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest { Document = new Document(), }; // Make the request AnalyzeSyntaxResponse response = await languageServiceClient.AnalyzeSyntaxAsync(request); // End snippet } /// <summary>Snippet for AnalyzeSyntax</summary> public void AnalyzeSyntax_RequestObject() { // Snippet: AnalyzeSyntax(AnalyzeSyntaxRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest { Document = new Document(), }; // Make the request AnalyzeSyntaxResponse response = languageServiceClient.AnalyzeSyntax(request); // End snippet } /// <summary>Snippet for ClassifyTextAsync</summary> public async Task ClassifyTextAsync() { // Snippet: ClassifyTextAsync(Document,CallSettings) // Additional: ClassifyTextAsync(Document,CancellationToken) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) Document document = new Document(); // Make the request ClassifyTextResponse response = await languageServiceClient.ClassifyTextAsync(document); // End snippet } /// <summary>Snippet for ClassifyText</summary> public void ClassifyText() { // Snippet: ClassifyText(Document,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) Document document = new Document(); // Make the request ClassifyTextResponse response = languageServiceClient.ClassifyText(document); // End snippet } /// <summary>Snippet for ClassifyTextAsync</summary> public async Task ClassifyTextAsync_RequestObject() { // Snippet: ClassifyTextAsync(ClassifyTextRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) ClassifyTextRequest request = new ClassifyTextRequest { Document = new Document(), }; // Make the request ClassifyTextResponse response = await languageServiceClient.ClassifyTextAsync(request); // End snippet } /// <summary>Snippet for ClassifyText</summary> public void ClassifyText_RequestObject() { // Snippet: ClassifyText(ClassifyTextRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) ClassifyTextRequest request = new ClassifyTextRequest { Document = new Document(), }; // Make the request ClassifyTextResponse response = languageServiceClient.ClassifyText(request); // End snippet } /// <summary>Snippet for AnnotateTextAsync</summary> public async Task AnnotateTextAsync() { // Snippet: AnnotateTextAsync(Document,AnnotateTextRequest.Types.Features,EncodingType?,CallSettings) // Additional: AnnotateTextAsync(Document,AnnotateTextRequest.Types.Features,EncodingType?,CancellationToken) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) Document document = new Document(); AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features(); EncodingType encodingType = EncodingType.None; // Make the request AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(document, features, encodingType); // End snippet } /// <summary>Snippet for AnnotateText</summary> public void AnnotateText() { // Snippet: AnnotateText(Document,AnnotateTextRequest.Types.Features,EncodingType?,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) Document document = new Document(); AnnotateTextRequest.Types.Features features = new AnnotateTextRequest.Types.Features(); EncodingType encodingType = EncodingType.None; // Make the request AnnotateTextResponse response = languageServiceClient.AnnotateText(document, features, encodingType); // End snippet } /// <summary>Snippet for AnnotateTextAsync</summary> public async Task AnnotateTextAsync_RequestObject() { // Snippet: AnnotateTextAsync(AnnotateTextRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = await LanguageServiceClient.CreateAsync(); // Initialize request argument(s) AnnotateTextRequest request = new AnnotateTextRequest { Document = new Document(), Features = new AnnotateTextRequest.Types.Features(), }; // Make the request AnnotateTextResponse response = await languageServiceClient.AnnotateTextAsync(request); // End snippet } /// <summary>Snippet for AnnotateText</summary> public void AnnotateText_RequestObject() { // Snippet: AnnotateText(AnnotateTextRequest,CallSettings) // Create client LanguageServiceClient languageServiceClient = LanguageServiceClient.Create(); // Initialize request argument(s) AnnotateTextRequest request = new AnnotateTextRequest { Document = new Document(), Features = new AnnotateTextRequest.Types.Features(), }; // Make the request AnnotateTextResponse response = languageServiceClient.AnnotateText(request); // End snippet } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data { /// <summary> /// Strongly-typed collection for the ImportBatchSummary class. /// </summary> [Serializable] public partial class ImportBatchSummaryCollection : ActiveList<ImportBatchSummary, ImportBatchSummaryCollection> { public ImportBatchSummaryCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>ImportBatchSummaryCollection</returns> public ImportBatchSummaryCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { ImportBatchSummary o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the ImportBatchSummary table. /// </summary> [Serializable] public partial class ImportBatchSummary : ActiveRecord<ImportBatchSummary>, IActiveRecord { #region .ctors and Default Settings public ImportBatchSummary() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public ImportBatchSummary(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public ImportBatchSummary(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public ImportBatchSummary(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("ImportBatchSummary", TableType.Table, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @"(newid())"; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarImportBatchID = new TableSchema.TableColumn(schema); colvarImportBatchID.ColumnName = "ImportBatchID"; colvarImportBatchID.DataType = DbType.Guid; colvarImportBatchID.MaxLength = 0; colvarImportBatchID.AutoIncrement = false; colvarImportBatchID.IsNullable = false; colvarImportBatchID.IsPrimaryKey = false; colvarImportBatchID.IsForeignKey = true; colvarImportBatchID.IsReadOnly = false; colvarImportBatchID.DefaultSetting = @""; colvarImportBatchID.ForeignKeyTableName = "ImportBatch"; schema.Columns.Add(colvarImportBatchID); TableSchema.TableColumn colvarSensorID = new TableSchema.TableColumn(schema); colvarSensorID.ColumnName = "SensorID"; colvarSensorID.DataType = DbType.Guid; colvarSensorID.MaxLength = 0; colvarSensorID.AutoIncrement = false; colvarSensorID.IsNullable = false; colvarSensorID.IsPrimaryKey = false; colvarSensorID.IsForeignKey = true; colvarSensorID.IsReadOnly = false; colvarSensorID.DefaultSetting = @""; colvarSensorID.ForeignKeyTableName = "Sensor"; schema.Columns.Add(colvarSensorID); TableSchema.TableColumn colvarInstrumentID = new TableSchema.TableColumn(schema); colvarInstrumentID.ColumnName = "InstrumentID"; colvarInstrumentID.DataType = DbType.Guid; colvarInstrumentID.MaxLength = 0; colvarInstrumentID.AutoIncrement = false; colvarInstrumentID.IsNullable = false; colvarInstrumentID.IsPrimaryKey = false; colvarInstrumentID.IsForeignKey = true; colvarInstrumentID.IsReadOnly = false; colvarInstrumentID.DefaultSetting = @""; colvarInstrumentID.ForeignKeyTableName = "Instrument"; schema.Columns.Add(colvarInstrumentID); TableSchema.TableColumn colvarStationID = new TableSchema.TableColumn(schema); colvarStationID.ColumnName = "StationID"; colvarStationID.DataType = DbType.Guid; colvarStationID.MaxLength = 0; colvarStationID.AutoIncrement = false; colvarStationID.IsNullable = false; colvarStationID.IsPrimaryKey = false; colvarStationID.IsForeignKey = true; colvarStationID.IsReadOnly = false; colvarStationID.DefaultSetting = @""; colvarStationID.ForeignKeyTableName = "Station"; schema.Columns.Add(colvarStationID); TableSchema.TableColumn colvarSiteID = new TableSchema.TableColumn(schema); colvarSiteID.ColumnName = "SiteID"; colvarSiteID.DataType = DbType.Guid; colvarSiteID.MaxLength = 0; colvarSiteID.AutoIncrement = false; colvarSiteID.IsNullable = false; colvarSiteID.IsPrimaryKey = false; colvarSiteID.IsForeignKey = true; colvarSiteID.IsReadOnly = false; colvarSiteID.DefaultSetting = @""; colvarSiteID.ForeignKeyTableName = "Site"; schema.Columns.Add(colvarSiteID); TableSchema.TableColumn colvarPhenomenonOfferingID = new TableSchema.TableColumn(schema); colvarPhenomenonOfferingID.ColumnName = "PhenomenonOfferingID"; colvarPhenomenonOfferingID.DataType = DbType.Guid; colvarPhenomenonOfferingID.MaxLength = 0; colvarPhenomenonOfferingID.AutoIncrement = false; colvarPhenomenonOfferingID.IsNullable = false; colvarPhenomenonOfferingID.IsPrimaryKey = false; colvarPhenomenonOfferingID.IsForeignKey = true; colvarPhenomenonOfferingID.IsReadOnly = false; colvarPhenomenonOfferingID.DefaultSetting = @""; colvarPhenomenonOfferingID.ForeignKeyTableName = "PhenomenonOffering"; schema.Columns.Add(colvarPhenomenonOfferingID); TableSchema.TableColumn colvarPhenomenonUOMID = new TableSchema.TableColumn(schema); colvarPhenomenonUOMID.ColumnName = "PhenomenonUOMID"; colvarPhenomenonUOMID.DataType = DbType.Guid; colvarPhenomenonUOMID.MaxLength = 0; colvarPhenomenonUOMID.AutoIncrement = false; colvarPhenomenonUOMID.IsNullable = false; colvarPhenomenonUOMID.IsPrimaryKey = false; colvarPhenomenonUOMID.IsForeignKey = true; colvarPhenomenonUOMID.IsReadOnly = false; colvarPhenomenonUOMID.DefaultSetting = @""; colvarPhenomenonUOMID.ForeignKeyTableName = "PhenomenonUOM"; schema.Columns.Add(colvarPhenomenonUOMID); TableSchema.TableColumn colvarCount = new TableSchema.TableColumn(schema); colvarCount.ColumnName = "Count"; colvarCount.DataType = DbType.Int32; colvarCount.MaxLength = 0; colvarCount.AutoIncrement = false; colvarCount.IsNullable = false; colvarCount.IsPrimaryKey = false; colvarCount.IsForeignKey = false; colvarCount.IsReadOnly = false; colvarCount.DefaultSetting = @""; colvarCount.ForeignKeyTableName = ""; schema.Columns.Add(colvarCount); TableSchema.TableColumn colvarValueCount = new TableSchema.TableColumn(schema); colvarValueCount.ColumnName = "ValueCount"; colvarValueCount.DataType = DbType.Int32; colvarValueCount.MaxLength = 0; colvarValueCount.AutoIncrement = false; colvarValueCount.IsNullable = false; colvarValueCount.IsPrimaryKey = false; colvarValueCount.IsForeignKey = false; colvarValueCount.IsReadOnly = false; colvarValueCount.DefaultSetting = @""; colvarValueCount.ForeignKeyTableName = ""; schema.Columns.Add(colvarValueCount); TableSchema.TableColumn colvarNullCount = new TableSchema.TableColumn(schema); colvarNullCount.ColumnName = "NullCount"; colvarNullCount.DataType = DbType.Int32; colvarNullCount.MaxLength = 0; colvarNullCount.AutoIncrement = false; colvarNullCount.IsNullable = true; colvarNullCount.IsPrimaryKey = false; colvarNullCount.IsForeignKey = false; colvarNullCount.IsReadOnly = true; colvarNullCount.DefaultSetting = @""; colvarNullCount.ForeignKeyTableName = ""; schema.Columns.Add(colvarNullCount); TableSchema.TableColumn colvarVerifiedCount = new TableSchema.TableColumn(schema); colvarVerifiedCount.ColumnName = "VerifiedCount"; colvarVerifiedCount.DataType = DbType.Int32; colvarVerifiedCount.MaxLength = 0; colvarVerifiedCount.AutoIncrement = false; colvarVerifiedCount.IsNullable = false; colvarVerifiedCount.IsPrimaryKey = false; colvarVerifiedCount.IsForeignKey = false; colvarVerifiedCount.IsReadOnly = false; colvarVerifiedCount.DefaultSetting = @""; colvarVerifiedCount.ForeignKeyTableName = ""; schema.Columns.Add(colvarVerifiedCount); TableSchema.TableColumn colvarUnverifiedCount = new TableSchema.TableColumn(schema); colvarUnverifiedCount.ColumnName = "UnverifiedCount"; colvarUnverifiedCount.DataType = DbType.Int32; colvarUnverifiedCount.MaxLength = 0; colvarUnverifiedCount.AutoIncrement = false; colvarUnverifiedCount.IsNullable = false; colvarUnverifiedCount.IsPrimaryKey = false; colvarUnverifiedCount.IsForeignKey = false; colvarUnverifiedCount.IsReadOnly = false; colvarUnverifiedCount.DefaultSetting = @""; colvarUnverifiedCount.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnverifiedCount); TableSchema.TableColumn colvarMinimum = new TableSchema.TableColumn(schema); colvarMinimum.ColumnName = "Minimum"; colvarMinimum.DataType = DbType.Double; colvarMinimum.MaxLength = 0; colvarMinimum.AutoIncrement = false; colvarMinimum.IsNullable = true; colvarMinimum.IsPrimaryKey = false; colvarMinimum.IsForeignKey = false; colvarMinimum.IsReadOnly = false; colvarMinimum.DefaultSetting = @""; colvarMinimum.ForeignKeyTableName = ""; schema.Columns.Add(colvarMinimum); TableSchema.TableColumn colvarMaximum = new TableSchema.TableColumn(schema); colvarMaximum.ColumnName = "Maximum"; colvarMaximum.DataType = DbType.Double; colvarMaximum.MaxLength = 0; colvarMaximum.AutoIncrement = false; colvarMaximum.IsNullable = true; colvarMaximum.IsPrimaryKey = false; colvarMaximum.IsForeignKey = false; colvarMaximum.IsReadOnly = false; colvarMaximum.DefaultSetting = @""; colvarMaximum.ForeignKeyTableName = ""; schema.Columns.Add(colvarMaximum); TableSchema.TableColumn colvarAverage = new TableSchema.TableColumn(schema); colvarAverage.ColumnName = "Average"; colvarAverage.DataType = DbType.Double; colvarAverage.MaxLength = 0; colvarAverage.AutoIncrement = false; colvarAverage.IsNullable = true; colvarAverage.IsPrimaryKey = false; colvarAverage.IsForeignKey = false; colvarAverage.IsReadOnly = false; colvarAverage.DefaultSetting = @""; colvarAverage.ForeignKeyTableName = ""; schema.Columns.Add(colvarAverage); TableSchema.TableColumn colvarStandardDeviation = new TableSchema.TableColumn(schema); colvarStandardDeviation.ColumnName = "StandardDeviation"; colvarStandardDeviation.DataType = DbType.Double; colvarStandardDeviation.MaxLength = 0; colvarStandardDeviation.AutoIncrement = false; colvarStandardDeviation.IsNullable = true; colvarStandardDeviation.IsPrimaryKey = false; colvarStandardDeviation.IsForeignKey = false; colvarStandardDeviation.IsReadOnly = false; colvarStandardDeviation.DefaultSetting = @""; colvarStandardDeviation.ForeignKeyTableName = ""; schema.Columns.Add(colvarStandardDeviation); TableSchema.TableColumn colvarVariance = new TableSchema.TableColumn(schema); colvarVariance.ColumnName = "Variance"; colvarVariance.DataType = DbType.Double; colvarVariance.MaxLength = 0; colvarVariance.AutoIncrement = false; colvarVariance.IsNullable = true; colvarVariance.IsPrimaryKey = false; colvarVariance.IsForeignKey = false; colvarVariance.IsReadOnly = false; colvarVariance.DefaultSetting = @""; colvarVariance.ForeignKeyTableName = ""; schema.Columns.Add(colvarVariance); TableSchema.TableColumn colvarLatitudeNorth = new TableSchema.TableColumn(schema); colvarLatitudeNorth.ColumnName = "LatitudeNorth"; colvarLatitudeNorth.DataType = DbType.Double; colvarLatitudeNorth.MaxLength = 0; colvarLatitudeNorth.AutoIncrement = false; colvarLatitudeNorth.IsNullable = true; colvarLatitudeNorth.IsPrimaryKey = false; colvarLatitudeNorth.IsForeignKey = false; colvarLatitudeNorth.IsReadOnly = false; colvarLatitudeNorth.DefaultSetting = @""; colvarLatitudeNorth.ForeignKeyTableName = ""; schema.Columns.Add(colvarLatitudeNorth); TableSchema.TableColumn colvarLatitudeSouth = new TableSchema.TableColumn(schema); colvarLatitudeSouth.ColumnName = "LatitudeSouth"; colvarLatitudeSouth.DataType = DbType.Double; colvarLatitudeSouth.MaxLength = 0; colvarLatitudeSouth.AutoIncrement = false; colvarLatitudeSouth.IsNullable = true; colvarLatitudeSouth.IsPrimaryKey = false; colvarLatitudeSouth.IsForeignKey = false; colvarLatitudeSouth.IsReadOnly = false; colvarLatitudeSouth.DefaultSetting = @""; colvarLatitudeSouth.ForeignKeyTableName = ""; schema.Columns.Add(colvarLatitudeSouth); TableSchema.TableColumn colvarLongitudeWest = new TableSchema.TableColumn(schema); colvarLongitudeWest.ColumnName = "LongitudeWest"; colvarLongitudeWest.DataType = DbType.Double; colvarLongitudeWest.MaxLength = 0; colvarLongitudeWest.AutoIncrement = false; colvarLongitudeWest.IsNullable = true; colvarLongitudeWest.IsPrimaryKey = false; colvarLongitudeWest.IsForeignKey = false; colvarLongitudeWest.IsReadOnly = false; colvarLongitudeWest.DefaultSetting = @""; colvarLongitudeWest.ForeignKeyTableName = ""; schema.Columns.Add(colvarLongitudeWest); TableSchema.TableColumn colvarLongitudeEast = new TableSchema.TableColumn(schema); colvarLongitudeEast.ColumnName = "LongitudeEast"; colvarLongitudeEast.DataType = DbType.Double; colvarLongitudeEast.MaxLength = 0; colvarLongitudeEast.AutoIncrement = false; colvarLongitudeEast.IsNullable = true; colvarLongitudeEast.IsPrimaryKey = false; colvarLongitudeEast.IsForeignKey = false; colvarLongitudeEast.IsReadOnly = false; colvarLongitudeEast.DefaultSetting = @""; colvarLongitudeEast.ForeignKeyTableName = ""; schema.Columns.Add(colvarLongitudeEast); TableSchema.TableColumn colvarElevationMinimum = new TableSchema.TableColumn(schema); colvarElevationMinimum.ColumnName = "ElevationMinimum"; colvarElevationMinimum.DataType = DbType.Double; colvarElevationMinimum.MaxLength = 0; colvarElevationMinimum.AutoIncrement = false; colvarElevationMinimum.IsNullable = true; colvarElevationMinimum.IsPrimaryKey = false; colvarElevationMinimum.IsForeignKey = false; colvarElevationMinimum.IsReadOnly = false; colvarElevationMinimum.DefaultSetting = @""; colvarElevationMinimum.ForeignKeyTableName = ""; schema.Columns.Add(colvarElevationMinimum); TableSchema.TableColumn colvarElevationMaximum = new TableSchema.TableColumn(schema); colvarElevationMaximum.ColumnName = "ElevationMaximum"; colvarElevationMaximum.DataType = DbType.Double; colvarElevationMaximum.MaxLength = 0; colvarElevationMaximum.AutoIncrement = false; colvarElevationMaximum.IsNullable = true; colvarElevationMaximum.IsPrimaryKey = false; colvarElevationMaximum.IsForeignKey = false; colvarElevationMaximum.IsReadOnly = false; colvarElevationMaximum.DefaultSetting = @""; colvarElevationMaximum.ForeignKeyTableName = ""; schema.Columns.Add(colvarElevationMaximum); TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema); colvarStartDate.ColumnName = "StartDate"; colvarStartDate.DataType = DbType.DateTime; colvarStartDate.MaxLength = 0; colvarStartDate.AutoIncrement = false; colvarStartDate.IsNullable = true; colvarStartDate.IsPrimaryKey = false; colvarStartDate.IsForeignKey = false; colvarStartDate.IsReadOnly = false; colvarStartDate.DefaultSetting = @""; colvarStartDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarStartDate); TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema); colvarEndDate.ColumnName = "EndDate"; colvarEndDate.DataType = DbType.DateTime; colvarEndDate.MaxLength = 0; colvarEndDate.AutoIncrement = false; colvarEndDate.IsNullable = true; colvarEndDate.IsPrimaryKey = false; colvarEndDate.IsForeignKey = false; colvarEndDate.IsReadOnly = false; colvarEndDate.DefaultSetting = @""; colvarEndDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarEndDate); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("ImportBatchSummary",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("ImportBatchID")] [Bindable(true)] public Guid ImportBatchID { get { return GetColumnValue<Guid>(Columns.ImportBatchID); } set { SetColumnValue(Columns.ImportBatchID, value); } } [XmlAttribute("SensorID")] [Bindable(true)] public Guid SensorID { get { return GetColumnValue<Guid>(Columns.SensorID); } set { SetColumnValue(Columns.SensorID, value); } } [XmlAttribute("InstrumentID")] [Bindable(true)] public Guid InstrumentID { get { return GetColumnValue<Guid>(Columns.InstrumentID); } set { SetColumnValue(Columns.InstrumentID, value); } } [XmlAttribute("StationID")] [Bindable(true)] public Guid StationID { get { return GetColumnValue<Guid>(Columns.StationID); } set { SetColumnValue(Columns.StationID, value); } } [XmlAttribute("SiteID")] [Bindable(true)] public Guid SiteID { get { return GetColumnValue<Guid>(Columns.SiteID); } set { SetColumnValue(Columns.SiteID, value); } } [XmlAttribute("PhenomenonOfferingID")] [Bindable(true)] public Guid PhenomenonOfferingID { get { return GetColumnValue<Guid>(Columns.PhenomenonOfferingID); } set { SetColumnValue(Columns.PhenomenonOfferingID, value); } } [XmlAttribute("PhenomenonUOMID")] [Bindable(true)] public Guid PhenomenonUOMID { get { return GetColumnValue<Guid>(Columns.PhenomenonUOMID); } set { SetColumnValue(Columns.PhenomenonUOMID, value); } } [XmlAttribute("Count")] [Bindable(true)] public int Count { get { return GetColumnValue<int>(Columns.Count); } set { SetColumnValue(Columns.Count, value); } } [XmlAttribute("ValueCount")] [Bindable(true)] public int ValueCount { get { return GetColumnValue<int>(Columns.ValueCount); } set { SetColumnValue(Columns.ValueCount, value); } } [XmlAttribute("NullCount")] [Bindable(true)] public int? NullCount { get { return GetColumnValue<int?>(Columns.NullCount); } set { SetColumnValue(Columns.NullCount, value); } } [XmlAttribute("VerifiedCount")] [Bindable(true)] public int VerifiedCount { get { return GetColumnValue<int>(Columns.VerifiedCount); } set { SetColumnValue(Columns.VerifiedCount, value); } } [XmlAttribute("UnverifiedCount")] [Bindable(true)] public int UnverifiedCount { get { return GetColumnValue<int>(Columns.UnverifiedCount); } set { SetColumnValue(Columns.UnverifiedCount, value); } } [XmlAttribute("Minimum")] [Bindable(true)] public double? Minimum { get { return GetColumnValue<double?>(Columns.Minimum); } set { SetColumnValue(Columns.Minimum, value); } } [XmlAttribute("Maximum")] [Bindable(true)] public double? Maximum { get { return GetColumnValue<double?>(Columns.Maximum); } set { SetColumnValue(Columns.Maximum, value); } } [XmlAttribute("Average")] [Bindable(true)] public double? Average { get { return GetColumnValue<double?>(Columns.Average); } set { SetColumnValue(Columns.Average, value); } } [XmlAttribute("StandardDeviation")] [Bindable(true)] public double? StandardDeviation { get { return GetColumnValue<double?>(Columns.StandardDeviation); } set { SetColumnValue(Columns.StandardDeviation, value); } } [XmlAttribute("Variance")] [Bindable(true)] public double? Variance { get { return GetColumnValue<double?>(Columns.Variance); } set { SetColumnValue(Columns.Variance, value); } } [XmlAttribute("LatitudeNorth")] [Bindable(true)] public double? LatitudeNorth { get { return GetColumnValue<double?>(Columns.LatitudeNorth); } set { SetColumnValue(Columns.LatitudeNorth, value); } } [XmlAttribute("LatitudeSouth")] [Bindable(true)] public double? LatitudeSouth { get { return GetColumnValue<double?>(Columns.LatitudeSouth); } set { SetColumnValue(Columns.LatitudeSouth, value); } } [XmlAttribute("LongitudeWest")] [Bindable(true)] public double? LongitudeWest { get { return GetColumnValue<double?>(Columns.LongitudeWest); } set { SetColumnValue(Columns.LongitudeWest, value); } } [XmlAttribute("LongitudeEast")] [Bindable(true)] public double? LongitudeEast { get { return GetColumnValue<double?>(Columns.LongitudeEast); } set { SetColumnValue(Columns.LongitudeEast, value); } } [XmlAttribute("ElevationMinimum")] [Bindable(true)] public double? ElevationMinimum { get { return GetColumnValue<double?>(Columns.ElevationMinimum); } set { SetColumnValue(Columns.ElevationMinimum, value); } } [XmlAttribute("ElevationMaximum")] [Bindable(true)] public double? ElevationMaximum { get { return GetColumnValue<double?>(Columns.ElevationMaximum); } set { SetColumnValue(Columns.ElevationMaximum, value); } } [XmlAttribute("StartDate")] [Bindable(true)] public DateTime? StartDate { get { return GetColumnValue<DateTime?>(Columns.StartDate); } set { SetColumnValue(Columns.StartDate, value); } } [XmlAttribute("EndDate")] [Bindable(true)] public DateTime? EndDate { get { return GetColumnValue<DateTime?>(Columns.EndDate); } set { SetColumnValue(Columns.EndDate, value); } } #endregion #region ForeignKey Properties private SAEON.Observations.Data.ImportBatch _ImportBatch = null; /// <summary> /// Returns a ImportBatch ActiveRecord object related to this ImportBatchSummary /// /// </summary> public SAEON.Observations.Data.ImportBatch ImportBatch { // get { return SAEON.Observations.Data.ImportBatch.FetchByID(this.ImportBatchID); } get { return _ImportBatch ?? (_ImportBatch = SAEON.Observations.Data.ImportBatch.FetchByID(this.ImportBatchID)); } set { SetColumnValue("ImportBatchID", value.Id); } } private SAEON.Observations.Data.Instrument _Instrument = null; /// <summary> /// Returns a Instrument ActiveRecord object related to this ImportBatchSummary /// /// </summary> public SAEON.Observations.Data.Instrument Instrument { // get { return SAEON.Observations.Data.Instrument.FetchByID(this.InstrumentID); } get { return _Instrument ?? (_Instrument = SAEON.Observations.Data.Instrument.FetchByID(this.InstrumentID)); } set { SetColumnValue("InstrumentID", value.Id); } } private SAEON.Observations.Data.PhenomenonOffering _PhenomenonOffering = null; /// <summary> /// Returns a PhenomenonOffering ActiveRecord object related to this ImportBatchSummary /// /// </summary> public SAEON.Observations.Data.PhenomenonOffering PhenomenonOffering { // get { return SAEON.Observations.Data.PhenomenonOffering.FetchByID(this.PhenomenonOfferingID); } get { return _PhenomenonOffering ?? (_PhenomenonOffering = SAEON.Observations.Data.PhenomenonOffering.FetchByID(this.PhenomenonOfferingID)); } set { SetColumnValue("PhenomenonOfferingID", value.Id); } } private SAEON.Observations.Data.PhenomenonUOM _PhenomenonUOM = null; /// <summary> /// Returns a PhenomenonUOM ActiveRecord object related to this ImportBatchSummary /// /// </summary> public SAEON.Observations.Data.PhenomenonUOM PhenomenonUOM { // get { return SAEON.Observations.Data.PhenomenonUOM.FetchByID(this.PhenomenonUOMID); } get { return _PhenomenonUOM ?? (_PhenomenonUOM = SAEON.Observations.Data.PhenomenonUOM.FetchByID(this.PhenomenonUOMID)); } set { SetColumnValue("PhenomenonUOMID", value.Id); } } private SAEON.Observations.Data.Sensor _Sensor = null; /// <summary> /// Returns a Sensor ActiveRecord object related to this ImportBatchSummary /// /// </summary> public SAEON.Observations.Data.Sensor Sensor { // get { return SAEON.Observations.Data.Sensor.FetchByID(this.SensorID); } get { return _Sensor ?? (_Sensor = SAEON.Observations.Data.Sensor.FetchByID(this.SensorID)); } set { SetColumnValue("SensorID", value.Id); } } private SAEON.Observations.Data.Site _Site = null; /// <summary> /// Returns a Site ActiveRecord object related to this ImportBatchSummary /// /// </summary> public SAEON.Observations.Data.Site Site { // get { return SAEON.Observations.Data.Site.FetchByID(this.SiteID); } get { return _Site ?? (_Site = SAEON.Observations.Data.Site.FetchByID(this.SiteID)); } set { SetColumnValue("SiteID", value.Id); } } private SAEON.Observations.Data.Station _Station = null; /// <summary> /// Returns a Station ActiveRecord object related to this ImportBatchSummary /// /// </summary> public SAEON.Observations.Data.Station Station { // get { return SAEON.Observations.Data.Station.FetchByID(this.StationID); } get { return _Station ?? (_Station = SAEON.Observations.Data.Station.FetchByID(this.StationID)); } set { SetColumnValue("StationID", value.Id); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(Guid varId,Guid varImportBatchID,Guid varSensorID,Guid varInstrumentID,Guid varStationID,Guid varSiteID,Guid varPhenomenonOfferingID,Guid varPhenomenonUOMID,int varCount,int varValueCount,int? varNullCount,int varVerifiedCount,int varUnverifiedCount,double? varMinimum,double? varMaximum,double? varAverage,double? varStandardDeviation,double? varVariance,double? varLatitudeNorth,double? varLatitudeSouth,double? varLongitudeWest,double? varLongitudeEast,double? varElevationMinimum,double? varElevationMaximum,DateTime? varStartDate,DateTime? varEndDate) { ImportBatchSummary item = new ImportBatchSummary(); item.Id = varId; item.ImportBatchID = varImportBatchID; item.SensorID = varSensorID; item.InstrumentID = varInstrumentID; item.StationID = varStationID; item.SiteID = varSiteID; item.PhenomenonOfferingID = varPhenomenonOfferingID; item.PhenomenonUOMID = varPhenomenonUOMID; item.Count = varCount; item.ValueCount = varValueCount; item.NullCount = varNullCount; item.VerifiedCount = varVerifiedCount; item.UnverifiedCount = varUnverifiedCount; item.Minimum = varMinimum; item.Maximum = varMaximum; item.Average = varAverage; item.StandardDeviation = varStandardDeviation; item.Variance = varVariance; item.LatitudeNorth = varLatitudeNorth; item.LatitudeSouth = varLatitudeSouth; item.LongitudeWest = varLongitudeWest; item.LongitudeEast = varLongitudeEast; item.ElevationMinimum = varElevationMinimum; item.ElevationMaximum = varElevationMaximum; item.StartDate = varStartDate; item.EndDate = varEndDate; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(Guid varId,Guid varImportBatchID,Guid varSensorID,Guid varInstrumentID,Guid varStationID,Guid varSiteID,Guid varPhenomenonOfferingID,Guid varPhenomenonUOMID,int varCount,int varValueCount,int? varNullCount,int varVerifiedCount,int varUnverifiedCount,double? varMinimum,double? varMaximum,double? varAverage,double? varStandardDeviation,double? varVariance,double? varLatitudeNorth,double? varLatitudeSouth,double? varLongitudeWest,double? varLongitudeEast,double? varElevationMinimum,double? varElevationMaximum,DateTime? varStartDate,DateTime? varEndDate) { ImportBatchSummary item = new ImportBatchSummary(); item.Id = varId; item.ImportBatchID = varImportBatchID; item.SensorID = varSensorID; item.InstrumentID = varInstrumentID; item.StationID = varStationID; item.SiteID = varSiteID; item.PhenomenonOfferingID = varPhenomenonOfferingID; item.PhenomenonUOMID = varPhenomenonUOMID; item.Count = varCount; item.ValueCount = varValueCount; item.NullCount = varNullCount; item.VerifiedCount = varVerifiedCount; item.UnverifiedCount = varUnverifiedCount; item.Minimum = varMinimum; item.Maximum = varMaximum; item.Average = varAverage; item.StandardDeviation = varStandardDeviation; item.Variance = varVariance; item.LatitudeNorth = varLatitudeNorth; item.LatitudeSouth = varLatitudeSouth; item.LongitudeWest = varLongitudeWest; item.LongitudeEast = varLongitudeEast; item.ElevationMinimum = varElevationMinimum; item.ElevationMaximum = varElevationMaximum; item.StartDate = varStartDate; item.EndDate = varEndDate; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn ImportBatchIDColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn SensorIDColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn InstrumentIDColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn StationIDColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn SiteIDColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn PhenomenonOfferingIDColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn PhenomenonUOMIDColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn CountColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn ValueCountColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn NullCountColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn VerifiedCountColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn UnverifiedCountColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn MinimumColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn MaximumColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn AverageColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn StandardDeviationColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn VarianceColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn LatitudeNorthColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn LatitudeSouthColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn LongitudeWestColumn { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn LongitudeEastColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn ElevationMinimumColumn { get { return Schema.Columns[22]; } } public static TableSchema.TableColumn ElevationMaximumColumn { get { return Schema.Columns[23]; } } public static TableSchema.TableColumn StartDateColumn { get { return Schema.Columns[24]; } } public static TableSchema.TableColumn EndDateColumn { get { return Schema.Columns[25]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string ImportBatchID = @"ImportBatchID"; public static string SensorID = @"SensorID"; public static string InstrumentID = @"InstrumentID"; public static string StationID = @"StationID"; public static string SiteID = @"SiteID"; public static string PhenomenonOfferingID = @"PhenomenonOfferingID"; public static string PhenomenonUOMID = @"PhenomenonUOMID"; public static string Count = @"Count"; public static string ValueCount = @"ValueCount"; public static string NullCount = @"NullCount"; public static string VerifiedCount = @"VerifiedCount"; public static string UnverifiedCount = @"UnverifiedCount"; public static string Minimum = @"Minimum"; public static string Maximum = @"Maximum"; public static string Average = @"Average"; public static string StandardDeviation = @"StandardDeviation"; public static string Variance = @"Variance"; public static string LatitudeNorth = @"LatitudeNorth"; public static string LatitudeSouth = @"LatitudeSouth"; public static string LongitudeWest = @"LongitudeWest"; public static string LongitudeEast = @"LongitudeEast"; public static string ElevationMinimum = @"ElevationMinimum"; public static string ElevationMaximum = @"ElevationMaximum"; public static string StartDate = @"StartDate"; public static string EndDate = @"EndDate"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace UnitTest.Epoxy { using System; using System.Collections; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Bond.Comm; using Bond.Comm.Epoxy; using NUnit.Framework; using UnitTest.Interfaces; [TestFixture] public class FrameTests { private const int UnknownFramelet = 0x1234; private readonly ArraySegment<byte> AnyContents = new ArraySegment<byte>(new byte[] { 0x62, 0x6F, 0x6E, 0x64 }); [Test] public void FrameletTypes_AreAsSpecified() { var expectedFramelets = new [] { new { EnumMember = FrameletType.EpoxyConfig, ExpectedValue = 0x4743 }, new { EnumMember = FrameletType.EpoxyHeaders, ExpectedValue = 0x5248 }, new { EnumMember = FrameletType.ErrorData, ExpectedValue = 0x4445 }, new { EnumMember = FrameletType.LayerData, ExpectedValue = 0x594C }, new { EnumMember = FrameletType.PayloadData, ExpectedValue = 0x4450 }, new { EnumMember = FrameletType.ProtocolError, ExpectedValue = 0x5245 }, }; foreach (var ft in expectedFramelets) { Assert.AreEqual( ft.ExpectedValue, (int)ft.EnumMember, "FrameletType {0} did not have the speced value", Enum.GetName(typeof(FrameletType), ft.EnumMember)); Assert.IsTrue( Framelet.IsKnownType((UInt16)ft.EnumMember), "FrameletType {0} is not known to Framelet", ft.EnumMember); } var expectedEnumMembers = from ft in expectedFramelets select ft.EnumMember; var enumMembers = Enum.GetValues(typeof (FrameletType)).Cast<FrameletType>(); CollectionAssert.AreEquivalent(expectedEnumMembers, enumMembers); } [Test] public void Framelet_ctor_UnknownFrameletType_Throws() { Assert.IsFalse(Enum.IsDefined(typeof (FrameletType), UnknownFramelet)); Assert.Throws<ArgumentException>(() => new Framelet((FrameletType)UnknownFramelet, AnyContents)); Assert.IsFalse(Framelet.IsKnownType((unchecked((UInt16)UnknownFramelet)))); } [Test] public void Framelet_ctor_NullEmptyContents_Throws() { var nullArraySegment = default(ArraySegment<byte>); var emptyArraySegment = new ArraySegment<byte>(new byte[0]); Assert.Throws<ArgumentException>(() => new Framelet(FrameletType.PayloadData, nullArraySegment)); Assert.Throws<ArgumentException>(() => new Framelet(FrameletType.PayloadData, emptyArraySegment)); } [Test] public void Framelet_Getters_ReturnConstructorValues() { var framelet = new Framelet(FrameletType.PayloadData, AnyContents); Assert.AreEqual(FrameletType.PayloadData, framelet.Type); Assert.AreEqual(AnyContents, framelet.Contents); } [Test] public void Frame_ctor_NegativeCapacity_Throws() { Assert.Throws<ArgumentOutOfRangeException>(() => new Frame(-1, LoggerTests.BlackHole)); } [Test] public void Frame_default_ctor_DoesntThrow() { var frame = new Frame(LoggerTests.BlackHole); Assert.AreEqual(0, frame.Count); CollectionAssert.IsEmpty(frame.Framelets); } [Test] public void Frame_Add_FrameletsCanBeRetreived() { var AnyOtherContents = new ArraySegment<byte>(new[] {(byte)0x00}); var expectedFramelets = new[] { new Framelet(FrameletType.EpoxyConfig, AnyContents), new Framelet(FrameletType.EpoxyConfig, AnyOtherContents), new Framelet(FrameletType.LayerData, AnyContents), new Framelet(FrameletType.EpoxyConfig, AnyContents), }; var frame = new Frame(4, LoggerTests.BlackHole); frame.Add(new Framelet(FrameletType.EpoxyConfig, AnyContents)); frame.Add(new Framelet(FrameletType.EpoxyConfig, AnyOtherContents)); frame.Add(new Framelet(FrameletType.LayerData, AnyContents)); frame.Add(new Framelet(FrameletType.EpoxyConfig, AnyContents)); Assert.AreEqual(4, frame.Count); Assert.AreEqual(frame.Framelets.Count, frame.Count); CollectionAssert.AreEqual(expectedFramelets, frame.Framelets); } [Test] public void Frame_Add_TotalCount_Updated() { var frame = new Frame(2, LoggerTests.BlackHole); int expectedSize = 2; Assert.AreEqual(expectedSize, frame.TotalSize); frame.Add(new Framelet(FrameletType.LayerData, AnyContents)); expectedSize += 2 + 4 + AnyContents.Count; Assert.AreEqual(expectedSize, frame.TotalSize); frame.Add(new Framelet(FrameletType.ProtocolError, AnyContents)); expectedSize += 2 + 4 + AnyContents.Count; Assert.AreEqual(expectedSize, frame.TotalSize); } [Test] public void Frame_Add_AddMoreThanUInt16Framelets_Throws() { var frame = new Frame((int)UInt16.MaxValue + 1, LoggerTests.BlackHole); for (int i = 0; i < UInt16.MaxValue; ++i) { frame.Add(new Framelet(FrameletType.LayerData, AnyContents)); } Assert.That( () => frame.Add(new Framelet(FrameletType.PayloadData, AnyContents)), Throws.InvalidOperationException.With.Message.ContainsSubstring("Exceeded maximum allowed count of framelets")); } [Test] public void Frame_Add_AddMoreThanInt32TotalSize_Throws() { var largeContents = new ArraySegment<byte>(new byte[2 * 65535]); int numFramesToAdd = Int32.MaxValue/largeContents.Count; var frame = new Frame(numFramesToAdd, LoggerTests.BlackHole); for (int i = 0; i < numFramesToAdd - 1; ++i) { frame.Add(new Framelet(FrameletType.LayerData, largeContents)); } Assert.That( () => frame.Add(new Framelet(FrameletType.LayerData, largeContents)), Throws.InvalidOperationException.With.Message.ContainsSubstring("Exceeded maximum size of frame")); } [Test] public void Frame_WriteAsync_EmptyFrame_Throws() { var frame = new Frame(LoggerTests.BlackHole); Assert.Throws<InvalidOperationException>(async () => await frame.WriteAsync(new MemoryStream())); } [Test] public async Task Frame_WriteAsync_OneFramelet_ContentsExpected() { var frame = new Frame(LoggerTests.BlackHole); frame.Add(new Framelet(FrameletType.EpoxyConfig, AnyContents)); var memStream = new MemoryStream(); await frame.WriteAsync(memStream); var expectedBytes = new[] { 0x01, 0x00, // frame count 0x43, 0x47, // EpoxyConfig framelet type 0x04, 0x00, 0x00, 0x00, // framelet length 0x62, 0x6F, 0x6E, 0x64 // AnyContents bytes }; CollectionAssert.AreEqual(expectedBytes, memStream.ToArray()); } [Test] public void Frame_ReadAsync_ZeroFramelets_Throws() { var zeroFrameletsStream = new FrameBuilder().Count(0).TakeStream(); Assert.Throws<EpoxyProtocolErrorException>(async () => await Frame.ReadAsync(zeroFrameletsStream, CancellationToken.None, LoggerTests.BlackHole)); } [Test] public void Frame_ReadAsync_UnknownFramelet_Throws() { var unknownFrameletStream = new FrameBuilder().Count(1).Type((FrameletType) UnknownFramelet).TakeStream(); Assert.Throws<EpoxyProtocolErrorException>(async () => await Frame.ReadAsync(unknownFrameletStream, CancellationToken.None, LoggerTests.BlackHole)); } [Test] public void Frame_ReadAsync_FrameletTooLarge_Throws() { var frameletTooLargeStream = new FrameBuilder().Count(1) .Type(FrameletType.PayloadData) .Size((UInt32) Int32.MaxValue + 1) .TakeStream(); Assert.Throws<EpoxyProtocolErrorException>(async () => await Frame.ReadAsync(frameletTooLargeStream, CancellationToken.None, LoggerTests.BlackHole)); } [Test] public void Frame_ReadAsync_EndOfStreamInCount_ReturnsNull() { var tooShortStream = new FrameBuilder().Count(1).TakeTooShortStream(); Assert.Null(Frame.ReadAsync(tooShortStream, CancellationToken.None, LoggerTests.BlackHole).Result); } [Test] public void Frame_ReadAsync_EndOfStreamInType_ReturnsNull() { var tooShortStream = new FrameBuilder().Count(1).Type(FrameletType.ProtocolError).TakeTooShortStream(); Assert.Null(Frame.ReadAsync(tooShortStream, CancellationToken.None, LoggerTests.BlackHole).Result); } [Test] public void Frame_ReadAsync_EndOfStreamInSize_ReturnsNull() { var tooShortStream = new FrameBuilder().Count(1).Type(FrameletType.ProtocolError).Size(4).TakeTooShortStream(); Assert.Null(Frame.ReadAsync(tooShortStream, CancellationToken.None, LoggerTests.BlackHole).Result); } [Test] public void Frame_ReadAsync_EndOfStreamInContent_ReturnsNull() { var tooShortStream = new FrameBuilder().Count(1).Type(FrameletType.ProtocolError).Size(4).Content(AnyContents).TakeTooShortStream(); Assert.Null(Frame.ReadAsync(tooShortStream, CancellationToken.None, LoggerTests.BlackHole).Result); } [Test] public async Task Frame_ReadAsync_CancellationRequested_ReturnsNull() { var cts = new CancellationTokenSource(); cts.Cancel(); var goodStream = new FrameBuilder().Count(1).Type(FrameletType.ProtocolError).Size(4).Content(AnyContents).TakeStream(); Frame frame = await Frame.ReadAsync(goodStream, cts.Token, LoggerTests.BlackHole); Assert.IsNull(frame); } [Test] public async Task Frame_RoundTrip_Works() { var expectedFramelets = new[] { new Framelet(FrameletType.EpoxyConfig, AnyContents), new Framelet(FrameletType.LayerData, AnyContents), new Framelet(FrameletType.EpoxyConfig, AnyContents), }; var frame = new Frame(LoggerTests.BlackHole); foreach (var framelet in expectedFramelets) { frame.Add(framelet); } var memStream = new MemoryStream(); await frame.WriteAsync(memStream); memStream.Seek(0, SeekOrigin.Begin); var resultFrame = await Frame.ReadAsync(memStream, CancellationToken.None, LoggerTests.BlackHole); CollectionAssert.AreEqual(expectedFramelets, resultFrame.Framelets, DeepFrameletComparer.Instance); } private class FrameBuilder { private MemoryStream stream = new MemoryStream(); public FrameBuilder Count(UInt16 size) { byte[] bytes = BitConverter.GetBytes(size); stream.Write(bytes, 0, bytes.Length); return this; } public FrameBuilder Type(FrameletType type) { byte[] bytes = BitConverter.GetBytes(unchecked((UInt16)type)); stream.Write(bytes, 0, bytes.Length); return this; } public FrameBuilder Size(UInt32 size) { byte[] bytes = BitConverter.GetBytes(size); stream.Write(bytes, 0, bytes.Length); return this; } public FrameBuilder Content(ArraySegment<byte> content) { stream.Write(content.Array, content.Offset, content.Count); return this; } public FrameBuilder Content(byte[] content) { return Content(new ArraySegment<byte>(content)); } public MemoryStream TakeStream() { var result = stream; stream = null; result.Seek(0, SeekOrigin.Begin); return result; } public MemoryStream TakeTooShortStream() { var originalStream = stream; stream = null; return new MemoryStream( originalStream.GetBuffer(), index: 0, count: (int)originalStream.Position - 1, writable: false, publiclyVisible: true); } } private class DeepFrameletComparer : IComparer { public static readonly DeepFrameletComparer Instance = new DeepFrameletComparer(); public int Compare(object x, object y) { Assert.That(x, Is.InstanceOf<Framelet>()); Assert.That(y, Is.InstanceOf<Framelet>()); var left = (Framelet)x; var right = (Framelet)y; int result = left.Type.CompareTo(right.Type); if (result != 0) { return result; } result = left.Contents.Count.CompareTo(right.Contents.Count); if (result != 0) { return result; } if (left.Contents.Array == null && right.Contents.Array != null) { return -1; } else if (left.Contents.Array != null && right.Contents.Array == null) { return 1; } // at this point, both counts are the same and both arrays have the samm // null /not-null status. If the arrays are null, the count will be 0, and we'll // skip this loop. Assert.AreEqual(left.Contents.Count, right.Contents.Count); Assert.IsTrue( (left.Contents.Array == null && right.Contents.Array == null) || (left.Contents.Array != null && right.Contents.Array != null)); for (int idx = 0; idx < left.Contents.Count; ++idx) { byte leftByte = left.Contents.Array[left.Contents.Offset + idx]; byte rightByte = right.Contents.Array[right.Contents.Offset + idx]; result = leftByte.CompareTo(rightByte); if (result != 0) { return result; } } return 0; } } } }
namespace Petstore { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// The Storage Management Client. /// </summary> public partial class StorageManagementClient : Microsoft.Rest.ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IStorageAccountsOperations. /// </summary> public virtual IStorageAccountsOperations StorageAccounts { get; private set; } /// <summary> /// Gets the IUsageOperations. /// </summary> public virtual IUsageOperations Usage { get; private set; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.StorageAccounts = new StorageAccountsOperations(this); this.Usage = new UsageOperations(this); this.BaseUri = new System.Uri("https://management.azure.com"); this.ApiVersion = "2015-06-15"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.Messages; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs { /// <summary> /// Packets for SmbNtCreateAndx Request /// </summary> public class SmbNtCreateAndxRequestPacket : SmbBatchedRequestPacket { #region Fields private SMB_COM_NT_CREATE_ANDX_Request_SMB_Parameters smbParameters; private SMB_COM_NT_CREATE_ANDX_Request_SMB_Data smbData; #endregion #region Properties /// <summary> /// get or set the Smb_Parameters:SMB_COM_NT_CREATE_ANDX_Request_SMB_Parameters /// </summary> public SMB_COM_NT_CREATE_ANDX_Request_SMB_Parameters SmbParameters { get { return this.smbParameters; } set { this.smbParameters = value; } } /// <summary> /// get or set the Smb_Data:SMB_COM_NT_CREATE_ANDX_Request_SMB_Data /// </summary> public SMB_COM_NT_CREATE_ANDX_Request_SMB_Data SmbData { get { return this.smbData; } set { this.smbData = value; } } /// <summary> /// the SmbCommand of the andx packet. /// </summary> protected override SmbCommand AndxCommand { get { return this.SmbParameters.AndXCommand; } } /// <summary> /// Set the AndXOffset from batched request /// </summary> protected override ushort AndXOffset { get { return this.smbParameters.AndXOffset; } set { this.smbParameters.AndXOffset = value; } } #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public SmbNtCreateAndxRequestPacket() : base() { this.InitDefaultValue(); } /// <summary> /// Constructor: Create a request directly from a buffer. /// </summary> public SmbNtCreateAndxRequestPacket(byte[] data) : base(data) { } /// <summary> /// Deep copy constructor. /// </summary> public SmbNtCreateAndxRequestPacket(SmbNtCreateAndxRequestPacket packet) : base(packet) { this.InitDefaultValue(); this.smbParameters.WordCount = packet.SmbParameters.WordCount; this.smbParameters.AndXCommand = packet.SmbParameters.AndXCommand; this.smbParameters.AndXReserved = packet.SmbParameters.AndXReserved; this.smbParameters.AndXOffset = packet.SmbParameters.AndXOffset; this.smbParameters.Reserved = packet.SmbParameters.Reserved; this.smbParameters.NameLength = packet.SmbParameters.NameLength; this.smbParameters.Flags = packet.SmbParameters.Flags; this.smbParameters.RootDirectoryFID = packet.SmbParameters.RootDirectoryFID; this.smbParameters.DesiredAccess = packet.SmbParameters.DesiredAccess; this.smbParameters.AllocationSize = packet.SmbParameters.AllocationSize; this.smbParameters.ExtFileAttributes = packet.SmbParameters.ExtFileAttributes; this.smbParameters.ShareAccess = packet.SmbParameters.ShareAccess; this.smbParameters.CreateDisposition = packet.SmbParameters.CreateDisposition; this.smbParameters.CreateOptions = packet.SmbParameters.CreateOptions; this.smbParameters.ImpersonationLevel = packet.SmbParameters.ImpersonationLevel; this.smbParameters.SecurityFlags = packet.smbParameters.SecurityFlags; this.smbData.ByteCount = packet.SmbData.ByteCount; this.smbData.Pad = packet.smbData.Pad; if (packet.smbData.FileName != null) { this.smbData.FileName = new byte[packet.smbData.FileName.Length]; Array.Copy(packet.smbData.FileName, this.smbData.FileName, packet.smbData.FileName.Length); } else { this.smbData.FileName = new byte[0]; } } #endregion #region override methods /// <summary> /// to create an instance of the StackPacket class that is identical to the current StackPacket. /// </summary> /// <returns>a new Packet cloned from this.</returns> public override StackPacket Clone() { return new SmbNtCreateAndxRequestPacket(this); } /// <summary> /// Encode the struct of SMB_COM_NT_CREATE_ANDX_Request_SMB_Parameters into the struct of SmbParameters /// </summary> protected override void EncodeParameters() { this.smbParametersBlock = TypeMarshal.ToStruct<SmbParameters>( CifsMessageUtils.ToBytes<SMB_COM_NT_CREATE_ANDX_Request_SMB_Parameters>(this.smbParameters)); } /// <summary> /// Encode the struct of SMB_COM_NT_CREATE_ANDX_Request_SMB_Data into the struct of SmbData /// </summary> protected override void EncodeData() { byte[] buf = ArrayUtility.ConcatenateArrays( BitConverter.GetBytes(this.SmbData.ByteCount), this.SmbData.Pad, this.SmbData.FileName); this.smbDataBlock = TypeMarshal.ToStruct<SmbData>(buf); } /// <summary> /// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters. /// </summary> protected override void DecodeParameters() { this.smbParameters = TypeMarshal.ToStruct<SMB_COM_NT_CREATE_ANDX_Request_SMB_Parameters>( TypeMarshal.ToBytes(this.smbParametersBlock)); } /// <summary> /// to decode the smb data: from the general SmbDada to the concrete Smb Data. /// </summary> protected override void DecodeData() { this.smbData.ByteCount = this.smbDataBlock.ByteCount; if ((this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == 0) { this.smbData.Pad = new byte[0]; this.smbData.FileName = this.smbDataBlock.Bytes; } else { this.smbData.Pad = new byte[] { this.smbDataBlock.Bytes[0] }; this.smbData.FileName = ArrayUtility.SubArray(this.smbDataBlock.Bytes, 1); } } #endregion #region initialize fields with default value /// <summary> /// init packet, set default field data /// </summary> private void InitDefaultValue() { if ((this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == 0) { this.smbData.Pad = new byte[0]; } else { this.smbData.Pad = new byte[1]; } this.smbData.FileName = new byte[0]; } #endregion } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using JetBrains.Annotations; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Targets; using NLog.Internal.Fakeables; #if SILVERLIGHT using System.Windows; #endif /// <summary> /// Creates and manages instances of <see cref="T:NLog.Logger" /> objects. /// </summary> public class LogFactory : IDisposable { #if !SILVERLIGHT private const int ReconfigAfterFileChangedTimeout = 1000; private static TimeSpan defaultFlushTimeout = TimeSpan.FromSeconds(15); private Timer reloadTimer; private readonly MultiFileWatcher watcher; #endif private static IAppDomain currentAppDomain; private readonly object syncRoot = new object(); private LoggingConfiguration config; private LogLevel globalThreshold = LogLevel.MinLevel; private bool configLoaded; // TODO: logsEnabled property might be possible to be encapsulated into LogFactory.LogsEnabler class. private int logsEnabled; private readonly LoggerCache loggerCache = new LoggerCache(); /// <summary> /// Occurs when logging <see cref="Configuration" /> changes. /// </summary> public event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged; #if !SILVERLIGHT /// <summary> /// Occurs when logging <see cref="Configuration" /> gets reloaded. /// </summary> public event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded; #endif /// <summary> /// Initializes a new instance of the <see cref="LogFactory" /> class. /// </summary> public LogFactory() { #if !SILVERLIGHT this.watcher = new MultiFileWatcher(); this.watcher.OnChange += this.ConfigFileChanged; #endif } /// <summary> /// Initializes a new instance of the <see cref="LogFactory" /> class. /// </summary> /// <param name="config">The config.</param> public LogFactory(LoggingConfiguration config) : this() { this.Configuration = config; } /// <summary> /// Gets the current <see cref="IAppDomain"/>. /// </summary> public static IAppDomain CurrentAppDomain { get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); } set { currentAppDomain = value; } } /// <summary> /// Gets or sets a value indicating whether exceptions should be thrown. /// </summary> /// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value> /// <remarks>By default exceptions are not thrown under any circumstances.</remarks> public bool ThrowExceptions { get; set; } /// <summary> /// Gets or sets the current logging configuration. /// </summary> public LoggingConfiguration Configuration { get { lock (this.syncRoot) { if (this.configLoaded) { return this.config; } this.configLoaded = true; #if !SILVERLIGHT if (this.config == null) { // Try to load default configuration. this.config = XmlLoggingConfiguration.AppConfig; } #endif // Retest the condition as we might have loaded a config. if (this.config == null) { foreach (string configFile in GetCandidateConfigFileNames()) { #if SILVERLIGHT Uri configFileUri = new Uri(configFile, UriKind.Relative); if (Application.GetResourceStream(configFileUri) != null) { LoadLoggingConfiguration(configFile); break; } #else if (File.Exists(configFile)) { LoadLoggingConfiguration(configFile); break; } #endif } } if (this.config != null) { #if !SILVERLIGHT config.Dump(); try { this.watcher.Watch(this.config.FileNamesToWatch); } catch (Exception exception) { InternalLogger.Warn("Cannot start file watching: {0}. File watching is disabled", exception); } #endif this.config.InitializeAll(); } return this.config; } } set { #if !SILVERLIGHT try { this.watcher.StopWatching(); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Cannot stop file watching: {0}", exception); } #endif lock (this.syncRoot) { LoggingConfiguration oldConfig = this.config; if (oldConfig != null) { InternalLogger.Info("Closing old configuration."); #if !SILVERLIGHT this.Flush(); #endif oldConfig.Close(); } this.config = value; this.configLoaded = true; if (this.config != null) { config.Dump(); this.config.InitializeAll(); this.ReconfigExistingLoggers(); #if !SILVERLIGHT try { this.watcher.Watch(this.config.FileNamesToWatch); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Warn("Cannot start file watching: {0}", exception); } #endif } this.OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(value, oldConfig)); } } } /// <summary> /// Gets or sets the global log threshold. Log events below this threshold are not logged. /// </summary> public LogLevel GlobalThreshold { get { return this.globalThreshold; } set { lock (this.syncRoot) { this.globalThreshold = value; this.ReconfigExistingLoggers(); } } } /// <summary> /// Gets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>. /// </summary> /// <value> /// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/> /// </value> [CanBeNull] public CultureInfo DefaultCultureInfo { get { var configuration = this.Configuration; return configuration != null ? configuration.DefaultCultureInfo : null; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting /// unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Creates a logger that discards all log messages. /// </summary> /// <returns>Null logger instance.</returns> public Logger CreateNullLogger() { TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1]; Logger newLogger = new Logger(); newLogger.Initialize(string.Empty, new LoggerConfiguration(targetsByLevel), this); return newLogger; } /// <summary> /// Gets the logger named after the currently-being-initialized class. /// </summary> /// <returns>The logger.</returns> /// <remarks>This is a slow-running method. /// Make sure you're not doing this in a loop.</remarks> [MethodImpl(MethodImplOptions.NoInlining)] public Logger GetCurrentClassLogger() { #if SILVERLIGHT var frame = new StackFrame(1); #else var frame = new StackFrame(1, false); #endif return this.GetLogger(frame.GetMethod().DeclaringType.FullName); } /// <summary> /// Gets the logger named after the currently-being-initialized class. /// </summary> /// <param name="loggerType">The type of the logger to create. The type must inherit from /// NLog.Logger.</param> /// <returns>The logger.</returns> /// <remarks>This is a slow-running method. Make sure you are not calling this method in a /// loop.</remarks> [MethodImpl(MethodImplOptions.NoInlining)] public Logger GetCurrentClassLogger(Type loggerType) { #if !SILVERLIGHT var frame = new StackFrame(1, false); #else var frame = new StackFrame(1); #endif return this.GetLogger(frame.GetMethod().DeclaringType.FullName, loggerType); } /// <summary> /// Gets the specified named logger. /// </summary> /// <param name="name">Name of the logger.</param> /// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument /// are not guaranteed to return the same logger reference.</returns> public Logger GetLogger(string name) { return this.GetLogger(new LoggerCacheKey(name, typeof(Logger))); } /// <summary> /// Gets the specified named logger. /// </summary> /// <param name="name">Name of the logger.</param> /// <param name="loggerType">The type of the logger to create. The type must inherit from NLog.Logger.</param> /// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the /// same argument aren't guaranteed to return the same logger reference.</returns> public Logger GetLogger(string name, Type loggerType) { return this.GetLogger(new LoggerCacheKey(name, loggerType)); } /// <summary> /// Loops through all loggers previously returned by GetLogger and recalculates their /// target and filter list. Useful after modifying the configuration programmatically /// to ensure that all loggers have been properly configured. /// </summary> public void ReconfigExistingLoggers() { if (this.config != null) { this.config.InitializeAll(); } foreach (var logger in loggerCache.Loggers) { logger.SetConfiguration(this.GetConfigurationForLogger(logger.Name, this.config)); } } #if !SILVERLIGHT /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> public void Flush() { this.Flush(defaultFlushTimeout); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time /// will be discarded.</param> public void Flush(TimeSpan timeout) { try { AsyncHelpers.RunSynchronously(cb => this.Flush(cb, timeout)); } catch (Exception e) { if (ThrowExceptions) { throw; } InternalLogger.Error(e.ToString()); } } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages /// after that time will be discarded.</param> public void Flush(int timeoutMilliseconds) { this.Flush(TimeSpan.FromMilliseconds(timeoutMilliseconds)); } #endif /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> public void Flush(AsyncContinuation asyncContinuation) { this.Flush(asyncContinuation, TimeSpan.MaxValue); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages /// after that time will be discarded.</param> public void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds) { this.Flush(asyncContinuation, TimeSpan.FromMilliseconds(timeoutMilliseconds)); } /// <summary> /// Flush any pending log messages (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param> public void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout) { try { InternalLogger.Trace("LogFactory.Flush({0})", timeout); var loggingConfiguration = this.Configuration; if (loggingConfiguration != null) { InternalLogger.Trace("Flushing all targets..."); loggingConfiguration.FlushAllTargets(AsyncHelpers.WithTimeout(asyncContinuation, timeout)); } else { asyncContinuation(null); } } catch (Exception e) { if (ThrowExceptions) { throw; } InternalLogger.Error(e.ToString()); } } /// <summary> /// Decreases the log enable counter and if it reaches -1 the logs are disabled. /// </summary> /// <remarks> /// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than /// or equal to <see cref="SuspendLogging"/> calls. /// </remarks> /// <returns>An object that implements IDisposable whose Dispose() method re-enables logging. /// To be used with C# <c>using ()</c> statement.</returns> [Obsolete("Use SuspendLogging() instead.")] public IDisposable DisableLogging() { return SuspendLogging(); } /// <summary> /// Increases the log enable counter and if it reaches 0 the logs are disabled. /// </summary> /// <remarks> /// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than /// or equal to <see cref="SuspendLogging"/> calls.</remarks> [Obsolete("Use ResumeLogging() instead.")] public void EnableLogging() { ResumeLogging(); } /// <summary> /// Decreases the log enable counter and if it reaches -1 the logs are disabled. /// </summary> /// <remarks> /// Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater than /// or equal to <see cref="SuspendLogging"/> calls. /// </remarks> /// <returns>An object that implements IDisposable whose Dispose() method re-enables logging. /// To be used with C# <c>using ()</c> statement.</returns> public IDisposable SuspendLogging() { lock (this.syncRoot) { this.logsEnabled--; if (this.logsEnabled == -1) { this.ReconfigExistingLoggers(); } } return new LogEnabler(this); } /// <summary> /// Increases the log enable counter and if it reaches 0 the logs are disabled. /// </summary> /// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater /// than or equal to <see cref="SuspendLogging"/> calls.</remarks> public void ResumeLogging() { lock (this.syncRoot) { this.logsEnabled++; if (this.logsEnabled == 0) { this.ReconfigExistingLoggers(); } } } /// <summary> /// Returns <see langword="true" /> if logging is currently enabled. /// </summary> /// <returns>A value of <see langword="true" /> if logging is currently enabled, /// <see langword="false"/> otherwise.</returns> /// <remarks>Logging is enabled if the number of <see cref="ResumeLogging"/> calls is greater /// than or equal to <see cref="SuspendLogging"/> calls.</remarks> public bool IsLoggingEnabled() { return this.logsEnabled >= 0; } /// <summary> /// Invoke the Changed event; called whenever list changes /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnConfigurationChanged(LoggingConfigurationChangedEventArgs e) { var changed = this.ConfigurationChanged; if (changed != null) { changed(this, e); } } #if !SILVERLIGHT internal void ReloadConfigOnTimer(object state) { LoggingConfiguration configurationToReload = (LoggingConfiguration)state; InternalLogger.Info("Reloading configuration..."); lock (this.syncRoot) { if (this.reloadTimer != null) { this.reloadTimer.Dispose(); this.reloadTimer = null; } this.watcher.StopWatching(); try { if (this.Configuration != configurationToReload) { throw new NLogConfigurationException("Config changed in between. Not reloading."); } LoggingConfiguration newConfig = configurationToReload.Reload(); //problem: XmlLoggingConfiguration.Initialize eats exception with invalid XML. ALso XmlLoggingConfiguration.Reload never returns null. //therefor we check the InitializeSucceeded property. var xmlConfig = newConfig as XmlLoggingConfiguration; if (xmlConfig != null) { if (!xmlConfig.InitializeSucceeded.HasValue || !xmlConfig.InitializeSucceeded.Value) { throw new NLogConfigurationException("Configuration.Reload() failed. Invalid XML?"); } } if (newConfig != null) { this.Configuration = newConfig; if (this.ConfigurationReloaded != null) { this.ConfigurationReloaded(this, new LoggingConfigurationReloadedEventArgs(true, null)); } } else { throw new NLogConfigurationException("Configuration.Reload() returned null. Not reloading."); } } catch (Exception exception) { if (exception is NLogConfigurationException) { InternalLogger.Warn(exception.Message); } else if (exception.MustBeRethrown()) { throw; } this.watcher.Watch(configurationToReload.FileNamesToWatch); var configurationReloadedDelegate = this.ConfigurationReloaded; if (configurationReloadedDelegate != null) { configurationReloadedDelegate(this, new LoggingConfigurationReloadedEventArgs(false, exception)); } } } } #endif private void GetTargetsByLevelForLogger(string name, IEnumerable<LoggingRule> rules, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels) { foreach (LoggingRule rule in rules) { if (!rule.NameMatches(name)) { continue; } for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i) { if (i < this.GlobalThreshold.Ordinal || suppressedLevels[i] || !rule.IsLoggingEnabledForLevel(LogLevel.FromOrdinal(i))) { continue; } if (rule.Final) suppressedLevels[i] = true; foreach (Target target in rule.Targets) { var awf = new TargetWithFilterChain(target, rule.Filters); if (lastTargetsByLevel[i] != null) { lastTargetsByLevel[i].NextInChain = awf; } else { targetsByLevel[i] = awf; } lastTargetsByLevel[i] = awf; } } // Recursively analyze the child rules. this.GetTargetsByLevelForLogger(name, rule.ChildRules, targetsByLevel, lastTargetsByLevel, suppressedLevels); } for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i) { TargetWithFilterChain tfc = targetsByLevel[i]; if (tfc != null) { tfc.PrecalculateStackTraceUsage(); } } } internal LoggerConfiguration GetConfigurationForLogger(string name, LoggingConfiguration configuration) { TargetWithFilterChain[] targetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1]; TargetWithFilterChain[] lastTargetsByLevel = new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 1]; bool[] suppressedLevels = new bool[LogLevel.MaxLevel.Ordinal + 1]; if (configuration != null && this.IsLoggingEnabled()) { this.GetTargetsByLevelForLogger(name, configuration.LoggingRules, targetsByLevel, lastTargetsByLevel, suppressedLevels); } InternalLogger.Debug("Targets for {0} by level:", name); for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; ++i) { StringBuilder sb = new StringBuilder(); sb.AppendFormat(CultureInfo.InvariantCulture, "{0} =>", LogLevel.FromOrdinal(i)); for (TargetWithFilterChain afc = targetsByLevel[i]; afc != null; afc = afc.NextInChain) { sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", afc.Target.Name); if (afc.FilterChain.Count > 0) { sb.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", afc.FilterChain.Count); } } InternalLogger.Debug(sb.ToString()); } return new LoggerConfiguration(targetsByLevel); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>True</c> to release both managed and unmanaged resources; /// <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { #if !SILVERLIGHT if (disposing) { this.watcher.Dispose(); if (this.reloadTimer != null) { this.reloadTimer.Dispose(); this.reloadTimer = null; } } #endif } private static IEnumerable<string> GetCandidateConfigFileNames() { #if SILVERLIGHT yield return "NLog.config"; #else // NLog.config from application directory if (CurrentAppDomain.BaseDirectory != null) { yield return Path.Combine(CurrentAppDomain.BaseDirectory, "NLog.config"); } // Current config file with .config renamed to .nlog string cf = CurrentAppDomain.ConfigurationFile; if (cf != null) { yield return Path.ChangeExtension(cf, ".nlog"); // .nlog file based on the non-vshost version of the current config file const string vshostSubStr = ".vshost."; if (cf.Contains(vshostSubStr)) { yield return Path.ChangeExtension(cf.Replace(vshostSubStr, "."), ".nlog"); } IEnumerable<string> privateBinPaths = CurrentAppDomain.PrivateBinPath; if (privateBinPaths != null) { foreach (var path in privateBinPaths) { if (path != null) { yield return Path.Combine(path, "NLog.config"); } } } } // Get path to NLog.dll.nlog only if the assembly is not in the GAC var nlogAssembly = typeof(LogFactory).Assembly; if (!nlogAssembly.GlobalAssemblyCache) { if (!string.IsNullOrEmpty(nlogAssembly.Location)) { yield return nlogAssembly.Location + ".nlog"; } } #endif } private Logger GetLogger(LoggerCacheKey cacheKey) { lock (this.syncRoot) { Logger existingLogger = loggerCache.Retrieve(cacheKey); if (existingLogger != null) { // Logger is still in cache and referenced. return existingLogger; } Logger newLogger; if (cacheKey.ConcreteType != null && cacheKey.ConcreteType != typeof(Logger)) { try { newLogger = (Logger)FactoryHelper.CreateInstance(cacheKey.ConcreteType); } catch(Exception ex) { if(ex.MustBeRethrown() || ThrowExceptions) { throw; } InternalLogger.Error("Cannot create instance of specified type. Proceeding with default type instance. Exception : {0}", ex); // Creating default instance of logger if instance of specified type cannot be created. cacheKey = new LoggerCacheKey(cacheKey.Name, typeof(Logger)); newLogger = new Logger(); } } else { newLogger = new Logger(); } if (cacheKey.ConcreteType != null) { newLogger.Initialize(cacheKey.Name, this.GetConfigurationForLogger(cacheKey.Name, this.Configuration), this); } // TODO: Clarify what is the intention when cacheKey.ConcreteType = null. // At the moment, a logger typeof(Logger) will be created but the ConcreteType // will remain null and inserted into the cache. // Should we set cacheKey.ConcreteType = typeof(Logger) for default loggers? loggerCache.InsertOrUpdate(cacheKey, newLogger); return newLogger; } } #if !SILVERLIGHT private void ConfigFileChanged(object sender, EventArgs args) { InternalLogger.Info("Configuration file change detected! Reloading in {0}ms...", LogFactory.ReconfigAfterFileChangedTimeout); // In the rare cases we may get multiple notifications here, // but we need to reload config only once. // // The trick is to schedule the reload in one second after // the last change notification comes in. lock (this.syncRoot) { if (this.reloadTimer == null) { this.reloadTimer = new Timer( this.ReloadConfigOnTimer, this.Configuration, LogFactory.ReconfigAfterFileChangedTimeout, Timeout.Infinite); } else { this.reloadTimer.Change( LogFactory.ReconfigAfterFileChangedTimeout, Timeout.Infinite); } } } #endif private void LoadLoggingConfiguration(string configFile) { InternalLogger.Debug("Loading config from {0}", configFile); this.config = new XmlLoggingConfiguration(configFile); } /// <summary> /// Logger cache key. /// </summary> internal class LoggerCacheKey : IEquatable<LoggerCacheKey> { public string Name { get; private set; } public Type ConcreteType { get; private set; } public LoggerCacheKey(string name, Type concreteType) { this.Name = name; this.ConcreteType = concreteType; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return this.ConcreteType.GetHashCode() ^ this.Name.GetHashCode(); } /// <summary> /// Determines if two objects are equal in value. /// </summary> /// <param name="obj">Other object to compare to.</param> /// <returns>True if objects are equal, false otherwise.</returns> public override bool Equals(object obj) { LoggerCacheKey key = obj as LoggerCacheKey; if (ReferenceEquals(key, null)) { return false; } return (this.ConcreteType == key.ConcreteType) && (key.Name == this.Name); } /// <summary> /// Determines if two objects of the same type are equal in value. /// </summary> /// <param name="key">Other object to compare to.</param> /// <returns>True if objects are equal, false otherwise.</returns> public bool Equals(LoggerCacheKey key) { if (ReferenceEquals(key, null)) { return false; } return (this.ConcreteType == key.ConcreteType) && (key.Name == this.Name); } } /// <summary> /// Logger cache. /// </summary> private class LoggerCache { // The values of WeakReferences are of type Logger i.e. Directory<LoggerCacheKey, Logger>. private readonly Dictionary<LoggerCacheKey, WeakReference> loggerCache = new Dictionary<LoggerCacheKey, WeakReference>(); /// <summary> /// Inserts or updates. /// </summary> /// <param name="cacheKey"></param> /// <param name="logger"></param> public void InsertOrUpdate(LoggerCacheKey cacheKey, Logger logger) { loggerCache[cacheKey] = new WeakReference(logger); } public Logger Retrieve(LoggerCacheKey cacheKey) { WeakReference loggerReference; if (loggerCache.TryGetValue(cacheKey, out loggerReference)) { // logger in the cache and still referenced return loggerReference.Target as Logger; } return null; } public IEnumerable<Logger> Loggers { get { return GetLoggers(); } } private IEnumerable<Logger> GetLoggers() { // TODO: Test if loggerCache.Values.ToList<Logger>() can be used for the conversion instead. List<Logger> values = new List<Logger>(loggerCache.Count); foreach (WeakReference loggerReference in loggerCache.Values) { Logger logger = loggerReference.Target as Logger; if (logger != null) { values.Add(logger); } } return values; } } /// <summary> /// Enables logging in <see cref="IDisposable.Dispose"/> implementation. /// </summary> private class LogEnabler : IDisposable { private LogFactory factory; /// <summary> /// Initializes a new instance of the <see cref="LogEnabler" /> class. /// </summary> /// <param name="factory">The factory.</param> public LogEnabler(LogFactory factory) { this.factory = factory; } /// <summary> /// Enables logging. /// </summary> void IDisposable.Dispose() { this.factory.ResumeLogging(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using hw.DebugFormatter; using hw.Helper; using JetBrains.Annotations; namespace hw.Debug { /// <summary> /// Summary description for Dumpable. /// </summary> [Dump("Dump")] [DebuggerDisplay("{DebuggerDumpString}")] public class Dumpable { static readonly Stack<MethodDumpTraceItem> _methodDumpTraceSwitches = new Stack<MethodDumpTraceItem>(); /// <summary> /// generate dump string to be shown in debug windows /// </summary> /// <returns> </returns> public virtual string DebuggerDump() { return Tracer.Dump(this); } /// <summary> /// dump string to be shown in debug windows /// </summary> [DisableDump] [UsedImplicitly] public string DebuggerDumpString { get { return DebuggerDump().Replace("\n", "\r\n"); } } [DisableDump] [UsedImplicitly] public string D => DebuggerDumpString; public void T() => Tracer.Line(DebuggerDumpString); /// <summary> /// Method dump with break, /// </summary> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] public static void NotImplementedFunction(params object[] p) { var os = Tracer.DumpMethodWithData("not implemented", null, p, 1); Tracer.Line(os); Tracer.TraceBreak(); } /// <summary> /// Method start dump, /// </summary> /// <param name="trace"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected void StartMethodDump(bool trace, params object[] p) { StartMethodDump(1, trace); if(IsMethodDumpTraceActive) { var os = Tracer.DumpMethodWithData("", this, p, 1); Tracer.Line(os); Tracer.IndentStart(); } } /// <summary> /// Method start dump, /// </summary> /// <param name="name"> </param> /// <param name="value"> </param> /// <returns> </returns> [DebuggerHidden] public static void Dump(string name, object value) { if(IsMethodDumpTraceActive) { var os = Tracer.DumpData("", new[] {name, value}, 1); Tracer.Line(os); } } /// <summary> /// Method dump, /// </summary> /// <param name="rv"> </param> /// <param name="breakExecution"> </param> /// <returns> </returns> [DebuggerHidden] protected static T ReturnMethodDump<T>(T rv, bool breakExecution = true) { if(IsMethodDumpTraceActive) { Tracer.IndentEnd(); Tracer.Line(Tracer.MethodHeader(stackFrameDepth: 1) + "[returns] " + Tracer.Dump(rv)); if(breakExecution) Tracer.TraceBreak(); } return rv; } /// <summary> /// Method dump, /// </summary> [DebuggerHidden] protected static void ReturnVoidMethodDump(bool breakExecution = true) { if(IsMethodDumpTraceActive) { Tracer.IndentEnd(); Tracer.Line(Tracer.MethodHeader(stackFrameDepth: 1) + "[returns]"); if(breakExecution) Tracer.TraceBreak(); } } [DebuggerHidden] protected void BreakExecution() { if(IsMethodDumpTraceActive) Tracer.TraceBreak(); } /// <summary> /// Method dump, /// </summary> [DebuggerHidden] protected static void EndMethodDump() { if(!Debugger.IsAttached) return; CheckDumpLevel(1); _methodDumpTraceSwitches.Pop(); } static void CheckDumpLevel(int depth) { if(!Debugger.IsAttached) return; var top = _methodDumpTraceSwitches.Peek(); Tracer.Assert(top.FrameCount == Tracer.CurrentFrameCount(depth + 1)); } /// <summary> /// Method dump with break, /// </summary> /// <param name="text"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected void DumpMethodWithBreak(string text, params object[] p) { var os = Tracer.DumpMethodWithData(text, this, p, 1); Tracer.Line(os); Tracer.TraceBreak(); } /// <summary> /// Method dump with break, /// </summary> /// <param name="text"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected static void DumpDataWithBreak(string text, params object[] p) { var os = Tracer.DumpData(text, p, 1); Tracer.Line(os); Tracer.TraceBreak(); } /// <summary> /// Method dump with break, /// </summary> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected void NotImplementedMethod(params object[] p) { if(IsInDump) throw new NotImplementedException(); var os = Tracer.DumpMethodWithData("not implemented", this, p, 1); Tracer.Line(os); Tracer.TraceBreak(); } public string Dump() { var oldIsInDump = _isInDump; _isInDump = true; try { return Dump(oldIsInDump); } finally { _isInDump = oldIsInDump; } } protected virtual string Dump(bool isRecursion) { var surround = "<recursion>"; if(!isRecursion) surround = DumpData().Surround("{", "}"); return GetType().PrettyName() + surround; } /// <summary> /// Gets a value indicating whether this instance is in dump. /// </summary> /// <value> /// <c>true</c> /// if this instance is in dump; otherwise, /// <c>false</c> /// . /// </value> /// created 23.09.2006 17:39 [DisableDump] public bool IsInDump { get { return _isInDump; } } bool _isInDump; public static bool? IsMethodDumpTraceInhibited; public virtual string DumpData() { string result; try { result = Tracer.DumpData(this); } catch(Exception) { result = "<not implemented>"; } return result; } public void Dispose() { } static void StartMethodDump(int depth, bool trace) { if(!Debugger.IsAttached) return; var frameCount = Tracer.CurrentFrameCount(depth + 1); _methodDumpTraceSwitches.Push(new MethodDumpTraceItem(frameCount, trace)); } sealed class MethodDumpTraceItem { readonly int _frameCount; readonly bool _trace; public MethodDumpTraceItem(int frameCount, bool trace) { _frameCount = frameCount; _trace = trace; } internal int FrameCount { get { return _frameCount; } } internal bool Trace { get { return _trace; } } } static bool IsMethodDumpTraceActive { get { if(IsMethodDumpTraceInhibited != null) return !IsMethodDumpTraceInhibited.Value; if(!Debugger.IsAttached) return false; //CheckDumpLevel(2); return _methodDumpTraceSwitches.Peek().Trace; } } } }
using System; using System.Messaging; using System.Threading; using System.Transactions; using log4net; using Rhino.ServiceBus.DataStructures; using Rhino.ServiceBus.Exceptions; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.Messages; using Rhino.ServiceBus.Msmq; using Rhino.ServiceBus.Transport; using MessageType = Rhino.ServiceBus.Transport.MessageType; using System.Linq; namespace Rhino.ServiceBus.LoadBalancer { public class MsmqLoadBalancer : AbstractMsmqListener { private readonly Uri secondaryLoadBalancer; private readonly IQueueStrategy queueStrategy; private readonly ILog logger = LogManager.GetLogger(typeof(MsmqLoadBalancer)); private readonly Queue<Uri> readyForWork = new Queue<Uri>(); private readonly Set<Uri> knownWorkers = new Set<Uri>(); private readonly Timer heartBeatTimer; private readonly Set<Uri> knownEndpoints = new Set<Uri>(); private MsmqReadyForWorkListener _readyForWorkListener; public event Action<Message> MessageBatchSentToAllWorkers; public event Action SentNewWorkerPersisted; public event Action SentNewEndpointPersisted; public MsmqLoadBalancer( IMessageSerializer serializer, IQueueStrategy queueStrategy, IEndpointRouter endpointRouter, Uri endpoint, int threadCount, TransactionalOptions transactional, IMessageBuilder<Message> messageBuilder) : base(queueStrategy, endpoint, threadCount, serializer, endpointRouter, transactional, messageBuilder) { heartBeatTimer = new Timer(SendHeartBeatToSecondaryServer); this.queueStrategy = queueStrategy; } public MsmqLoadBalancer( IMessageSerializer serializer, IQueueStrategy queueStrategy, IEndpointRouter endpointRouter, Uri endpoint, int threadCount, Uri secondaryLoadBalancer, TransactionalOptions transactional, IMessageBuilder<Message> messageBuilder) : this(serializer, queueStrategy, endpointRouter, endpoint, threadCount, transactional, messageBuilder) { this.secondaryLoadBalancer = secondaryLoadBalancer; } protected void SendHeartBeatToSecondaryServer(object ignored) { SendToQueue(secondaryLoadBalancer, new Heartbeat { From = Endpoint.Uri, At = DateTime.Now, }); } public Set<Uri> KnownWorkers { get { return knownWorkers; } } public Set<Uri> KnownEndpoints { get { return knownEndpoints; } } public int NumberOfWorkersReadyToHandleMessages { get { return readyForWork.TotalCount; } } protected override void BeforeStart(OpenedQueue queue) { try { queueStrategy.InitializeQueue(Endpoint, QueueType.LoadBalancer); } catch (Exception e) { throw new TransportException( "Could not open queue for load balancer: " + Endpoint + Environment.NewLine + "Queue path: " + MsmqUtil.GetQueuePath(Endpoint), e); } try { ReadUrisFromSubQueue(KnownWorkers, SubQueue.Workers); } catch (Exception e) { throw new InvalidOperationException("Could not read workers subqueue", e); } try { ReadUrisFromSubQueue(KnownEndpoints, SubQueue.Endpoints); } catch (Exception e) { throw new InvalidOperationException("Could not read endpoints subqueue", e); } RemoveAllReadyToWorkMessages(); } private void ReadUrisFromSubQueue(Set<Uri> set, SubQueue subQueue) { using (var q = MsmqUtil.GetQueuePath(Endpoint).Open(QueueAccessMode.Receive)) using (var sq = q.OpenSubQueue(subQueue, QueueAccessMode.SendAndReceive)) { var messages = sq.GetAllMessagesWithStringFormatter(); foreach (var message in messages) { var uriString = message.Body.ToString(); set.Add(new Uri(uriString)); } } } private void RemoveAllReadyToWorkMessages() { using (var tx = new TransactionScope()) using (var readyForWorkQueue = MsmqUtil.GetQueuePath(Endpoint).Open(QueueAccessMode.SendAndReceive)) using (var enumerator = readyForWorkQueue.GetMessageEnumerator2()) { try { while (enumerator.MoveNext()) { while ( enumerator.Current != null && enumerator.Current.Label == typeof(ReadyToWork).FullName) { var current = enumerator.RemoveCurrent(readyForWorkQueue.GetTransactionType()); HandleLoadBalancerMessage(readyForWorkQueue, current); } } } catch (MessageQueueException e) { if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout) throw; } readyForWork.Clear(); tx.Complete(); } } protected override void AfterStart(OpenedQueue queue) { if (_readyForWorkListener != null) { _readyForWorkListener.ReadyToWorkMessageArrived += readyForWorkMessage => HandleReadyForWork(queue, readyForWorkMessage); _readyForWorkListener.Start(); } if (secondaryLoadBalancer != null) { foreach (var queueUri in KnownEndpoints.GetValues()) { logger.InfoFormat("Notifying {0} that primary load balancer {1} is taking over from secondary", queueUri, Endpoint.Uri ); SendToQueue(queueUri, new Reroute { NewEndPoint = Endpoint.Uri, OriginalEndPoint = Endpoint.Uri }); } SendHeartBeatToSecondaryServer(null); heartBeatTimer.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); Reroute reroute; if (_readyForWorkListener != null) reroute = new Reroute { NewEndPoint = _readyForWorkListener.Endpoint.Uri, OriginalEndPoint = _readyForWorkListener.Endpoint.Uri }; else reroute = new Reroute { NewEndPoint = Endpoint.Uri, OriginalEndPoint = Endpoint.Uri }; SendToAllWorkers( GenerateMsmqMessageFromMessageBatch(reroute), "Rerouting {1} back to {0}" ); } if (ShouldNotifyWorkersLoaderIsReadyToAcceptWorkOnStartup) NotifyWorkersThatLoaderIsReadyToAcceptWork(); } protected virtual bool ShouldNotifyWorkersLoaderIsReadyToAcceptWorkOnStartup { get { return true; } } public MsmqReadyForWorkListener ReadyForWorkListener { get { return _readyForWorkListener; } set { _readyForWorkListener = value; } } protected void NotifyWorkersThatLoaderIsReadyToAcceptWork() { var acceptingWork = new AcceptingWork { Endpoint = Endpoint.Uri }; SendToAllWorkers( GenerateMsmqMessageFromMessageBatch(acceptingWork), "Notifing {1} that {0} is accepting work" ); } protected override void OnStop() { if(_readyForWorkListener !=null) _readyForWorkListener.Dispose(); heartBeatTimer.Dispose(); } protected override void HandlePeekedMessage(OpenedQueue queue, Message message) { try { using (var tx = new TransactionScope(TransactionScopeOption.Required, TransportUtil.GetTransactionTimeout())) { message = queue.TryGetMessageFromQueue(message.Id); if (message == null) return; PersistEndpoint(queue, message); switch ((MessageType)message.AppSpecific) { case MessageType.ShutDownMessageMarker: //silently cnsume the message break; case MessageType.LoadBalancerMessageMarker: HandleLoadBalancerMessage(queue, message); break; case MessageType.AdministrativeMessageMarker: SendToAllWorkers(message, "Dispatching administrative message from {0} to load balancer {1}"); break; default: HandleStandardMessage(queue, message); break; } tx.Complete(); } } catch (Exception e) { logger.Error("Fail to process load balanced message properly", e); } } private void PersistEndpoint(OpenedQueue queue, Message message) { var queueUri = MsmqUtil.GetQueueUri(message.ResponseQueue); if (queueUri == null) return; bool needToPersist = knownEndpoints.Add(queueUri); if (needToPersist == false) return; logger.InfoFormat("Adding new endpoint: {0}", queueUri); var persistedEndPoint = new Message { Formatter = new XmlMessageFormatter(new[] { typeof(string) }), Body = queueUri.ToString(), Label = ("Known end point: " + queueUri).EnsureLabelLength() }; queue.Send(persistedEndPoint.SetSubQueueToSendTo(SubQueue.Endpoints)); SendToQueue(secondaryLoadBalancer, new NewEndpointPersisted { PersistedEndpoint = queueUri }); Raise(SentNewEndpointPersisted); } protected void SendToQueue(Uri queueUri, params object[] msgs) { if (queueUri == null) return; try { var queueInfo = MsmqUtil.GetQueuePath(new Endpoint { Uri = queueUri }); using (var secondaryLoadBalancerQueue = queueInfo.Open(QueueAccessMode.Send)) { secondaryLoadBalancerQueue.Send(GenerateMsmqMessageFromMessageBatch(msgs)); } } catch (Exception e) { throw new LoadBalancerException("Could not send message to queue: " + queueUri, e); } } private void HandleStandardMessage(OpenedQueue queue, Message message) { var worker = readyForWork.Dequeue(); if (worker == null) // handle message later { queue.Send(message); } else { var workerEndpoint = endpointRouter.GetRoutedEndpoint(worker); using (var workerQueue = MsmqUtil.GetQueuePath(workerEndpoint).Open(QueueAccessMode.Send)) { logger.DebugFormat("Dispatching message '{0}' to {1}", message.Id, workerEndpoint.Uri); workerQueue.Send(message); } } } private void SendToAllWorkers(Message message, string logMessage) { var values = KnownWorkers.GetValues(); foreach (var worker in values) { var workerEndpoint = endpointRouter.GetRoutedEndpoint(worker); using (var workerQueue = MsmqUtil.GetQueuePath(workerEndpoint).Open(QueueAccessMode.Send)) { logger.DebugFormat(logMessage, Endpoint.Uri, worker); workerQueue.Send(message); } } if (values.Length == 0) return; var copy = MessageBatchSentToAllWorkers; if (copy != null) copy(message); } private void HandleLoadBalancerMessage(OpenedQueue queue, Message message) { foreach (var msg in DeserializeMessages(queue, message, null)) { var query = msg as QueryForAllKnownWorkersAndEndpoints; if (query != null) { SendKnownWorkersAndKnownEndpoints(message.ResponseQueue); continue; } var queryReadyForWorkQueueUri = msg as QueryReadyForWorkQueueUri; if (queryReadyForWorkQueueUri != null) { SendReadyForWorkQueueUri(message.ResponseQueue); continue; } var work = msg as ReadyToWork; if (work != null) { HandleReadyForWork(queue, work); } HandleLoadBalancerMessages(msg); } } private void HandleReadyForWork(OpenedQueue queue, ReadyToWork work) { logger.DebugFormat("{0} is ready to work", work.Endpoint); var needToAddToQueue = KnownWorkers.Add(work.Endpoint); if (needToAddToQueue) AddWorkerToQueue(queue, work); readyForWork.Enqueue(work.Endpoint); } private void SendReadyForWorkQueueUri(MessageQueue responseQueue) { if (responseQueue == null) return; try { var transactionType = MessageQueueTransactionType.None; if (Endpoint.Transactional.GetValueOrDefault()) transactionType = Transaction.Current == null ? MessageQueueTransactionType.Single : MessageQueueTransactionType.Automatic; var newEndpoint = ReadyForWorkListener != null ? ReadyForWorkListener.Endpoint.Uri : Endpoint.Uri; var message = new ReadyForWorkQueueUri {Endpoint = newEndpoint}; responseQueue.Send(GenerateMsmqMessageFromMessageBatch(message), transactionType); } catch (Exception e) { logger.Error("Failed to send known ready for work queue uri", e); } } private void SendKnownWorkersAndKnownEndpoints(MessageQueue responseQueue) { if (responseQueue == null) return; try { var endpoints = KnownEndpoints.GetValues(); var workers = KnownWorkers.GetValues(); var transactionType = MessageQueueTransactionType.None; if (Endpoint.Transactional.GetValueOrDefault()) transactionType = Transaction.Current == null ? MessageQueueTransactionType.Single : MessageQueueTransactionType.Automatic; var index = 0; while (index < endpoints.Length) { var endpointsBatch = endpoints .Skip(index) .Take(256) .Select(x => new NewEndpointPersisted { PersistedEndpoint = x }) .ToArray(); index += endpointsBatch.Length; responseQueue.Send(GenerateMsmqMessageFromMessageBatch(endpointsBatch), transactionType); } index = 0; while (index < workers.Length) { var workersBatch = workers .Skip(index) .Take(256) .Select(x => new NewWorkerPersisted { Endpoint = x }) .ToArray(); index += workersBatch.Length; responseQueue.Send(GenerateMsmqMessageFromMessageBatch(workersBatch), transactionType); } } catch (Exception e) { logger.Error("Failed to send known endpoints and known workers", e); } } protected virtual void HandleLoadBalancerMessages(object msg) { } private void AddWorkerToQueue(OpenedQueue queue, ReadyToWork work) { var persistedWorker = new Message { Formatter = new XmlMessageFormatter(new[] { typeof(string) }), Body = work.Endpoint.ToString(), Label = ("Known worker: " + work.Endpoint).EnsureLabelLength() }; logger.DebugFormat("New worker: {0}", work.Endpoint); queue.Send(persistedWorker.SetSubQueueToSendTo(SubQueue.Workers)); SendToQueue(secondaryLoadBalancer, new NewWorkerPersisted { Endpoint = work.Endpoint }); Raise(SentNewWorkerPersisted); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class GetKeysStringDictionaryTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; StringDictionary sd; // simple string values string[] values = { "", " ", "a", "aa", "tExt", " spAces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "one", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; Array arr; ICollection ks; // Keys collection int ind; // initialize IntStrings intl = new IntlStrings(); // [] StringDictionary is constructed as expected //----------------------------------------------------------------- sd = new StringDictionary(); // [] get Keys on empty dictionary // if (sd.Count > 0) sd.Clear(); if (sd.Keys.Count != 0) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", sd.Keys.Count)); } // // [] get Keys on filled dictionary // int len = values.Length; sd.Clear(); for (int i = 0; i < len; i++) { sd.Add(keys[i], values[i]); } if (sd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len)); } ks = sd.Keys; if (ks.Count != len) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count)); } arr = Array.CreateInstance(typeof(string), len); ks.CopyTo(arr, 0); for (int i = 0; i < len; i++) { ind = Array.IndexOf(arr, keys[i].ToLowerInvariant()); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key. Search result: {2}", i, keys[i], ind)); } } // // [] get Keys on dictionary with identical values // sd.Clear(); string intlStr = intl.GetRandomString(MAX_LEN); sd.Add("keykey1", intlStr); // 1st duplicate for (int i = 0; i < len; i++) { sd.Add(keys[i], values[i]); } sd.Add("keykey2", intlStr); // 2nd duplicate if (sd.Count != len + 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len + 2)); } // get Keys // ks = sd.Keys; if (ks.Count != sd.Count) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count)); } arr = Array.CreateInstance(typeof(string), len + 2); ks.CopyTo(arr, 0); for (int i = 0; i < len; i++) { ind = Array.IndexOf(arr, keys[i].ToLowerInvariant()); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key", i, keys[i])); } } ind = Array.IndexOf(arr, "keykey1"); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain {0} key", "keykey1")); } ind = Array.IndexOf(arr, "keykey2"); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain \"{0}\" key", "keykey2")); } // // Intl strings // [] get Keys on dictionary filled with Intl strings // string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } // // will use first half of array as values and second half as keys // sd.Clear(); for (int i = 0; i < len; i++) { sd.Add(intlValues[i + len], intlValues[i]); } if (sd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len)); } ks = sd.Keys; if (ks.Count != len) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count)); } arr = Array.CreateInstance(typeof(string), len); ks.CopyTo(arr, 0); for (int i = 0; i < arr.Length; i++) { ind = Array.IndexOf(arr, intlValues[i + len].ToLowerInvariant()); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain \"{1}\" key", i, intlValues[i + len])); } } // // Case sensitivity: keys are always lowercased - not doing it // [] Change dictionary and check Keys // sd.Clear(); for (int i = 0; i < len; i++) { sd.Add(keys[i], values[i]); } if (sd.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len)); } ks = sd.Keys; if (ks.Count != len) { Assert.False(true, string.Format("Error, returned Keys.Count = {0}", ks.Count)); } sd.Remove(keys[0]); if (sd.Count != len - 1) { Assert.False(true, string.Format("Error, didn't remove element")); } if (ks.Count != len - 1) { Assert.False(true, string.Format("Error, Keys were not updated after removal")); } arr = Array.CreateInstance(typeof(string), sd.Count); ks.CopyTo(arr, 0); ind = Array.IndexOf(arr, keys[0].ToLowerInvariant()); if (ind >= 0) { Assert.False(true, string.Format("Error, Keys still contains removed key " + ind)); } sd.Add(keys[0], "new item"); if (sd.Count != len) { Assert.False(true, string.Format("Error, didn't add element")); } if (ks.Count != len) { Assert.False(true, string.Format("Error, Keys were not updated after addition")); } arr = Array.CreateInstance(typeof(string), sd.Count); ks.CopyTo(arr, 0); ind = Array.IndexOf(arr, keys[0].ToLowerInvariant()); if (ind < 0) { Assert.False(true, string.Format("Error, Keys doesn't contain added key ")); } } } }
using Lucene.Net.Analysis.Tokenattributes; using System; namespace Lucene.Net.Util { using System.Diagnostics; // javadoc /* * 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. */ /// <summary> /// Provides support for converting byte sequences to Strings and back again. /// The resulting Strings preserve the original byte sequences' sort order. /// <p/> /// The Strings are constructed using a Base 8000h encoding of the original /// binary data - each char of an encoded String represents a 15-bit chunk /// from the byte sequence. Base 8000h was chosen because it allows for all /// lower 15 bits of char to be used without restriction; the surrogate range /// [U+D8000-U+DFFF] does not represent valid chars, and would require /// complicated handling to avoid them and allow use of char's high bit. /// <p/> /// Although unset bits are used as padding in the final char, the original /// byte sequence could contain trailing bytes with no set bits (null bytes): /// padding is indistinguishable from valid information. To overcome this /// problem, a char is appended, indicating the number of encoded bytes in the /// final content char. /// <p/> /// /// @lucene.experimental </summary> /// @deprecated Implement <seealso cref="ITermToBytesRefAttribute"/> and store bytes directly /// instead. this class will be removed in Lucene 5.0 [Obsolete("Implement <seealso cref=TermToBytesRefAttribute/> and store bytes directly")] public sealed class IndexableBinaryStringTools { private static readonly CodingCase[] CODING_CASES = new CodingCase[] { new CodingCase(7, 1), new CodingCase(14, 6, 2), new CodingCase(13, 5, 3), new CodingCase(12, 4, 4), new CodingCase(11, 3, 5), new CodingCase(10, 2, 6), new CodingCase(9, 1, 7), new CodingCase(8, 0) }; // Export only static methods private IndexableBinaryStringTools() { } /// <summary> /// Returns the number of chars required to encode the given bytes. /// </summary> /// <param name="inputArray"> byte sequence to be encoded </param> /// <param name="inputOffset"> initial offset into inputArray </param> /// <param name="inputLength"> number of bytes in inputArray </param> /// <returns> The number of chars required to encode the number of bytes. </returns> public static int GetEncodedLength(sbyte[] inputArray, int inputOffset, int inputLength) { // Use long for intermediaries to protect against overflow return (int)((8L * inputLength + 14L) / 15L) + 1; } /// <summary> /// Returns the number of bytes required to decode the given char sequence. /// </summary> /// <param name="encoded"> char sequence to be decoded </param> /// <param name="offset"> initial offset </param> /// <param name="length"> number of characters </param> /// <returns> The number of bytes required to decode the given char sequence </returns> public static int GetDecodedLength(char[] encoded, int offset, int length) { int numChars = length - 1; if (numChars <= 0) { return 0; } else { // Use long for intermediaries to protect against overflow long numFullBytesInFinalChar = encoded[offset + length - 1]; long numEncodedChars = numChars - 1; return (int)((numEncodedChars * 15L + 7L) / 8L + numFullBytesInFinalChar); } } /// <summary> /// Encodes the input byte sequence into the output char sequence. Before /// calling this method, ensure that the output array has sufficient /// capacity by calling <seealso cref="#getEncodedLength(byte[], int, int)"/>. /// </summary> /// <param name="inputArray"> byte sequence to be encoded </param> /// <param name="inputOffset"> initial offset into inputArray </param> /// <param name="inputLength"> number of bytes in inputArray </param> /// <param name="outputArray"> char sequence to store encoded result </param> /// <param name="outputOffset"> initial offset into outputArray </param> /// <param name="outputLength"> length of output, must be getEncodedLength </param> public static void Encode(sbyte[] inputArray, int inputOffset, int inputLength, char[] outputArray, int outputOffset, int outputLength) { Debug.Assert(outputLength == GetEncodedLength(inputArray, inputOffset, inputLength)); if (inputLength > 0) { int inputByteNum = inputOffset; int caseNum = 0; int outputCharNum = outputOffset; CodingCase codingCase; for (; inputByteNum + CODING_CASES[caseNum].NumBytes <= inputLength; ++outputCharNum) { codingCase = CODING_CASES[caseNum]; if (2 == codingCase.NumBytes) { outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.InitialShift) + (((int)((uint)(inputArray[inputByteNum + 1] & 0xFF) >> codingCase.FinalShift)) & codingCase.FinalMask) & (short)0x7FFF); } // numBytes is 3 else { outputArray[outputCharNum] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.InitialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.MiddleShift) + (((int)((uint)(inputArray[inputByteNum + 2] & 0xFF) >> codingCase.FinalShift)) & codingCase.FinalMask) & (short)0x7FFF); } inputByteNum += codingCase.AdvanceBytes; if (++caseNum == CODING_CASES.Length) { caseNum = 0; } } // Produce final char (if any) and trailing count chars. codingCase = CODING_CASES[caseNum]; if (inputByteNum + 1 < inputLength) // codingCase.numBytes must be 3 { outputArray[outputCharNum++] = (char)((((inputArray[inputByteNum] & 0xFF) << codingCase.InitialShift) + ((inputArray[inputByteNum + 1] & 0xFF) << codingCase.MiddleShift)) & (short)0x7FFF); // Add trailing char containing the number of full bytes in final char outputArray[outputCharNum++] = (char)1; } else if (inputByteNum < inputLength) { outputArray[outputCharNum++] = (char)(((inputArray[inputByteNum] & 0xFF) << codingCase.InitialShift) & (short)0x7FFF); // Add trailing char containing the number of full bytes in final char outputArray[outputCharNum++] = caseNum == 0 ? (char)1 : (char)0; } // No left over bits - last char is completely filled. else { // Add trailing char containing the number of full bytes in final char outputArray[outputCharNum++] = (char)1; } } } /// <summary> /// Decodes the input char sequence into the output byte sequence. Before /// calling this method, ensure that the output array has sufficient capacity /// by calling <seealso cref="#getDecodedLength(char[], int, int)"/>. /// </summary> /// <param name="inputArray"> char sequence to be decoded </param> /// <param name="inputOffset"> initial offset into inputArray </param> /// <param name="inputLength"> number of chars in inputArray </param> /// <param name="outputArray"> byte sequence to store encoded result </param> /// <param name="outputOffset"> initial offset into outputArray </param> /// <param name="outputLength"> length of output, must be /// getDecodedLength(inputArray, inputOffset, inputLength) </param> public static void Decode(char[] inputArray, int inputOffset, int inputLength, sbyte[] outputArray, int outputOffset, int outputLength) { Debug.Assert(outputLength == GetDecodedLength(inputArray, inputOffset, inputLength)); int numInputChars = inputLength - 1; int numOutputBytes = outputLength; if (numOutputBytes > 0) { int caseNum = 0; int outputByteNum = outputOffset; int inputCharNum = inputOffset; short inputChar; CodingCase codingCase; for (; inputCharNum < numInputChars - 1; ++inputCharNum) { codingCase = CODING_CASES[caseNum]; inputChar = (short)inputArray[inputCharNum]; if (2 == codingCase.NumBytes) { if (0 == caseNum) { outputArray[outputByteNum] = (sbyte)((short)((ushort)inputChar >> codingCase.InitialShift)); } else { outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.InitialShift)); } outputArray[outputByteNum + 1] = (sbyte)((inputChar & codingCase.FinalMask) << codingCase.FinalShift); } // numBytes is 3 else { outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.InitialShift)); outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.MiddleMask) >> codingCase.MiddleShift)); outputArray[outputByteNum + 2] = (sbyte)((inputChar & codingCase.FinalMask) << codingCase.FinalShift); } outputByteNum += codingCase.AdvanceBytes; if (++caseNum == CODING_CASES.Length) { caseNum = 0; } } // Handle final char inputChar = (short)inputArray[inputCharNum]; codingCase = CODING_CASES[caseNum]; if (0 == caseNum) { outputArray[outputByteNum] = 0; } outputArray[outputByteNum] += (sbyte)((short)((ushort)inputChar >> codingCase.InitialShift)); int bytesLeft = numOutputBytes - outputByteNum; if (bytesLeft > 1) { if (2 == codingCase.NumBytes) { outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.FinalMask) >> codingCase.FinalShift)); } // numBytes is 3 else { outputArray[outputByteNum + 1] = (sbyte)((int)((uint)(inputChar & codingCase.MiddleMask) >> codingCase.MiddleShift)); if (bytesLeft > 2) { outputArray[outputByteNum + 2] = (sbyte)((inputChar & codingCase.FinalMask) << codingCase.FinalShift); } } } } } internal class CodingCase { internal int NumBytes, InitialShift, MiddleShift, FinalShift, AdvanceBytes = 2; internal short MiddleMask, FinalMask; internal CodingCase(int initialShift, int middleShift, int finalShift) { this.NumBytes = 3; this.InitialShift = initialShift; this.MiddleShift = middleShift; this.FinalShift = finalShift; this.FinalMask = (short)((int)((uint)(short)0xFF >> finalShift)); this.MiddleMask = (short)((short)0xFF << middleShift); } internal CodingCase(int initialShift, int finalShift) { this.NumBytes = 2; this.InitialShift = initialShift; this.FinalShift = finalShift; this.FinalMask = (short)((int)((uint)(short)0xFF >> finalShift)); if (finalShift != 0) { AdvanceBytes = 1; } } } } }
using System; using System.Diagnostics; using System.Security; namespace System.Windows.Input { ///////////////////////////////////////////////////////////////////////// /// <summary> /// The Stylus class represents all stylus devices /// </summary> public static class Stylus { ///////////////////////////////////////////////////////////////////// /// <summary> /// PreviewStylusDown /// </summary> public static readonly RoutedEvent PreviewStylusDownEvent = EventManager.RegisterRoutedEvent("PreviewStylusDown", RoutingStrategy.Tunnel, typeof(StylusDownEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the PreviewStylusDown attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddPreviewStylusDownHandler(DependencyObject element, StylusDownEventHandler handler) { UIElement.AddHandler(element, PreviewStylusDownEvent, handler); } /// <summary> /// Removes a handler for the PreviewStylusDown attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemovePreviewStylusDownHandler(DependencyObject element, StylusDownEventHandler handler) { UIElement.RemoveHandler(element, PreviewStylusDownEvent, handler); } /// <summary> /// StylusDown /// </summary> public static readonly RoutedEvent StylusDownEvent = EventManager.RegisterRoutedEvent("StylusDown", RoutingStrategy.Bubble, typeof(StylusDownEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusDown attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusDownHandler(DependencyObject element, StylusDownEventHandler handler) { UIElement.AddHandler(element, StylusDownEvent, handler); } /// <summary> /// Removes a handler for the StylusDown attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusDownHandler(DependencyObject element, StylusDownEventHandler handler) { UIElement.RemoveHandler(element, StylusDownEvent, handler); } /// <summary> /// PreviewStylusUp /// </summary> public static readonly RoutedEvent PreviewStylusUpEvent = EventManager.RegisterRoutedEvent("PreviewStylusUp", RoutingStrategy.Tunnel, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the PreviewStylusUp attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddPreviewStylusUpHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, PreviewStylusUpEvent, handler); } /// <summary> /// Removes a handler for the PreviewStylusUp attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemovePreviewStylusUpHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, PreviewStylusUpEvent, handler); } /// <summary> /// StylusUp /// </summary> public static readonly RoutedEvent StylusUpEvent = EventManager.RegisterRoutedEvent("StylusUp", RoutingStrategy.Bubble, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusUp attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusUpHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, StylusUpEvent, handler); } /// <summary> /// Removes a handler for the StylusUp attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusUpHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, StylusUpEvent, handler); } /// <summary> /// PreviewStylusMove /// </summary> public static readonly RoutedEvent PreviewStylusMoveEvent = EventManager.RegisterRoutedEvent("PreviewStylusMove", RoutingStrategy.Tunnel, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the PreviewStylusMove attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddPreviewStylusMoveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, PreviewStylusMoveEvent, handler); } /// <summary> /// Removes a handler for the PreviewStylusMove attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemovePreviewStylusMoveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, PreviewStylusMoveEvent, handler); } /// <summary> /// StylusMove /// </summary> public static readonly RoutedEvent StylusMoveEvent = EventManager.RegisterRoutedEvent("StylusMove", RoutingStrategy.Bubble, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusMove attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusMoveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, StylusMoveEvent, handler); } /// <summary> /// Removes a handler for the StylusMove attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusMoveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, StylusMoveEvent, handler); } /// <summary> /// PreviewStylusInAirMove /// </summary> public static readonly RoutedEvent PreviewStylusInAirMoveEvent = EventManager.RegisterRoutedEvent("PreviewStylusInAirMove", RoutingStrategy.Tunnel, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the PreviewStylusInAirMove attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddPreviewStylusInAirMoveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, PreviewStylusInAirMoveEvent, handler); } /// <summary> /// Removes a handler for the PreviewStylusInAirMove attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemovePreviewStylusInAirMoveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, PreviewStylusInAirMoveEvent, handler); } /// <summary> /// StylusInAirMove /// </summary> public static readonly RoutedEvent StylusInAirMoveEvent = EventManager.RegisterRoutedEvent("StylusInAirMove", RoutingStrategy.Bubble, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusInAirMove attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusInAirMoveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, StylusInAirMoveEvent, handler); } /// <summary> /// Removes a handler for the StylusInAirMove attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusInAirMoveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, StylusInAirMoveEvent, handler); } /// <summary> /// StylusEnter /// </summary> public static readonly RoutedEvent StylusEnterEvent = EventManager.RegisterRoutedEvent("StylusEnter", RoutingStrategy.Direct, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusEnter attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusEnterHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, StylusEnterEvent, handler); } /// <summary> /// Removes a handler for the StylusEnter attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusEnterHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, StylusEnterEvent, handler); } /// <summary> /// StylusLeave /// </summary> public static readonly RoutedEvent StylusLeaveEvent = EventManager.RegisterRoutedEvent("StylusLeave", RoutingStrategy.Direct, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusLeave attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusLeaveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, StylusLeaveEvent, handler); } /// <summary> /// Removes a handler for the StylusLeave attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusLeaveHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, StylusLeaveEvent, handler); } /// <summary> /// PreviewStylusInRange /// </summary> public static readonly RoutedEvent PreviewStylusInRangeEvent = EventManager.RegisterRoutedEvent("PreviewStylusInRange", RoutingStrategy.Tunnel, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the PreviewStylusInRange attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddPreviewStylusInRangeHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, PreviewStylusInRangeEvent, handler); } /// <summary> /// Removes a handler for the PreviewStylusInRange attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemovePreviewStylusInRangeHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, PreviewStylusInRangeEvent, handler); } /// <summary> /// StylusInRange /// </summary> public static readonly RoutedEvent StylusInRangeEvent = EventManager.RegisterRoutedEvent("StylusInRange", RoutingStrategy.Bubble, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusInRange attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusInRangeHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, StylusInRangeEvent, handler); } /// <summary> /// Removes a handler for the StylusInRange attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusInRangeHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, StylusInRangeEvent, handler); } /// <summary> /// PreviewStylusOutOfRange /// </summary> public static readonly RoutedEvent PreviewStylusOutOfRangeEvent = EventManager.RegisterRoutedEvent("PreviewStylusOutOfRange", RoutingStrategy.Tunnel, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the PreviewStylusOutOfRange attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddPreviewStylusOutOfRangeHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, PreviewStylusOutOfRangeEvent, handler); } /// <summary> /// Removes a handler for the PreviewStylusOutOfRange attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemovePreviewStylusOutOfRangeHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, PreviewStylusOutOfRangeEvent, handler); } /// <summary> /// StylusOutOfRange /// </summary> public static readonly RoutedEvent StylusOutOfRangeEvent = EventManager.RegisterRoutedEvent("StylusOutOfRange", RoutingStrategy.Bubble, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusOutOfRange attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusOutOfRangeHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, StylusOutOfRangeEvent, handler); } /// <summary> /// Removes a handler for the StylusOutOfRange attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusOutOfRangeHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, StylusOutOfRangeEvent, handler); } /// <summary> /// PreviewStylusSystemGesture /// </summary> public static readonly RoutedEvent PreviewStylusSystemGestureEvent = EventManager.RegisterRoutedEvent("PreviewStylusSystemGesture", RoutingStrategy.Tunnel, typeof(StylusSystemGestureEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the PreviewStylusSystemGesture attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddPreviewStylusSystemGestureHandler(DependencyObject element, StylusSystemGestureEventHandler handler) { UIElement.AddHandler(element, PreviewStylusSystemGestureEvent, handler); } /// <summary> /// Removes a handler for the PreviewStylusSystemGesture attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemovePreviewStylusSystemGestureHandler(DependencyObject element, StylusSystemGestureEventHandler handler) { UIElement.RemoveHandler(element, PreviewStylusSystemGestureEvent, handler); } /// <summary> /// StylusSystemGesture /// </summary> public static readonly RoutedEvent StylusSystemGestureEvent = EventManager.RegisterRoutedEvent("StylusSystemGesture", RoutingStrategy.Bubble, typeof(StylusSystemGestureEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusSystemGesture attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusSystemGestureHandler(DependencyObject element, StylusSystemGestureEventHandler handler) { UIElement.AddHandler(element, StylusSystemGestureEvent, handler); } /// <summary> /// Removes a handler for the StylusSystemGesture attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusSystemGestureHandler(DependencyObject element, StylusSystemGestureEventHandler handler) { UIElement.RemoveHandler(element, StylusSystemGestureEvent, handler); } /// <summary> /// GotStylusCapture /// </summary> public static readonly RoutedEvent GotStylusCaptureEvent = EventManager.RegisterRoutedEvent("GotStylusCapture", RoutingStrategy.Bubble, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the GotStylusCapture attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddGotStylusCaptureHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, GotStylusCaptureEvent, handler); } /// <summary> /// Removes a handler for the GotStylusCapture attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveGotStylusCaptureHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, GotStylusCaptureEvent, handler); } /// <summary> /// LostStylusCapture /// </summary> public static readonly RoutedEvent LostStylusCaptureEvent = EventManager.RegisterRoutedEvent("LostStylusCapture", RoutingStrategy.Bubble, typeof(StylusEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the LostStylusCapture attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddLostStylusCaptureHandler(DependencyObject element, StylusEventHandler handler) { UIElement.AddHandler(element, LostStylusCaptureEvent, handler); } /// <summary> /// Removes a handler for the LostStylusCapture attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveLostStylusCaptureHandler(DependencyObject element, StylusEventHandler handler) { UIElement.RemoveHandler(element, LostStylusCaptureEvent, handler); } /// <summary> /// StylusButtonDown /// </summary> public static readonly RoutedEvent StylusButtonDownEvent = EventManager.RegisterRoutedEvent("StylusButtonDown", RoutingStrategy.Bubble, typeof(StylusButtonEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusButtonDown attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusButtonDownHandler(DependencyObject element, StylusButtonEventHandler handler) { UIElement.AddHandler(element, StylusButtonDownEvent, handler); } /// <summary> /// Removes a handler for the StylusButtonDown attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusButtonDownHandler(DependencyObject element, StylusButtonEventHandler handler) { UIElement.RemoveHandler(element, StylusButtonDownEvent, handler); } /// <summary> /// StylusButtonUp /// </summary> public static readonly RoutedEvent StylusButtonUpEvent = EventManager.RegisterRoutedEvent("StylusButtonUp", RoutingStrategy.Bubble, typeof(StylusButtonEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the StylusButtonUp attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddStylusButtonUpHandler(DependencyObject element, StylusButtonEventHandler handler) { UIElement.AddHandler(element, StylusButtonUpEvent, handler); } /// <summary> /// Removes a handler for the StylusButtonUp attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemoveStylusButtonUpHandler(DependencyObject element, StylusButtonEventHandler handler) { UIElement.RemoveHandler(element, StylusButtonUpEvent, handler); } /// <summary> /// PreviewStylusButtonDown /// </summary> public static readonly RoutedEvent PreviewStylusButtonDownEvent = EventManager.RegisterRoutedEvent("PreviewStylusButtonDown", RoutingStrategy.Tunnel, typeof(StylusButtonEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the PreviewStylusButtonDown attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddPreviewStylusButtonDownHandler(DependencyObject element, StylusButtonEventHandler handler) { UIElement.AddHandler(element, PreviewStylusButtonDownEvent, handler); } /// <summary> /// Removes a handler for the PreviewStylusButtonDown attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemovePreviewStylusButtonDownHandler(DependencyObject element, StylusButtonEventHandler handler) { UIElement.RemoveHandler(element, PreviewStylusButtonDownEvent, handler); } /// <summary> /// PreviewStylusButtonUp /// </summary> public static readonly RoutedEvent PreviewStylusButtonUpEvent = EventManager.RegisterRoutedEvent("PreviewStylusButtonUp", RoutingStrategy.Tunnel, typeof(StylusButtonEventHandler), typeof(Stylus)); /// <summary> /// Adds a handler for the PreviewStylusButtonUp attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be added</param> public static void AddPreviewStylusButtonUpHandler(DependencyObject element, StylusButtonEventHandler handler) { UIElement.AddHandler(element, PreviewStylusButtonUpEvent, handler); } /// <summary> /// Removes a handler for the PreviewStylusButtonUp attached event /// </summary> /// <param name="element">UIElement or ContentElement that listens to this event</param> /// <param name="handler">Event Handler to be removed</param> public static void RemovePreviewStylusButtonUpHandler(DependencyObject element, StylusButtonEventHandler handler) { UIElement.RemoveHandler(element, PreviewStylusButtonUpEvent, handler); } /// <summary> /// Reads the attached property IsPressAndHoldEnabled from the given element. /// </summary> /// <param name="element">The element from which to read the attached property.</param> /// <returns>The property's value.</returns> /// <seealso cref="Stylus.IsPressAndHoldEnabledProperty" /> [AttachedPropertyBrowsableForType(typeof(DependencyObject))] public static bool GetIsPressAndHoldEnabled(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } object boolValue = element.GetValue(IsPressAndHoldEnabledProperty); if (boolValue == null) return false; // If we don't find property then return false. else return (bool)boolValue; } /// <summary> /// Writes the attached property IsPressAndHoldEnabled to the given element. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="enabled">The property value to set</param> /// <seealso cref="Stylus.IsPressAndHoldEnabledProperty" /> public static void SetIsPressAndHoldEnabled(DependencyObject element, bool enabled) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(IsPressAndHoldEnabledProperty, enabled); } /// <summary> /// DependencyProperty for IsPressAndHoldEnabled property. /// </summary> /// <seealso cref="Stylus.GetIsPressAndHoldEnabled" /> /// <seealso cref="Stylus.SetIsPressAndHoldEnabled" /> public static readonly DependencyProperty IsPressAndHoldEnabledProperty = DependencyProperty.RegisterAttached("IsPressAndHoldEnabled", typeof(bool), typeof(Stylus), new PropertyMetadata(true)); // note we can't specify inherits in frameworkcore. new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits) /// <summary> /// Reads the attached property IsFlicksEnabled from the given element. /// </summary> /// <param name="element">The element from which to read the attached property.</param> /// <returns>The property's value.</returns> /// <seealso cref="Stylus.IsFlicksEnabledProperty" /> [AttachedPropertyBrowsableForType(typeof(DependencyObject))] public static bool GetIsFlicksEnabled(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } object boolValue = element.GetValue(IsFlicksEnabledProperty); if (boolValue == null) return false; // If we don't find property then return false. else return (bool)boolValue; } /// <summary> /// Writes the attached property IsFlicksEnabled to the given element. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="enabled">The property value to set</param> /// <seealso cref="Stylus.IsFlicksEnabledProperty" /> public static void SetIsFlicksEnabled(DependencyObject element, bool enabled) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(IsFlicksEnabledProperty, enabled); } /// <summary> /// DependencyProperty for IsFlicksEnabled property. /// </summary> /// <seealso cref="Stylus.GetIsFlicksEnabled" /> /// <seealso cref="Stylus.SetIsFlicksEnabled" /> public static readonly DependencyProperty IsFlicksEnabledProperty = DependencyProperty.RegisterAttached("IsFlicksEnabled", typeof(bool), typeof(Stylus), new PropertyMetadata(true)); // note we can't specify inherits in frameworkcore. new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits) /// <summary> /// Reads the attached property IsTapFeedbackEnabled from the given element. /// </summary> /// <param name="element">The element from which to read the attached property.</param> /// <returns>The property's value.</returns> /// <seealso cref="Stylus.IsTapFeedbackEnabledProperty" /> [AttachedPropertyBrowsableForType(typeof(DependencyObject))] public static bool GetIsTapFeedbackEnabled(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } object boolValue = element.GetValue(IsTapFeedbackEnabledProperty); if (boolValue == null) return false; // If we don't find property then return false. else return (bool)boolValue; } /// <summary> /// Writes the attached property IsTapFeedbackEnabled to the given element. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="enabled">The property value to set</param> /// <seealso cref="Stylus.IsTapFeedbackEnabledProperty" /> public static void SetIsTapFeedbackEnabled(DependencyObject element, bool enabled) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(IsTapFeedbackEnabledProperty, enabled); } /// <summary> /// DependencyProperty for IsTapFeedbackEnabled property. /// </summary> /// <seealso cref="Stylus.GetIsTapFeedbackEnabled" /> /// <seealso cref="Stylus.SetIsTapFeedbackEnabled" /> public static readonly DependencyProperty IsTapFeedbackEnabledProperty = DependencyProperty.RegisterAttached("IsTapFeedbackEnabled", typeof(bool), typeof(Stylus), new PropertyMetadata(true)); // note we can't specify inherits in frameworkcore. new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits) /// <summary> /// Reads the attached property IsTouchFeedbackEnabled from the given element. /// </summary> /// <param name="element">The element from which to read the attached property.</param> /// <returns>The property's value.</returns> /// <seealso cref="Stylus.IsTouchFeedbackEnabledProperty" /> public static bool GetIsTouchFeedbackEnabled(DependencyObject element) { if (element == null) { throw new ArgumentNullException("element"); } object boolValue = element.GetValue(IsTouchFeedbackEnabledProperty); if (boolValue == null) return false; // If we don't find property then return false. else return (bool)boolValue; } /// <summary> /// Writes the attached property IsTouchFeedbackEnabled to the given element. /// </summary> /// <param name="element">The element to which to write the attached property.</param> /// <param name="enabled">The property value to set</param> /// <seealso cref="Stylus.IsTouchFeedbackEnabledProperty" /> public static void SetIsTouchFeedbackEnabled(DependencyObject element, bool enabled) { if (element == null) { throw new ArgumentNullException("element"); } element.SetValue(IsTouchFeedbackEnabledProperty, enabled); } /// <summary> /// DependencyProperty for IsTouchFeedbackEnabled property. /// </summary> /// <seealso cref="Stylus.GetIsTouchFeedbackEnabled" /> /// <seealso cref="Stylus.SetIsTouchFeedbackEnabled" /> public static readonly DependencyProperty IsTouchFeedbackEnabledProperty = DependencyProperty.RegisterAttached("IsTouchFeedbackEnabled", typeof(bool), typeof(Stylus), new PropertyMetadata(true)); // note we can't specify inherits in frameworkcore. new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.Inherits) ///////////////////////////////////////////////////////////////////// /// <summary> /// Returns the element that the stylus is over. /// </summary> public static IInputElement DirectlyOver { get { StylusDevice stylusDevice = Stylus.CurrentStylusDevice; if (stylusDevice == null) return null; return stylusDevice.DirectlyOver; } } ///////////////////////////////////////////////////////////////////// /// <summary> /// Returns the element that has captured the stylus. /// </summary> public static IInputElement Captured { get { StylusDevice stylusDevice = Stylus.CurrentStylusDevice; if (stylusDevice == null) { return Mouse.Captured; } return stylusDevice.Captured; } } ///////////////////////////////////////////////////////////////////// /// <summary> /// Captures the stylus to a particular element. /// </summary> /// <param name="element"> /// The element to capture the stylus to. /// </param> public static bool Capture(IInputElement element) { return Capture(element, CaptureMode.Element); } ///////////////////////////////////////////////////////////////////// /// <summary> /// Captures the stylus to a particular element. /// </summary> /// <param name="element"> /// The element to capture the stylus to. /// </param> /// <param name="captureMode"> /// The kind of capture to acquire. /// </param> public static bool Capture(IInputElement element, CaptureMode captureMode) { // The stylus code watches mouse capture changes and it will trigger us to // [....] up all the stylusdevice capture settings to be the same as the mouse. // So we just call Mouse.Capture() here to trigger this all to happen. return Mouse.Capture(element, captureMode); } /// <summary> /// Forces the sytlus to resynchronize. /// </summary> public static void Synchronize() { StylusDevice curDevice = Stylus.CurrentStylusDevice; if (null != curDevice) { curDevice.Synchronize(); } } ///////////////////////////////////////////////////////////////////// /// <summary> /// [TBS] /// </summary> /// <SecurityNote> /// Critical - calls SecurityCritical code StylusLogic.CurrentStylusLogic /// PublicOK: Used to get the currently active StylusDevice which is safe to expose. /// this is safe as: /// Takes no input and returns no security critical data. /// </SecurityNote> public static StylusDevice CurrentStylusDevice { [SecurityCritical] get { return StylusLogic.CurrentStylusLogic.CurrentStylusDevice; } } } }
// // EqualizerPresetComboBox.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Hyena; namespace Banshee.Equalizer.Gui { public class EqualizerPresetComboBox : Gtk.ComboBox { private EqualizerManager manager; private ListStore store; private EqualizerSetting active_eq; private int user_count; private TreeIter separator_iter = TreeIter.Zero; public EqualizerPresetComboBox () : this (EqualizerManager.Instance) { } public EqualizerPresetComboBox (EqualizerManager manager) : base (true) { if (manager == null) { throw new ArgumentNullException ("provide an EqualizerManager or use default constructor"); } this.manager = manager; BuildWidget (); } private void BuildWidget () { store = new ListStore (typeof (string), typeof (EqualizerSetting)); Model = store; EntryTextColumn = 0; store.DefaultSortFunc = (model, ia, ib) => { var a = GetEqualizerSettingForIter (ia); var b = GetEqualizerSettingForIter (ib); if (a != null && b != null) { return a.IsReadOnly == b.IsReadOnly ? a.Name.CompareTo (b.Name) : a.IsReadOnly.CompareTo (b.IsReadOnly); } else if (a == null && b == null) { return 0; } else if ((a == null && b.IsReadOnly) || (b == null && !a.IsReadOnly)) { return -1; } else if ((a == null && !b.IsReadOnly) || (b == null && a.IsReadOnly)) { return 1; } return 0; }; store.SetSortColumnId (-1, SortType.Ascending); RowSeparatorFunc = (model, iter) => store.GetValue (iter, 0) as String == String.Empty && store.GetValue (iter, 1) == null; foreach (EqualizerSetting eq in manager) { AddEqualizerSetting(eq); } manager.EqualizerAdded += (o, e) => AddEqualizerSetting (e.Value); manager.EqualizerRemoved += (o, e) => RemoveEqualizerSetting (e.Value); } protected override void OnChanged () { EqualizerSetting eq = ActiveEqualizer; if (eq != null) { active_eq = eq; } else if (eq == null && active_eq == null) { base.OnChanged (); return; } else if (eq == null) { eq = active_eq; } if (Entry == null || eq.IsReadOnly) { return; } eq.Name = Entry.Text; TreeIter iter; if (GetIterForEqualizerSetting (eq, out iter)) { store.SetValue (iter, 0, eq.Name); } if (eq != ActiveEqualizer) { ActiveEqualizer = eq; base.OnChanged (); } } public bool ActivateFirstEqualizer () { TreeIter iter; if (store.IterNthChild (out iter, 0)) { ActiveEqualizer = GetEqualizerSettingForIter (iter); return true; } return false; } private void AddEqualizerSetting (EqualizerSetting eq) { if (!eq.IsReadOnly) { user_count++; if (separator_iter.Equals (TreeIter.Zero)) { // FIXME: Very strange bug if (null, null) is stored // here regarding RowSeparatorFunc - not sure where the // bug might be, but I'm 99% sure this is a bug in GTK+ // or Gtk#. I demand answers! Thanks to Sandy Armstrong // for thinking outside of his box. separator_iter = store.AppendValues (String.Empty, null); } } store.AppendValues (eq.Name, eq); } private void RemoveEqualizerSetting (EqualizerSetting eq) { TreeIter iter; if (GetIterForEqualizerSetting (eq, out iter)) { if (!eq.IsReadOnly && --user_count <= 0) { user_count = 0; store.Remove (ref separator_iter); separator_iter = TreeIter.Zero; } store.Remove (ref iter); } if (!ActivateFirstEqualizer ()) { active_eq = null; if (Entry != null) { Entry.Text = String.Empty; } } } private EqualizerSetting GetEqualizerSettingForIter (TreeIter iter) { return store.GetValue (iter, 1) as EqualizerSetting; } private bool GetIterForEqualizerSetting (EqualizerSetting eq, out TreeIter iter) { for (int i = 0, n = store.IterNChildren (); i < n; i++) { if (store.IterNthChild (out iter, i) && store.GetValue (iter, 1) == eq) { return true; } } iter = TreeIter.Zero; return false; } public EqualizerSetting ActiveEqualizer { get { TreeIter iter; return GetActiveIter (out iter) ? GetEqualizerSettingForIter (iter) : null; } set { active_eq = value; if (value != null) { Entry.IsEditable = !active_eq.IsReadOnly; } TreeIter iter; if (GetIterForEqualizerSetting (value, out iter)) { SetActiveIter (iter); } } } } }
// 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.IO; using System.Linq; using JetBrains.Annotations; using Microsoft.Win32; using osu.Framework.Allocation; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Framework.Threading; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Legacy; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Rulesets; using osu.Game.Tournament.Models; namespace osu.Game.Tournament.IPC { public class FileBasedIPC : MatchIPCInfo { public Storage IPCStorage { get; private set; } [Resolved] protected IAPIProvider API { get; private set; } [Resolved] protected RulesetStore Rulesets { get; private set; } [Resolved] private GameHost host { get; set; } [Resolved] private LadderInfo ladder { get; set; } [Resolved] private StableInfo stableInfo { get; set; } private int lastBeatmapId; private ScheduledDelegate scheduled; private GetBeatmapRequest beatmapLookupRequest; [BackgroundDependencyLoader] private void load() { var stablePath = stableInfo.StablePath ?? findStablePath(); initialiseIPCStorage(stablePath); } [CanBeNull] private Storage initialiseIPCStorage(string path) { scheduled?.Cancel(); IPCStorage = null; try { if (string.IsNullOrEmpty(path)) return null; IPCStorage = new DesktopStorage(path, host as DesktopGameHost); const string file_ipc_filename = "ipc.txt"; const string file_ipc_state_filename = "ipc-state.txt"; const string file_ipc_scores_filename = "ipc-scores.txt"; const string file_ipc_channel_filename = "ipc-channel.txt"; if (IPCStorage.Exists(file_ipc_filename)) { scheduled = Scheduler.AddDelayed(delegate { try { using (var stream = IPCStorage.GetStream(file_ipc_filename)) using (var sr = new StreamReader(stream)) { var beatmapId = int.Parse(sr.ReadLine().AsNonNull()); var mods = int.Parse(sr.ReadLine().AsNonNull()); if (lastBeatmapId != beatmapId) { beatmapLookupRequest?.Cancel(); lastBeatmapId = beatmapId; var existing = ladder.CurrentMatch.Value?.Round.Value?.Beatmaps.FirstOrDefault(b => b.ID == beatmapId && b.BeatmapInfo != null); if (existing != null) Beatmap.Value = existing.BeatmapInfo; else { beatmapLookupRequest = new GetBeatmapRequest(new BeatmapInfo { OnlineBeatmapID = beatmapId }); beatmapLookupRequest.Success += b => Beatmap.Value = b.ToBeatmapInfo(Rulesets); API.Queue(beatmapLookupRequest); } } Mods.Value = (LegacyMods)mods; } } catch { // file might be in use. } try { using (var stream = IPCStorage.GetStream(file_ipc_channel_filename)) using (var sr = new StreamReader(stream)) { ChatChannel.Value = sr.ReadLine(); } } catch (Exception) { // file might be in use. } try { using (var stream = IPCStorage.GetStream(file_ipc_state_filename)) using (var sr = new StreamReader(stream)) { State.Value = (TourneyState)Enum.Parse(typeof(TourneyState), sr.ReadLine().AsNonNull()); } } catch (Exception) { // file might be in use. } try { using (var stream = IPCStorage.GetStream(file_ipc_scores_filename)) using (var sr = new StreamReader(stream)) { Score1.Value = int.Parse(sr.ReadLine()); Score2.Value = int.Parse(sr.ReadLine()); } } catch (Exception) { // file might be in use. } }, 250, true); } } catch (Exception e) { Logger.Error(e, "Stable installation could not be found; disabling file based IPC"); } return IPCStorage; } /// <summary> /// Manually sets the path to the directory used for inter-process communication with a cutting-edge install. /// </summary> /// <param name="path">Path to the IPC directory</param> /// <returns>Whether the supplied path was a valid IPC directory.</returns> public bool SetIPCLocation(string path) { if (path == null || !ipcFileExistsInDirectory(path)) return false; var newStorage = initialiseIPCStorage(stableInfo.StablePath = path); if (newStorage == null) return false; stableInfo.SaveChanges(); return true; } /// <summary> /// Tries to automatically detect the path to the directory used for inter-process communication /// with a cutting-edge install. /// </summary> /// <returns>Whether an IPC directory was successfully auto-detected.</returns> public bool AutoDetectIPCLocation() => SetIPCLocation(findStablePath()); private static bool ipcFileExistsInDirectory(string p) => p != null && File.Exists(Path.Combine(p, "ipc.txt")); [CanBeNull] private string findStablePath() { var stableInstallPath = findFromEnvVar() ?? findFromRegistry() ?? findFromLocalAppData() ?? findFromDotFolder(); Logger.Log($"Stable path for tourney usage: {stableInstallPath}"); return stableInstallPath; } private string findFromEnvVar() { try { Logger.Log("Trying to find stable with environment variables"); string stableInstallPath = Environment.GetEnvironmentVariable("OSU_STABLE_PATH"); if (ipcFileExistsInDirectory(stableInstallPath)) return stableInstallPath; } catch { } return null; } private string findFromLocalAppData() { Logger.Log("Trying to find stable in %LOCALAPPDATA%"); string stableInstallPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"osu!"); if (ipcFileExistsInDirectory(stableInstallPath)) return stableInstallPath; return null; } private string findFromDotFolder() { Logger.Log("Trying to find stable in dotfolders"); string stableInstallPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".osu"); if (ipcFileExistsInDirectory(stableInstallPath)) return stableInstallPath; return null; } private string findFromRegistry() { Logger.Log("Trying to find stable in registry"); try { string stableInstallPath; using (RegistryKey key = Registry.ClassesRoot.OpenSubKey("osu")) stableInstallPath = key?.OpenSubKey(@"shell\open\command")?.GetValue(string.Empty)?.ToString()?.Split('"')[1].Replace("osu!.exe", ""); if (ipcFileExistsInDirectory(stableInstallPath)) return stableInstallPath; } catch { } return null; } } }
/* * @(#)DOMNodeImpl.java 1.11 2000/08/16 * */ using System; using DOMException = Comzept.Genesis.Tidy.Dom.DOMException; namespace Comzept.Genesis.Tidy.Xml.Dom { /// <summary> /// DOMNodeImpl</summary> /// <remarks> /// (c) 1998-2000 (W3C) MIT, INRIA, Keio University /// See Tidy.java for the copyright notice. /// Derived from <a href="http://www.w3.org/People/Raggett/tidy"> /// HTML Tidy Release 4 Aug 2000</a> /// </remarks> /// /// <author> Dave Raggett dsr@w3.org /// </author> /// <author> Andy Quick ac.quick@sympatico.ca (translation to Java) /// </author> /// <version> 1.4, 1999/09/04 DOM Support /// </version> /// <version> 1.5, 1999/10/23 Tidy Release 27 Sep 1999 /// </version> /// <version> 1.6, 1999/11/01 Tidy Release 22 Oct 1999 /// </version> /// <version> 1.7, 1999/12/06 Tidy Release 30 Nov 1999 /// </version> /// <version> 1.8, 2000/01/22 Tidy Release 13 Jan 2000 /// </version> /// <version> 1.9, 2000/06/03 Tidy Release 30 Apr 2000 /// </version> /// <version> 1.10, 2000/07/22 Tidy Release 8 Jul 2000 /// </version> /// <version> 1.11, 2000/08/16 Tidy Release 4 Aug 2000 /// </version> public class DOMNodeImpl : Comzept.Genesis.Tidy.Dom.Node { //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" virtual public System.String NodeValue { get { System.String value_Renamed = ""; //BAK 10/10/2000 replaced null if (adaptee.type == Node.TextNode || adaptee.type == Node.CDATATag || adaptee.type == Node.CommentTag || adaptee.type == Node.ProcInsTag) { if (adaptee.textarray != null && adaptee.start < adaptee.end) { value_Renamed = Lexer.getString(adaptee.textarray, adaptee.start, adaptee.end - adaptee.start); } } return value_Renamed; } set { if (adaptee.type == Node.TextNode || adaptee.type == Node.CDATATag || adaptee.type == Node.CommentTag || adaptee.type == Node.ProcInsTag) { sbyte[] textarray = Lexer.getBytes(value); adaptee.textarray = textarray; adaptee.start = 0; adaptee.end = textarray.Length; } } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.NodeNodeName"> /// </seealso> virtual public System.String NodeName { get { return adaptee.element; } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.NodeNodeType"> /// </seealso> virtual public short NodeType { get { short result = - 1; switch (adaptee.type) { case Node.RootNode: result = Comzept.Genesis.Tidy.Dom.Node_Fields.DOCUMENT_NODE; break; case Node.DocTypeTag: result = Comzept.Genesis.Tidy.Dom.Node_Fields.DOCUMENT_TYPE_NODE; break; case Node.CommentTag: result = Comzept.Genesis.Tidy.Dom.Node_Fields.COMMENT_NODE; break; case Node.ProcInsTag: result = Comzept.Genesis.Tidy.Dom.Node_Fields.PROCESSING_INSTRUCTION_NODE; break; case Node.TextNode: result = Comzept.Genesis.Tidy.Dom.Node_Fields.TEXT_NODE; break; case Node.CDATATag: result = Comzept.Genesis.Tidy.Dom.Node_Fields.CDATA_SECTION_NODE; break; case Node.StartTag: case Node.StartEndTag: result = Comzept.Genesis.Tidy.Dom.Node_Fields.ELEMENT_NODE; break; } return result; } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.ParentNode"> /// </seealso> virtual public Comzept.Genesis.Tidy.Dom.Node ParentNode { get { if (adaptee.parent != null) return adaptee.parent.Adapter; else return null; } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.ChildNodes"> /// </seealso> virtual public Comzept.Genesis.Tidy.Dom.NodeList ChildNodes { get { return new DOMNodeListImpl(adaptee); } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.FirstChild"> /// </seealso> virtual public Comzept.Genesis.Tidy.Dom.Node FirstChild { get { if (adaptee.content != null) return adaptee.content.Adapter; else return null; } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.LastChild"> /// </seealso> virtual public Comzept.Genesis.Tidy.Dom.Node LastChild { get { if (adaptee.last != null) return adaptee.last.Adapter; else return null; } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.PreviousSibling"> /// </seealso> virtual public Comzept.Genesis.Tidy.Dom.Node PreviousSibling { get { if (adaptee.prev != null) return adaptee.prev.Adapter; else return null; } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.NextSibling"> /// </seealso> virtual public Comzept.Genesis.Tidy.Dom.Node NextSibling { get { if (adaptee.next != null) return adaptee.next.Adapter; else return null; } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.Attributes"> /// </seealso> virtual public Comzept.Genesis.Tidy.Dom.NamedNodeMap Attributes { get { return new DOMAttrMapImpl(adaptee.attributes); } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.OwnerDocument"> /// </seealso> virtual public Comzept.Genesis.Tidy.Dom.Document OwnerDocument { get { Node node; node = this.adaptee; if (node != null && node.type == Node.RootNode) return null; for (node = this.adaptee; node != null && node.type != Node.RootNode; node = node.parent) ; if (node != null) return (Comzept.Genesis.Tidy.Dom.Document) node.Adapter; else return null; } } /// <summary> DOM2 - not implemented.</summary> virtual public System.String NamespaceURI { get { return null; } } //UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'" /// <summary> DOM2 - not implemented.</summary> /// <summary> DOM2 - not implemented.</summary> virtual public System.String Prefix { get { return null; } set { } } /// <summary> DOM2 - not implemented.</summary> virtual public System.String LocalName { get { return null; } } protected internal Node adaptee; protected internal DOMNodeImpl(Node adaptee) { this.adaptee = adaptee; } /* --------------------- DOM ---------------------------- */ /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.insertBefore"> /// </seealso> public virtual Comzept.Genesis.Tidy.Dom.Node insertBefore(Comzept.Genesis.Tidy.Dom.Node newChild, Comzept.Genesis.Tidy.Dom.Node refChild) { // TODO - handle newChild already in tree if (newChild == null) return null; if (!(newChild is DOMNodeImpl)) { throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR, "newChild not instanceof DOMNodeImpl"); } DOMNodeImpl newCh = (DOMNodeImpl) newChild; if (this.adaptee.type == Node.RootNode) { if (newCh.adaptee.type != Node.DocTypeTag && newCh.adaptee.type != Node.ProcInsTag) { throw new DOMExceptionImpl(DOMException.HIERARCHY_REQUEST_ERR, "newChild cannot be a child of this node"); } } else if (this.adaptee.type == Node.StartTag) { if (newCh.adaptee.type != Node.StartTag && newCh.adaptee.type != Node.StartEndTag && newCh.adaptee.type != Node.CommentTag && newCh.adaptee.type != Node.TextNode && newCh.adaptee.type != Node.CDATATag) { throw new DOMExceptionImpl(DOMException.HIERARCHY_REQUEST_ERR, "newChild cannot be a child of this node"); } } if (refChild == null) { Node.insertNodeAtEnd(this.adaptee, newCh.adaptee); if (this.adaptee.type == Node.StartEndTag) { this.adaptee.Type = Node.StartTag; } } else { Node ref_Renamed = this.adaptee.content; while (ref_Renamed != null) { if (ref_Renamed.Adapter == refChild) break; ref_Renamed = ref_Renamed.next; } if (ref_Renamed == null) { throw new DOMExceptionImpl(DOMException.NOT_FOUND_ERR, "refChild not found"); } Node.insertNodeBeforeElement(ref_Renamed, newCh.adaptee); } return newChild; } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.replaceChild"> /// </seealso> public virtual Comzept.Genesis.Tidy.Dom.Node replaceChild(Comzept.Genesis.Tidy.Dom.Node newChild, Comzept.Genesis.Tidy.Dom.Node oldChild) { // TODO - handle newChild already in tree if (newChild == null) return null; if (!(newChild is DOMNodeImpl)) { throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR, "newChild not instanceof DOMNodeImpl"); } DOMNodeImpl newCh = (DOMNodeImpl) newChild; if (this.adaptee.type == Node.RootNode) { if (newCh.adaptee.type != Node.DocTypeTag && newCh.adaptee.type != Node.ProcInsTag) { throw new DOMExceptionImpl(DOMException.HIERARCHY_REQUEST_ERR, "newChild cannot be a child of this node"); } } else if (this.adaptee.type == Node.StartTag) { if (newCh.adaptee.type != Node.StartTag && newCh.adaptee.type != Node.StartEndTag && newCh.adaptee.type != Node.CommentTag && newCh.adaptee.type != Node.TextNode && newCh.adaptee.type != Node.CDATATag) { throw new DOMExceptionImpl(DOMException.HIERARCHY_REQUEST_ERR, "newChild cannot be a child of this node"); } } if (oldChild == null) { throw new DOMExceptionImpl(DOMException.NOT_FOUND_ERR, "oldChild not found"); } else { Node n; Node ref_Renamed = this.adaptee.content; while (ref_Renamed != null) { if (ref_Renamed.Adapter == oldChild) break; ref_Renamed = ref_Renamed.next; } if (ref_Renamed == null) { throw new DOMExceptionImpl(DOMException.NOT_FOUND_ERR, "oldChild not found"); } newCh.adaptee.next = ref_Renamed.next; newCh.adaptee.prev = ref_Renamed.prev; newCh.adaptee.last = ref_Renamed.last; newCh.adaptee.parent = ref_Renamed.parent; newCh.adaptee.content = ref_Renamed.content; if (ref_Renamed.parent != null) { if (ref_Renamed.parent.content == ref_Renamed) ref_Renamed.parent.content = newCh.adaptee; if (ref_Renamed.parent.last == ref_Renamed) ref_Renamed.parent.last = newCh.adaptee; } if (ref_Renamed.prev != null) { ref_Renamed.prev.next = newCh.adaptee; } if (ref_Renamed.next != null) { ref_Renamed.next.prev = newCh.adaptee; } for (n = ref_Renamed.content; n != null; n = n.next) { if (n.parent == ref_Renamed) n.parent = newCh.adaptee; } } return oldChild; } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.removeChild"> /// </seealso> public virtual Comzept.Genesis.Tidy.Dom.Node removeChild(Comzept.Genesis.Tidy.Dom.Node oldChild) { if (oldChild == null) return null; Node ref_Renamed = this.adaptee.content; while (ref_Renamed != null) { if (ref_Renamed.Adapter == oldChild) break; ref_Renamed = ref_Renamed.next; } if (ref_Renamed == null) { throw new DOMExceptionImpl(DOMException.NOT_FOUND_ERR, "refChild not found"); } Node.discardElement(ref_Renamed); if (this.adaptee.content == null && this.adaptee.type == Node.StartTag) { this.adaptee.Type = Node.StartEndTag; } return oldChild; } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.appendChild"> /// </seealso> public virtual Comzept.Genesis.Tidy.Dom.Node appendChild(Comzept.Genesis.Tidy.Dom.Node newChild) { // TODO - handle newChild already in tree if (newChild == null) return null; if (!(newChild is DOMNodeImpl)) { throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR, "newChild not instanceof DOMNodeImpl"); } DOMNodeImpl newCh = (DOMNodeImpl) newChild; if (this.adaptee.type == Node.RootNode) { if (newCh.adaptee.type != Node.DocTypeTag && newCh.adaptee.type != Node.ProcInsTag) { throw new DOMExceptionImpl(DOMException.HIERARCHY_REQUEST_ERR, "newChild cannot be a child of this node"); } } else if (this.adaptee.type == Node.StartTag) { if (newCh.adaptee.type != Node.StartTag && newCh.adaptee.type != Node.StartEndTag && newCh.adaptee.type != Node.CommentTag && newCh.adaptee.type != Node.TextNode && newCh.adaptee.type != Node.CDATATag) { throw new DOMExceptionImpl(DOMException.HIERARCHY_REQUEST_ERR, "newChild cannot be a child of this node"); } } Node.insertNodeAtEnd(this.adaptee, newCh.adaptee); if (this.adaptee.type == Node.StartEndTag) { this.adaptee.Type = Node.StartTag; } return newChild; } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.hasChildNodes"> /// </seealso> public virtual bool hasChildNodes() { return (adaptee.content != null); } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.cloneNode"> /// </seealso> public virtual Comzept.Genesis.Tidy.Dom.Node cloneNode(bool deep) { Node node = adaptee.cloneNode(deep); node.parent = null; return node.Adapter; } /// <summary> DOM2 - not implemented.</summary> public virtual void normalize() { } /// <summary> DOM2 - not implemented.</summary> public virtual bool supports(System.String feature, System.String version) { return isSupported(feature, version); } /// <summary> DOM2 - not implemented.</summary> public virtual bool isSupported(System.String feature, System.String version) { return false; } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Node.hasAttributes"> /// contributed by dlp@users.sourceforge.net /// </seealso> public virtual bool hasAttributes() { return adaptee.attributes != null; } } }
// **************************************************************** // Copyright 2011, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.IO; using System.Text; using System.Reflection; using System.Collections.Generic; using System.Runtime.InteropServices; namespace NUnit.ProjectEditor { /// <summary> /// Static methods for manipulating doc paths, including both directories /// and files. Some synonyms for System.Path methods are included as well. /// </summary> public class PathUtils { public const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010; public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; public const int MAX_PATH = 256; protected static char DirectorySeparatorChar = Path.DirectorySeparatorChar; protected static char AltDirectorySeparatorChar = Path.AltDirectorySeparatorChar; #region Public methods public static bool IsAssemblyFileType( string path ) { string extension = Path.GetExtension( path ).ToLower(); return extension == ".dll" || extension == ".exe"; } /// <summary> /// Returns the relative path from a base directory to another /// directory or file. /// </summary> public static string RelativePath( string from, string to ) { if (from == null) throw new ArgumentNullException (from); if (to == null) throw new ArgumentNullException (to); string toPathRoot = Path.GetPathRoot(to); if (toPathRoot == null || toPathRoot == string.Empty) return to; string fromPathRoot = Path.GetPathRoot(from); if (!PathsEqual(toPathRoot, fromPathRoot)) return null; string fromNoRoot = from.Substring(fromPathRoot.Length); string toNoRoot = to.Substring(toPathRoot.Length); string[] _from = SplitPath(fromNoRoot); string[] _to = SplitPath(toNoRoot); StringBuilder sb = new StringBuilder (Math.Max (from.Length, to.Length)); int last_common, min = Math.Min (_from.Length, _to.Length); for (last_common = 0; last_common < min; ++last_common) { if (!PathsEqual(_from[last_common], _to[last_common])) break; } if (last_common < _from.Length) sb.Append (".."); for (int i = last_common + 1; i < _from.Length; ++i) { sb.Append (PathUtils.DirectorySeparatorChar).Append (".."); } if (sb.Length > 0) sb.Append (PathUtils.DirectorySeparatorChar); if (last_common < _to.Length) sb.Append (_to [last_common]); for (int i = last_common + 1; i < _to.Length; ++i) { sb.Append (PathUtils.DirectorySeparatorChar).Append (_to [i]); } return sb.ToString (); } /// <summary> /// Return the canonical form of a path. /// </summary> public static string Canonicalize( string path ) { List<string> parts = new List<string>( path.Split( DirectorySeparatorChar, AltDirectorySeparatorChar ) ); for( int index = 0; index < parts.Count; ) { string part = parts[index]; switch( part ) { case ".": parts.RemoveAt( index ); break; case "..": parts.RemoveAt( index ); if ( index > 0 ) parts.RemoveAt( --index ); break; default: index++; break; } } return String.Join( DirectorySeparatorChar.ToString(), parts.ToArray() ); } /// <summary> /// True if the two paths are the same. However, two paths /// to the same file or directory using different network /// shares or drive letters are not treated as equal. /// </summary> public static bool SamePath( string path1, string path2 ) { return string.Compare( Canonicalize(path1), Canonicalize(path2), PathUtils.IsWindows() ) == 0; } /// <summary> /// True if the two paths are the same or if the second is /// directly or indirectly under the first. Note that paths /// using different network shares or drive letters are /// considered unrelated, even if they end up referencing /// the same subtrees in the file system. /// </summary> public static bool SamePathOrUnder( string path1, string path2 ) { path1 = Canonicalize( path1 ); path2 = Canonicalize( path2 ); int length1 = path1.Length; int length2 = path2.Length; // if path1 is longer, then path2 can't be under it if ( length1 > length2 ) return false; // if lengths are the same, check for equality if ( length1 == length2 ) return string.Compare( path1, path2, IsWindows() ) == 0; // path 2 is longer than path 1: see if initial parts match if ( string.Compare( path1, path2.Substring( 0, length1 ), IsWindows() ) != 0 ) return false; // must match through or up to a directory separator boundary return path2[length1-1] == DirectorySeparatorChar || path2[length1] == DirectorySeparatorChar; } public static string Combine( string path1, params string[] morePaths ) { string result = path1; foreach( string path in morePaths ) result = Path.Combine( result, path ); return result; } // TODO: This logic should be in shared source public static string GetAssemblyPath( Assembly assembly ) { string uri = assembly.CodeBase; // If it wasn't loaded locally, use the Location if ( !uri.StartsWith( Uri.UriSchemeFile ) ) return assembly.Location; return GetAssemblyPathFromFileUri( uri ); } // Separate method for testability public static string GetAssemblyPathFromFileUri( string uri ) { // Skip over the file:// int start = Uri.UriSchemeFile.Length + Uri.SchemeDelimiter.Length; if ( PathUtils.DirectorySeparatorChar == '\\' ) { if ( uri[start] == '/' && uri[start+2] == ':' ) ++start; } else { if ( uri[start] != '/' ) --start; } return uri.Substring( start ); } #endregion #region Helper Methods private static bool IsWindows() { return PathUtils.DirectorySeparatorChar == '\\'; } private static string[] SplitPath(string path) { char[] separators = new char[] { PathUtils.DirectorySeparatorChar, PathUtils.AltDirectorySeparatorChar }; #if CLR_2_0 || CLR_4_0 return path.Split(separators, StringSplitOptions.RemoveEmptyEntries); #else string[] trialSplit = path.Split(separators); int emptyEntries = 0; foreach(string piece in trialSplit) if (piece == string.Empty) emptyEntries++; if (emptyEntries == 0) return trialSplit; string[] finalSplit = new string[trialSplit.Length - emptyEntries]; int index = 0; foreach(string piece in trialSplit) if (piece != string.Empty) finalSplit[index++] = piece; return finalSplit; #endif } private static bool PathsEqual(string path1, string path2) { #if CLR_2_0 || CLR_4_0 if (PathUtils.IsWindows()) return path1.Equals(path2, StringComparison.InvariantCultureIgnoreCase); else return path1.Equals(path2, StringComparison.InvariantCulture); #else if (PathUtils.IsWindows()) return path1.ToLower().Equals(path2.ToLower()); else return path1.Equals(path2); #endif } #endregion } }
using System.Diagnostics; namespace Community.CsharpSqlite { using sqlite3_callback = Sqlite3.dxCallback; using sqlite3_stmt = Sqlite3.Vdbe; public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** Main file for the SQLite library. The routines in this file ** implement the programmer interface to the library. Routines in ** other files are for internal use by SQLite and should not be ** accessed by users of the library. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" /* ** Execute SQL code. Return one of the SQLITE_ success/failure ** codes. Also write an error message into memory obtained from ** malloc() and make pzErrMsg point to that message. ** ** If the SQL is a query, then for each row in the query result ** the xCallback() function is called. pArg becomes the first ** argument to xCallback(). If xCallback=NULL then no callback ** is invoked, even for queries. */ //C# Alias static public int exec(sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ int NoCallback, int NoArgs, int NoErrors) { string Errors = ""; return sqlite3_exec(db, zSql, null, null, ref Errors); } static public int exec(sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ int NoErrors) { string Errors = ""; return sqlite3_exec(db, zSql, xCallback, pArg, ref Errors); } static public int exec(sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ ref string pzErrMsg /* Write error messages here */) { return sqlite3_exec(db, zSql, xCallback, pArg, ref pzErrMsg); } //OVERLOADS static public int sqlite3_exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ int NoCallback, int NoArgs, int NoErrors ) { string Errors = ""; return sqlite3_exec(db, zSql, null, null, ref Errors); } static public int sqlite3_exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ int NoErrors ) { string Errors = ""; return sqlite3_exec(db, zSql, xCallback, pArg, ref Errors); } static public int sqlite3_exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ ref string pzErrMsg /* Write error messages here */ ) { int rc = SQLITE_OK; /* Return code */ string zLeftover = ""; /* Tail of unprocessed SQL */ sqlite3_stmt pStmt = null; /* The current SQL statement */ string[] azCols = null; /* Names of result columns */ int nRetry = 0; /* Number of retry attempts */ int callbackIsInit; /* True if callback data is initialized */ if (!sqlite3SafetyCheckOk(db)) return SQLITE_MISUSE_BKPT(); if (zSql == null) zSql = ""; sqlite3_mutex_enter(db.mutex); sqlite3Error(db, SQLITE_OK, 0); while ((rc == SQLITE_OK || (rc == SQLITE_SCHEMA && (++nRetry) < 2)) && zSql != "") { int nCol; string[] azVals = null; pStmt = null; rc = sqlite3_prepare(db, zSql, -1, ref pStmt, ref zLeftover); Debug.Assert(rc == SQLITE_OK || pStmt == null); if (rc != SQLITE_OK) { continue; } if (pStmt == null) { /* this happens for a comment or white-space */ zSql = zLeftover; continue; } callbackIsInit = 0; nCol = sqlite3_column_count(pStmt); while (true) { int i; rc = sqlite3_step(pStmt); /* Invoke the callback function if required */ if (xCallback != null && (SQLITE_ROW == rc || (SQLITE_DONE == rc && callbackIsInit == 0 && (db.flags & SQLITE_NullCallback) != 0))) { if (0 == callbackIsInit) { azCols = new string[nCol];//sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); //if ( azCols == null ) //{ // goto exec_out; //} for (i = 0; i < nCol; i++) { azCols[i] = sqlite3_column_name(pStmt, i); /* sqlite3VdbeSetColName() installs column names as UTF8 ** strings so there is no way for sqlite3_column_name() to fail. */ Debug.Assert(azCols[i] != null); } callbackIsInit = 1; } if (rc == SQLITE_ROW) { azVals = new string[nCol];// azCols[nCol]; for (i = 0; i < nCol; i++) { azVals[i] = sqlite3_column_text(pStmt, i); if (azVals[i] == null && sqlite3_column_type(pStmt, i) != SQLITE_NULL) { //db.mallocFailed = 1; //goto exec_out; } } } if (xCallback(pArg, nCol, azVals, azCols) != 0) { rc = SQLITE_ABORT; sqlite3VdbeFinalize(ref pStmt); pStmt = null; sqlite3Error(db, SQLITE_ABORT, 0); goto exec_out; } } if (rc != SQLITE_ROW) { rc = sqlite3VdbeFinalize(ref pStmt); pStmt = null; if (rc != SQLITE_SCHEMA) { nRetry = 0; if ((zSql = zLeftover) != "") { int zindex = 0; while (zindex < zSql.Length && sqlite3Isspace(zSql[zindex])) zindex++; if (zindex != 0) zSql = zindex < zSql.Length ? zSql.Substring(zindex) : ""; } } break; } } sqlite3DbFree(db, ref azCols); azCols = null; } exec_out: if (pStmt != null) sqlite3VdbeFinalize(ref pStmt); sqlite3DbFree(db, ref azCols); rc = sqlite3ApiExit(db, rc); if (rc != SQLITE_OK && ALWAYS(rc == sqlite3_errcode(db)) && pzErrMsg != null) { //int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db)); //pzErrMsg = sqlite3Malloc(nErrMsg); //if (pzErrMsg) //{ // memcpy(pzErrMsg, sqlite3_errmsg(db), nErrMsg); //}else{ //rc = SQLITE_NOMEM; //sqlite3Error(db, SQLITE_NOMEM, 0); //} pzErrMsg = sqlite3_errmsg(db); } else if (pzErrMsg != "") { pzErrMsg = ""; } Debug.Assert((rc & db.errMask) == rc); sqlite3_mutex_leave(db.mutex); return rc; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { using System.Text; using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Globalization; // TimeSpan represents a duration of time. A TimeSpan can be negative // or positive. // // TimeSpan is internally represented as a number of milliseconds. While // this maps well into units of time such as hours and days, any // periods longer than that aren't representable in a nice fashion. // For instance, a month can be between 28 and 31 days, while a year // can contain 365 or 364 days. A decade can have between 1 and 3 leapyears, // depending on when you map the TimeSpan into the calendar. This is why // we do not provide Years() or Months(). // // Note: System.TimeSpan needs to interop with the WinRT structure // type Windows::Foundation:TimeSpan. These types are currently binary-compatible in // memory so no custom marshalling is required. If at any point the implementation // details of this type should change, or new fields added, we need to remember to add // an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public struct TimeSpan : IComparable #if GENERICS_WORK , IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable #endif { public const long TicksPerMillisecond = 10000; private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond; public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000 private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001 public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000 private const double MinutesPerTick = 1.0 / TicksPerMinute; // 1.6666666666667e-9 public const long TicksPerHour = TicksPerMinute * 60; // 36,000,000,000 private const double HoursPerTick = 1.0 / TicksPerHour; // 2.77777777777777778e-11 public const long TicksPerDay = TicksPerHour * 24; // 864,000,000,000 private const double DaysPerTick = 1.0 / TicksPerDay; // 1.1574074074074074074e-12 private const int MillisPerSecond = 1000; private const int MillisPerMinute = MillisPerSecond * 60; // 60,000 private const int MillisPerHour = MillisPerMinute * 60; // 3,600,000 private const int MillisPerDay = MillisPerHour * 24; // 86,400,000 internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond; internal const long MinSeconds = Int64.MinValue / TicksPerSecond; internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond; internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond; internal const long TicksPerTenthSecond = TicksPerMillisecond * 100; public static readonly TimeSpan Zero = new TimeSpan(0); public static readonly TimeSpan MaxValue = new TimeSpan(Int64.MaxValue); public static readonly TimeSpan MinValue = new TimeSpan(Int64.MinValue); // internal so that DateTime doesn't have to call an extra get // method for some arithmetic operations. internal long _ticks; //public TimeSpan() { // _ticks = 0; //} public TimeSpan(long ticks) { this._ticks = ticks; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public TimeSpan(int hours, int minutes, int seconds) { _ticks = TimeToTicks(hours, minutes, seconds); } public TimeSpan(int days, int hours, int minutes, int seconds) : this(days,hours,minutes,seconds,0) { } public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds; if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds) throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong")); _ticks = (long)totalMilliSeconds * TicksPerMillisecond; } public long Ticks { get { return _ticks; } } public int Days { get { return (int)(_ticks / TicksPerDay); } } public int Hours { get { return (int)((_ticks / TicksPerHour) % 24); } } public int Milliseconds { get { return (int)((_ticks / TicksPerMillisecond) % 1000); } } public int Minutes { get { return (int)((_ticks / TicksPerMinute) % 60); } } public int Seconds { get { return (int)((_ticks / TicksPerSecond) % 60); } } public double TotalDays { get { return ((double)_ticks) * DaysPerTick; } } public double TotalHours { get { return (double)_ticks * HoursPerTick; } } public double TotalMilliseconds { get { double temp = (double)_ticks * MillisecondsPerTick; if (temp > MaxMilliSeconds) return (double)MaxMilliSeconds; if (temp < MinMilliSeconds) return (double)MinMilliSeconds; return temp; } } public double TotalMinutes { get { return (double)_ticks * MinutesPerTick; } } public double TotalSeconds { #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif get { return (double)_ticks * SecondsPerTick; } } public TimeSpan Add(TimeSpan ts) { long result = _ticks + ts._ticks; // Overflow if signs of operands was identical and result's // sign was opposite. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63)) throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong")); return new TimeSpan(result); } // Compares two TimeSpan values, returning an integer that indicates their // relationship. // public static int Compare(TimeSpan t1, TimeSpan t2) { if (t1._ticks > t2._ticks) return 1; if (t1._ticks < t2._ticks) return -1; return 0; } // Returns a value less than zero if this object public int CompareTo(Object value) { if (value == null) return 1; if (!(value is TimeSpan)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTimeSpan")); long t = ((TimeSpan)value)._ticks; if (_ticks > t) return 1; if (_ticks < t) return -1; return 0; } #if GENERICS_WORK public int CompareTo(TimeSpan value) { long t = value._ticks; if (_ticks > t) return 1; if (_ticks < t) return -1; return 0; } #endif public static TimeSpan FromDays(double value) { return Interval(value, MillisPerDay); } public TimeSpan Duration() { if (Ticks==TimeSpan.MinValue.Ticks) throw new OverflowException(Environment.GetResourceString("Overflow_Duration")); Contract.EndContractBlock(); return new TimeSpan(_ticks >= 0? _ticks: -_ticks); } public override bool Equals(Object value) { if (value is TimeSpan) { return _ticks == ((TimeSpan)value)._ticks; } return false; } public bool Equals(TimeSpan obj) { return _ticks == obj._ticks; } public static bool Equals(TimeSpan t1, TimeSpan t2) { return t1._ticks == t2._ticks; } public override int GetHashCode() { return (int)_ticks ^ (int)(_ticks >> 32); } public static TimeSpan FromHours(double value) { return Interval(value, MillisPerHour); } private static TimeSpan Interval(double value, int scale) { if (Double.IsNaN(value)) throw new ArgumentException(Environment.GetResourceString("Arg_CannotBeNaN")); Contract.EndContractBlock(); double tmp = value * scale; double millis = tmp + (value >= 0? 0.5: -0.5); if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond)) throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong")); return new TimeSpan((long)millis * TicksPerMillisecond); } public static TimeSpan FromMilliseconds(double value) { return Interval(value, 1); } public static TimeSpan FromMinutes(double value) { return Interval(value, MillisPerMinute); } public TimeSpan Negate() { if (Ticks==TimeSpan.MinValue.Ticks) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return new TimeSpan(-_ticks); } public static TimeSpan FromSeconds(double value) { return Interval(value, MillisPerSecond); } public TimeSpan Subtract(TimeSpan ts) { long result = _ticks - ts._ticks; // Overflow if signs of operands was different and result's // sign was opposite from the first argument's sign. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((_ticks >> 63 != ts._ticks >> 63) && (_ticks >> 63 != result >> 63)) throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong")); return new TimeSpan(result); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static TimeSpan FromTicks(long value) { return new TimeSpan(value); } internal static long TimeToTicks(int hour, int minute, int second) { // totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31, // which is less than 2^44, meaning we won't overflow totalSeconds. long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second; if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds) throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong")); return totalSeconds * TicksPerSecond; } // See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat #region ParseAndFormat public static TimeSpan Parse(String s) { /* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */ return TimeSpanParse.Parse(s, null); } public static TimeSpan Parse(String input, IFormatProvider formatProvider) { return TimeSpanParse.Parse(input, formatProvider); } public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider) { return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider) { return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) { TimeSpanParse.ValidateStyles(styles, "styles"); return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) { TimeSpanParse.ValidateStyles(styles, "styles"); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } public static Boolean TryParse(String s, out TimeSpan result) { return TimeSpanParse.TryParse(s, null, out result); } public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result) { return TimeSpanParse.TryParse(input, formatProvider, out result); } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { TimeSpanParse.ValidateStyles(styles, "styles"); return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { TimeSpanParse.ValidateStyles(styles, "styles"); return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); } public override String ToString() { return TimeSpanFormat.Format(this, null, null); } public String ToString(String format) { return TimeSpanFormat.Format(this, format, null); } public String ToString(String format, IFormatProvider formatProvider) { if (LegacyMode) { return TimeSpanFormat.Format(this, null, null); } else { return TimeSpanFormat.Format(this, format, formatProvider); } } #endregion public static TimeSpan operator -(TimeSpan t) { if (t._ticks==TimeSpan.MinValue._ticks) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); return new TimeSpan(-t._ticks); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static TimeSpan operator -(TimeSpan t1, TimeSpan t2) { return t1.Subtract(t2); } public static TimeSpan operator +(TimeSpan t) { return t; } public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) { return t1.Add(t2); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static bool operator ==(TimeSpan t1, TimeSpan t2) { return t1._ticks == t2._ticks; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static bool operator !=(TimeSpan t1, TimeSpan t2) { return t1._ticks != t2._ticks; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static bool operator <(TimeSpan t1, TimeSpan t2) { return t1._ticks < t2._ticks; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static bool operator <=(TimeSpan t1, TimeSpan t2) { return t1._ticks <= t2._ticks; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static bool operator >(TimeSpan t1, TimeSpan t2) { return t1._ticks > t2._ticks; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static bool operator >=(TimeSpan t1, TimeSpan t2) { return t1._ticks >= t2._ticks; } // // In .NET Framework v1.0 - v3.5 System.TimeSpan did not implement IFormattable // The composite formatter ignores format specifiers on types that do not implement // IFormattable, so the following code would 'just work' by using TimeSpan.ToString() // under the hood: // String.Format("{0:_someRandomFormatString_}", myTimeSpan); // // In .NET Framework v4.0 System.TimeSpan implements IFormattable. This causes the // composite formatter to call TimeSpan.ToString(string format, FormatProvider provider) // and pass in "_someRandomFormatString_" for the format parameter. When the format // parameter is invalid a FormatException is thrown. // // The 'NetFx40_TimeSpanLegacyFormatMode' per-AppDomain configuration option and the 'TimeSpan_LegacyFormatMode' // process-wide configuration option allows applications to run with the v1.0 - v3.5 legacy behavior. When // either switch is specified the format parameter is ignored and the default output is returned. // // There are three ways to use the process-wide configuration option: // // 1) Config file (MyApp.exe.config) // <?xml version ="1.0"?> // <configuration> // <runtime> // <TimeSpan_LegacyFormatMode enabled="true"/> // </runtime> // </configuration> // 2) Environment variable // set COMPLUS_TimeSpan_LegacyFormatMode=1 // 3) RegistryKey // [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework] // "TimeSpan_LegacyFormatMode"=dword:00000001 // #if !FEATURE_CORECLR [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool LegacyFormatMode(); #endif // !FEATURE_CORECLR // // In Silverlight v4, specifying the APP_EARLIER_THAN_SL4.0 quirks mode allows applications to // run in v2 - v3 legacy behavior. // #if !FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif private static bool GetLegacyFormatMode() { #if !FEATURE_CORECLR && !MONO if (LegacyFormatMode()) // FCALL to check COMPLUS_TimeSpan_LegacyFormatMode return true; return CompatibilitySwitches.IsNetFx40TimeSpanLegacyFormatMode; #else return CompatibilitySwitches.IsAppEarlierThanSilverlight4; #endif // !FEATURE_CORECLR } private static volatile bool _legacyConfigChecked; private static volatile bool _legacyMode; private static bool LegacyMode { get { if (!_legacyConfigChecked) { // no need to lock - idempotent _legacyMode = GetLegacyFormatMode(); _legacyConfigChecked = true; } return _legacyMode; } } } }
/* * Copyright (c) 2006-2008, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using OpenMetaverse.Packets; using System.Reflection; namespace OpenMetaverse { /// <summary> /// Static helper functions and global variables /// </summary> public static class Helpers { /// <summary>This header flag signals that ACKs are appended to the packet</summary> public const byte MSG_APPENDED_ACKS = 0x10; /// <summary>This header flag signals that this packet has been sent before</summary> public const byte MSG_RESENT = 0x20; /// <summary>This header flags signals that an ACK is expected for this packet</summary> public const byte MSG_RELIABLE = 0x40; /// <summary>This header flag signals that the message is compressed using zerocoding</summary> public const byte MSG_ZEROCODED = 0x80; /// <summary> /// Passed to Logger.Log() to identify the severity of a log entry /// </summary> public enum LogLevel { /// <summary>No logging information will be output</summary> None, /// <summary>Non-noisy useful information, may be helpful in /// debugging a problem</summary> Info, /// <summary>A non-critical error occurred. A warning will not /// prevent the rest of the library from operating as usual, /// although it may be indicative of an underlying issue</summary> Warning, /// <summary>A critical error has occurred. Generally this will /// be followed by the network layer shutting down, although the /// stability of the library after an error is uncertain</summary> Error, /// <summary>Used for internal testing, this logging level can /// generate very noisy (long and/or repetitive) messages. Don't /// pass this to the Log() function, use DebugLog() instead. /// </summary> Debug }; /// <summary> /// /// </summary> /// <param name="offset"></param> /// <returns></returns> public static short TEOffsetShort(float offset) { offset = Utils.Clamp(offset, -1.0f, 1.0f); offset *= 32767.0f; return (short)Math.Round(offset); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <returns></returns> public static float TEOffsetFloat(byte[] bytes, int pos) { float offset = (float)BitConverter.ToInt16(bytes, pos); return offset / 32767.0f; } /// <summary> /// /// </summary> /// <param name="rotation"></param> /// <returns></returns> public static short TERotationShort(float rotation) { const float TWO_PI = 6.283185307179586476925286766559f; return (short)Math.Round(((Math.IEEERemainder(rotation, TWO_PI) / TWO_PI) * 32768.0f) + 0.5f); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="pos"></param> /// <returns></returns> public static float TERotationFloat(byte[] bytes, int pos) { const float TWO_PI = 6.283185307179586476925286766559f; return ((float)(bytes[pos] | (bytes[pos + 1] << 8)) / 32768.0f) * TWO_PI; } public static byte TEGlowByte(float glow) { return (byte)(glow * 255.0f); } public static float TEGlowFloat(byte[] bytes, int pos) { return (float)bytes[pos] / 255.0f; } /// <summary> /// Given an X/Y location in absolute (grid-relative) terms, a region /// handle is returned along with the local X/Y location in that region /// </summary> /// <param name="globalX">The absolute X location, a number such as /// 255360.35</param> /// <param name="globalY">The absolute Y location, a number such as /// 255360.35</param> /// <param name="localX">The sim-local X position of the global X /// position, a value from 0.0 to 256.0</param> /// <param name="localY">The sim-local Y position of the global Y /// position, a value from 0.0 to 256.0</param> /// <returns>A 64-bit region handle that can be used to teleport to</returns> public static ulong GlobalPosToRegionHandle(float globalX, float globalY, out float localX, out float localY) { uint x = ((uint)globalX / 256) * 256; uint y = ((uint)globalY / 256) * 256; localX = globalX - (float)x; localY = globalY - (float)y; return Utils.UIntsToLong(x, y); } /// <summary> /// Converts a floating point number to a terse string format used for /// transmitting numbers in wearable asset files /// </summary> /// <param name="val">Floating point number to convert to a string</param> /// <returns>A terse string representation of the input number</returns> public static string FloatToTerseString(float val) { string s = string.Format(Utils.EnUsCulture, "{0:.00}", val); if (val == 0) return ".00"; // Trim trailing zeroes while (s[s.Length - 1] == '0') s = s.Remove(s.Length - 1, 1); // Remove superfluous decimal places after the trim if (s[s.Length - 1] == '.') s = s.Remove(s.Length - 1, 1); // Remove leading zeroes after a negative sign else if (s[0] == '-' && s[1] == '0') s = s.Remove(1, 1); // Remove leading zeroes in positive numbers else if (s[0] == '0') s = s.Remove(0, 1); return s; } /// <summary> /// Convert a variable length field (byte array) to a string, with a /// field name prepended to each line of the output /// </summary> /// <remarks>If the byte array has unprintable characters in it, a /// hex dump will be written instead</remarks> /// <param name="output">The StringBuilder object to write to</param> /// <param name="bytes">The byte array to convert to a string</param> /// <param name="fieldName">A field name to prepend to each line of output</param> internal static void FieldToString(StringBuilder output, byte[] bytes, string fieldName) { // Check for a common case if (bytes.Length == 0) return; bool printable = true; for (int i = 0; i < bytes.Length; ++i) { // Check if there are any unprintable characters in the array if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09 && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00) { printable = false; break; } } if (printable) { if (fieldName.Length > 0) { output.Append(fieldName); output.Append(": "); } if (bytes[bytes.Length - 1] == 0x00) output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1)); else output.Append(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length)); } else { for (int i = 0; i < bytes.Length; i += 16) { if (i != 0) output.Append('\n'); if (fieldName.Length > 0) { output.Append(fieldName); output.Append(": "); } for (int j = 0; j < 16; j++) { if ((i + j) < bytes.Length) output.Append(String.Format("{0:X2} ", bytes[i + j])); else output.Append(" "); } } } } /// <summary> /// Decode a zerocoded byte array, used to decompress packets marked /// with the zerocoded flag /// </summary> /// <remarks>Any time a zero is encountered, the next byte is a count /// of how many zeroes to expand. One zero is encoded with 0x00 0x01, /// two zeroes is 0x00 0x02, three zeroes is 0x00 0x03, etc. The /// first four bytes are copied directly to the output buffer. /// </remarks> /// <param name="src">The byte array to decode</param> /// <param name="srclen">The length of the byte array to decode. This /// would be the length of the packet up to (but not including) any /// appended ACKs</param> /// <param name="dest">The output byte array to decode to</param> /// <returns>The length of the output buffer</returns> public static int ZeroDecode(byte[] src, int srclen, byte[] dest) { if (srclen > src.Length) throw new ArgumentException("srclen cannot be greater than src.Length"); uint zerolen = 0; int bodylen = 0; uint i = 0; try { Buffer.BlockCopy(src, 0, dest, 0, 6); zerolen = 6; bodylen = srclen; for (i = zerolen; i < bodylen; i++) { if (src[i] == 0x00) { for (byte j = 0; j < src[i + 1]; j++) { dest[zerolen++] = 0x00; } i++; } else { dest[zerolen++] = src[i]; } } // Copy appended ACKs for (; i < srclen; i++) { dest[zerolen++] = src[i]; } return (int)zerolen; } catch (Exception ex) { Logger.Log(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}\n{5}", i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null), ex), LogLevel.Error); throw new IndexOutOfRangeException(String.Format("Zerodecoding error: i={0}, srclen={1}, bodylen={2}, zerolen={3}\n{4}\n{5}", i, srclen, bodylen, zerolen, Utils.BytesToHexString(src, srclen, null), ex.InnerException)); } } /// <summary> /// Encode a byte array with zerocoding. Used to compress packets marked /// with the zerocoded flag. Any zeroes in the array are compressed down /// to a single zero byte followed by a count of how many zeroes to expand /// out. A single zero becomes 0x00 0x01, two zeroes becomes 0x00 0x02, /// three zeroes becomes 0x00 0x03, etc. The first four bytes are copied /// directly to the output buffer. /// </summary> /// <param name="src">The byte array to encode</param> /// <param name="srclen">The length of the byte array to encode</param> /// <param name="dest">The output byte array to encode to</param> /// <returns>The length of the output buffer</returns> public static int ZeroEncode(byte[] src, int srclen, byte[] dest) { uint zerolen = 0; byte zerocount = 0; Buffer.BlockCopy(src, 0, dest, 0, 6); zerolen += 6; int bodylen; if ((src[0] & MSG_APPENDED_ACKS) == 0) { bodylen = srclen; } else { bodylen = srclen - src[srclen - 1] * 4 - 1; } uint i; for (i = zerolen; i < bodylen; i++) { if (src[i] == 0x00) { zerocount++; if (zerocount == 0) { dest[zerolen++] = 0x00; dest[zerolen++] = 0xff; zerocount++; } } else { if (zerocount != 0) { dest[zerolen++] = 0x00; dest[zerolen++] = (byte)zerocount; zerocount = 0; } dest[zerolen++] = src[i]; } } if (zerocount != 0) { dest[zerolen++] = 0x00; dest[zerolen++] = (byte)zerocount; } // copy appended ACKs for (; i < srclen; i++) { dest[zerolen++] = src[i]; } return (int)zerolen; } /// <summary> /// Calculates the CRC (cyclic redundancy check) needed to upload inventory. /// </summary> /// <param name="creationDate">Creation date</param> /// <param name="saleType">Sale type</param> /// <param name="invType">Inventory type</param> /// <param name="type">Type</param> /// <param name="assetID">Asset ID</param> /// <param name="groupID">Group ID</param> /// <param name="salePrice">Sale price</param> /// <param name="ownerID">Owner ID</param> /// <param name="creatorID">Creator ID</param> /// <param name="itemID">Item ID</param> /// <param name="folderID">Folder ID</param> /// <param name="everyoneMask">Everyone mask (permissions)</param> /// <param name="flags">Flags</param> /// <param name="nextOwnerMask">Next owner mask (permissions)</param> /// <param name="groupMask">Group mask (permissions)</param> /// <param name="ownerMask">Owner mask (permissions)</param> /// <returns>The calculated CRC</returns> public static uint InventoryCRC(int creationDate, byte saleType, sbyte invType, sbyte type, UUID assetID, UUID groupID, int salePrice, UUID ownerID, UUID creatorID, UUID itemID, UUID folderID, uint everyoneMask, uint flags, uint nextOwnerMask, uint groupMask, uint ownerMask) { uint CRC = 0; // IDs CRC += assetID.CRC(); // AssetID CRC += folderID.CRC(); // FolderID CRC += itemID.CRC(); // ItemID // Permission stuff CRC += creatorID.CRC(); // CreatorID CRC += ownerID.CRC(); // OwnerID CRC += groupID.CRC(); // GroupID // CRC += another 4 words which always seem to be zero -- unclear if this is a UUID or what CRC += ownerMask; CRC += nextOwnerMask; CRC += everyoneMask; CRC += groupMask; // The rest of the CRC fields CRC += flags; // Flags CRC += (uint)invType; // InvType CRC += (uint)type; // Type CRC += (uint)creationDate; // CreationDate CRC += (uint)salePrice; // SalePrice CRC += (uint)((uint)saleType * 0x07073096); // SaleType return CRC; } /// <summary> /// Attempts to load a file embedded in the assembly /// </summary> /// <param name="resourceName">The filename of the resource to load</param> /// <returns>A Stream for the requested file, or null if the resource /// was not successfully loaded</returns> public static System.IO.Stream GetResourceStream(string resourceName) { return GetResourceStream(resourceName, "openmetaverse_data"); } /// <summary> /// Attempts to load a file either embedded in the assembly or found in /// a given search path /// </summary> /// <param name="resourceName">The filename of the resource to load</param> /// <param name="searchPath">An optional path that will be searched if /// the asset is not found embedded in the assembly</param> /// <returns>A Stream for the requested file, or null if the resource /// was not successfully loaded</returns> public static System.IO.Stream GetResourceStream(string resourceName, string searchPath) { if (searchPath != null) { Assembly gea = Assembly.GetEntryAssembly(); if (gea == null) gea = typeof (Helpers).Assembly; string dirname = "."; if (gea != null && gea.Location != null) { dirname = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(gea.Location), searchPath); } string filename = System.IO.Path.Combine(dirname, resourceName); try { return new System.IO.FileStream( filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); } catch (Exception ex) { Logger.Log(string.Format("Failed opening resource from file {0}: {1}", filename, ex.Message), LogLevel.Error); } } else { try { System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); System.IO.Stream s = a.GetManifestResourceStream("OpenMetaverse.Resources." + resourceName); if (s != null) return s; } catch (Exception ex) { Logger.Log(string.Format("Failed opening resource stream: {0}", ex.Message), LogLevel.Error); } } return null; } /// <summary> /// Converts a list of primitives to an object that can be serialized /// with the LLSD system /// </summary> /// <param name="prims">Primitives to convert to a serializable object</param> /// <returns>An object that can be serialized with LLSD</returns> public static StructuredData.OSD PrimListToOSD(List<Primitive> prims) { StructuredData.OSDMap map = new OpenMetaverse.StructuredData.OSDMap(prims.Count); for (int i = 0; i < prims.Count; i++) map.Add(prims[i].LocalID.ToString(), prims[i].GetOSD()); return map; } /// <summary> /// Deserializes OSD in to a list of primitives /// </summary> /// <param name="osd">Structure holding the serialized primitive list, /// must be of the SDMap type</param> /// <returns>A list of deserialized primitives</returns> public static List<Primitive> OSDToPrimList(StructuredData.OSD osd) { if (osd.Type != StructuredData.OSDType.Map) throw new ArgumentException("LLSD must be in the Map structure"); StructuredData.OSDMap map = (StructuredData.OSDMap)osd; List<Primitive> prims = new List<Primitive>(map.Count); foreach (KeyValuePair<string, StructuredData.OSD> kvp in map) { Primitive prim = Primitive.FromOSD(kvp.Value); prim.LocalID = UInt32.Parse(kvp.Key); prims.Add(prim); } return prims; } /// <summary> /// Converts a struct or class object containing fields only into a key value separated string /// </summary> /// <param name="t">The struct object</param> /// <returns>A string containing the struct fields as the keys, and the field value as the value separated</returns> /// <example> /// <code> /// // Add the following code to any struct or class containing only fields to override the ToString() /// // method to display the values of the passed object /// /// /// <summary>Print the struct data as a string</summary> /// ///<returns>A string containing the field name, and field value</returns> ///public override string ToString() ///{ /// return Helpers.StructToString(this); ///} /// </code> /// </example> public static string StructToString(object t) { StringBuilder result = new StringBuilder(); Type structType = t.GetType(); FieldInfo[] fields = structType.GetFields(); foreach (FieldInfo field in fields) { result.Append(field.Name + ": " + field.GetValue(t) + " "); } result.AppendLine(); return result.ToString().TrimEnd(); } } }
#region Namespaces using System; using System.Collections.Generic; using System.Linq; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Architecture; using Autodesk.Revit.UI; using System.Text; #endregion namespace SpatialElementGeometryCalculator { [Transaction( TransactionMode.Manual )] public class Command : IExternalCommand { public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication uiapp = commandData.Application; Document doc = uiapp.ActiveUIDocument.Document; Result rc; try { SpatialElementBoundaryOptions sebOptions = new SpatialElementBoundaryOptions { SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.Finish }; IEnumerable<Element> rooms = new FilteredElementCollector( doc ) .OfClass( typeof( SpatialElement ) ) .Where<Element>( e => ( e is Room ) ); List<string> compareWallAndRoom = new List<string>(); OpeningHandler openingHandler = new OpeningHandler(); List<SpatialBoundaryCache> lstSpatialBoundaryCache = new List<SpatialBoundaryCache>(); foreach( Room room in rooms ) { if( room == null ) continue; if( room.Location == null ) continue; if( room.Area.Equals( 0 ) ) continue; Autodesk.Revit.DB.SpatialElementGeometryCalculator calc = new Autodesk.Revit.DB.SpatialElementGeometryCalculator( doc, sebOptions ); SpatialElementGeometryResults results = calc.CalculateSpatialElementGeometry( room ); Solid roomSolid = results.GetGeometry(); foreach( Face face in results.GetGeometry().Faces ) { IList<SpatialElementBoundarySubface> boundaryFaceInfo = results.GetBoundaryFaceInfo( face ); foreach( var spatialSubFace in boundaryFaceInfo ) { if( spatialSubFace.SubfaceType != SubfaceType.Side ) { continue; } SpatialBoundaryCache spatialData = new SpatialBoundaryCache(); Wall wall = doc.GetElement( spatialSubFace .SpatialBoundaryElement.HostElementId ) as Wall; if( wall == null ) { continue; } WallType wallType = doc.GetElement( wall.GetTypeId() ) as WallType; if( wallType.Kind == WallKind.Curtain ) { // Leave out, as curtain walls are not painted. LogCreator.LogEntry( "WallType is CurtainWall" ); continue; } HostObject hostObject = wall as HostObject; IList<ElementId> insertsThisHost = hostObject.FindInserts( true, false, true, true ); double openingArea = 0; foreach( ElementId idInsert in insertsThisHost ) { string countOnce = room.Id.ToString() + wall.Id.ToString() + idInsert.ToString(); if( !compareWallAndRoom.Contains( countOnce ) ) { Element elemOpening = doc.GetElement( idInsert ) as Element; openingArea = openingArea + openingHandler.GetOpeningArea( wall, elemOpening, room, roomSolid ); compareWallAndRoom.Add( countOnce ); } } // Cache SpatialElementBoundarySubface info. spatialData.roomName = room.Name; spatialData.idElement = wall.Id; spatialData.idMaterial = spatialSubFace .GetBoundingElementFace().MaterialElementId; spatialData.dblNetArea = Util.sqFootToSquareM( spatialSubFace.GetSubface().Area - openingArea ); spatialData.dblOpeningArea = Util.sqFootToSquareM( openingArea ); lstSpatialBoundaryCache.Add( spatialData ); } // end foreach subface from which room bounding elements are derived } // end foreach Face } // end foreach Room List<string> t = new List<string>(); List<SpatialBoundaryCache> groupedData = SortByRoom( lstSpatialBoundaryCache ); foreach( SpatialBoundaryCache sbc in groupedData ) { t.Add( sbc.roomName + "; all wall types and materials: " + sbc.AreaReport ); } Util.InfoMsg2( "Total Net Area in m2 by Room", string.Join( System.Environment.NewLine, t ) ); t.Clear(); groupedData = SortByRoomAndWallType( lstSpatialBoundaryCache ); foreach( SpatialBoundaryCache sbc in groupedData ) { Element elemWall = doc.GetElement( sbc.idElement ) as Element; t.Add( sbc.roomName + "; " + elemWall.Name + "(" + sbc.idElement.ToString() + "): " + sbc.AreaReport ); } Util.InfoMsg2( "Net Area in m2 by Wall Type", string.Join( System.Environment.NewLine, t ) ); t.Clear(); groupedData = SortByRoomAndMaterial( lstSpatialBoundaryCache ); foreach( SpatialBoundaryCache sbc in groupedData ) { string materialName = ( sbc.idMaterial == ElementId.InvalidElementId ) ? string.Empty : doc.GetElement( sbc.idMaterial ).Name; t.Add( sbc.roomName + "; " + materialName + ": " + sbc.AreaReport ); } Util.InfoMsg2( "Net Area in m2 by Outer Layer Material", string.Join( System.Environment.NewLine, t ) ); rc = Result.Succeeded; } catch( Exception ex ) { TaskDialog.Show( "Room Boundaries", ex.Message + "\r\n" + ex.StackTrace ); rc = Result.Failed; } return rc; } /// <summary> /// Convert square feet to square meters /// with two decimal places precision. /// </summary> static double SqFootToSquareM( double sqFoot ) { return Math.Round( sqFoot * 0.092903, 2 ); } List<SpatialBoundaryCache> SortByRoom( List<SpatialBoundaryCache> lstRawData ) { var sortedCache = from rawData in lstRawData group rawData by new { room = rawData.roomName } into sortedData select new SpatialBoundaryCache() { roomName = sortedData.Key.room, idElement = ElementId.InvalidElementId, dblNetArea = sortedData.Sum( x => x.dblNetArea ), dblOpeningArea = sortedData.Sum( y => y.dblOpeningArea ), }; return sortedCache.ToList(); } List<SpatialBoundaryCache> SortByRoomAndWallType( List<SpatialBoundaryCache> lstRawData ) { var sortedCache = from rawData in lstRawData group rawData by new { room = rawData.roomName, wallid = rawData.idElement } into sortedData select new SpatialBoundaryCache() { roomName = sortedData.Key.room, idElement = sortedData.Key.wallid, dblNetArea = sortedData.Sum( x => x.dblNetArea ), dblOpeningArea = sortedData.Sum( y => y.dblOpeningArea ), }; return sortedCache.ToList(); } List<SpatialBoundaryCache> SortByRoomAndMaterial( List<SpatialBoundaryCache> lstRawData ) { var sortedCache = from rawData in lstRawData group rawData by new { room = rawData.roomName, mid = rawData.idMaterial } into sortedData select new SpatialBoundaryCache() { roomName = sortedData.Key.room, idMaterial = sortedData.Key.mid, dblNetArea = sortedData.Sum( x => x.dblNetArea ), dblOpeningArea = sortedData.Sum( y => y.dblOpeningArea ), }; return sortedCache.ToList(); } /// <summary> /// Return wall openings using GetDependentElements /// </summary> static IList<ElementId> GetOpenings( Wall wall ) { ElementMulticategoryFilter emcf = new ElementMulticategoryFilter( new List<ElementId>() { new ElementId(BuiltInCategory.OST_Windows), new ElementId(BuiltInCategory.OST_Doors) } ); return wall.GetDependentElements( emcf ); } } }
using System.Collections.Specialized; using System.Globalization; using Skybrud.Social.Twitter.Attributes; using Skybrud.Social.Twitter.Enums; using Skybrud.Social.Twitter.OAuth; using Skybrud.Social.Twitter.Options; namespace Skybrud.Social.Twitter.Endpoints.Raw { public class TwitterStatusesRawEndpoint { public TwitterOAuthClient Client { get; private set; } internal TwitterStatusesRawEndpoint(TwitterOAuthClient client) { Client = client; } #region Get information about a single tweet /// <summary> /// Alias of GetStatusMessage(). Gets the raw API response for a status message (tweet) with the specified ID. /// </summary> /// <param name="id">The ID of the status message.</param> /// <see cref="https://dev.twitter.com/docs/api/1.1/get/statuses/show/:id"/> [TwitterMethod(rateLimited: true, rate: "180/user, 180/app", authentication: TwitterAuthentication.Required)] public string GetTweet(long id) { return GetStatusMessage(id, null); } /// <summary> /// Alias of GetStatusMessage(). Gets the raw API response for a status message (tweet) with the specified ID. /// </summary> /// <param name="id">The ID of the status message.</param> /// <param name="options">The options used when making the call to the API.</param> /// <see cref="https://dev.twitter.com/docs/api/1.1/get/statuses/show/:id"/> [TwitterMethod(rateLimited: true, rate: "180/user, 180/app", authentication: TwitterAuthentication.Required)] public string GetTweet(long id, TwitterStatusMessageOptions options) { return GetStatusMessage(id, options); } /// <summary> /// Gets the raw API response for a status message (tweet) with the specified ID. /// </summary> /// <param name="id">The ID of the status message.</param> /// <see cref="https://dev.twitter.com/docs/api/1.1/get/statuses/show/:id"/> [TwitterMethod(rateLimited: true, rate: "180/user, 180/app", authentication: TwitterAuthentication.Required)] public string GetStatusMessage(long id) { return GetStatusMessage(id, null); } /// <summary> /// Gets the raw API response for a status message (tweet) with the specified ID. /// </summary> /// <param name="id">The ID of the status message.</param> /// <param name="options">The options used when making the call to the API.</param> /// <see cref="https://dev.twitter.com/docs/api/1.1/get/statuses/show/:id"/> [TwitterMethod(rateLimited: true, rate: "180/user, 180/app", authentication: TwitterAuthentication.Required)] public string GetStatusMessage(long id, TwitterStatusMessageOptions options) { // Define the query string NameValueCollection qs = new NameValueCollection { { "id", id.ToString(CultureInfo.InvariantCulture) } }; if (options != null) { if (options.TrimUser) qs.Add("trim_user", "true"); if (options.IncludeMyRetweet) qs.Add("include_my_retweet", "true"); if (options.IncludeEntities) qs.Add("include_entities", "true"); } // Make the call to the API return Client.DoHttpRequestAsString("GET", "https://api.twitter.com/1.1/statuses/show.json", qs); } #endregion #region Gets the timeline for a specific user /// <summary> /// Get the raw API response for a user's timeline. /// </summary> /// <param name="userId">The ID of the user.</param> /// <see cref="https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline"/> /// <returns></returns> [TwitterMethod(rateLimited: true, rate: "180/user, 300/app", authentication: TwitterAuthentication.Required)] public string GetUserTimeline(long userId) { return GetUserTimeline(userId, null); } /// <summary> /// Get the raw API response for a user's timeline. /// </summary> /// <param name="userId">The ID of the user.</param> /// <param name="options">The options used when making the call to the API.</param> /// <see cref="https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline"/> /// <returns></returns> [TwitterMethod(rateLimited: true, rate: "180/user, 300/app", authentication: TwitterAuthentication.Required)] public string GetUserTimeline(long userId, TwitterTimelineOptions options) { // Define the query string NameValueCollection qs = new NameValueCollection { { "user_id", userId + "" } }; // Add optional parameters if (options != null) { if (options.SinceId > 0) qs.Add("since_id", options.SinceId + ""); if (options.Count > 0) qs.Add("count", options.Count + ""); if (options.MaxId > 0) qs.Add("max_id", options.MaxId + ""); if (options.TrimUser) qs.Add("trim_user", "true"); if (options.ExcludeReplies) qs.Add("exclude_replies", "true"); if (options.ContributorDetails) qs.Add("contributor_details", "true"); if (!options.IncludeRetweets) qs.Add("include_rts", "false"); } // Make the call to the API return Client.DoHttpRequestAsString("GET", "https://api.twitter.com/1.1/statuses/user_timeline.json", qs); } /// <summary> /// Get the raw API response for a user's timeline. /// </summary> /// <param name="screenName">The screen name of the user.</param> /// <see cref="https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline"/> /// <returns></returns> [TwitterMethod(rateLimited: true, rate: "180/user, 300/app", authentication: TwitterAuthentication.Required)] public string GetUserTimeline(string screenName) { return GetUserTimeline(screenName, null); } /// <summary> /// Get the raw API response for a user's timeline. /// </summary> /// <param name="screenName">The screen name of the user.</param> /// <param name="options">The options used when making the call to the API.</param> /// <see cref="https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline"/> /// <returns></returns> [TwitterMethod(rateLimited: true, rate: "180/user, 300/app", authentication: TwitterAuthentication.Required)] public string GetUserTimeline(string screenName, TwitterTimelineOptions options) { // Define the query string NameValueCollection qs = new NameValueCollection { { "screen_name", screenName } }; // Add optional parameters if (options != null) { if (options.SinceId > 0) qs.Add("since_id", options.SinceId + ""); if (options.Count > 0) qs.Add("count", options.Count + ""); if (options.MaxId > 0) qs.Add("max_id", options.MaxId + ""); if (options.TrimUser) qs.Add("trim_user", "true"); if (options.ExcludeReplies) qs.Add("exclude_replies", "true"); if (options.ContributorDetails) qs.Add("contributor_details", "true"); if (!options.IncludeRetweets) qs.Add("include_rts", "false"); } // Make the call to the API return Client.DoHttpRequestAsString("GET", "https://api.twitter.com/1.1/statuses/user_timeline.json", qs); } #endregion #region GetHomeTimeline(...) /// <summary> /// Gets a collection of the most recent Tweets and retweets posted by the authenticating /// user and the users they follow. /// </summary> public string GetHomeTimeline() { return GetHomeTimeline(null); } /// <summary> /// Gets a collection of the most recent Tweets and retweets posted by the authenticating /// user and the users they follow. /// </summary> /// <param name="options">The options for the call.</param> public string GetHomeTimeline(TwitterTimelineOptions options) { // Initialize the query string NameValueCollection qs = new NameValueCollection(); // Add optional parameters if (options != null) { if (options.SinceId > 0) qs.Add("since_id", options.SinceId + ""); if (options.Count > 0) qs.Add("count", options.Count + ""); if (options.MaxId > 0) qs.Add("max_id", options.MaxId + ""); if (options.TrimUser) qs.Add("trim_user", "true"); if (options.ExcludeReplies) qs.Add("exclude_replies", "true"); if (options.ContributorDetails) qs.Add("contributor_details", "true"); } // Make the call to the API return Client.DoHttpRequestAsString("GET", "https://api.twitter.com/1.1/statuses/home_timeline.json", qs); } #endregion #region GetMentionsTimeline(...) /// <summary> /// Gets a collection of the most recent Tweets and retweets posted by the authenticating user and the users they follow. /// </summary> public string GetMentionsTimeline() { return GetMentionsTimeline(null); } /// <summary> /// Gets the most recent mentions (tweets containing a users's @screen_name) for the authenticating user. /// </summary> /// <param name="options">The options for the call.</param> public string GetMentionsTimeline(TwitterTimelineOptions options) { // Initialize the query string NameValueCollection qs = new NameValueCollection(); // Add optional parameters if (options != null) { if (options.SinceId > 0) qs.Add("since_id", options.SinceId + ""); if (options.Count > 0) qs.Add("count", options.Count + ""); if (options.MaxId > 0) qs.Add("max_id", options.MaxId + ""); if (options.TrimUser) qs.Add("trim_user", "true"); if (options.ExcludeReplies) qs.Add("exclude_replies", "true"); if (options.ContributorDetails) qs.Add("contributor_details", "true"); } // Make the call to the API return Client.DoHttpRequestAsString("GET", "https://api.twitter.com/1.1/statuses/mentions_timeline.json", qs); } #endregion #region GetRetweetsOfMe(...) /// <summary> /// Returns the most recent tweets authored by the authenticating user that have been retweeted by others. /// </summary> public string GetRetweetsOfMe() { return GetRetweetsOfMe(null); } /// <summary> /// Returns the most recent tweets authored by the authenticating user that have been retweeted by others. /// </summary> /// <param name="options">The options for the call.</param> public string GetRetweetsOfMe(TwitterTimelineOptions options) { // Initialize the query string NameValueCollection qs = new NameValueCollection(); // Add optional parameters if (options != null) { if (options.SinceId > 0) qs.Add("since_id", options.SinceId + ""); if (options.Count > 0) qs.Add("count", options.Count + ""); if (options.MaxId > 0) qs.Add("max_id", options.MaxId + ""); if (options.TrimUser) qs.Add("trim_user", "true"); if (options.ExcludeReplies) qs.Add("exclude_replies", "true"); if (options.ContributorDetails) qs.Add("contributor_details", "true"); } // Make the call to the API return Client.DoHttpRequestAsString("GET", "https://api.twitter.com/1.1/statuses/retweets_of_me.json", qs); } #endregion #region PostStatusMessage(...) /// <summary> /// Posts the specified status message. /// </summary> /// <param name="status">The status message to send.</param> public string PostStatusMessage(string status) { return PostStatusMessage(status, null); } /// <summary> /// Posts the specified status message. /// </summary> /// <param name="status">The status message to send.</param> /// <param name="replyTo">The ID of the status message to reply to.</param> public string PostStatusMessage(string status, long? replyTo) { // Construct the POST data NameValueCollection postData = new NameValueCollection {{"status", status}}; if (replyTo != null) postData.Add("in_reply_to_status_id", replyTo.ToString()); // Make the call to the API return Client.DoHttpRequestAsString("POST", "https://api.twitter.com/1.1/statuses/update.json", null, postData); } #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Threading.Tasks; using Erwine.Leonard.T.GDIPlus.Palette.ColorCaches.Common; using Erwine.Leonard.T.GDIPlus.Palette.Ditherers; using Erwine.Leonard.T.GDIPlus.Palette.Extensions; using Erwine.Leonard.T.GDIPlus.Palette.PathProviders; using Erwine.Leonard.T.GDIPlus.Palette.Quantizers; namespace Erwine.Leonard.T.GDIPlus.Palette.Helpers { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public class ImageBuffer : IDisposable { #region | Fields | private Int32[] fastBitX; private Int32[] fastByteX; private Int32[] fastY; private readonly Bitmap bitmap; private readonly BitmapData bitmapData; private readonly ImageLockMode lockMode; private List<Color> cachedPalette; #endregion #region | Delegates | public delegate Boolean ProcessPixelFunction(Pixel pixel); public delegate Boolean ProcessPixelAdvancedFunction(Pixel pixel, ImageBuffer buffer); public delegate Boolean TransformPixelFunction(Pixel sourcePixel, Pixel targetPixel); public delegate Boolean TransformPixelAdvancedFunction(Pixel sourcePixel, Pixel targetPixel, ImageBuffer sourceBuffer, ImageBuffer targetBuffer); #endregion #region | Properties | public Int32 Width { get; private set; } public Int32 Height { get; private set; } public Int32 Size { get; private set; } public Int32 Stride { get; private set; } public Int32 BitDepth { get; private set; } public Int32 BytesPerPixel { get; private set; } public Boolean IsIndexed { get; private set; } public PixelFormat PixelFormat { get; private set; } #endregion #region | Calculated properties | /// <summary> /// Gets a value indicating whether this buffer can be read. /// </summary> /// <value> /// <c>true</c> if this instance can read; otherwise, <c>false</c>. /// </value> public Boolean CanRead { get { return lockMode == ImageLockMode.ReadOnly || lockMode == ImageLockMode.ReadWrite; } } /// <summary> /// Gets a value indicating whether this buffer can written to. /// </summary> /// <value> /// <c>true</c> if this instance can write; otherwise, <c>false</c>. /// </value> public Boolean CanWrite { get { return lockMode == ImageLockMode.WriteOnly || lockMode == ImageLockMode.ReadWrite; } } /// <summary> /// Gets or sets the palette. /// </summary> public List<Color> Palette { get { return UpdatePalette(); } set { bitmap.SetPalette(value); cachedPalette = value; } } #endregion #region | Constructors | /// <summary> /// Initializes a new instance of the <see cref="ImageBuffer"/> class. /// </summary> public ImageBuffer(Image bitmap, ImageLockMode lockMode) : this((Bitmap) bitmap, lockMode) { } /// <summary> /// Initializes a new instance of the <see cref="ImageBuffer"/> class. /// </summary> public ImageBuffer(Bitmap bitmap, ImageLockMode lockMode) { // locks the image data this.bitmap = bitmap; this.lockMode = lockMode; // gathers the informations Width = bitmap.Width; Height = bitmap.Height; PixelFormat = bitmap.PixelFormat; IsIndexed = PixelFormat.IsIndexed(); BitDepth = PixelFormat.GetBitDepth(); BytesPerPixel = Math.Max(1, BitDepth >> 3); // determines the bounds of an image, and locks the data in a specified mode Rectangle bounds = Rectangle.FromLTRB(0, 0, Width, Height); // locks the bitmap data lock (bitmap) bitmapData = bitmap.LockBits(bounds, lockMode, PixelFormat); // creates internal buffer Stride = bitmapData.Stride < 0 ? -bitmapData.Stride : bitmapData.Stride; Size = Stride*Height; // precalculates the offsets Precalculate(); } #endregion #region | Maintenance methods | private void Precalculate() { fastBitX = new Int32[Width]; fastByteX = new Int32[Width]; fastY = new Int32[Height]; // precalculates the x-coordinates for (Int32 x = 0; x < Width; x++) { fastBitX[x] = x*BitDepth; fastByteX[x] = fastBitX[x] >> 3; fastBitX[x] = fastBitX[x] % 8; } // precalculates the y-coordinates for (Int32 y = 0; y < Height; y++) { fastY[y] = y * bitmapData.Stride; } } public Int32 GetBitOffset(Int32 x) { return fastBitX[x]; } public Byte[] Copy() { // transfers whole image to a working memory Byte[] result = new Byte[Size]; Marshal.Copy(bitmapData.Scan0, result, 0, Size); // returns the backup return result; } public void Paste(Byte[] buffer) { // commits the data to a bitmap Marshal.Copy(buffer, 0, bitmapData.Scan0, Size); } #endregion #region | Pixel read methods | public void ReadPixel(Pixel pixel, Byte[] buffer = null) { // determines pixel offset at [x, y] Int32 offset = fastByteX[pixel.X] + fastY[pixel.Y]; // reads the pixel from a bitmap if (buffer == null) { pixel.ReadRawData(bitmapData.Scan0 + offset); } else // reads the pixel from a buffer { pixel.ReadData(buffer, offset); } } public Int32 GetIndexFromPixel(Pixel pixel) { Int32 result; // determines whether the format is indexed if (IsIndexed) { result = pixel.Index; } else // not possible to get index from a non-indexed format { String message = string.Format("Cannot retrieve index for a non-indexed format. Please use Color (or Value) property instead."); throw new NotSupportedException(message); } return result; } public Color GetColorFromPixel(Pixel pixel) { Color result; // determines whether the format is indexed if (pixel.IsIndexed) { Int32 index = pixel.Index; result = pixel.Parent.GetPaletteColor(index); } else // gets color from a non-indexed format { result = pixel.Color; } // returns the found color return result; } public Int32 ReadIndexUsingPixel(Pixel pixel, Byte[] buffer = null) { // reads the pixel from bitmap/buffer ReadPixel(pixel, buffer); // returns the found color return GetIndexFromPixel(pixel); } public Color ReadColorUsingPixel(Pixel pixel, Byte[] buffer = null) { // reads the pixel from bitmap/buffer ReadPixel(pixel, buffer); // returns the found color return GetColorFromPixel(pixel); } public Int32 ReadIndexUsingPixelFrom(Pixel pixel, Int32 x, Int32 y, Byte[] buffer = null) { // redirects pixel -> [x, y] pixel.Update(x, y); // reads index from a bitmap/buffer using pixel, and stores it in the pixel return ReadIndexUsingPixel(pixel, buffer); } public Color ReadColorUsingPixelFrom(Pixel pixel, Int32 x, Int32 y, Byte[] buffer = null) { // redirects pixel -> [x, y] pixel.Update(x, y); // reads color from a bitmap/buffer using pixel, and stores it in the pixel return ReadColorUsingPixel(pixel, buffer); } #endregion #region | Pixel write methods | private void WritePixel(Pixel pixel, Byte[] buffer = null) { // determines pixel offset at [x, y] Int32 offset = fastByteX[pixel.X] + fastY[pixel.Y]; // writes the pixel to a bitmap if (buffer == null) { pixel.WriteRawData(bitmapData.Scan0 + offset); } else // writes the pixel to a buffer { pixel.WriteData(buffer, offset); } } public void SetIndexToPixel(Pixel pixel, Int32 index, Byte[] buffer = null) { // determines whether the format is indexed if (IsIndexed) { pixel.Index = (Byte) index; } else // cannot write color to an indexed format { String message = string.Format("Cannot set index for a non-indexed format. Please use Color (or Value) property instead."); throw new NotSupportedException(message); } } public void SetColorToPixel(Pixel pixel, Color color, IColorQuantizer quantizer) { // determines whether the format is indexed if (pixel.IsIndexed) { // last chance if quantizer is provided, use it if (quantizer != null) { Byte index = (Byte)quantizer.GetPaletteIndex(color, pixel.X, pixel.Y); pixel.Index = index; } else // cannot write color to an index format { String message = string.Format("Cannot retrieve color for an indexed format. Use GetPixelIndex() instead."); throw new NotSupportedException(message); } } else // sets color to a non-indexed format { pixel.Color = color; } } public void WriteIndexUsingPixel(Pixel pixel, Int32 index, Byte[] buffer = null) { // sets index to pixel (pixel's index is updated) SetIndexToPixel(pixel, index, buffer); // writes pixel to a bitmap/buffer WritePixel(pixel, buffer); } public void WriteColorUsingPixel(Pixel pixel, Color color, IColorQuantizer quantizer, Byte[] buffer = null) { // sets color to pixel (pixel is updated with color) SetColorToPixel(pixel, color, quantizer); // writes pixel to a bitmap/buffer WritePixel(pixel, buffer); } public void WriteIndexUsingPixelAt(Pixel pixel, Int32 x, Int32 y, Int32 index, Byte[] buffer = null) { // redirects pixel -> [x, y] pixel.Update(x, y); // writes color to bitmap/buffer using pixel WriteIndexUsingPixel(pixel, index, buffer); } public void WriteColorUsingPixelAt(Pixel pixel, Int32 x, Int32 y, Color color, IColorQuantizer quantizer, Byte[] buffer = null) { // redirects pixel -> [x, y] pixel.Update(x, y); // writes color to bitmap/buffer using pixel WriteColorUsingPixel(pixel, color, quantizer, buffer); } #endregion #region | Generic methods | private void ProcessInParallel(ICollection<Point> path, Action<LineTask> process, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(process, "process"); // updates the palette UpdatePalette(); // prepares parallel processing Double pointsPerTask = (1.0*path.Count)/parallelTaskCount; LineTask[] lineTasks = new LineTask[parallelTaskCount]; Double pointOffset = 0.0; // creates task for each batch of rows for (Int32 index = 0; index < parallelTaskCount; index++) { lineTasks[index] = new LineTask((Int32) pointOffset, (Int32) (pointOffset + pointsPerTask)); pointOffset += pointsPerTask; } // process the image in a parallel manner Parallel.ForEach(lineTasks, process); } #endregion #region | Processing methods | private void ProcessPerPixelBase(IList<Point> path, Delegate processingAction, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(path, "path"); Guard.CheckNull(processingAction, "processPixelFunction"); // determines mode Boolean isAdvanced = processingAction is ProcessPixelAdvancedFunction; // prepares the per pixel task Action<LineTask> processPerPixel = lineTask => { // initializes variables per task Pixel pixel = new Pixel(this); for (Int32 pathOffset = lineTask.StartOffset; pathOffset < lineTask.EndOffset; pathOffset++) { Point point = path[pathOffset]; Boolean allowWrite; // enumerates the pixel, and returns the control to the outside pixel.Update(point.X, point.Y); // when read is allowed, retrieves current value (in bytes) if (CanRead) ReadPixel(pixel); // process the pixel by custom user operation if (isAdvanced) { ProcessPixelAdvancedFunction processAdvancedFunction = (ProcessPixelAdvancedFunction) processingAction; allowWrite = processAdvancedFunction(pixel, this); } else // use simplified version with pixel parameter only { ProcessPixelFunction processFunction = (ProcessPixelFunction) processingAction; allowWrite = processFunction(pixel); } // when write is allowed, copies the value back to the row buffer if (CanWrite && allowWrite) WritePixel(pixel); } }; // processes image per pixel ProcessInParallel(path, processPerPixel, parallelTaskCount); } public void ProcessPerPixel(IList<Point> path, ProcessPixelFunction processPixelFunction, Int32 parallelTaskCount = 4) { ProcessPerPixelBase(path, processPixelFunction, parallelTaskCount); } public void ProcessPerPixelAdvanced(IList<Point> path, ProcessPixelAdvancedFunction processPixelAdvancedFunction, Int32 parallelTaskCount = 4) { ProcessPerPixelBase(path, processPixelAdvancedFunction, parallelTaskCount); } #endregion #region | Transformation functions | private void TransformPerPixelBase(ImageBuffer target, IList<Point> path, Delegate transformAction, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(path, "path"); Guard.CheckNull(target, "target"); Guard.CheckNull(transformAction, "transformAction"); // updates the palette UpdatePalette(); target.UpdatePalette(); // checks the dimensions if (Width != target.Width || Height != target.Height) { const String message = "Both images have to have the same dimensions."; throw new ArgumentOutOfRangeException(message); } // determines mode Boolean isAdvanced = transformAction is TransformPixelAdvancedFunction; // process the image in a parallel manner Action<LineTask> transformPerPixel = lineTask => { // creates individual pixel structures per task Pixel sourcePixel = new Pixel(this); Pixel targetPixel = new Pixel(target); // enumerates the pixels row by row for (Int32 pathOffset = lineTask.StartOffset; pathOffset < lineTask.EndOffset; pathOffset++) { Point point = path[pathOffset]; Boolean allowWrite; // enumerates the pixel, and returns the control to the outside sourcePixel.Update(point.X, point.Y); targetPixel.Update(point.X, point.Y); // when read is allowed, retrieves current value (in bytes) if (CanRead) ReadPixel(sourcePixel); if (target.CanRead) target.ReadPixel(targetPixel); // process the pixel by custom user operation if (isAdvanced) { TransformPixelAdvancedFunction transformAdvancedFunction = (TransformPixelAdvancedFunction) transformAction; allowWrite = transformAdvancedFunction(sourcePixel, targetPixel, this, target); } else // use simplified version with pixel parameters only { TransformPixelFunction transformFunction = (TransformPixelFunction) transformAction; allowWrite = transformFunction(sourcePixel, targetPixel); } // when write is allowed, copies the value back to the row buffer if (target.CanWrite && allowWrite) target.WritePixel(targetPixel); } }; // transforms image per pixel ProcessInParallel(path, transformPerPixel, parallelTaskCount); } public void TransformPerPixel(ImageBuffer target, IList<Point> path, TransformPixelFunction transformPixelFunction, Int32 parallelTaskCount = 4) { TransformPerPixelBase(target, path, transformPixelFunction, parallelTaskCount); } public void TransformPerPixelAdvanced(ImageBuffer target, IList<Point> path, TransformPixelAdvancedFunction transformPixelAdvancedFunction, Int32 parallelTaskCount = 4) { TransformPerPixelBase(target, path, transformPixelAdvancedFunction, parallelTaskCount); } #endregion #region | Scan colors methods | public void ScanColors(IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(quantizer, "quantizer"); // determines which method of color retrieval to use IList<Point> path = quantizer.GetPointPath(Width, Height); // use different scanning method depending whether the image format is indexed ProcessPixelFunction scanColors = pixel => { quantizer.AddColor(GetColorFromPixel(pixel), pixel.X, pixel.Y); return false; }; // performs the image scan, using a chosen method ProcessPerPixel(path, scanColors, parallelTaskCount); } public static void ScanImageColors(Image sourceImage, IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { source.ScanColors(quantizer, parallelTaskCount); } } #endregion #region | Synthetize palette methods | public List<Color> SynthetizePalette(IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(quantizer, "quantizer"); // Step 1 - prepares quantizer for another round quantizer.Prepare(this); // Step 2 - scans the source image for the colors ScanColors(quantizer, parallelTaskCount); // Step 3 - synthetises the palette, and returns the result return quantizer.GetPalette(colorCount); } public static List<Color> SynthetizeImagePalette(Image sourceImage, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { return source.SynthetizePalette(quantizer, colorCount, parallelTaskCount); } } #endregion #region | Quantize methods | public void Quantize(ImageBuffer target, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // performs the pure quantization wihout dithering Quantize(target, quantizer, null, colorCount, parallelTaskCount); } public void Quantize(ImageBuffer target, IColorQuantizer quantizer, IColorDitherer ditherer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(target, "target"); Guard.CheckNull(quantizer, "quantizer"); // initializes quantization parameters Boolean isTargetIndexed = target.PixelFormat.IsIndexed(); // step 1 - prepares the palettes List<Color> targetPalette = isTargetIndexed ? SynthetizePalette(quantizer, colorCount, parallelTaskCount) : null; // step 2 - updates the bitmap palette target.bitmap.SetPalette(targetPalette); target.UpdatePalette(true); // step 3 - prepares ditherer (optional) if (ditherer != null) ditherer.Prepare(quantizer, colorCount, this, target); // step 4 - prepares the quantization function TransformPixelFunction quantize = (sourcePixel, targetPixel) => { // reads the pixel color Color color = GetColorFromPixel(sourcePixel); // converts alpha to solid color color = QuantizationHelper.ConvertAlpha(color); // quantizes the pixel SetColorToPixel(targetPixel, color, quantizer); // marks pixel as processed by default Boolean result = true; // preforms inplace dithering (optional) if (ditherer != null && ditherer.IsInplace) { result = ditherer.ProcessPixel(sourcePixel, targetPixel); } // returns the result return result; }; // step 5 - generates the target image IList<Point> path = quantizer.GetPointPath(Width, Height); TransformPerPixel(target, path, quantize, parallelTaskCount); // step 6 - preforms non-inplace dithering (optional) if (ditherer != null && !ditherer.IsInplace) { Dither(target, ditherer, quantizer, colorCount, 1); } // step 7 - finishes the dithering (optional) if (ditherer != null) ditherer.Finish(); // step 8 - clean-up quantizer.Finish(); } public static Image QuantizeImage(ImageBuffer source, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // performs the pure quantization wihout dithering return QuantizeImage(source, quantizer, null, colorCount, parallelTaskCount); } public static Image QuantizeImage(ImageBuffer source, IColorQuantizer quantizer, IColorDitherer ditherer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // creates a target bitmap in an appropriate format PixelFormat targetPixelFormat = Extend.GetFormatByColorCount(colorCount); Image result = new Bitmap(source.Width, source.Height, targetPixelFormat); // lock mode ImageLockMode lockMode = ditherer == null ? ImageLockMode.WriteOnly : ImageLockMode.ReadWrite; // wraps target image to a buffer using (ImageBuffer target = new ImageBuffer(result, lockMode)) { source.Quantize(target, quantizer, ditherer, colorCount, parallelTaskCount); return result; } } public static Image QuantizeImage(Image sourceImage, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // performs the pure quantization wihout dithering return QuantizeImage(sourceImage, quantizer, null, colorCount, parallelTaskCount); } public static Image QuantizeImage(Image sourceImage, IColorQuantizer quantizer, IColorDitherer ditherer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // lock mode ImageLockMode lockMode = ditherer == null ? ImageLockMode.ReadOnly : ImageLockMode.ReadWrite; // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, lockMode)) { return QuantizeImage(source, quantizer, ditherer, colorCount, parallelTaskCount); } } #endregion #region | Calculate mean error methods | public Double CalculateMeanError(ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(target, "target"); // initializes the error Int64 totalError = 0; // prepares the function TransformPixelFunction calculateMeanError = (sourcePixel, targetPixel) => { Color sourceColor = GetColorFromPixel(sourcePixel); Color targetColor = GetColorFromPixel(targetPixel); totalError += ColorModelHelper.GetColorEuclideanDistance(ColorModel.RedGreenBlue, sourceColor, targetColor); return false; }; // performs the image scan, using a chosen method IList<Point> standardPath = new StandardPathProvider().GetPointPath(Width, Height); TransformPerPixel(target, standardPath, calculateMeanError, parallelTaskCount); // returns the calculates RMSD return Math.Sqrt(totalError/(3.0*Width*Height)); } public static Double CalculateImageMeanError(ImageBuffer source, ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // use other override to calculate error return source.CalculateMeanError(target, parallelTaskCount); } public static Double CalculateImageMeanError(ImageBuffer source, Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateMeanError(target, parallelTaskCount); } } public static Double CalculateImageMeanError(Image sourceImage, ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateMeanError(target, parallelTaskCount); } } public static Double CalculateImageMeanError(Image sourceImage, Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateMeanError(target, parallelTaskCount); } } #endregion #region | Calculate normalized mean error methods | public Double CalculateNormalizedMeanError(ImageBuffer target, Int32 parallelTaskCount = 4) { return CalculateMeanError(target, parallelTaskCount) / 255.0; } public static Double CalculateImageNormalizedMeanError(ImageBuffer source, Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateNormalizedMeanError(target, parallelTaskCount); } } public static Double CalculateImageNormalizedMeanError(Image sourceImage, ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateNormalizedMeanError(target, parallelTaskCount); } } public static Double CalculateImageNormalizedMeanError(ImageBuffer source, ImageBuffer target, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // use other override to calculate error return source.CalculateNormalizedMeanError(target, parallelTaskCount); } public static Double CalculateImageNormalizedMeanError(Image sourceImage, Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error return source.CalculateNormalizedMeanError(target, parallelTaskCount); } } #endregion #region | Change pixel format methods | public void ChangeFormat(ImageBuffer target, IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(target, "target"); Guard.CheckNull(quantizer, "quantizer"); // gathers some information about the target format Boolean hasSourceAlpha = PixelFormat.HasAlpha(); Boolean hasTargetAlpha = target.PixelFormat.HasAlpha(); Boolean isTargetIndexed = target.PixelFormat.IsIndexed(); Boolean isSourceDeepColor = PixelFormat.IsDeepColor(); Boolean isTargetDeepColor = target.PixelFormat.IsDeepColor(); // step 1 to 3 - prepares the palettes if (isTargetIndexed) SynthetizePalette(quantizer, target.PixelFormat.GetColorCount(), parallelTaskCount); // prepares the quantization function TransformPixelFunction changeFormat = (sourcePixel, targetPixel) => { // if both source and target formats are deep color formats, copies a value directly if (isSourceDeepColor && isTargetDeepColor) { //UInt64 value = sourcePixel.Value; //targetPixel.SetValue(value); } else { // retrieves a source image color Color color = GetColorFromPixel(sourcePixel); // if alpha is not present in the source image, but is present in the target, make one up if (!hasSourceAlpha && hasTargetAlpha) { Int32 argb = 255 << 24 | color.R << 16 | color.G << 8 | color.B; color = Color.FromArgb(argb); } // sets the color to a target pixel SetColorToPixel(targetPixel, color, quantizer); } // allows to write (obviously) the transformed pixel return true; }; // step 5 - generates the target image IList<Point> standardPath = new StandardPathProvider().GetPointPath(Width, Height); TransformPerPixel(target, standardPath, changeFormat, parallelTaskCount); } public static void ChangeFormat(ImageBuffer source, PixelFormat targetFormat, IColorQuantizer quantizer, out Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // creates a target bitmap in an appropriate format targetImage = new Bitmap(source.Width, source.Height, targetFormat); // wraps target image to a buffer using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.WriteOnly)) { source.ChangeFormat(target, quantizer, parallelTaskCount); } } public static void ChangeFormat(Image sourceImage, PixelFormat targetFormat, IColorQuantizer quantizer, out Image targetImage, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { ChangeFormat(source, targetFormat, quantizer, out targetImage, parallelTaskCount); } } #endregion #region | Dithering methods | public void Dither(ImageBuffer target, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(target, "target"); Guard.CheckNull(ditherer, "ditherer"); Guard.CheckNull(quantizer, "quantizer"); // prepares ditherer for another round ditherer.Prepare(quantizer, colorCount, this, target); // processes the image via the ditherer IList<Point> path = ditherer.GetPointPath(Width, Height); TransformPerPixel(target, path, ditherer.ProcessPixel, parallelTaskCount); } public static void DitherImage(ImageBuffer source, ImageBuffer target, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); // use other override to calculate error source.Dither(target, ditherer, quantizer, colorCount, parallelTaskCount); } public static void DitherImage(ImageBuffer source, Image targetImage, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(source, "source"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error source.Dither(target, ditherer, quantizer, colorCount, parallelTaskCount); } } public static void DitherImage(Image sourceImage, ImageBuffer target, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { // use other override to calculate error source.Dither(target, ditherer, quantizer, colorCount, parallelTaskCount); } } public static void DitherImage(Image sourceImage, Image targetImage, IColorDitherer ditherer, IColorQuantizer quantizer, Int32 colorCount, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); Guard.CheckNull(targetImage, "targetImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) using (ImageBuffer target = new ImageBuffer(targetImage, ImageLockMode.ReadOnly)) { // use other override to calculate error source.Dither(target, ditherer, quantizer, colorCount, parallelTaskCount); } } #endregion #region | Gamma correction | public void CorrectGamma(Single gamma, IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(quantizer, "quantizer"); // determines which method of color retrieval to use IList<Point> path = quantizer.GetPointPath(Width, Height); // calculates gamma ramp Int32[] gammaRamp = new Int32[256]; for (Int32 index = 0; index < 256; ++index) { gammaRamp[index] = Clamp((Int32) ((255.0f*Math.Pow(index/255.0f, 1.0f/gamma)) + 0.5f)); } // use different scanning method depending whether the image format is indexed ProcessPixelFunction correctGamma = pixel => { Color oldColor = GetColorFromPixel(pixel); Int32 red = gammaRamp[oldColor.R]; Int32 green = gammaRamp[oldColor.G]; Int32 blue = gammaRamp[oldColor.B]; Color newColor = Color.FromArgb(red, green, blue); SetColorToPixel(pixel, newColor, quantizer); return true; }; // performs the image scan, using a chosen method ProcessPerPixel(path, correctGamma, parallelTaskCount); } public static void CorrectImageGamma(Image sourceImage, Single gamma, IColorQuantizer quantizer, Int32 parallelTaskCount = 4) { // checks parameters Guard.CheckNull(sourceImage, "sourceImage"); // wraps source image to a buffer using (ImageBuffer source = new ImageBuffer(sourceImage, ImageLockMode.ReadOnly)) { source.CorrectGamma(gamma, quantizer, parallelTaskCount); } } #endregion #region | Palette methods | public static Int32 Clamp(Int32 value, Int32 minimum = 0, Int32 maximum = 255) { if (value < minimum) value = minimum; if (value > maximum) value = maximum; return value; } private List<Color> UpdatePalette(Boolean forceUpdate = false) { if (IsIndexed && (cachedPalette == null || forceUpdate)) { cachedPalette = bitmap.GetPalette(); } return cachedPalette; } public Color GetPaletteColor(Int32 paletteIndex) { return cachedPalette[paletteIndex]; } #endregion #region << IDisposable >> public void Dispose() { // releases the image lock lock (bitmap) bitmap.UnlockBits(bitmapData); } #endregion #region | Sub-classes | private class LineTask { /// <summary> /// Gets or sets the start offset. /// </summary> public Int32 StartOffset { get; private set; } /// <summary> /// Gets or sets the end offset. /// </summary> public Int32 EndOffset { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="LineTask"/> class. /// </summary> public LineTask(Int32 startOffset, Int32 endOffset) { StartOffset = startOffset; EndOffset = endOffset; } } #endregion } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdigEngine.Extensions { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Markdig.Helpers; using Markdig.Renderers; using Markdig.Renderers.Html; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class HtmlCodeSnippetRenderer : HtmlObjectRenderer<CodeSnippet> { private const string TagPrefix = "snippet"; private const string WarningMessageId = "codeIncludeNotFound"; private const string DefaultWarningMessage = "It looks like the sample you are looking for does not exist."; private const string WarningTitleId = "warning"; private const string DefaultWarningTitle = "<h5>WARNING</h5>"; // C# code snippet comment block: // <[/]snippetname> private const string CFamilyCodeSnippetCommentStartLineTemplate = "//<{tagname}>"; private const string CFamilyCodeSnippetCommentEndLineTemplate = "//</{tagname}>"; // C# code snippet region block: start -> #region snippetname, end -> #endregion private const string CSharpCodeSnippetRegionStartLineTemplate = "#region{tagname}"; private const string CSharpCodeSnippetRegionEndLineTemplate = "#endregion"; // VB code snippet comment block: ' <[/]snippetname> private const string BasicFamilyCodeSnippetCommentStartLineTemplate = "'<{tagname}>"; private const string BasicFamilyCodeSnippetCommentEndLineTemplate = "'</{tagname}>"; // VB code snippet Region block: start -> # Region "snippetname", end -> # End Region private const string VBCodeSnippetRegionRegionStartLineTemplate = "#region{tagname}"; private const string VBCodeSnippetRegionRegionEndLineTemplate = "#endregion"; // XML code snippet block: <!-- <[/]snippetname> --> private const string MarkupLanguageFamilyCodeSnippetCommentStartLineTemplate = "<!--<{tagname}>-->"; private const string MarkupLanguageFamilyCodeSnippetCommentEndLineTemplate = "<!--</{tagname}>-->"; // Sql code snippet block: -- <[/]snippetname> private const string SqlFamilyCodeSnippetCommentStartLineTemplate = "--<{tagname}>"; private const string SqlFamilyCodeSnippetCommentEndLineTemplate = "--</{tagname}>"; // Python code snippet comment block: # <[/]snippetname> private const string ScriptFamilyCodeSnippetCommentStartLineTemplate = "#<{tagname}>"; private const string ScriptFamilyCodeSnippetCommentEndLineTemplate = "#</{tagname}>"; // Batch code snippet comment block: rem <[/]snippetname> private const string BatchFileCodeSnippetRegionStartLineTemplate = "rem<{tagname}>"; private const string BatchFileCodeSnippetRegionEndLineTemplate = "rem</{tagname}>"; // Erlang code snippet comment block: % <[/]snippetname> private const string ErlangCodeSnippetRegionStartLineTemplate = "%<{tagname}>"; private const string ErlangCodeSnippetRegionEndLineTemplate = "%</{tagname}>"; // Lisp code snippet comment block: ; <[/]snippetname> private const string LispCodeSnippetRegionStartLineTemplate = ";<{tagname}>"; private const string LispCodeSnippetRegionEndLineTemplate = ";</{tagname}>"; // css code snippet comment block: ; <[/]snippetname> private const string CSSCodeSnippetRegionStartLineTemplate = "/*<{tagname}>*/"; private const string CSSCodeSnippetRegionEndLineTemplate = "/*</{tagname}>*/"; private static readonly IReadOnlyDictionary<string, string[]> s_languageAlias = new Dictionary<string, string[]> { { "actionscript", new string[] {"as" } }, { "arduino", new string[] {"ino" } }, { "assembly", new string[] {"nasm", "asm" } }, { "batchfile", new string[] {"bat", "cmd" } }, { "css", Array.Empty<string>() }, { "cpp", new string[] {"c", "c++", "objective-c", "obj-c", "objc", "objectivec", "h", "hpp", "cc", "m" } }, { "csharp", new string[] {"cs"} }, { "cuda", new string[] {"cu", "cuh" } }, { "d", new string[] {"dlang"} }, { "everything", new string[] {"example" } }, //this is the catch all to try and process unforseen languages { "erlang", new string[] {"erl" } }, { "fsharp", new string[] {"fs", "fsi", "fsx" } }, { "go", new string[] {"golang" } }, { "handlebars", new string[] {"hbs" } }, { "haskell", new string[] {"hs" } }, { "html", new string[] { "jsp", "asp", "aspx", "ascx" } }, { "cshtml", new string[] {"aspx-cs", "aspx-csharp" } }, { "vbhtml", new string[] {"aspx-vb" } }, { "java", new string[] {"gradle" } }, { "javascript", new string[] {"js", "node", "json" } }, { "lisp", new string[] {"lsp" } }, { "lua", Array.Empty<string>() }, { "matlab", Array.Empty<string>() }, { "pascal", new string[] {"pas" } }, { "perl", new string[] {"pl" } }, { "php", Array.Empty<string>() }, { "powershell", new string[] {"posh", "ps1" } }, { "processing", new string[] {"pde" } }, { "python", new string[] {"py" } }, { "r", Array.Empty<string>() }, { "react", new string[] {"tsx" } }, { "ruby", new string[] {"ru", "erb", "rb", "" } }, { "rust", new string[] {"rs" } }, { "scala", Array.Empty<string>() }, { "shell", new string[] {"sh", "bash" } }, { "smalltalk", new string[] {"st" } }, { "sql", Array.Empty<string>() }, { "swift", Array.Empty<string>() }, { "typescript", new string[] {"ts" } }, { "xaml", Array.Empty<string>() }, { "xml", new string[] {"xsl", "xslt", "xsd", "wsdl", "csdl", "edmx" } }, { "vb", new string[] {"vbnet", "vbscript", "bas", "vbs", "vba" } } }; private static readonly Dictionary<string, string> s_languageByFileExtension = new Dictionary<string, string>(); // If we ever come across a language that has not been defined above, we shouldn't break the build. // We can at least try it with a default language, "C#" for now, and try and resolve the code snippet. private static readonly HashSet<CodeSnippetExtractor> s_defaultExtractors = new HashSet<CodeSnippetExtractor>(); // Language names and aliases follow http://highlightjs.readthedocs.org/en/latest/css-classes-reference.html#language-names-and-aliases // Language file extensions follow https://github.com/github/linguist/blob/master/lib/linguist/languages.yml // Currently only supports parts of the language names, aliases and extensions // Later we can move the repository's supported/custom language names, aliases, extensions and corresponding comments regexes to docfx build configuration private static readonly Dictionary<string, HashSet<CodeSnippetExtractor>> s_languageExtractors = new Dictionary<string, HashSet<CodeSnippetExtractor>>(); private readonly MarkdownContext _context; static HtmlCodeSnippetRenderer() { BuildFileExtensionLanguageMap(); AddExtractorItems(new[] { "vb", "vbhtml" }, new CodeSnippetExtractor(BasicFamilyCodeSnippetCommentStartLineTemplate, BasicFamilyCodeSnippetCommentEndLineTemplate)); AddExtractorItems(new[] { "actionscript", "arduino", "assembly", "cpp", "csharp", "cshtml", "cuda", "d", "fsharp", "go", "java", "javascript", "objectivec", "pascal", "php", "processing", "react", "rust", "scala", "smalltalk", "swift", "typescript" }, new CodeSnippetExtractor(CFamilyCodeSnippetCommentStartLineTemplate, CFamilyCodeSnippetCommentEndLineTemplate)); AddExtractorItems(new[] { "xml", "xaml", "handlebars", "html", "cshtml", "php", "react", "ruby", "vbhtml" }, new CodeSnippetExtractor(MarkupLanguageFamilyCodeSnippetCommentStartLineTemplate, MarkupLanguageFamilyCodeSnippetCommentEndLineTemplate)); AddExtractorItems(new[] { "haskell", "lua", "sql" }, new CodeSnippetExtractor(SqlFamilyCodeSnippetCommentStartLineTemplate, SqlFamilyCodeSnippetCommentEndLineTemplate)); AddExtractorItems(new[] { "perl", "powershell", "python", "r", "ruby", "shell" }, new CodeSnippetExtractor(ScriptFamilyCodeSnippetCommentStartLineTemplate, ScriptFamilyCodeSnippetCommentEndLineTemplate)); AddExtractorItems(new[] { "batchfile" }, new CodeSnippetExtractor(BatchFileCodeSnippetRegionStartLineTemplate, BatchFileCodeSnippetRegionEndLineTemplate)); AddExtractorItems(new[] { "csharp", "cshtml" }, new CodeSnippetExtractor(CSharpCodeSnippetRegionStartLineTemplate, CSharpCodeSnippetRegionEndLineTemplate, false)); AddExtractorItems(new[] { "erlang", "matlab" }, new CodeSnippetExtractor(ErlangCodeSnippetRegionStartLineTemplate, ErlangCodeSnippetRegionEndLineTemplate)); AddExtractorItems(new[] { "lisp" }, new CodeSnippetExtractor(LispCodeSnippetRegionStartLineTemplate, LispCodeSnippetRegionEndLineTemplate)); AddExtractorItems(new[] { "vb", "vbhtml" }, new CodeSnippetExtractor(VBCodeSnippetRegionRegionStartLineTemplate, VBCodeSnippetRegionRegionEndLineTemplate, false)); AddExtractorItems(new[] { "css" }, new CodeSnippetExtractor(CSSCodeSnippetRegionStartLineTemplate, CSSCodeSnippetRegionEndLineTemplate, false)); static void BuildFileExtensionLanguageMap() { foreach (var (language, aliases) in s_languageAlias.Select(i => (i.Key, i.Value))) { Debug.Assert(!language.StartsWith(".")); s_languageByFileExtension.Add(language, language); s_languageByFileExtension.Add($".{language}", language); foreach (var alias in aliases) { Debug.Assert(!alias.StartsWith(".")); s_languageByFileExtension.Add(alias, language); s_languageByFileExtension.Add($".{alias}", language); } } } static void AddExtractorItems(string[] languages, CodeSnippetExtractor extractor) { s_defaultExtractors.Add(extractor); foreach (var language in languages) { AddExtractorItem(language, extractor); AddExtractorItem($".{language}", extractor); if (s_languageAlias.TryGetValue(language, out var aliases)) { foreach (var alias in aliases) { AddExtractorItem(alias, extractor); AddExtractorItem($".{alias}", extractor); } } } } static void AddExtractorItem(string language, CodeSnippetExtractor extractor) { if (s_languageExtractors.TryGetValue(language, out var extractors)) { extractors.Add(extractor); } else { s_languageExtractors[language] = new HashSet<CodeSnippetExtractor> { extractor }; } } } public HtmlCodeSnippetRenderer(MarkdownContext context) { _context = context; } public static string GetLanguageByFileExtension(string extension) { return s_languageByFileExtension.TryGetValue(extension, out var result) ? result : null; } protected override void Write(HtmlRenderer renderer, CodeSnippet codeSnippet) { var (content, codeSnippetPath) = _context.ReadFile(codeSnippet.CodePath, codeSnippet); if (content == null) { _context.LogWarning("codesnippet-not-found", $"Invalid code snippet link: '{codeSnippet.CodePath}'.", codeSnippet); renderer.Write(GetWarning()); return; } codeSnippet.SetAttributeString(); renderer.Write("<pre><code").WriteAttributes(codeSnippet).Write(">"); renderer.WriteEscape(GetContent(content, codeSnippet)); renderer.Write("</code></pre>"); } private string GetNoteBookContent(string content, string tagName, CodeSnippet obj) { JObject contentObject = null; try { contentObject = JObject.Parse(content); } catch (JsonReaderException ex) { _context.LogError("not-notebook-content", "Not a valid Notebook. " + ex.ToString(), obj); return string.Empty; } string sourceJsonPath = $"$..cells[?(@.metadata.name=='{tagName}')].source"; JToken sourceObject = null; try { sourceObject = contentObject.SelectToken(sourceJsonPath); } catch (JsonException) { _context.LogError("multiple-tags-with-same-name", $"Multiple entries with the name '{tagName}' where found in the notebook.", obj); return string.Empty; } if (sourceObject == null) { _context.LogError("tag-not-found", $"The name '{tagName}' is not present in the notebook file.", obj); return string.Empty; } StringBuilder showCode = new StringBuilder(); string[] lines = ((JArray)sourceObject).ToObject<string[]>(); for (int i = 0; i < lines.Length; i++) { showCode.Append(lines[i]); } return showCode.ToString(); } public string GetContent(string content, CodeSnippet obj) { var allLines = ReadAllLines(content).ToArray(); // code range priority: tag > #L1 > start/end > range > default if (!string.IsNullOrEmpty(obj.TagName)) { var lang = obj.Language ?? Path.GetExtension(obj.CodePath); if (obj.IsNotebookCode) { return GetNoteBookContent(content, obj.TagName, obj); } if (!s_languageExtractors.TryGetValue(lang, out var extractors)) { extractors = s_defaultExtractors; _context.LogWarning( "unknown-language-code", $"Unrecognized language value '{lang}' in code snippet '{obj.TagName}' in file '{obj.CodePath}'. Your code snippet might not render correctly. If this is the case, you can request a new value or use range instead.", obj); } var tagWithPrefix = TagPrefix + obj.TagName; foreach (var extractor in extractors) { HashSet<int> tagLines = new HashSet<int>(); var tagToCoderangeMapping = extractor.GetAllTags(allLines, ref tagLines); if (tagToCoderangeMapping.TryGetValue(obj.TagName, out var cr) || tagToCoderangeMapping.TryGetValue(tagWithPrefix, out cr)) { return GetCodeLines(allLines, obj, new List<CodeRange> { cr }, tagLines); } } } else if (obj.BookMarkRange != null) { return GetCodeLines(allLines, obj, new List<CodeRange> { obj.BookMarkRange }); } else if (obj.StartEndRange != null) { return GetCodeLines(allLines, obj, new List<CodeRange> { obj.StartEndRange }); } else if (obj.CodeRanges != null) { return GetCodeLines(allLines, obj, obj.CodeRanges); } else { return GetCodeLines(allLines, obj, new List<CodeRange> { new CodeRange { Start = 0, End = allLines.Length } }); } return string.Empty; } private static IEnumerable<string> ReadAllLines(string content) { string line; var reader = new StringReader(content); while ((line = reader.ReadLine()) != null) { yield return line; } } private string GetCodeLines(string[] allLines, CodeSnippet obj, List<CodeRange> codeRanges, HashSet<int> ignoreLines = null) { List<string> codeLines = new List<string>(); StringBuilder showCode = new StringBuilder(); int commonIndent = int.MaxValue; foreach (var codeRange in codeRanges) { for (int lineNumber = Math.Max(codeRange.Start - 1, 0); lineNumber < Math.Min(codeRange.End, allLines.Length); lineNumber++) { if (ignoreLines != null && ignoreLines.Contains(lineNumber)) continue; if (IsBlankLine(allLines[lineNumber])) { codeLines.Add(allLines[lineNumber]); } else { int indentSpaces = 0; string rawCodeLine = CountAndReplaceIndentSpaces(allLines[lineNumber], out indentSpaces); commonIndent = Math.Min(commonIndent, indentSpaces); codeLines.Add(rawCodeLine); } } } int dedent = obj.DedentLength == null || obj.DedentLength < 0 ? commonIndent : (int)obj.DedentLength; foreach (var rawCodeLine in codeLines) { showCode.Append($"{DedentString(rawCodeLine, dedent)}\n"); } return showCode.ToString(); } private string DedentString(string source, int dedent) { int validDedent = Math.Min(dedent, source.Length); for (int i = 0; i < validDedent; i++) { if (source[i] != ' ') return source.Substring(i); } return source.Substring(validDedent); } private bool IsBlankLine(string line) { return line == ""; } private string CountAndReplaceIndentSpaces(string line, out int count) { StringBuilder sb = new StringBuilder(); count = 0; for (int i = 0; i < line.Length; i++) { char c = line[i]; if (c == ' ') { sb.Append(' '); count++; } else if (c == '\t') { int newCount = CharHelper.AddTab(count); sb.Append(' ', newCount - count); count = newCount; } else { sb.Append(line, i, line.Length - i); break; } } return sb.ToString(); } private bool IsLineInRange(int lineNumber, List<CodeRange> allCodeRanges) { if (allCodeRanges.Count() == 0) return true; for (int rangeNumber = 0; rangeNumber < allCodeRanges.Count(); rangeNumber++) { var range = allCodeRanges[rangeNumber]; if (lineNumber >= range.Start && lineNumber <= range.End) return true; } return false; } private int GetTagLineNumber(string[] lines, string tagLine) { for (int index = 0; index < lines.Length; index++) { var line = lines[index]; var targetColumn = 0; var match = true; for (int column = 0; column < line.Length; column++) { var c = line[column]; if (c != ' ') { if (targetColumn >= tagLine.Length || tagLine[targetColumn] != Char.ToUpper(c)) { match = false; break; } targetColumn++; } } if (match && targetColumn == tagLine.Length) return index + 1; } return -1; } private string GetWarning() { var warningTitle = _context.GetToken(WarningTitleId) ?? DefaultWarningTitle; var warningMessage = _context.GetToken(WarningMessageId) ?? DefaultWarningMessage; return $@"<div class=""WARNING""> {warningTitle} <p>{warningMessage}</p> </div>"; } public static bool TryGetLineRanges(string query, out List<CodeRange> codeRanges) { codeRanges = null; if (string.IsNullOrEmpty(query)) return false; var rangesSplit = query.Split(new[] { ',' }); foreach (var range in rangesSplit) { if (!TryGetLineRange(range, out var codeRange, false)) { return false; } if (codeRanges == null) { codeRanges = new List<CodeRange>(); } codeRanges.Add(codeRange); } return true; } public static bool TryGetLineRange(string query, out CodeRange codeRange, bool withL = true) { codeRange = null; if (string.IsNullOrEmpty(query)) return false; int endLine; var splitLine = query.Split(new[] { '-' }); if (splitLine.Length > 2) return false; var result = TryGetLineNumber(splitLine[0], out var startLine, withL); endLine = startLine; if (splitLine.Length > 1) { result &= TryGetLineNumber(splitLine[1], out endLine, withL); } codeRange = new CodeRange { Start = startLine, End = endLine }; return result; } public static bool TryGetLineNumber(string lineNumberString, out int lineNumber, bool withL = true) { lineNumber = int.MaxValue; if (string.IsNullOrEmpty(lineNumberString)) return true; if (withL && (lineNumberString.Length < 2 || Char.ToUpper(lineNumberString[0]) != 'L')) return false; return int.TryParse(withL ? lineNumberString.Substring(1) : lineNumberString, out lineNumber); } } }
/* ==================================================================== 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.UserModel { using System; using System.Collections; using NPOI.DDF; using NPOI.HSSF.Record; using NPOI.Util; using NPOI.SS.UserModel; using System.Collections.Generic; using NPOI.HSSF.Model; using NPOI.SS.Util; /// <summary> /// The patriarch is the toplevel container for shapes in a sheet. It does /// little other than act as a container for other shapes and Groups. /// @author Glen Stampoultzis (glens at apache.org) /// </summary> public class HSSFPatriarch : HSSFShapeContainer, IDrawing { private static POILogger log = POILogFactory.GetLogger(typeof(HSSFPatriarch)); List<HSSFShape> _shapes = new List<HSSFShape>(); private HSSFSheet _sheet; private EscherSpgrRecord _spgrRecord; private EscherContainerRecord _mainSpgrContainer; /** * The EscherAggregate we have been bound to. * (This will handle writing us out into records, * and building up our shapes from the records) */ private EscherAggregate _boundAggregate; /// <summary> /// Creates the patriarch. /// </summary> /// <param name="sheet">the sheet this patriarch is stored in.</param> /// <param name="boundAggregate">The bound aggregate.</param> public HSSFPatriarch(HSSFSheet sheet, EscherAggregate boundAggregate) { _boundAggregate = boundAggregate; _sheet = sheet; _mainSpgrContainer = _boundAggregate.GetEscherContainer().ChildContainers[0]; EscherContainerRecord spContainer = (EscherContainerRecord)_boundAggregate.GetEscherContainer() .ChildContainers[0].GetChild(0); _spgrRecord = (EscherSpgrRecord)spContainer.GetChildById(EscherSpgrRecord.RECORD_ID); BuildShapeTree(); } public static HSSFPatriarch CreatePatriarch(HSSFPatriarch patriarch, HSSFSheet sheet) { HSSFPatriarch newPatriarch = new HSSFPatriarch(sheet, new EscherAggregate(true)); newPatriarch.AfterCreate(); foreach (HSSFShape shape in patriarch.Children) { HSSFShape newShape; if (shape is HSSFShapeGroup) { newShape = ((HSSFShapeGroup)shape).CloneShape(newPatriarch); } else { newShape = shape.CloneShape(); } newPatriarch.OnCreate(newShape); newPatriarch.AddShape(newShape); } return newPatriarch; } /** * check if any shapes contain wrong data * At now(13.08.2010) check if patriarch contains 2 or more comments with same coordinates */ protected internal void PreSerialize() { Dictionary<int, NoteRecord> tailRecords = _boundAggregate.TailRecords; /** * contains coordinates of comments we iterate over */ Hashtable coordinates = new Hashtable(tailRecords.Count); foreach (NoteRecord rec in tailRecords.Values) { String noteRef = new CellReference(rec.Row, rec.Column).FormatAsString(); // A1-style notation if (coordinates.Contains(noteRef)) { throw new InvalidOperationException("found multiple cell comments for cell " + noteRef); } else { coordinates.Add(noteRef, null); } } } /** * @param shape to be removed * @return true of shape is removed */ public bool RemoveShape(HSSFShape shape) { bool isRemoved = _mainSpgrContainer.RemoveChildRecord(shape.GetEscherContainer()); if (isRemoved) { shape.AfterRemove(this); _shapes.Remove(shape); } return isRemoved; } internal void AfterCreate() { DrawingManager2 drawingManager = ((HSSFWorkbook)_sheet.Workbook).Workbook.DrawingManager; short dgId = drawingManager.FindNewDrawingGroupId(); _boundAggregate.SetDgId(dgId); _boundAggregate.SetMainSpRecordId(NewShapeId()); drawingManager.IncrementDrawingsSaved(); } /// <summary> /// Creates a new Group record stored Under this patriarch. /// </summary> /// <param name="anchor">the client anchor describes how this Group is attached /// to the sheet.</param> /// <returns>the newly created Group.</returns> public HSSFShapeGroup CreateGroup(HSSFClientAnchor anchor) { HSSFShapeGroup group = new HSSFShapeGroup(null, anchor); AddShape(group); OnCreate(group); return group; } /// <summary> /// Creates a simple shape. This includes such shapes as lines, rectangles, /// and ovals. /// </summary> /// <param name="anchor">the client anchor describes how this Group is attached /// to the sheet.</param> /// <returns>the newly created shape.</returns> public HSSFSimpleShape CreateSimpleShape(HSSFClientAnchor anchor) { HSSFSimpleShape shape = new HSSFSimpleShape(null, anchor); AddShape(shape); //open existing file OnCreate(shape); return shape; } /// <summary> /// Creates a picture. /// </summary> /// <param name="anchor">the client anchor describes how this Group is attached /// to the sheet.</param> /// <param name="pictureIndex">Index of the picture.</param> /// <returns>the newly created shape.</returns> public IPicture CreatePicture(HSSFClientAnchor anchor, int pictureIndex) { HSSFPicture shape = new HSSFPicture(null, (HSSFClientAnchor)anchor); shape.PictureIndex = pictureIndex; AddShape(shape); //open existing file OnCreate(shape); return shape; } /// <summary> /// CreatePicture /// </summary> /// <param name="anchor">the client anchor describes how this picture is attached to the sheet.</param> /// <param name="pictureIndex">the index of the picture in the workbook collection of pictures.</param> /// <returns>return newly created shape</returns> public IPicture CreatePicture(IClientAnchor anchor, int pictureIndex) { return CreatePicture((HSSFClientAnchor)anchor, pictureIndex); } /// <summary> /// Creates a polygon /// </summary> /// <param name="anchor">the client anchor describes how this Group is attached /// to the sheet.</param> /// <returns>the newly Created shape.</returns> public HSSFPolygon CreatePolygon(IClientAnchor anchor) { HSSFPolygon shape = new HSSFPolygon(null, (HSSFAnchor)anchor); AddShape(shape); OnCreate(shape); return shape; } /// <summary> /// Constructs a textbox Under the patriarch. /// </summary> /// <param name="anchor">the client anchor describes how this Group is attached /// to the sheet.</param> /// <returns>the newly Created textbox.</returns> public HSSFSimpleShape CreateTextbox(IClientAnchor anchor) { HSSFTextbox shape = new HSSFTextbox(null, (HSSFAnchor)anchor); AddShape(shape); OnCreate(shape); return shape; } /** * Constructs a cell comment. * * @param anchor the client anchor describes how this comment is attached * to the sheet. * @return the newly created comment. */ public HSSFComment CreateComment(HSSFAnchor anchor) { HSSFComment shape = new HSSFComment(null, anchor); AddShape(shape); OnCreate(shape); return shape; } /** * YK: used to create autofilters * * @see org.apache.poi.hssf.usermodel.HSSFSheet#setAutoFilter(int, int, int, int) */ public HSSFSimpleShape CreateComboBox(HSSFAnchor anchor) { HSSFCombobox shape = new HSSFCombobox(null, anchor); AddShape(shape); OnCreate(shape); return shape; } /// <summary> /// Constructs a cell comment. /// </summary> /// <param name="anchor">the client anchor describes how this comment is attached /// to the sheet.</param> /// <returns>the newly created comment.</returns> public IComment CreateCellComment(IClientAnchor anchor) { return CreateComment((HSSFAnchor)anchor); } private void SetFlipFlags(HSSFShape shape) { EscherSpRecord sp = (EscherSpRecord)shape.GetEscherContainer().GetChildById(EscherSpRecord.RECORD_ID); if (shape.Anchor.IsHorizontallyFlipped) { sp.Flags = (sp.Flags | EscherSpRecord.FLAG_FLIPHORIZ); } if (shape.Anchor.IsVerticallyFlipped) { sp.Flags = (sp.Flags | EscherSpRecord.FLAG_FLIPVERT); } } /// <summary> /// Returns a list of all shapes contained by the patriarch. /// </summary> /// <value>The children.</value> public IList<HSSFShape> Children { get { return _shapes; } } /** * add a shape to this drawing */ public void AddShape(HSSFShape shape) { shape.Patriarch = this; _shapes.Add(shape); } private void OnCreate(HSSFShape shape) { EscherContainerRecord spgrContainer = _boundAggregate.GetEscherContainer().ChildContainers[0]; EscherContainerRecord spContainer = shape.GetEscherContainer(); int shapeId = NewShapeId(); shape.ShapeId = shapeId; spgrContainer.AddChildRecord(spContainer); shape.AfterInsert(this); SetFlipFlags(shape); } /// <summary> /// Total count of all children and their children's children. /// </summary> /// <value>The count of all children.</value> public int CountOfAllChildren { get { int count = _shapes.Count; for (IEnumerator iterator = _shapes.GetEnumerator(); iterator.MoveNext(); ) { HSSFShape shape = (HSSFShape)iterator.Current; count += shape.CountOfAllChildren; } return count; } } /// <summary> /// Sets the coordinate space of this Group. All children are contrained /// to these coordinates. /// </summary> /// <param name="x1">The x1.</param> /// <param name="y1">The y1.</param> /// <param name="x2">The x2.</param> /// <param name="y2">The y2.</param> public void SetCoordinates(int x1, int y1, int x2, int y2) { _spgrRecord.RectY1 = (y1); _spgrRecord.RectY2 = (y2); _spgrRecord.RectX1 = (x1); _spgrRecord.RectX2 = (x2); } public void Clear() { List<HSSFShape> copy = new List<HSSFShape>(_shapes); foreach (HSSFShape shape in copy) { RemoveShape(shape); } } internal int NewShapeId() { DrawingManager2 dm = ((HSSFWorkbook)_sheet.Workbook).Workbook.DrawingManager; EscherDgRecord dg = (EscherDgRecord)_boundAggregate.GetEscherContainer().GetChildById(EscherDgRecord.RECORD_ID); short drawingGroupId = dg.DrawingGroupId; return dm.AllocateShapeId(drawingGroupId, dg); } /// <summary> /// Does this HSSFPatriarch contain a chart? /// (Technically a reference to a chart, since they /// Get stored in a different block of records) /// FIXME - detect chart in all cases (only seems /// to work on some charts so far) /// </summary> /// <returns> /// <c>true</c> if this instance contains chart; otherwise, <c>false</c>. /// </returns> public bool ContainsChart() { // TODO - support charts properly in usermodel // We're looking for a EscherOptRecord EscherOptRecord optRecord = (EscherOptRecord) _boundAggregate.FindFirstWithId(EscherOptRecord.RECORD_ID); if (optRecord == null) { // No opt record, can't have chart return false; } for (IEnumerator it = optRecord.EscherProperties.GetEnumerator(); it.MoveNext(); ) { EscherProperty prop = (EscherProperty)it.Current; if (prop.PropertyNumber == 896 && prop.IsComplex) { EscherComplexProperty cp = (EscherComplexProperty)prop; String str = StringUtil.GetFromUnicodeLE(cp.ComplexData); //Console.Error.WriteLine(str); if (str.Equals("Chart 1\0")) { return true; } } } return false; } /// <summary> /// The top left x coordinate of this Group. /// </summary> /// <value>The x1.</value> public int X1 { get { return _spgrRecord.RectX1; } } /// <summary> /// The top left y coordinate of this Group. /// </summary> /// <value>The y1.</value> public int Y1 { get { return _spgrRecord.RectY1; } } /// <summary> /// The bottom right x coordinate of this Group. /// </summary> /// <value>The x2.</value> public int X2 { get { return _spgrRecord.RectX2; } } /// <summary> /// The bottom right y coordinate of this Group. /// </summary> /// <value>The y2.</value> public int Y2 { get { return _spgrRecord.RectY2; } } /// <summary> /// Returns the aggregate escher record we're bound to /// </summary> /// <returns></returns> internal EscherAggregate GetBoundAggregate() { return _boundAggregate; } internal EscherAggregate getBoundAggregate() { return _boundAggregate; } /** * Creates a new client anchor and sets the top-left and bottom-right * coordinates of the anchor. * * @param dx1 the x coordinate in EMU within the first cell. * @param dy1 the y coordinate in EMU within the first cell. * @param dx2 the x coordinate in EMU within the second cell. * @param dy2 the y coordinate in EMU within the second cell. * @param col1 the column (0 based) of the first cell. * @param row1 the row (0 based) of the first cell. * @param col2 the column (0 based) of the second cell. * @param row2 the row (0 based) of the second cell. * @return the newly created client anchor */ public IClientAnchor CreateAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) { return new HSSFClientAnchor(dx1, dy1, dx2, dy2, (short)col1, row1, (short)col2, row2); } public IChart CreateChart(IClientAnchor anchor) { throw new RuntimeException("NotImplemented"); } /** * create shape tree from existing escher records tree */ public void BuildShapeTree() { EscherContainerRecord dgContainer = _boundAggregate.GetEscherContainer(); if (dgContainer == null) { return; } EscherContainerRecord spgrConrainer = dgContainer.ChildContainers[0]; IList<EscherContainerRecord> spgrChildren = spgrConrainer.ChildContainers; for (int i = 0; i < spgrChildren.Count; i++) { EscherContainerRecord spContainer = spgrChildren[i]; if (i != 0) { HSSFShapeFactory.CreateShapeTree(spContainer, _boundAggregate, this, ((HSSFWorkbook)_sheet.Workbook).RootDirectory); } } } public List<HSSFShape> GetShapes() { return _shapes; } public IEnumerator<HSSFShape> GetEnumerator() { return _shapes.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _shapes.GetEnumerator(); } protected internal HSSFSheet Sheet { get { return _sheet; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using System.Xml.XPath; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TestUtilities { public static class AssertUtil { public static void RequiresMta() { if (Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA) { Assert.Inconclusive("Test requires MTA appartment to call COM reliably. Add solution item <root>\\Build\\Default.testsettings."); } } public static void Throws<TExpected>(Action throwingAction) { Throws<TExpected>(throwingAction, null); } public static void Throws<TExpected>(Action throwingAction, string description) { bool exceptionThrown = false; Type expectedType = typeof(TExpected); try { throwingAction(); } catch (Exception ex) { exceptionThrown = true; Type thrownType = ex.GetType(); if (!expectedType.IsAssignableFrom(thrownType)) { Assert.Fail("AssertUtil.Throws failure. Expected exception {0} not assignable from exception {1}, message: {2}", expectedType.FullName, thrownType.FullName, description); } } if (!exceptionThrown) { Assert.Fail("AssertUtil.Throws failure. Expected exception {0} but not exception thrown, message: {1}", expectedType.FullName, description); } } public static void MissingDependency(string dependency) { Assert.Inconclusive("Missing Dependency: {0}", dependency); } public static void ArrayEquals<T>(IEnumerable<T> expected, IEnumerable<T> actual) { if (expected == null) { throw new ArgumentNullException("expected"); } if (actual == null) { Assert.Fail("Actual collection is null."); } Assert.AreEqual(expected.Count(), actual.Count()); var expectedIt = expected.GetEnumerator(); var actualIt = actual.GetEnumerator(); for (var i = 0; expectedIt.MoveNext() && actualIt.MoveNext(); ++i) { Assert.AreEqual(expectedIt.Current, actualIt.Current, string.Format("Assetion failed at index {0}", i)); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1")] public static void ArrayEquals(IList expected, IList actual, Func<object, object, bool> comparison) { if (expected == null) { throw new ArgumentNullException("expected"); } if (actual == null) { Assert.Fail("AssertUtils.ArrayEquals failure. Actual collection is null."); } if (comparison == null) { throw new ArgumentNullException("comparison"); } if (expected.Count != actual.Count) { Assert.Fail("AssertUtils.ArrayEquals failure. Expected collection with length {0} but got collection with length {1}", expected.Count, actual.Count); } for (int i = 0; i < expected.Count; i++) { if (!comparison(expected[i], actual[i])) { Assert.Fail("AssertUtils.ArrayEquals failure. Expected value {0} at position {1} but got value {2}", expected[i], i, actual[i]); } } } /// <summary> /// Asserts that two doubles are equal with regard to floating point error. /// Uses a default error message /// </summary> /// <param name="expected">Expected double value</param> /// <param name="actual">Actual double value</param> public static void DoublesEqual(double expected, double actual) { DoublesEqual(expected, actual, String.Format("AssertUtils.DoublesEqual failure. Expected value {0} but got value {1}", expected, actual)); } /// <summary> /// Asserts that two doubles are equal with regard to floating point error /// </summary> /// <param name="expected">Expected double value</param> /// <param name="actual">Actual double value</param> /// <param name="error">Error message to display</param> public static void DoublesEqual(double expected, double actual, string error) { if (!(expected - actual < double.Epsilon && expected - actual > -double.Epsilon)) { Assert.Fail(error); } } [System.Diagnostics.DebuggerStepThrough] public static void Contains(string source, params string[] values) { foreach (var v in values) { if (!source.Contains(v)) { Assert.Fail(String.Format("{0} does not contain {1}", source, v)); } } } [System.Diagnostics.DebuggerStepThrough] public static void Contains<T>(IEnumerable<T> source, T value) { foreach (var v in source) { if (v.Equals(value)) { return; } } Assert.Fail(String.Format("{0} does not contain {1}", MakeText(source), value)); } [System.Diagnostics.DebuggerStepThrough] public static void AreEqual<T>(IEnumerable<T> source, params T[] value) { var items = source.ToArray(); var message = string.Format( "Expected: <\n{0}\n>.\nActual: <\n{1}\n>.", string.Join("\n", value), string.Join("\n", items) ); Console.WriteLine(message); Assert.AreEqual(value.Length, items.Length, message); for (int i = 0; i < value.Length; i++) { Assert.AreEqual(value[i], items[i]); } } [System.Diagnostics.DebuggerStepThrough] public static void DoesntContain<T>(IEnumerable<T> source, T value) { foreach (var v in source) { if (v.Equals(value)) { Assert.Fail(String.Format("{0} contains {1}", MakeText(source), value)); } } } [System.Diagnostics.DebuggerStepThrough] public static void ContainsExactly<T>(IEnumerable<T> source, IEnumerable<T> expected) { ContainsExactly(new HashSet<T>(source), expected.ToArray()); } [System.Diagnostics.DebuggerStepThrough] public static void ContainsExactly<T>(IEnumerable<T> source, params T[] expected) { ContainsExactly(new HashSet<T>(source), expected); } [System.Diagnostics.DebuggerStepThrough] public static void ContainsExactly<T>(HashSet<T> set, params T[] expected) { if (set.ContainsExactly(expected)) { return; } Assert.Fail(String.Format("ContainsExactly failed.\n\nExpected:\n{0}\n\nActual:\n{1}\n\nExpected not in actual:\n{2}\n\nActual not in expected:\n{3}", MakeText(expected), MakeText(set), MakeText(expected.Except(set)), MakeText(set.Except(expected)))); } [System.Diagnostics.DebuggerStepThrough] public static void ContainsAtLeast<T>(IEnumerable<T> source, IEnumerable<T> values) { ContainsAtLeast(new HashSet<T>(source), values.ToArray()); } [System.Diagnostics.DebuggerStepThrough] public static void ContainsAtLeast<T>(IEnumerable<T> source, params T[] values) { ContainsAtLeast(new HashSet<T>(source), values); } [System.Diagnostics.DebuggerStepThrough] public static void ContainsAtLeast<T>(HashSet<T> set, params T[] values) { if (set.IsSupersetOf(values)) { return; } var missing = new HashSet<T>(values); missing.ExceptWith(set); Assert.Fail(String.Format("Expected at least {0}, didn't find {1}. All: {2}", MakeText(values), MakeText(missing), MakeText(set) )); } public static string MakeText<T>(IEnumerable<T> values) { var ss = values.Select(x => x == null ? "(null)" : x.ToString()).ToArray(); bool multiline = ss.Sum(s => s.Length) > 60; var sb = new StringBuilder("{"); if (multiline) { sb.Append("\n"); } bool first = true; foreach (var s in ss) { if (first) { first = false; } else { sb.Append(multiline ? ",\n" : ", "); } sb.Append(s); } if (multiline) { sb.Append("\n"); } sb.Append("}"); return sb.ToString(); } public static void AreEqual(Regex expected, string actual, string message = null) { if (!expected.IsMatch(actual)) { Assert.Fail(string.Format("Expected <{0}>. Actual <{1}>. {2}", expected, actual, message ?? "")); } } public static void AreEqual(string expected, XmlDocument actual, string message = null) { var expectedDoc = new XmlDocument(); expectedDoc.LoadXml(expected); AreEqual(expectedDoc, actual, message); } public static void AreEqual(XmlDocument expected, XmlDocument actual, string message = null) { var nav1 = expected.CreateNavigator(); var nav2 = actual.CreateNavigator(); if (string.IsNullOrEmpty(message)) { message = string.Empty; } else { message = " " + message; } AreXPathNavigatorsEqual(nav1, nav2, message); } private static string GetFullPath(XPathNavigator nav) { nav = nav.CreateNavigator(); var names = new Stack<string>(); names.Push(nav.Name); while (nav.MoveToParent()) { names.Push(nav.Name); } return "/" + string.Join("/", names); } private static void AreXPathNavigatorsEqual(XPathNavigator nav1, XPathNavigator nav2, string message) { while (true) { if (nav1.Name != nav2.Name) { Assert.Fail("Expected element <{0}>. Actual element <{1}>.{2}", nav1.Name, nav2.Name, message); } var anav1 = nav1.CreateNavigator(); var anav2 = nav2.CreateNavigator(); var attr1 = new List<string>(); var attr2 = new List<string>(); if (anav1.MoveToFirstAttribute()) { do { attr1.Add(string.Format("{0}=\"{1}\"", anav1.Name, anav1.Value)); } while (anav1.MoveToNextAttribute()); } if (anav2.MoveToFirstAttribute()) { do { attr2.Add(string.Format("{0}=\"{1}\"", anav2.Name, anav2.Value)); } while (anav2.MoveToNextAttribute()); } AssertUtil.ContainsExactly(attr2, attr1); var cnav1 = nav1.CreateNavigator(); var cnav2 = nav2.CreateNavigator(); if (cnav1.MoveToFirstChild()) { if (cnav2.MoveToFirstChild()) { AreXPathNavigatorsEqual(cnav1, cnav2, message); } else { Assert.Fail("Expected element {0}.{1}", GetFullPath(cnav1), message); } } else if (cnav2.MoveToFirstChild()) { Assert.Fail("Unexpected element {0}.{1}", GetFullPath(cnav2), message); } if (nav1.MoveToNext()) { if (nav2.MoveToNext()) { continue; } else { Assert.Fail("Expected element {0}.{1}", GetFullPath(nav1), message); } } else if (nav2.MoveToNext()) { Assert.Fail("Unexpected element {0}.{1}", GetFullPath(nav2), message); } break; } } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class CanvassPositionDecoder { public const ushort BLOCK_LENGTH = 28; public const ushort TEMPLATE_ID = 50; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private CanvassPositionDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public CanvassPositionDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public CanvassPositionDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int LogLeadershipTermIdId() { return 1; } public static int LogLeadershipTermIdSinceVersion() { return 0; } public static int LogLeadershipTermIdEncodingOffset() { return 0; } public static int LogLeadershipTermIdEncodingLength() { return 8; } public static string LogLeadershipTermIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LogLeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LogLeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LogLeadershipTermIdMaxValue() { return 9223372036854775807L; } public long LogLeadershipTermId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int LogPositionId() { return 2; } public static int LogPositionSinceVersion() { return 0; } public static int LogPositionEncodingOffset() { return 8; } public static int LogPositionEncodingLength() { return 8; } public static string LogPositionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LogPositionNullValue() { return -9223372036854775808L; } public static long LogPositionMinValue() { return -9223372036854775807L; } public static long LogPositionMaxValue() { return 9223372036854775807L; } public long LogPosition() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int LeadershipTermIdId() { return 3; } public static int LeadershipTermIdSinceVersion() { return 0; } public static int LeadershipTermIdEncodingOffset() { return 16; } public static int LeadershipTermIdEncodingLength() { return 8; } public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long LeadershipTermIdNullValue() { return -9223372036854775808L; } public static long LeadershipTermIdMinValue() { return -9223372036854775807L; } public static long LeadershipTermIdMaxValue() { return 9223372036854775807L; } public long LeadershipTermId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public static int FollowerMemberIdId() { return 4; } public static int FollowerMemberIdSinceVersion() { return 0; } public static int FollowerMemberIdEncodingOffset() { return 24; } public static int FollowerMemberIdEncodingLength() { return 4; } public static string FollowerMemberIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int FollowerMemberIdNullValue() { return -2147483648; } public static int FollowerMemberIdMinValue() { return -2147483647; } public static int FollowerMemberIdMaxValue() { return 2147483647; } public int FollowerMemberId() { return _buffer.GetInt(_offset + 24, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[CanvassPosition](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='logLeadershipTermId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LogLeadershipTermId="); builder.Append(LogLeadershipTermId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='logPosition', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LogPosition="); builder.Append(LogPosition()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("LeadershipTermId="); builder.Append(LeadershipTermId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='followerMemberId', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int32', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=4, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("FollowerMemberId="); builder.Append(FollowerMemberId()); Limit(originalLimit); return builder; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Collections { public sealed partial class BitArray : System.Collections.ICollection, System.Collections.IEnumerable { public BitArray(bool[] values) { } public BitArray(byte[] bytes) { } public BitArray(System.Collections.BitArray bits) { } public BitArray(int length) { } public BitArray(int length, bool defaultValue) { } public BitArray(int[] values) { } public bool this[int index] { get { return default(bool); } set { } } public int Length { get { return default(int); } set { } } public int Count { get { return default(int); } } public bool IsReadOnly { get { return default(bool); } } public bool IsSynchronized { get { return default(bool); } } public object Clone() { return default(System.Collections.BitArray); } public object SyncRoot { get { return default(object); } } public System.Collections.BitArray And(System.Collections.BitArray value) { return default(System.Collections.BitArray); } public bool Get(int index) { return default(bool); } public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public System.Collections.BitArray Not() { return default(System.Collections.BitArray); } public System.Collections.BitArray Or(System.Collections.BitArray value) { return default(System.Collections.BitArray); } public void Set(int index, bool value) { } public void SetAll(bool value) { } public void CopyTo(System.Array array, int index) { } public System.Collections.BitArray Xor(System.Collections.BitArray value) { return default(System.Collections.BitArray); } } public static partial class StructuralComparisons { public static System.Collections.IComparer StructuralComparer { get { return default(System.Collections.IComparer); } } public static System.Collections.IEqualityComparer StructuralEqualityComparer { get { return default(System.Collections.IEqualityComparer); } } } } namespace System.Collections.Generic { public abstract partial class Comparer<T> : System.Collections.Generic.IComparer<T>, System.Collections.IComparer { protected Comparer() { } public static System.Collections.Generic.Comparer<T> Default { get { return default(System.Collections.Generic.Comparer<T>); } } public abstract int Compare(T x, T y); public static System.Collections.Generic.Comparer<T> Create(System.Comparison<T> comparison) { return default(System.Collections.Generic.Comparer<T>); } int System.Collections.IComparer.Compare(object x, object y) { return default(int); } } public partial class Dictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public Dictionary() { } public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public Dictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey> comparer) { } public Dictionary(System.Collections.Generic.IEqualityComparer<TKey> comparer) { } protected Dictionary(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public Dictionary(int capacity) { } public Dictionary(int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer) { } public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { return default(System.Collections.Generic.IEqualityComparer<TKey>); } } public int Count { get { return default(int); } } public TValue this[TKey key] { get { return default(TValue); } set { } } public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get { return default(System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection); } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { return default(bool); } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.ICollection<TKey>); } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.ICollection<TValue>); } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.IEnumerable<TKey>); } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.IEnumerable<TValue>); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } } object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } } System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } } public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection Values { get { return default(System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection); } } public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { return default(bool); } public bool ContainsValue(TValue value) { return default(bool); } public System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator GetEnumerator() { return default(System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator); } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual void OnDeserialization(object sender) { } public bool Remove(TKey key) { return default(bool); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { return default(bool); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return default(bool); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable { public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { return default(System.Collections.Generic.KeyValuePair<TKey, TValue>); } } System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { return default(System.Collections.DictionaryEntry); } } object System.Collections.IDictionaryEnumerator.Key { get { return default(object); } } object System.Collections.IDictionaryEnumerator.Value { get { return default(object); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable { public KeyCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void CopyTo(TKey[] array, int index) { } public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { return default(System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection.Enumerator); } void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { } void System.Collections.Generic.ICollection<TKey>.Clear() { } bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { return default(bool); } bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { return default(bool); } System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TKey>); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable { public TKey Current { get { return default(TKey); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable { public ValueCollection(System.Collections.Generic.Dictionary<TKey, TValue> dictionary) { } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void CopyTo(TValue[] array, int index) { } public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { return default(System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection.Enumerator); } void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { } void System.Collections.Generic.ICollection<TValue>.Clear() { } bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { return default(bool); } bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { return default(bool); } System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TValue>); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable { public TValue Current { get { return default(TValue); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } } public abstract partial class EqualityComparer<T> : System.Collections.Generic.IEqualityComparer<T>, System.Collections.IEqualityComparer { protected EqualityComparer() { } public static System.Collections.Generic.EqualityComparer<T> Default { get { return default(System.Collections.Generic.EqualityComparer<T>); } } public abstract bool Equals(T x, T y); public abstract int GetHashCode(T obj); bool System.Collections.IEqualityComparer.Equals(object x, object y) { return default(bool); } int System.Collections.IEqualityComparer.GetHashCode(object obj) { return default(int); } } public partial class HashSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public HashSet() { } public HashSet(System.Collections.Generic.IEnumerable<T> collection) { } public HashSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IEqualityComparer<T> comparer) { } public HashSet(System.Collections.Generic.IEqualityComparer<T> comparer) { } protected HashSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Collections.Generic.IEqualityComparer<T> Comparer { get { return default(System.Collections.Generic.IEqualityComparer<T>); } } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } } public bool Add(T item) { return default(bool); } public void Clear() { } public bool Contains(T item) { return default(bool); } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int arrayIndex) { } public void CopyTo(T[] array, int arrayIndex, int count) { } public static IEqualityComparer<HashSet<T>> CreateSetComparer() { return default(IEqualityComparer<HashSet<T>>); } public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { } public System.Collections.Generic.HashSet<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.HashSet<T>.Enumerator); } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { } public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public virtual void OnDeserialization(object sender) { } public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public bool Remove(T item) { return default(bool); } public int RemoveWhere(System.Predicate<T> match) { return default(int); } public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { } void System.Collections.Generic.ICollection<T>.Add(T item) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public void TrimExcess() { } public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { public T Current { get { return default(T); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } public partial class LinkedList<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public LinkedList() { } public LinkedList(System.Collections.Generic.IEnumerable<T> collection) { } protected LinkedList(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public int Count { get { return default(int); } } public System.Collections.Generic.LinkedListNode<T> First { get { return default(System.Collections.Generic.LinkedListNode<T>); } } public System.Collections.Generic.LinkedListNode<T> Last { get { return default(System.Collections.Generic.LinkedListNode<T>); } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public System.Collections.Generic.LinkedListNode<T> AddAfter(System.Collections.Generic.LinkedListNode<T> node, T value) { return default(System.Collections.Generic.LinkedListNode<T>); } public void AddAfter(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { } public System.Collections.Generic.LinkedListNode<T> AddBefore(System.Collections.Generic.LinkedListNode<T> node, T value) { return default(System.Collections.Generic.LinkedListNode<T>); } public void AddBefore(System.Collections.Generic.LinkedListNode<T> node, System.Collections.Generic.LinkedListNode<T> newNode) { } public System.Collections.Generic.LinkedListNode<T> AddFirst(T value) { return default(System.Collections.Generic.LinkedListNode<T>); } public void AddFirst(System.Collections.Generic.LinkedListNode<T> node) { } public System.Collections.Generic.LinkedListNode<T> AddLast(T value) { return default(System.Collections.Generic.LinkedListNode<T>); } public void AddLast(System.Collections.Generic.LinkedListNode<T> node) { } public void Clear() { } public bool Contains(T value) { return default(bool); } public void CopyTo(T[] array, int index) { } public System.Collections.Generic.LinkedListNode<T> Find(T value) { return default(System.Collections.Generic.LinkedListNode<T>); } public System.Collections.Generic.LinkedListNode<T> FindLast(T value) { return default(System.Collections.Generic.LinkedListNode<T>); } public System.Collections.Generic.LinkedList<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.LinkedList<T>.Enumerator); } public virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual void OnDeserialization(object sender) { } public bool Remove(T value) { return default(bool); } public void Remove(System.Collections.Generic.LinkedListNode<T> node) { } public void RemoveFirst() { } public void RemoveLast() { } void System.Collections.Generic.ICollection<T>.Add(T value) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public T Current { get { return default(T); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public bool MoveNext() { return default(bool); } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(Object sender) { } void System.Collections.IEnumerator.Reset() { } } } public sealed partial class LinkedListNode<T> { public LinkedListNode(T value) { } public System.Collections.Generic.LinkedList<T> List { get { return default(System.Collections.Generic.LinkedList<T>); } } public System.Collections.Generic.LinkedListNode<T> Next { get { return default(System.Collections.Generic.LinkedListNode<T>); } } public System.Collections.Generic.LinkedListNode<T> Previous { get { return default(System.Collections.Generic.LinkedListNode<T>); } } public T Value { get { return default(T); } set { } } } public partial class List<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { public List() { } public List(System.Collections.Generic.IEnumerable<T> collection) { } public List(int capacity) { } public int Capacity { get { return default(int); } set { } } public int Count { get { return default(int); } } public T this[int index] { get { return default(T); } set { } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IList.IsFixedSize { get { return default(bool); } } bool System.Collections.IList.IsReadOnly { get { return default(bool); } } object System.Collections.IList.this[int index] { get { return default(object); } set { } } public void Add(T item) { } public void AddRange(System.Collections.Generic.IEnumerable<T> collection) { } public System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly() { return default(System.Collections.ObjectModel.ReadOnlyCollection<T>); } public int BinarySearch(T item) { return default(int); } public int BinarySearch(T item, System.Collections.Generic.IComparer<T> comparer) { return default(int); } public int BinarySearch(int index, int count, T item, System.Collections.Generic.IComparer<T> comparer) { return default(int); } public void Clear() { } public bool Contains(T item) { return default(bool); } public List<TOutput> ConvertAll<TOutput>(System.Converter<T,TOutput> converter) { return default(List<TOutput>); } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int arrayIndex) { } public void CopyTo(int index, T[] array, int arrayIndex, int count) { } public bool Exists(System.Predicate<T> match) { return default(bool); } public T Find(System.Predicate<T> match) { return default(T); } public System.Collections.Generic.List<T> FindAll(System.Predicate<T> match) { return default(System.Collections.Generic.List<T>); } public int FindIndex(int startIndex, int count, System.Predicate<T> match) { return default(int); } public int FindIndex(int startIndex, System.Predicate<T> match) { return default(int); } public int FindIndex(System.Predicate<T> match) { return default(int); } public T FindLast(System.Predicate<T> match) { return default(T); } public int FindLastIndex(int startIndex, int count, System.Predicate<T> match) { return default(int); } public int FindLastIndex(int startIndex, System.Predicate<T> match) { return default(int); } public int FindLastIndex(System.Predicate<T> match) { return default(int); } public void ForEach(System.Action<T> action) { } public System.Collections.Generic.List<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.List<T>.Enumerator); } public System.Collections.Generic.List<T> GetRange(int index, int count) { return default(System.Collections.Generic.List<T>); } public int IndexOf(T item) { return default(int); } public int IndexOf(T item, int index) { return default(int); } public int IndexOf(T item, int index, int count) { return default(int); } public void Insert(int index, T item) { } public void InsertRange(int index, System.Collections.Generic.IEnumerable<T> collection) { } public int LastIndexOf(T item) { return default(int); } public int LastIndexOf(T item, int index) { return default(int); } public int LastIndexOf(T item, int index, int count) { return default(int); } public bool Remove(T item) { return default(bool); } public int RemoveAll(System.Predicate<T> match) { return default(int); } public void RemoveAt(int index) { } public void RemoveRange(int index, int count) { } public void Reverse() { } public void Reverse(int index, int count) { } public void Sort() { } public void Sort(System.Collections.Generic.IComparer<T> comparer) { } public void Sort(System.Comparison<T> comparison) { } public void Sort(int index, int count, System.Collections.Generic.IComparer<T> comparer) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); } void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } int System.Collections.IList.Add(object item) { return default(int); } bool System.Collections.IList.Contains(object item) { return default(bool); } int System.Collections.IList.IndexOf(object item) { return default(int); } void System.Collections.IList.Insert(int index, object item) { } void System.Collections.IList.Remove(object item) { } public T[] ToArray() { return default(T[]); } public void TrimExcess() { } public bool TrueForAll(System.Predicate<T> match) { return default(bool); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { public T Current { get { return default(T); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } public partial class Queue<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable { public Queue() { } public Queue(System.Collections.Generic.IEnumerable<T> collection) { } public Queue(int capacity) { } public int Count { get { return default(int); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void Clear() { } public bool Contains(T item) { return default(bool); } public void CopyTo(T[] array, int arrayIndex) { } public T Dequeue() { return default(T); } public void Enqueue(T item) { } public System.Collections.Generic.Queue<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.Queue<T>.Enumerator); } public T Peek() { return default(T); } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public T[] ToArray() { return default(T[]); } public void TrimExcess() { } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { public T Current { get { return default(T); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } public partial class SortedDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public SortedDictionary() { } public SortedDictionary(System.Collections.Generic.IComparer<TKey> comparer) { } public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public SortedDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { } public System.Collections.Generic.IComparer<TKey> Comparer { get { return default(System.Collections.Generic.IComparer<TKey>); } } public int Count { get { return default(int); } } public TValue this[TKey key] { get { return default(TValue); } set { } } public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection Keys { get { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection); } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { return default(bool); } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.ICollection<TKey>); } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.ICollection<TValue>); } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.IEnumerable<TKey>); } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.IEnumerable<TValue>); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } } object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } } System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } } public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection Values { get { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection); } } public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { return default(bool); } public bool ContainsValue(TValue value) { return default(bool); } public void CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { } public System.Collections.Generic.SortedDictionary<TKey, TValue>.Enumerator GetEnumerator() { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.Enumerator); } public bool Remove(TKey key) { return default(bool); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { return default(bool); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return default(bool); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator, System.IDisposable { public System.Collections.Generic.KeyValuePair<TKey, TValue> Current { get { return default(System.Collections.Generic.KeyValuePair<TKey, TValue>); } } System.Collections.DictionaryEntry System.Collections.IDictionaryEnumerator.Entry { get { return default(System.Collections.DictionaryEntry); } } object System.Collections.IDictionaryEnumerator.Key { get { return default(object); } } object System.Collections.IDictionaryEnumerator.Value { get { return default(object); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable { public KeyCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void CopyTo(TKey[] array, int index) { } public System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection.Enumerator GetEnumerator() { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.KeyCollection.Enumerator); } void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { } void System.Collections.Generic.ICollection<TKey>.Clear() { } bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { return default(bool); } bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { return default(bool); } System.Collections.Generic.IEnumerator<TKey> System.Collections.Generic.IEnumerable<TKey>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TKey>); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<TKey>, System.Collections.IEnumerator, System.IDisposable { public TKey Current { get { return default(TKey); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable { public ValueCollection(System.Collections.Generic.SortedDictionary<TKey, TValue> dictionary) { } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void CopyTo(TValue[] array, int index) { } public System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection.Enumerator GetEnumerator() { return default(System.Collections.Generic.SortedDictionary<TKey, TValue>.ValueCollection.Enumerator); } void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { } void System.Collections.Generic.ICollection<TValue>.Clear() { } bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { return default(bool); } bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { return default(bool); } System.Collections.Generic.IEnumerator<TValue> System.Collections.Generic.IEnumerable<TValue>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TValue>); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<TValue>, System.Collections.IEnumerator, System.IDisposable { public TValue Current { get { return default(TValue); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } } public partial class SortedList<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public SortedList() { } public SortedList(System.Collections.Generic.IComparer<TKey> comparer) { } public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public SortedList(System.Collections.Generic.IDictionary<TKey, TValue> dictionary, System.Collections.Generic.IComparer<TKey> comparer) { } public SortedList(int capacity) { } public SortedList(int capacity, System.Collections.Generic.IComparer<TKey> comparer) { } public int Capacity { get { return default(int); } set { } } public System.Collections.Generic.IComparer<TKey> Comparer { get { return default(System.Collections.Generic.IComparer<TKey>); } } public int Count { get { return default(int); } } public TValue this[TKey key] { get { return default(TValue); } set { } } public System.Collections.Generic.IList<TKey> Keys { get { return default(System.Collections.Generic.IList<TKey>); } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { return default(bool); } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.ICollection<TKey>); } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.ICollection<TValue>); } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.IEnumerable<TKey>); } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.IEnumerable<TValue>); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } } object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } } System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } } public System.Collections.Generic.IList<TValue> Values { get { return default(System.Collections.Generic.IList<TValue>); } } public void Add(TKey key, TValue value) { } public void Clear() { } public bool ContainsKey(TKey key) { return default(bool); } public bool ContainsValue(TValue value) { return default(bool); } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); } public int IndexOfKey(TKey key) { return default(int); } public int IndexOfValue(TValue value) { return default(int); } public bool Remove(TKey key) { return default(bool); } public void RemoveAt(int index) { } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); } void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { } void System.Collections.IDictionary.Add(object key, object value) { } bool System.Collections.IDictionary.Contains(object key) { return default(bool); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public void TrimExcess() { } public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return default(bool); } } public partial class SortedSet<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.ISet<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public SortedSet() { } public SortedSet(System.Collections.Generic.IComparer<T> comparer) { } public SortedSet(System.Collections.Generic.IEnumerable<T> collection) { } public SortedSet(System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IComparer<T> comparer) { } protected SortedSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public System.Collections.Generic.IComparer<T> Comparer { get { return default(System.Collections.Generic.IComparer<T>); } } public int Count { get { return default(int); } } public T Max { get { return default(T); } } public T Min { get { return default(T); } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public bool Add(T item) { return default(bool); } public virtual void Clear() { } public virtual bool Contains(T item) { return default(bool); } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int index) { } public void CopyTo(T[] array, int index, int count) { } public static IEqualityComparer<SortedSet<T>> CreateSetComparer() { return default(IEqualityComparer<SortedSet<T>>); } public static IEqualityComparer<SortedSet<T>> CreateSetComparer(IEqualityComparer<T> memberEqualityComparer) { return default(IEqualityComparer<SortedSet<T>>); } public void ExceptWith(System.Collections.Generic.IEnumerable<T> other) { } public System.Collections.Generic.SortedSet<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.SortedSet<T>.Enumerator); } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } protected virtual void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual System.Collections.Generic.SortedSet<T> GetViewBetween(T lowerValue, T upperValue) { return default(System.Collections.Generic.SortedSet<T>); } public virtual void IntersectWith(System.Collections.Generic.IEnumerable<T> other) { } public bool IsProperSubsetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public bool IsProperSupersetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public bool IsSubsetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public bool IsSupersetOf(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } protected virtual void OnDeserialization(object sender) { } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } public bool Overlaps(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public bool Remove(T item) { return default(bool); } public int RemoveWhere(System.Predicate<T> match) { return default(int); } public System.Collections.Generic.IEnumerable<T> Reverse() { return default(System.Collections.Generic.IEnumerable<T>); } public bool SetEquals(System.Collections.Generic.IEnumerable<T> other) { return default(bool); } public void SymmetricExceptWith(System.Collections.Generic.IEnumerable<T> other) { } void System.Collections.Generic.ICollection<T>.Add(T item) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public void UnionWith(System.Collections.Generic.IEnumerable<T> other) { } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable { public T Current { get { return default(T); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public bool MoveNext() { return default(bool); } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender) { } void System.Collections.IEnumerator.Reset() { } } } public partial class Stack<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable { public Stack() { } public Stack(System.Collections.Generic.IEnumerable<T> collection) { } public Stack(int capacity) { } public int Count { get { return default(int); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void Clear() { } public bool Contains(T item) { return default(bool); } public void CopyTo(T[] array, int arrayIndex) { } public System.Collections.Generic.Stack<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.Stack<T>.Enumerator); } public T Peek() { return default(T); } public T Pop() { return default(T); } public void Push(T item) { } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(System.Collections.Generic.IEnumerator<T>); } void System.Collections.ICollection.CopyTo(System.Array array, int arrayIndex) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public T[] ToArray() { return default(T[]); } public void TrimExcess() { } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { public T Current { get { return default(T); } } object System.Collections.IEnumerator.Current { get { return default(object); } } public void Dispose() { } public bool MoveNext() { return default(bool); } void System.Collections.IEnumerator.Reset() { } } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; #if NET_45 using System.Collections.Generic; #endif namespace Octokit { /// <summary> /// A client for GitHub's Repositories API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/">Repositories API documentation</a> for more details. /// </remarks> public interface IRepositoriesClient { /// <summary> /// Client for managing pull requests. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/pulls/">Pull Requests API documentation</a> for more details /// </remarks> IPullRequestsClient PullRequest { get; } /// <summary> /// Client for managing commit comments in a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information. /// </remarks> [Obsolete("Comment information is now available under the Comment property. This will be removed in a future update.")] IRepositoryCommentsClient RepositoryComments { get; } /// <summary> /// Client for managing commit comments in a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information. /// </remarks> IRepositoryCommentsClient Comment { get; } /// <summary> /// Client for managing deploy keys in a repository. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/keys/">Repository Deploy Keys API documentation</a> for more information. /// </remarks> IRepositoryDeployKeysClient DeployKeys { get; } /// <summary> /// Client for managing the contents of a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/contents/">Repository Contents API documentation</a> for more information. /// </remarks> IRepositoryContentsClient Content { get; } /// <summary> /// Creates a new repository for the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information. /// </remarks> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/> instance for the created repository.</returns> Task<Repository> Create(NewRepository newRepository); /// <summary> /// Creates a new repository in the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information. /// </remarks> /// <param name="organizationLogin">Login of the organization in which to create the repository</param> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/> instance for the created repository</returns> Task<Repository> Create(string organizationLogin, NewRepository newRepository); /// <summary> /// Deletes the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information. /// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(string owner, string name); /// <summary> /// Deletes the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information. /// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required. /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(int repositoryId); /// <summary> /// Gets the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/></returns> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] Task<Repository> Get(string owner, string name); /// <summary> /// Gets the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/></returns> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] Task<Repository> Get(int repositoryId); /// <summary> /// Gets all public repositories. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] Task<IReadOnlyList<Repository>> GetAllPublic(); /// <summary> /// Gets all public repositories since the integer ID of the last Repository that you've seen. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters of the last repository seen</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllPublic(PublicRepositoryRequest request); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] Task<IReadOnlyList<Repository>> GetAllForCurrent(); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// </remarks> /// <param name="options">Options for changing the API response</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(ApiOptions options); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters to filter results on</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// </remarks> /// <param name="request">Search parameters to filter results on</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request, ApiOptions options); /// <summary> /// Gets all repositories owned by the specified user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="login">The account name to search for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForUser(string login); /// <summary> /// Gets all repositories owned by the specified user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information. /// </remarks> /// <param name="login">The account name to search for</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForUser(string login, ApiOptions options); /// <summary> /// Gets all repositories owned by the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="organization">The organization name to search for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForOrg(string organization); /// <summary> /// Gets all repositories owned by the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information. /// </remarks> /// <param name="organization">The organization name to search for</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForOrg(string organization, ApiOptions options); /// <summary> /// A client for GitHub's Commit Status API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more /// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a> /// that announced this feature. /// </remarks> [Obsolete("Use Status instead")] ICommitStatusClient CommitStatus { get; } /// <summary> /// A client for GitHub's Commit Status API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more /// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a> /// that announced this feature. /// </remarks> ICommitStatusClient Status { get; } /// <summary> /// A client for GitHub's Repository Hooks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/hooks/">Hooks API documentation</a> for more information.</remarks> IRepositoryHooksClient Hooks { get; } /// <summary> /// A client for GitHub's Repository Forks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/forks/">Forks API documentation</a> for more information.</remarks> IRepositoryForksClient Forks { get; } /// <summary> /// A client for GitHub's Repo Collaborators. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details /// </remarks> [Obsolete("Collaborator information is now available under the Collaborator property. This will be removed in a future update.")] IRepoCollaboratorsClient RepoCollaborators { get; } /// <summary> /// A client for GitHub's Repo Collaborators. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details /// </remarks> IRepoCollaboratorsClient Collaborator { get; } /// <summary> /// Client for GitHub's Repository Deployments API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/deployment/">Collaborators API documentation</a> for more details /// </remarks> IDeploymentsClient Deployment { get; } /// <summary> /// Client for GitHub's Repository Statistics API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statistics/">Statistics API documentation</a> for more details ///</remarks> IStatisticsClient Statistics { get; } /// <summary> /// Client for GitHub's Repository Commits API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details ///</remarks> [Obsolete("Commit information is now available under the Commit property. This will be removed in a future update.")] IRepositoryCommitsClient Commits { get; } /// <summary> /// Client for GitHub's Repository Commits API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details ///</remarks> IRepositoryCommitsClient Commit { get; } /// <summary> /// Access GitHub's Releases API. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/repos/releases/ /// </remarks> IReleasesClient Release { get; } /// <summary> /// Client for GitHub's Repository Merging API /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/merging/">Merging API documentation</a> for more details ///</remarks> IMergingClient Merging { get; } /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> Task<IReadOnlyList<Branch>> GetAllBranches(string owner, string name); /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> Task<IReadOnlyList<Branch>> GetAllBranches(int repositoryId); /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> Task<IReadOnlyList<Branch>> GetAllBranches(string owner, string name, ApiOptions options); /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> Task<IReadOnlyList<Branch>> GetAllBranches(int repositoryId, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(int repositoryId); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(int repositoryId, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(int repositoryId, bool includeAnonymous); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(int repositoryId, bool includeAnonymous, ApiOptions options); /// <summary> /// Gets all languages for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All languages used in the repository and the number of bytes of each language.</returns> Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(string owner, string name); /// <summary> /// Gets all languages for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <returns>All languages used in the repository and the number of bytes of each language.</returns> Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(int repositoryId); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(int repositoryId); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name, ApiOptions options); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(int repositoryId, ApiOptions options); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(int repositoryId); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name, ApiOptions options); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(int repositoryId, ApiOptions options); /// <summary> /// Gets the specified branch. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get-branch">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="branchName">The name of the branch</param> /// <returns>The specified <see cref="T:Octokit.Branch"/></returns> Task<Branch> GetBranch(string owner, string name, string branchName); /// <summary> /// Gets the specified branch. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get-branch">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The ID of the repository</param> /// <param name="branchName">The name of the branch</param> /// <returns>The specified <see cref="T:Octokit.Branch"/></returns> Task<Branch> GetBranch(int repositoryId, string branchName); /// <summary> /// Updates the specified repository with the values given in <paramref name="update"/> /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="update">New values to update the repository with</param> /// <returns>The updated <see cref="T:Octokit.Repository"/></returns> Task<Repository> Edit(string owner, string name, RepositoryUpdate update); /// <summary> /// Updates the specified repository with the values given in <paramref name="update"/> /// </summary> /// <param name="repositoryId">The ID of the repository</param> /// <param name="update">New values to update the repository with</param> /// <returns>The updated <see cref="T:Octokit.Repository"/></returns> Task<Repository> Edit(int repositoryId, RepositoryUpdate update); /// <summary> /// Edit the specified branch with the values given in <paramref name="update"/> /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="branch">The name of the branch</param> /// <param name="update">New values to update the branch with</param> /// <returns>The updated <see cref="T:Octokit.Branch"/></returns> Task<Branch> EditBranch(string owner, string name, string branch, BranchUpdate update); /// <summary> /// Edit the specified branch with the values given in <paramref name="update"/> /// </summary> /// <param name="repositoryId">The ID of the repository</param> /// <param name="branch">The name of the branch</param> /// <param name="update">New values to update the branch with</param> /// <returns>The updated <see cref="T:Octokit.Branch"/></returns> Task<Branch> EditBranch(int repositoryId, string branch, BranchUpdate update); /// <summary> /// A client for GitHub's Repository Pages API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/pages/">Repository Pages API documentation</a> for more information. /// </remarks> IRepositoryPagesClient Page { get; } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.Methods.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Client.Methods { /// <summary> /// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpEntityEnclosingRequestBase /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpEntityEnclosingRequestBase", AccessFlags = 1057)] public abstract partial class HttpEntityEnclosingRequestBase : global::Org.Apache.Http.Client.Methods.HttpRequestBase, global::Org.Apache.Http.IHttpEntityEnclosingRequest /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpEntityEnclosingRequestBase() /* MethodBuilder.Create */ { } /// <java-name> /// getEntity /// </java-name> [Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)] public virtual global::Org.Apache.Http.IHttpEntity GetEntity() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.IHttpEntity); } /// <java-name> /// setEntity /// </java-name> [Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)] public virtual void SetEntity(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */ { } /// <summary> /// <para>Tells if this request should use the expect-continue handshake. The expect continue handshake gives the server a chance to decide whether to accept the entity enclosing request before the possibly lengthy entity is sent across the wire. </para> /// </summary> /// <returns> /// <para>true if the expect continue handshake should be used, false if not. </para> /// </returns> /// <java-name> /// expectContinue /// </java-name> [Dot42.DexImport("expectContinue", "()Z", AccessFlags = 1)] public virtual bool ExpectContinue() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)] public override object Clone() /* MethodBuilder.Create */ { return default(object); } [Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)] public override global::Org.Apache.Http.IRequestLine GetRequestLine() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IRequestLine); } [Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)] public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.ProtocolVersion); } [Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)] public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } [Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)] public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)] public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */ { } /// <java-name> /// getEntity /// </java-name> public global::Org.Apache.Http.IHttpEntity Entity { [Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)] get{ return GetEntity(); } [Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)] set{ SetEntity(value); } } public global::Org.Apache.Http.IRequestLine RequestLine { [Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)] get{ return GetRequestLine(); } } public global::Org.Apache.Http.ProtocolVersion ProtocolVersion { [Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)] get{ return GetProtocolVersion(); } } public global::Org.Apache.Http.IHeader[] AllHeaders { [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] get{ return GetAllHeaders(); } } public global::Org.Apache.Http.Params.IHttpParams Params { [Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] get{ return GetParams(); } [Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)] set{ SetParams(value); } } } /// <summary> /// <para>HTTP HEAD method. </para><para>The HTTP HEAD method is defined in section 9.4 of : <blockquote><para>The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpHead /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpHead", AccessFlags = 33)] public partial class HttpHead : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "HEAD"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpHead() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpHead(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpHead(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP TRACE method. </para><para>The HTTP TRACE method is defined in section 9.6 of : <blockquote><para>The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpTrace /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpTrace", AccessFlags = 33)] public partial class HttpTrace : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "TRACE"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpTrace() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpTrace(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpTrace(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>Extended version of the HttpRequest interface that provides convenience methods to access request properties such as request URI and method type.</para><para><para></para><para></para><title>Revision:</title><para>659191 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpUriRequest /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpUriRequest", AccessFlags = 1537)] public partial interface IHttpUriRequest : global::Org.Apache.Http.IHttpRequest /* scope: __dot42__ */ { /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)] string GetMethod() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the URI this request uses, such as <code></code>. </para> /// </summary> /// <java-name> /// getURI /// </java-name> [Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1025)] global::System.Uri GetURI() /* MethodBuilder.Create */ ; /// <summary> /// <para>Aborts execution of the request.</para><para></para> /// </summary> /// <java-name> /// abort /// </java-name> [Dot42.DexImport("abort", "()V", AccessFlags = 1025)] void Abort() /* MethodBuilder.Create */ ; /// <summary> /// <para>Tests if the request execution has been aborted.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isAborted /// </java-name> [Dot42.DexImport("isAborted", "()Z", AccessFlags = 1025)] bool IsAborted() /* MethodBuilder.Create */ ; } /// <summary> /// <para>HTTP POST method. </para><para>The HTTP POST method is defined in section 9.5 of : <blockquote><para>The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions: <ul><li><para>Annotation of existing resources </para></li><li><para>Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles </para></li><li><para>Providing a block of data, such as the result of submitting a form, to a data-handling process </para></li><li><para>Extending a database through an append operation </para></li></ul></para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpPost /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpPost", AccessFlags = 33)] public partial class HttpPost : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "POST"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpPost() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpPost(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpPost(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP PUT method. </para><para>The HTTP PUT method is defined in section 9.6 of : <blockquote><para>The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpPut /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpPut", AccessFlags = 33)] public partial class HttpPut : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "PUT"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpPut() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpPut(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpPut(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP GET method. </para><para>The HTTP GET method is defined in section 9.3 of : <blockquote><para>The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. </para></blockquote></para><para>GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).</para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpGet /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpGet", AccessFlags = 33)] public partial class HttpGet : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "GET"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpGet() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpGet(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpGet(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>HTTP DELETE method </para><para>The HTTP DELETE method is defined in section 9.7 of : <blockquote><para>The DELETE method requests that the origin server delete the resource identified by the Request-URI. [...] The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. </para></blockquote></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpDelete /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpDelete", AccessFlags = 33)] public partial class HttpDelete : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "DELETE"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpDelete() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpDelete(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpDelete(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpRequestBase /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpRequestBase", AccessFlags = 1057)] public abstract partial class HttpRequestBase : global::Org.Apache.Http.Message.AbstractHttpMessage, global::Org.Apache.Http.Client.Methods.IHttpUriRequest, global::Org.Apache.Http.Client.Methods.IAbortableHttpRequest, global::Java.Lang.ICloneable /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpRequestBase() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)] public virtual string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the protocol version this message is compatible with. </para> /// </summary> /// <java-name> /// getProtocolVersion /// </java-name> [Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)] public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.ProtocolVersion); } /// <summary> /// <para>Returns the URI this request uses, such as <code></code>. </para> /// </summary> /// <java-name> /// getURI /// </java-name> [Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)] public virtual global::System.Uri GetURI() /* MethodBuilder.Create */ { return default(global::System.Uri); } /// <summary> /// <para>Returns the request line of this request. </para> /// </summary> /// <returns> /// <para>the request line. </para> /// </returns> /// <java-name> /// getRequestLine /// </java-name> [Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)] public virtual global::Org.Apache.Http.IRequestLine GetRequestLine() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.IRequestLine); } /// <java-name> /// setURI /// </java-name> [Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)] public virtual void SetURI(global::System.Uri uri) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionRequest /// </java-name> [Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1)] public virtual void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */ { } /// <java-name> /// setReleaseTrigger /// </java-name> [Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1)] public virtual void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */ { } /// <summary> /// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para> /// </summary> /// <java-name> /// abort /// </java-name> [Dot42.DexImport("abort", "()V", AccessFlags = 1)] public virtual void Abort() /* MethodBuilder.Create */ { } /// <summary> /// <para>Tests if the request execution has been aborted.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isAborted /// </java-name> [Dot42.DexImport("isAborted", "()Z", AccessFlags = 1)] public virtual bool IsAborted() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object Clone() /* MethodBuilder.Create */ { return default(object); } [Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)] public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } [Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader); } [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeader[]); } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)] public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)] public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)] public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)] public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.IHeaderIterator); } [Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)] public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)] get{ return GetMethod(); } } /// <summary> /// <para>Returns the protocol version this message is compatible with. </para> /// </summary> /// <java-name> /// getProtocolVersion /// </java-name> public global::Org.Apache.Http.ProtocolVersion ProtocolVersion { [Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)] get{ return GetProtocolVersion(); } } /// <summary> /// <para>Returns the URI this request uses, such as <code></code>. </para> /// </summary> /// <java-name> /// getURI /// </java-name> public global::System.Uri URI { [Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)] get{ return GetURI(); } [Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)] set{ SetURI(value); } } /// <summary> /// <para>Returns the request line of this request. </para> /// </summary> /// <returns> /// <para>the request line. </para> /// </returns> /// <java-name> /// getRequestLine /// </java-name> public global::Org.Apache.Http.IRequestLine RequestLine { [Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)] get{ return GetRequestLine(); } } public global::Org.Apache.Http.IHeader[] AllHeaders { [Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)] get{ return GetAllHeaders(); } } } /// <summary> /// <para>HTTP OPTIONS method. </para><para>The HTTP OPTIONS method is defined in section 9.2 of : <blockquote><para>The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/HttpOptions /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/HttpOptions", AccessFlags = 33)] public partial class HttpOptions : global::Org.Apache.Http.Client.Methods.HttpRequestBase /* scope: __dot42__ */ { /// <java-name> /// METHOD_NAME /// </java-name> [Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)] public const string METHOD_NAME = "OPTIONS"; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public HttpOptions() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)] public HttpOptions(global::System.Uri uri) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public HttpOptions(string uri) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetMethod() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getAllowedMethods /// </java-name> [Dot42.DexImport("getAllowedMethods", "(Lorg/apache/http/HttpResponse;)Ljava/util/Set;", AccessFlags = 1, Signature = "(Lorg/apache/http/HttpResponse;)Ljava/util/Set<Ljava/lang/String;>;")] public virtual global::Java.Util.ISet<string> GetAllowedMethods(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<string>); } /// <summary> /// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para> /// </summary> /// <java-name> /// getMethod /// </java-name> public string Method { [Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMethod(); } } } /// <summary> /// <para>Interface representing an HTTP request that can be aborted by shutting down the underlying HTTP connection.</para><para><para></para><para></para><title>Revision:</title><para>639600 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/methods/AbortableHttpRequest /// </java-name> [Dot42.DexImport("org/apache/http/client/methods/AbortableHttpRequest", AccessFlags = 1537)] public partial interface IAbortableHttpRequest /* scope: __dot42__ */ { /// <summary> /// <para>Sets the ClientConnectionRequest callback that can be used to abort a long-lived request for a connection. If the request is already aborted, throws an IOException.</para><para><para>ClientConnectionManager </para><simplesectsep></simplesectsep><para>ThreadSafeClientConnManager </para></para> /// </summary> /// <java-name> /// setConnectionRequest /// </java-name> [Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1025)] void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */ ; /// <summary> /// <para>Sets the ConnectionReleaseTrigger callback that can be used to abort an active connection. Typically, this will be the ManagedClientConnection itself. If the request is already aborted, throws an IOException. </para> /// </summary> /// <java-name> /// setReleaseTrigger /// </java-name> [Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1025)] void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */ ; /// <summary> /// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para> /// </summary> /// <java-name> /// abort /// </java-name> [Dot42.DexImport("abort", "()V", AccessFlags = 1025)] void Abort() /* MethodBuilder.Create */ ; } }
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using NUnit.Framework; using Newtonsoft.Json.Schema; using Google.Apis.Discovery.Schema; namespace Google.Apis.Tests.Apis.Discovery.Schema { /// <summary> /// Tests the "FutureJsonSchemaResolver" class /// </summary> [TestFixture] public class FutureJsonSchemaResolverTest { /// <summary> /// Confirms that the class will throw an exception when adding duplicate schemas /// </summary> [Test] public void TestAddDuplicateFail() { var resolver = new FutureJsonSchemaResolver(); Assert.AreEqual(0, resolver.LoadedSchemas.Count); var schema1 = new JsonSchema { Id = "1" }; var schema2 = new JsonSchema { Id = "1" }; resolver.LoadedSchemas.Add(schema1); Assert.AreEqual(1, resolver.LoadedSchemas.Count); Assert.Throws<InvalidOperationException>(() => resolver.LoadedSchemas.Add(schema1)); Assert.AreEqual(1, resolver.LoadedSchemas.Count); Assert.Throws<InvalidOperationException>(() => resolver.LoadedSchemas.Add(schema2)); Assert.AreEqual(1, resolver.LoadedSchemas.Count); } /// <summary> /// Confirms that adding future json schemas to the resolver works /// </summary> [Test] public void TestAddResolveFuture() { var resolver = new FutureJsonSchemaResolver(); Assert.AreEqual(0, resolver.LoadedSchemas.Count); var futureSchema1 = new FutureJsonSchema("1"); var schema1 = new JsonSchema { Id = "1", Title = "Title For 1" }; var futureSchema2 = new FutureJsonSchema("2"); var schema2 = new JsonSchema { Id = "2", Title = "Title For 2" }; resolver.LoadedSchemas.Add(futureSchema1); resolver.LoadedSchemas.Add(futureSchema2); Assert.AreEqual(2, resolver.LoadedSchemas.Count); resolver.LoadedSchemas.Add(schema2); Assert.AreEqual(2, resolver.LoadedSchemas.Count); var resolvedFuture2 = resolver.GetSchema("2") as FutureJsonSchema; var resolvedFuture1 = resolver.GetSchema("1") as FutureJsonSchema; Assert.NotNull(resolvedFuture1); Assert.NotNull(resolvedFuture2); Assert.AreSame(resolvedFuture1, futureSchema1); Assert.AreSame(resolvedFuture2, futureSchema2); Assert.IsFalse(resolvedFuture1.Resolved); Assert.IsTrue(resolvedFuture2.Resolved); Assert.AreEqual("Title For 2", resolvedFuture2.Title); Assert.IsNull(resolvedFuture1.Title); resolver.LoadedSchemas.Add(schema1); Assert.AreEqual(2, resolver.LoadedSchemas.Count); resolvedFuture2 = resolver.GetSchema("2") as FutureJsonSchema; resolvedFuture1 = resolver.GetSchema("1") as FutureJsonSchema; Assert.NotNull(resolvedFuture1); Assert.NotNull(resolvedFuture2); Assert.AreSame(resolvedFuture1, futureSchema1); Assert.AreSame(resolvedFuture2, futureSchema2); Assert.IsTrue(resolvedFuture1.Resolved); Assert.IsTrue(resolvedFuture2.Resolved); Assert.AreEqual("Title For 2", resolvedFuture2.Title); Assert.AreEqual("Title For 1", resolvedFuture1.Title); } /// <summary> /// Tests that the adding of schema works /// </summary> [Test] public void TestAddSimple() { var resolver = new FutureJsonSchemaResolver(); Assert.AreEqual(0, resolver.LoadedSchemas.Count); var schema1 = new JsonSchema { Id = "1" }; var schema2 = new JsonSchema { Id = "2" }; resolver.LoadedSchemas.Add(schema1); Assert.AreEqual(1, resolver.LoadedSchemas.Count); Assert.True(ReferenceEquals(schema1, resolver.LoadedSchemas[0])); resolver.LoadedSchemas.Add(schema2); Assert.AreEqual(2, resolver.LoadedSchemas.Count); Assert.True(ReferenceEquals(schema1, resolver.LoadedSchemas[0])); Assert.True(ReferenceEquals(schema2, resolver.LoadedSchemas[1])); } /// <summary> /// Tests that the Add and Get operations for schemas work /// </summary> [Test] public void TestGetSchemaSimpleMissing() { var schema1 = new JsonSchema { Id = "1", Title = "Title For 1" }; var schema2 = new JsonSchema { Id = "2", Title = "Title For 2" }; var schema3 = new JsonSchema { Id = "3", Title = "Title For 3" }; var resolver = new FutureJsonSchemaResolver(); resolver.LoadedSchemas.Add(schema1); resolver.LoadedSchemas.Add(schema2); resolver.LoadedSchemas.Add(schema3); var resolvedSchema2 = resolver.GetSchema("2"); var resolvedSchema1 = resolver.GetSchema("1"); var resolvedSchema3 = resolver.GetSchema("3"); var resolvedSchema4 = resolver.GetSchema("4") as FutureJsonSchema; var resolvedSchema5 = resolver.GetSchema("5") as FutureJsonSchema; Assert.AreSame(schema1, resolvedSchema1); Assert.AreSame(schema2, resolvedSchema2); Assert.AreSame(schema3, resolvedSchema3); Assert.IsNotNull(resolvedSchema4); Assert.IsNotNull(resolvedSchema5); Assert.False(resolvedSchema4.Resolved); Assert.False(resolvedSchema5.Resolved); } /// <summary> /// Tests that the resolver supports present schemas /// </summary> [Test] public void TestGetSchemaSimplePresent() { var schema1 = new JsonSchema { Id = "1", Title = "Title For 1" }; var schema2 = new JsonSchema { Id = "2", Title = "Title For 2" }; var schema3 = new JsonSchema { Id = "3", Title = "Title For 3" }; var resolver = new FutureJsonSchemaResolver(); resolver.LoadedSchemas.Add(schema1); resolver.LoadedSchemas.Add(schema2); resolver.LoadedSchemas.Add(schema3); var resolvedSchema2 = resolver.GetSchema("2"); var resolvedSchema1 = resolver.GetSchema("1"); var resolvedSchema3 = resolver.GetSchema("3"); Assert.AreSame(schema1, resolvedSchema1); Assert.AreSame(schema2, resolvedSchema2); Assert.AreSame(schema3, resolvedSchema3); } /// <summary> /// Tests the ResolveAndVerify feature /// </summary> [Test] public void TestValidate() { var schema1 = new JsonSchema { Id = "1", Title = "Title For 1" }; var schema2 = new JsonSchema { Id = "2", Title = "Title For 2" }; var schema3 = new JsonSchema { Id = "3", Title = "Title For 3" }; var schema4 = new JsonSchema { Id = "4", Title = "Title For 4" }; var schema5 = new JsonSchema { Id = "5", Title = "Title For 5" }; var resolver = new FutureJsonSchemaResolver(); resolver.LoadedSchemas.Add(schema1); resolver.LoadedSchemas.Add(schema2); resolver.LoadedSchemas.Add(schema3); resolver.GetSchema("4"); // Adds 4 resolver.GetSchema("5"); // Adds 5 Assert.Throws<InvalidOperationException>(resolver.ResolveAndVerify); resolver.LoadedSchemas.Add(schema5); Assert.Throws<InvalidOperationException>(resolver.ResolveAndVerify); resolver.LoadedSchemas.Add(schema4); Assert.DoesNotThrow(resolver.ResolveAndVerify); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog { using System; using System.Collections.Generic; using System.Linq; using NLog.Internal; /// <summary> /// Nested Diagnostics Context - a thread-local structure that keeps a stack /// of strings and provides methods to output them in layouts /// </summary> public static class NestedDiagnosticsContext { private static readonly object dataSlot = ThreadLocalStorageHelper.AllocateDataSlot(); /// <summary> /// Gets the top NDC message but doesn't remove it. /// </summary> /// <returns>The top message. .</returns> public static string TopMessage => FormatHelper.ConvertToString(TopObject, null); /// <summary> /// Gets the top NDC object but doesn't remove it. /// </summary> /// <returns>The object at the top of the NDC stack if defined; otherwise <c>null</c>.</returns> public static object TopObject => PeekObject(); private static Stack<object> GetThreadStack(bool create = true) { return ThreadLocalStorageHelper.GetDataForSlot<Stack<object>>(dataSlot, create); } /// <summary> /// Pushes the specified text on current thread NDC. /// </summary> /// <param name="text">The text to be pushed.</param> /// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns> public static IDisposable Push(string text) { return Push((object)text); } /// <summary> /// Pushes the specified object on current thread NDC. /// </summary> /// <param name="value">The object to be pushed.</param> /// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns> public static IDisposable Push(object value) { Stack<object> stack = GetThreadStack(true); int previousCount = stack.Count; stack.Push(value); return new StackPopper(stack, previousCount); } /// <summary> /// Pops the top message off the NDC stack. /// </summary> /// <returns>The top message which is no longer on the stack.</returns> public static string Pop() { return Pop(null); } /// <summary> /// Pops the top message from the NDC stack. /// </summary> /// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting the value to a string.</param> /// <returns>The top message, which is removed from the stack, as a string value.</returns> public static string Pop(IFormatProvider formatProvider) { return FormatHelper.ConvertToString(PopObject() ?? string.Empty, formatProvider); } /// <summary> /// Pops the top object off the NDC stack. /// </summary> /// <returns>The object from the top of the NDC stack, if defined; otherwise <c>null</c>.</returns> public static object PopObject() { Stack<object> stack = GetThreadStack(true); return (stack.Count > 0) ? stack.Pop() : null; } /// <summary> /// Peeks the first object on the NDC stack /// </summary> /// <returns>The object from the top of the NDC stack, if defined; otherwise <c>null</c>.</returns> public static object PeekObject() { Stack<object> stack = GetThreadStack(false); return (stack?.Count > 0) ? stack.Peek() : null; } /// <summary> /// Clears current thread NDC stack. /// </summary> public static void Clear() { Stack<object> stack = GetThreadStack(false); stack?.Clear(); } /// <summary> /// Gets all messages on the stack. /// </summary> /// <returns>Array of strings on the stack.</returns> public static string[] GetAllMessages() { return GetAllMessages(null); } /// <summary> /// Gets all messages from the stack, without removing them. /// </summary> /// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting a value to a string.</param> /// <returns>Array of strings.</returns> public static string[] GetAllMessages(IFormatProvider formatProvider) { Stack<object> stack = GetThreadStack(false); if (stack == null) return ArrayHelper.Empty<string>(); else return stack.Select((o) => FormatHelper.ConvertToString(o, formatProvider)).ToArray(); } /// <summary> /// Gets all objects on the stack. /// </summary> /// <returns>Array of objects on the stack.</returns> public static object[] GetAllObjects() { Stack<object> stack = GetThreadStack(false); if (stack == null) return ArrayHelper.Empty<object>(); else return stack.ToArray(); } /// <summary> /// Resets the stack to the original count during <see cref="IDisposable.Dispose"/>. /// </summary> private sealed class StackPopper : IDisposable { private readonly Stack<object> _stack; private readonly int _previousCount; /// <summary> /// Initializes a new instance of the <see cref="StackPopper" /> class. /// </summary> /// <param name="stack">The stack.</param> /// <param name="previousCount">The previous count.</param> public StackPopper(Stack<object> stack, int previousCount) { _stack = stack; _previousCount = previousCount; } /// <summary> /// Reverts the stack to original item count. /// </summary> void IDisposable.Dispose() { while (_stack.Count > _previousCount) { _stack.Pop(); } } } } }
using System; using System.IO; using System.Runtime.InteropServices; using System.Collections.Generic; using Mono.Unix; using Mono.Unix.Native; namespace Platform.VirtualFileSystem.Providers.Local { public class NativePosix : NativeManaged { public override bool SupportsAlternateContentStreams { get { return false; } } public override string GetSymbolicLinkTarget(string path) { UnixSymbolicLinkInfo symbolicLinkInfo; try { symbolicLinkInfo = new UnixSymbolicLinkInfo(path); } catch (InvalidOperationException) { /* Not a symbolic link */ return null; } string retval = null; try { if (!symbolicLinkInfo.IsSymbolicLink) { return null; } retval = symbolicLinkInfo.ContentsPath; if (retval != "/" && retval.EndsWith("/")) { retval = retval.Substring(0, retval.Length - 1); } } catch (OutOfMemoryException) { throw; } catch (StackOverflowException) { throw; } catch { } return retval; } public override NodeType GetSymbolicLinkTargetType(string path) { UnixSymbolicLinkInfo obj; try { obj = new UnixSymbolicLinkInfo(path); } catch (InvalidOperationException) { /* Not a symbolic link */ return null; } try { if (!obj.IsSymbolicLink) { return null; } var retval = obj.GetContents(); if (retval == null) { return null; } var isDirectory = retval.IsDirectory; if (isDirectory) { return NodeType.Directory; } var isRegularFile = retval.IsRegularFile; if (isRegularFile) { return NodeType.File; } return null; } catch (OutOfMemoryException) { throw; } catch (StackOverflowException) { throw; } catch (Exception) { return null; } } public override IEnumerable<string> ListExtendedAttributes(string path) { string[] retval; var size = Syscall.listxattr(path, out retval); if (size == -1) { var err = Marshal.GetLastWin32Error(); if (err == (int)Errno.ERANGE) { yield break; } else if (err == (int)Errno.ENOENT) { throw new FileNodeNotFoundException(); } else { throw new NotSupportedException(); } } for (var i = 0; i < retval.Length; i++) { if (retval[i].StartsWith("user.")) { yield return retval[i].Substring(5); } yield return retval[i]; } } public override byte[] GetExtendedAttribute(string path, string attributeName) { long size; var buffer = new byte[256]; if (attributeName.IndexOf('.') < 0) { attributeName = "user." + attributeName; } while (true) { size = Syscall.getxattr(path, attributeName, buffer, (ulong)buffer.Length); if (size > 0) { break; } var err = Marshal.GetLastWin32Error(); if (err == (int)Errno.ERANGE) { buffer = new byte[size]; continue; } else if (err == (int)Errno.EOPNOTSUPP) { throw new NotSupportedException("GetExtendedAttribute: " + path); } else if (err == (int)Errno.ENOENT) { throw new FileNodeNotFoundException("FileNotFound: " + path); } else { throw new NotSupportedException("GetExtendedAttribute: " + path + " (errno=" + err + ")"); } } if (size == buffer.Length) { return buffer; } else { return ArrayUtils.NewArray(buffer, 0, (int)size); } } public override void SetExtendedAttribute(string path, string attributeName, byte[] value, int offset, int count) { int x; int err; if (attributeName.IndexOf('.') < 0) { attributeName = "user." + attributeName; } if (value == null) { x = Syscall.removexattr(path, attributeName); if (x == 0) { return; } err = Marshal.GetLastWin32Error(); if (err == (int)Errno.ENOENT) { throw new FileNotFoundException(); } if (err == (int)Errno.ENODATA) { // Deleting a non-existant attribute is ok } else if (err == (int)Errno.EOPNOTSUPP) { throw new NotSupportedException("File system for file [" + path + "] does not support extended attributes"); } } else { x = Syscall.setxattr(path, attributeName, value, (ulong)value.Length, 0); if (x == 0) { return; } err = Marshal.GetLastWin32Error(); if (err == (int)Errno.ENOSPC || err == (int)Errno.EDQUOT) { throw new System.IO.IOException("Not enough disk space"); } else if (err == (int)Errno.EOPNOTSUPP) { throw new NotSupportedException("File system for file [" + path + "] does not support extended attributes"); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Threading; namespace System.Net.Security { // // This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context. // internal class _SslStream { private static AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback); private static AsyncProtocolCallback s_resumeAsyncWriteCallback = new AsyncProtocolCallback(ResumeAsyncWriteCallback); private static AsyncProtocolCallback s_resumeAsyncReadCallback = new AsyncProtocolCallback(ResumeAsyncReadCallback); private static AsyncProtocolCallback s_readHeaderCallback = new AsyncProtocolCallback(ReadHeaderCallback); private static AsyncProtocolCallback s_readFrameCallback = new AsyncProtocolCallback(ReadFrameCallback); private const int PinnableReadBufferSize = 4096 * 4 + 32; // We read in 16K chunks + headers. private static PinnableBufferCache s_PinnableReadBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableReadBufferSize); private const int PinnableWriteBufferSize = 4096 + 1024; // We write in 4K chunks + encryption overhead. private static PinnableBufferCache s_PinnableWriteBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableWriteBufferSize); private SslState _SslState; private int _NestedWrite; private int _NestedRead; // Never updated directly, special properties are used. This is the read buffer. private byte[] _InternalBuffer; private bool _InternalBufferFromPinnableCache; private byte[] _PinnableOutputBuffer; // Used for writes when we can do it. private byte[] _PinnableOutputBufferInUse; // Remembers what UNENCRYPTED buffer is using _PinnableOutputBuffer. private int _InternalOffset; private int _InternalBufferCount; private FixedSizeReader _Reader; internal _SslStream(SslState sslState) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage1("CTOR: In System.Net._SslStream.SslStream", this.GetHashCode()); } _SslState = sslState; _Reader = new FixedSizeReader(_SslState.InnerStream); } // If we have a read buffer from the pinnable cache, return it. private void FreeReadBuffer() { if (_InternalBufferFromPinnableCache) { s_PinnableReadBufferCache.FreeBuffer(_InternalBuffer); _InternalBufferFromPinnableCache = false; } _InternalBuffer = null; } ~_SslStream() { if (_InternalBufferFromPinnableCache) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Read Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_InternalBuffer)); } FreeReadBuffer(); } if (_PinnableOutputBuffer != null) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Write Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_PinnableOutputBuffer)); } s_PinnableWriteBufferCache.FreeBuffer(_PinnableOutputBuffer); } } internal int Read(byte[] buffer, int offset, int count) { return ProcessRead(buffer, offset, count, null); } internal void Write(byte[] buffer, int offset, int count) { ProcessWrite(buffer, offset, count, null); } internal bool DataAvailable { get { return InternalBufferCount != 0; } } private byte[] InternalBuffer { get { return _InternalBuffer; } } private int InternalOffset { get { return _InternalOffset; } } private int InternalBufferCount { get { return _InternalBufferCount; } } private void SkipBytes(int decrCount) { _InternalOffset += decrCount; _InternalBufferCount -= decrCount; } // // This will set the internal offset to "curOffset" and ensure internal buffer. // If not enough, reallocate and copy up to "curOffset". // private void EnsureInternalBufferSize(int curOffset, int addSize) { if (_InternalBuffer == null || _InternalBuffer.Length < addSize + curOffset) { bool wasPinnable = _InternalBufferFromPinnableCache; byte[] saved = _InternalBuffer; int newSize = addSize + curOffset; if (newSize <= PinnableReadBufferSize) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize IS pinnable", this.GetHashCode(), newSize); } _InternalBufferFromPinnableCache = true; _InternalBuffer = s_PinnableReadBufferCache.AllocateBuffer(); } else { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize NOT pinnable", this.GetHashCode(), newSize); } _InternalBufferFromPinnableCache = false; _InternalBuffer = new byte[newSize]; } if (saved != null && curOffset != 0) { Buffer.BlockCopy(saved, 0, _InternalBuffer, 0, curOffset); } if (wasPinnable) { s_PinnableReadBufferCache.FreeBuffer(saved); } } _InternalOffset = curOffset; _InternalBufferCount = curOffset + addSize; } // // Validates user parameteres for all Read/Write methods. // private void ValidateParameters(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (count > buffer.Length - offset) { throw new ArgumentOutOfRangeException("count", SR.net_offset_plus_count); } } // // Combined sync/async write method. For sync case asyncRequest==null. // private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { ValidateParameters(buffer, offset, count); if (Interlocked.Exchange(ref _NestedWrite, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginWrite" : "Write"), "write")); } bool failed = false; try { StartWriting(buffer, offset, count, asyncRequest); } catch (Exception e) { _SslState.FinishWrite(); failed = true; if (e is IOException) { throw; } throw new IOException(SR.net_io_write, e); } finally { if (asyncRequest == null || failed) { _NestedWrite = 0; } } } private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { if (asyncRequest != null) { asyncRequest.SetNextRequest(buffer, offset, count, s_resumeAsyncWriteCallback); } // We loop to this method from the callback. // If the last chunk was just completed from async callback (count < 0), we complete user request. if (count >= 0) { byte[] outBuffer = null; if (_PinnableOutputBufferInUse == null) { if (_PinnableOutputBuffer == null) { _PinnableOutputBuffer = s_PinnableWriteBufferCache.AllocateBuffer(); } _PinnableOutputBufferInUse = buffer; outBuffer = _PinnableOutputBuffer; if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Trying Pinnable", this.GetHashCode(), count, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer)); } } else { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.StartWriting BufferInUse", this.GetHashCode(), count); } } do { // Request a write IO slot. if (_SslState.CheckEnqueueWrite(asyncRequest)) { // Operation is async and has been queued, return. return; } int chunkBytes = Math.Min(count, _SslState.MaxDataSize); int encryptedBytes; Interop.SecurityStatus errorCode = _SslState.EncryptData(buffer, offset, chunkBytes, ref outBuffer, out encryptedBytes); if (errorCode != Interop.SecurityStatus.OK) { ProtocolToken message = new ProtocolToken(null, errorCode); throw new IOException(SR.net_io_encrypt, message.GetException()); } if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Got Encrypted Buffer", this.GetHashCode(), encryptedBytes, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer)); } if (asyncRequest != null) { // Prepare for the next request. asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, s_resumeAsyncWriteCallback); IAsyncResult ar = _SslState.InnerStreamAPM.BeginWrite(outBuffer, 0, encryptedBytes, s_writeCallback, asyncRequest); if (!ar.CompletedSynchronously) { return; } _SslState.InnerStreamAPM.EndWrite(ar); } else { _SslState.InnerStream.Write(outBuffer, 0, encryptedBytes); } offset += chunkBytes; count -= chunkBytes; // Release write IO slot. _SslState.FinishWrite(); } while (count != 0); } if (asyncRequest != null) { asyncRequest.CompleteUser(); } if (buffer == _PinnableOutputBufferInUse) { _PinnableOutputBufferInUse = null; if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage1("In System.Net._SslStream.StartWriting Freeing buffer.", this.GetHashCode()); } } } // // Combined sync/async read method. For sync request asyncRequest==null // There is a little overhead because we need to pass buffer/offset/count used only in sync. // Still the benefit is that we have a common sync/async code path. // private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { ValidateParameters(buffer, offset, count); if (Interlocked.Exchange(ref _NestedRead, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest != null ? "BeginRead" : "Read"), "read")); } bool failed = false; try { int copyBytes; if (InternalBufferCount != 0) { copyBytes = InternalBufferCount > count ? count : InternalBufferCount; if (copyBytes != 0) { Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes); SkipBytes(copyBytes); } if (asyncRequest != null) { asyncRequest.CompleteUser((object)copyBytes); } return copyBytes; } return StartReading(buffer, offset, count, asyncRequest); } catch (Exception e) { _SslState.FinishRead(null); failed = true; if (e is IOException) { throw; } throw new IOException(SR.net_io_read, e); } finally { // If sync request or exception. if (asyncRequest == null || failed) { _NestedRead = 0; } } } // // To avoid recursion when decrypted 0 bytes this method will loop until a decrypted result at least 1 byte. // private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { int result = 0; GlobalLog.Assert(InternalBufferCount == 0, "SslStream::StartReading()|Previous frame was not consumed. InternalBufferCount:{0}", InternalBufferCount); do { if (asyncRequest != null) { asyncRequest.SetNextRequest(buffer, offset, count, s_resumeAsyncReadCallback); } int copyBytes = _SslState.CheckEnqueueRead(buffer, offset, count, asyncRequest); if (copyBytes == 0) { //Queued but not completed! return 0; } if (copyBytes != -1) { if (asyncRequest != null) { asyncRequest.CompleteUser((object)copyBytes); } return copyBytes; } } // When we read -1 bytes means we have decrypted 0 bytes or rehandshaking, need looping. while ((result = StartFrameHeader(buffer, offset, count, asyncRequest)) == -1); return result; } // // Need read frame size first // private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { int readBytes = 0; // // Always pass InternalBuffer for SSPI "in place" decryption. // A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption. // // Reset internal buffer for a new frame. EnsureInternalBufferSize(0, SecureChannel.ReadHeaderSize); if (asyncRequest != null) { asyncRequest.SetNextRequest(InternalBuffer, 0, SecureChannel.ReadHeaderSize, s_readHeaderCallback); _Reader.AsyncReadPacket(asyncRequest); if (!asyncRequest.MustCompleteSynchronously) { return 0; } readBytes = asyncRequest.Result; } else { readBytes = _Reader.ReadPacket(InternalBuffer, 0, SecureChannel.ReadHeaderSize); } return StartFrameBody(readBytes, buffer, offset, count, asyncRequest); } private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { if (readBytes == 0) { //EOF : Reset the buffer as we did not read anything into it. SkipBytes(InternalBufferCount); if (asyncRequest != null) { asyncRequest.CompleteUser((object)0); } return 0; } // Now readBytes is a payload size. readBytes = _SslState.GetRemainingFrameSize(InternalBuffer, readBytes); if (readBytes < 0) { throw new IOException(SR.net_frame_read_size); } EnsureInternalBufferSize(SecureChannel.ReadHeaderSize, readBytes); if (asyncRequest != null) //Async { asyncRequest.SetNextRequest(InternalBuffer, SecureChannel.ReadHeaderSize, readBytes, s_readFrameCallback); _Reader.AsyncReadPacket(asyncRequest); if (!asyncRequest.MustCompleteSynchronously) { return 0; } readBytes = asyncRequest.Result; } else //Sync { readBytes = _Reader.ReadPacket(InternalBuffer, SecureChannel.ReadHeaderSize, readBytes); } return ProcessFrameBody(readBytes, buffer, offset, count, asyncRequest); } // // readBytes == SSL Data Payload size on input or 0 on EOF // private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { if (readBytes == 0) { // EOF throw new IOException(SR.net_io_eof); } // Set readBytes to total number of received bytes. readBytes += SecureChannel.ReadHeaderSize; // Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_. int data_offset = 0; Interop.SecurityStatus errorCode = _SslState.DecryptData(InternalBuffer, ref data_offset, ref readBytes); if (errorCode != Interop.SecurityStatus.OK) { byte[] extraBuffer = null; if (readBytes != 0) { extraBuffer = new byte[readBytes]; Buffer.BlockCopy(InternalBuffer, data_offset, extraBuffer, 0, readBytes); } // Reset internal buffer count. SkipBytes(InternalBufferCount); return ProcessReadErrorCode(errorCode, buffer, offset, count, asyncRequest, extraBuffer); } if (readBytes == 0 && count != 0) { // Read again since remote side has sent encrypted 0 bytes. SkipBytes(InternalBufferCount); return -1; } // Decrypted data start from "data_offset" offset, the total count can be shrunk after decryption. EnsureInternalBufferSize(0, data_offset + readBytes); SkipBytes(data_offset); if (readBytes > count) { readBytes = count; } Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes); // This will adjust both the remaining internal buffer count and the offset. SkipBytes(readBytes); _SslState.FinishRead(null); if (asyncRequest != null) { asyncRequest.CompleteUser((object)readBytes); } return readBytes; } // // Only processing SEC_I_RENEGOTIATE. // private int ProcessReadErrorCode(Interop.SecurityStatus errorCode, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest, byte[] extraBuffer) { // ERROR - examine what kind ProtocolToken message = new ProtocolToken(null, errorCode); GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::***Processing an error Status = " + message.Status.ToString()); if (message.Renegotiate) { _SslState.ReplyOnReAuthentication(extraBuffer); // Loop on read. return -1; } if (message.CloseConnection) { _SslState.FinishRead(null); if (asyncRequest != null) { asyncRequest.CompleteUser((object)0); } return 0; } throw new IOException(SR.net_io_decrypt, message.GetException()); } private static void WriteCallback(IAsyncResult transportResult) { if (transportResult.CompletedSynchronously) { return; } GlobalLog.Assert(transportResult.AsyncState is AsyncProtocolRequest, "SslStream::WriteCallback|State type is wrong, expected AsyncProtocolRequest."); AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState; _SslStream sslStream = (_SslStream)asyncRequest.AsyncObject; try { sslStream._SslState.InnerStreamAPM.EndWrite(transportResult); sslStream._SslState.FinishWrite(); if (asyncRequest.Count == 0) { // This was the last chunk. asyncRequest.Count = -1; } sslStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest); } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } sslStream._SslState.FinishWrite(); asyncRequest.CompleteWithError(e); } } // // This is used in a rare situation when async Read is resumed from completed handshake. // private static void ResumeAsyncReadCallback(AsyncProtocolRequest request) { try { ((_SslStream)request.AsyncObject).StartReading(request.Buffer, request.Offset, request.Count, request); } catch (Exception e) { if (request.IsUserCompleted) { // This will throw on a worker thread. throw; } ((_SslStream)request.AsyncObject)._SslState.FinishRead(null); request.CompleteWithError(e); } } // // This is used in a rare situation when async Write is resumed from completed handshake // private static void ResumeAsyncWriteCallback(AsyncProtocolRequest asyncRequest) { try { ((_SslStream)asyncRequest.AsyncObject).StartWriting( asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest); } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } ((_SslStream)asyncRequest.AsyncObject)._SslState.FinishWrite(); asyncRequest.CompleteWithError(e); } } private static void ReadHeaderCallback(AsyncProtocolRequest asyncRequest) { // Async ONLY completion. try { _SslStream sslStream = (_SslStream)asyncRequest.AsyncObject; BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult; if (-1 == sslStream.StartFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest)) { // In case we decrypted 0 bytes start another reading. sslStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest); } } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } asyncRequest.CompleteWithError(e); } } private static void ReadFrameCallback(AsyncProtocolRequest asyncRequest) { // Async ONLY completion. try { _SslStream sslStream = (_SslStream)asyncRequest.AsyncObject; BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult; if (-1 == sslStream.ProcessFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest)) { // In case we decrypted 0 bytes start another reading. sslStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest); } } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } asyncRequest.CompleteWithError(e); } } } }
namespace BooCompiler.Tests { using NUnit.Framework; [TestFixture] public class GeneratorsIntegrationTestFixture : AbstractCompilerTestCase { [Test] public void generator_calling_external_super_with_arguments_2() { RunCompilerTestCase(@"generator-calling-external-super-with-arguments-2.boo"); } [Test] public void generator_calling_external_super_with_arguments() { RunCompilerTestCase(@"generator-calling-external-super-with-arguments.boo"); } [Test] public void generator_calling_super_with_arguments_2() { RunCompilerTestCase(@"generator-calling-super-with-arguments-2.boo"); } [Test] public void generator_calling_super_with_arguments() { RunCompilerTestCase(@"generator-calling-super-with-arguments.boo"); } [Test] public void generator_calling_super() { RunCompilerTestCase(@"generator-calling-super.boo"); } [Test] public void generator_of_static_class_is_transient() { RunCompilerTestCase(@"generator-of-static-class-is-transient.boo"); } [Test] public void generator_of_transient_class_is_transient() { RunCompilerTestCase(@"generator-of-transient-class-is-transient.boo"); } [Test] public void generators_1() { RunCompilerTestCase(@"generators-1.boo"); } [Test] public void generators_10() { RunCompilerTestCase(@"generators-10.boo"); } [Test] public void generators_11() { RunCompilerTestCase(@"generators-11.boo"); } [Test] public void generators_12() { RunCompilerTestCase(@"generators-12.boo"); } [Test] public void generators_13() { RunCompilerTestCase(@"generators-13.boo"); } [Test] public void generators_14() { RunCompilerTestCase(@"generators-14.boo"); } [Test] public void generators_15() { RunCompilerTestCase(@"generators-15.boo"); } [Test] public void generators_16() { RunCompilerTestCase(@"generators-16.boo"); } [Category("FailsOnMono4")][Test] public void generators_17() { RunCompilerTestCase(@"generators-17.boo"); } [Test] public void generators_18() { RunCompilerTestCase(@"generators-18.boo"); } [Test] public void generators_19() { RunCompilerTestCase(@"generators-19.boo"); } [Test] public void generators_2() { RunCompilerTestCase(@"generators-2.boo"); } [Test] public void generators_20() { RunCompilerTestCase(@"generators-20.boo"); } [Test] public void generators_21() { RunCompilerTestCase(@"generators-21.boo"); } [Test] public void generators_3() { RunCompilerTestCase(@"generators-3.boo"); } [Test] public void generators_4() { RunCompilerTestCase(@"generators-4.boo"); } [Test] public void generators_5() { RunCompilerTestCase(@"generators-5.boo"); } [Test] public void generators_6() { RunCompilerTestCase(@"generators-6.boo"); } [Test] public void generators_7() { RunCompilerTestCase(@"generators-7.boo"); } [Test] public void generators_8() { RunCompilerTestCase(@"generators-8.boo"); } [Test] public void generators_9() { RunCompilerTestCase(@"generators-9.boo"); } [Ignore("BOO-759 - generic generator methods are not supported")][Test] public void generic_generator_1() { RunCompilerTestCase(@"generic-generator-1.boo"); } [Test] public void label_issue_1() { RunCompilerTestCase(@"label-issue-1.boo"); } [Test] public void list_generators_1() { RunCompilerTestCase(@"list-generators-1.boo"); } [Test] public void list_generators_2() { RunCompilerTestCase(@"list-generators-2.boo"); } [Test] public void list_generators_3() { RunCompilerTestCase(@"list-generators-3.boo"); } [Test] public void list_generators_4() { RunCompilerTestCase(@"list-generators-4.boo"); } [Test] public void list_generators_5() { RunCompilerTestCase(@"list-generators-5.boo"); } [Test] public void to_string() { RunCompilerTestCase(@"to-string.boo"); } [Test] public void yield_1() { RunCompilerTestCase(@"yield-1.boo"); } [Test] public void yield_10() { RunCompilerTestCase(@"yield-10.boo"); } [Test] public void yield_11() { RunCompilerTestCase(@"yield-11.boo"); } [Test] public void yield_12() { RunCompilerTestCase(@"yield-12.boo"); } [Test] public void yield_13() { RunCompilerTestCase(@"yield-13.boo"); } [Test] public void yield_14() { RunCompilerTestCase(@"yield-14.boo"); } [Test] public void yield_15() { RunCompilerTestCase(@"yield-15.boo"); } [Test] public void yield_16() { RunCompilerTestCase(@"yield-16.boo"); } [Test] public void yield_17() { RunCompilerTestCase(@"yield-17.boo"); } [Test] public void yield_2() { RunCompilerTestCase(@"yield-2.boo"); } [Test] public void yield_3() { RunCompilerTestCase(@"yield-3.boo"); } [Test] public void yield_4() { RunCompilerTestCase(@"yield-4.boo"); } [Test] public void yield_5() { RunCompilerTestCase(@"yield-5.boo"); } [Test] public void yield_6() { RunCompilerTestCase(@"yield-6.boo"); } [Test] public void yield_7() { RunCompilerTestCase(@"yield-7.boo"); } [Test] public void yield_8() { RunCompilerTestCase(@"yield-8.boo"); } [Test] public void yield_9() { RunCompilerTestCase(@"yield-9.boo"); } [Test] public void yield_null_as_IEnumerator() { RunCompilerTestCase(@"yield-null-as-IEnumerator.boo"); } [Test] public void yield_null() { RunCompilerTestCase(@"yield-null.boo"); } override protected string GetRelativeTestCasesPath() { return "integration/generators"; } } }
// 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.Diagnostics; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions; using osu.Framework.Extensions.ExceptionExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Screens; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Multiplayer; using osu.Game.Online.Rooms; using osu.Game.Overlays; using osu.Game.Screens.OnlinePlay.Match.Components; using osuTK; namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match { public class MultiplayerMatchSettingsOverlay : RoomSettingsOverlay { private MatchSettings settings; protected override OsuButton SubmitButton => settings.ApplyButton; [Resolved] private OngoingOperationTracker ongoingOperationTracker { get; set; } protected override bool IsLoading => ongoingOperationTracker.InProgress.Value; public MultiplayerMatchSettingsOverlay(Room room) : base(room) { } protected override void SelectBeatmap() => settings.SelectBeatmap(); protected override OnlinePlayComposite CreateSettings(Room room) => settings = new MatchSettings(room) { RelativeSizeAxes = Axes.Both, RelativePositionAxes = Axes.Y, SettingsApplied = Hide }; protected class MatchSettings : OnlinePlayComposite { private const float disabled_alpha = 0.2f; public Action SettingsApplied; public OsuTextBox NameField, MaxParticipantsField; public RoomAvailabilityPicker AvailabilityPicker; public MatchTypePicker TypePicker; public OsuEnumDropdown<QueueMode> QueueModeDropdown; public OsuTextBox PasswordTextBox; public TriangleButton ApplyButton; public OsuSpriteText ErrorText; private OsuSpriteText typeLabel; private LoadingLayer loadingLayer; public void SelectBeatmap() { if (matchSubScreen.IsCurrentScreen()) matchSubScreen.Push(new MultiplayerMatchSongSelect(matchSubScreen.Room)); } [Resolved] private MultiplayerMatchSubScreen matchSubScreen { get; set; } [Resolved] private IRoomManager manager { get; set; } [Resolved] private MultiplayerClient client { get; set; } [Resolved] private OngoingOperationTracker ongoingOperationTracker { get; set; } private readonly IBindable<bool> operationInProgress = new BindableBool(); [CanBeNull] private IDisposable applyingSettingsOperation; private readonly Room room; private Drawable playlistContainer; private DrawableRoomPlaylist drawablePlaylist; public MatchSettings(Room room) { this.room = room; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider, OsuColour colours) { InternalChildren = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colourProvider.Background4 }, new GridContainer { RelativeSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.AutoSize), }, Content = new[] { new Drawable[] { new OsuScrollContainer { Padding = new MarginPadding { Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING, Vertical = 10 }, RelativeSizeAxes = Axes.Both, Children = new[] { new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(0, 10), Children = new[] { new Container { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Padding = new MarginPadding { Horizontal = WaveOverlayContainer.WIDTH_PADDING }, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new SectionContainer { Padding = new MarginPadding { Right = FIELD_PADDING / 2 }, Children = new[] { new Section("Room name") { Child = NameField = new OsuTextBox { RelativeSizeAxes = Axes.X, TabbableContentContainer = this, LengthLimit = 100, }, }, new Section("Room visibility") { Alpha = disabled_alpha, Child = AvailabilityPicker = new RoomAvailabilityPicker { Enabled = { Value = false } }, }, new Section("Game type") { Child = new FillFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Direction = FillDirection.Vertical, Spacing = new Vector2(7), Children = new Drawable[] { TypePicker = new MatchTypePicker { RelativeSizeAxes = Axes.X, }, typeLabel = new OsuSpriteText { Font = OsuFont.GetFont(size: 14), Colour = colours.Yellow }, }, }, }, new Section("Queue mode") { Child = new Container { RelativeSizeAxes = Axes.X, Height = 40, Child = QueueModeDropdown = new OsuEnumDropdown<QueueMode> { RelativeSizeAxes = Axes.X } } } }, }, new SectionContainer { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Padding = new MarginPadding { Left = FIELD_PADDING / 2 }, Children = new[] { new Section("Max participants") { Alpha = disabled_alpha, Child = MaxParticipantsField = new OsuNumberBox { RelativeSizeAxes = Axes.X, TabbableContentContainer = this, ReadOnly = true, }, }, new Section("Password (optional)") { Child = PasswordTextBox = new OsuPasswordTextBox { RelativeSizeAxes = Axes.X, TabbableContentContainer = this, LengthLimit = 255, }, }, } } }, }, playlistContainer = new FillFlowContainer { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Width = 0.5f, Depth = float.MaxValue, Spacing = new Vector2(5), Children = new Drawable[] { drawablePlaylist = new DrawableRoomPlaylist { RelativeSizeAxes = Axes.X, Height = DrawableRoomPlaylistItem.HEIGHT }, new PurpleTriangleButton { RelativeSizeAxes = Axes.X, Height = 40, Text = "Select beatmap", Action = SelectBeatmap } } } } } }, }, }, new Drawable[] { new Container { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Y = 2, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colourProvider.Background5 }, new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Spacing = new Vector2(0, 20), Margin = new MarginPadding { Vertical = 20 }, Padding = new MarginPadding { Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING }, Children = new Drawable[] { ApplyButton = new CreateOrUpdateButton { Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, Size = new Vector2(230, 55), Enabled = { Value = false }, Action = apply, }, ErrorText = new OsuSpriteText { Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, Alpha = 0, Depth = 1, Colour = colours.RedDark } } } } } } } }, loadingLayer = new LoadingLayer(true) }; TypePicker.Current.BindValueChanged(type => typeLabel.Text = type.NewValue.GetLocalisableDescription(), true); RoomName.BindValueChanged(name => NameField.Text = name.NewValue, true); Availability.BindValueChanged(availability => AvailabilityPicker.Current.Value = availability.NewValue, true); Type.BindValueChanged(type => TypePicker.Current.Value = type.NewValue, true); MaxParticipants.BindValueChanged(count => MaxParticipantsField.Text = count.NewValue?.ToString(), true); RoomID.BindValueChanged(roomId => playlistContainer.Alpha = roomId.NewValue == null ? 1 : 0, true); Password.BindValueChanged(password => PasswordTextBox.Text = password.NewValue ?? string.Empty, true); QueueMode.BindValueChanged(mode => QueueModeDropdown.Current.Value = mode.NewValue, true); operationInProgress.BindTo(ongoingOperationTracker.InProgress); operationInProgress.BindValueChanged(v => { if (v.NewValue) loadingLayer.Show(); else loadingLayer.Hide(); }); } protected override void LoadComplete() { base.LoadComplete(); drawablePlaylist.Items.BindTo(Playlist); drawablePlaylist.SelectedItem.BindTo(CurrentPlaylistItem); } protected override void Update() { base.Update(); ApplyButton.Enabled.Value = Playlist.Count > 0 && NameField.Text.Length > 0 && !operationInProgress.Value; } private void apply() { if (!ApplyButton.Enabled.Value) return; hideError(); Debug.Assert(applyingSettingsOperation == null); applyingSettingsOperation = ongoingOperationTracker.BeginOperation(); // If the client is already in a room, update via the client. // Otherwise, update the room directly in preparation for it to be submitted to the API on match creation. if (client.Room != null) { client.ChangeSettings( name: NameField.Text, password: PasswordTextBox.Text, matchType: TypePicker.Current.Value, queueMode: QueueModeDropdown.Current.Value) .ContinueWith(t => Schedule(() => { if (t.IsCompletedSuccessfully) onSuccess(room); else onError(t.Exception?.AsSingular().Message ?? "Error changing settings."); })); } else { room.Name.Value = NameField.Text; room.Availability.Value = AvailabilityPicker.Current.Value; room.Type.Value = TypePicker.Current.Value; room.Password.Value = PasswordTextBox.Current.Value; room.QueueMode.Value = QueueModeDropdown.Current.Value; if (int.TryParse(MaxParticipantsField.Text, out int max)) room.MaxParticipants.Value = max; else room.MaxParticipants.Value = null; manager?.CreateRoom(room, onSuccess, onError); } } private void hideError() => ErrorText.FadeOut(50); private void onSuccess(Room room) { Debug.Assert(applyingSettingsOperation != null); SettingsApplied?.Invoke(); applyingSettingsOperation.Dispose(); applyingSettingsOperation = null; } private void onError(string text) { Debug.Assert(applyingSettingsOperation != null); // see https://github.com/ppy/osu-web/blob/2c97aaeb64fb4ed97c747d8383a35b30f57428c7/app/Models/Multiplayer/PlaylistItem.php#L48. const string not_found_prefix = "beatmaps not found:"; if (text.StartsWith(not_found_prefix, StringComparison.Ordinal)) { ErrorText.Text = "The selected beatmap is not available online."; CurrentPlaylistItem.Value.MarkInvalid(); } else { ErrorText.Text = text; } ErrorText.FadeIn(50); applyingSettingsOperation.Dispose(); applyingSettingsOperation = null; } } public class CreateOrUpdateButton : TriangleButton { [Resolved(typeof(Room), nameof(Room.RoomID))] private Bindable<long?> roomId { get; set; } protected override void LoadComplete() { base.LoadComplete(); roomId.BindValueChanged(id => Text = id.NewValue == null ? "Create" : "Update", true); } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.Yellow; Triangles.ColourLight = colours.YellowLight; Triangles.ColourDark = colours.YellowDark; } } } }
using System; using System.Collections.Generic; using System.Windows.Forms; using TribalWars.Villages; using TribalWars.Villages.Units; using TribalWars.Worlds; using TribalWars.Worlds.Events; using TribalWars.Worlds.Events.Impls; namespace TribalWars.Controls.Distance { #region Enum /// <summary> /// /// </summary> public enum ShowDistanceEnum { TravelTime = 0, TravelTime2, ArrivalTime, ReturnTime } #endregion /// <summary> /// Holder type for DistanceControls /// </summary> public class DistanceCollectionControl : FlowLayoutPanel { #region Constants public const int TravelWidth = 77; public const int TimeWidth = 100; #endregion #region Fields private List<DistanceControl> _items; private Village _villageStart; private Village _villageEnd; //private Button _moraleButton; private readonly Button _speedButton; private readonly ContextMenuStrip _speedStrip; private ShowDistanceEnum _speed = ShowDistanceEnum.TravelTime; #endregion #region Properties /// <summary> /// Gets or sets the current speed display type /// </summary> public ShowDistanceEnum CurrentSpeed { get { return _speed; } set { _speed = value; } } /// <summary> /// Gets the list of Distance buttons /// </summary> public List<DistanceControl> Items { get { return _items; } } /// <summary> /// Gets or sets the bullseye village /// </summary> public Village VillageStart { get { return _villageStart; } set { _villageStart = value; } } /// <summary> /// Gets or sets the target village /// </summary> public Village VillageEnd { get { return _villageEnd; } set { _villageEnd = value; } } /// <summary> /// Gets the ContextMenuStrip containing the different speed options /// </summary> public ContextMenuStrip SpeedStrip { get { return _speedStrip; } } #endregion #region Constructors public DistanceCollectionControl() { AutoSize = false; BackColor = System.Drawing.Color.Transparent; Margin = new Padding(0); Padding = new Padding(0); World.Default.EventPublisher.Loaded += World_Loaded; World.Default.Map.EventPublisher.VillagesSelected += World_VillagesSelected; // Loads the speed strip & items _speedStrip = new ContextMenuStrip(); _speedStrip.Items.Add(new DistanceContextMenuItem("Travel time", ShowDistanceEnum.TravelTime, this)); _speedStrip.Items.Add(new DistanceContextMenuItem("Travel time * 2", ShowDistanceEnum.TravelTime2, this)); _speedStrip.Items.Add(new DistanceContextMenuItem("Arrival time", ShowDistanceEnum.ArrivalTime, this)); _speedStrip.Items.Add(new DistanceContextMenuItem("Return time", ShowDistanceEnum.ReturnTime, this)); ((ToolStripMenuItem)_speedStrip.Items[0]).Checked = true; _speedButton = new Button(); _speedButton.AutoSize = false; _speedButton.Image = Properties.Resources.speed; _speedButton.ContextMenuStrip = _speedStrip; _speedButton.Size = new System.Drawing.Size(21, 21); _speedButton.Text = string.Empty; _speedButton.FlatStyle = FlatStyle.Flat; _speedButton.FlatAppearance.BorderSize = 0; _speedButton.Margin = new Padding(0); _speedButton.Padding = new Padding(0); _speedButton.Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif, 15, System.Drawing.FontStyle.Bold); _speedButton.MouseClick += SpeedButton_MouseClick; Controls.Add(_speedButton); #region Commented Morale // morale /*_moraleButton = new Button(); _moraleButton.AutoSize = false; _moraleButton.Size = new System.Drawing.Size(70, 21); _moraleButton.Text = string.Empty; _moraleButton.FlatStyle = FlatStyle.Flat; _moraleButton.FlatAppearance.BorderSize = 0; _moraleButton.Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif, 15, System.Drawing.FontStyle.Bold); Controls.Add(_moraleButton);*/ #endregion } #endregion #region Event Handlers private void SpeedButton_MouseClick(object sender, MouseEventArgs e) { // Show the context menu _speedStrip.Show(_speedButton, e.Location); } private void World_VillagesSelected(object sender, VillagesEventArgs e) { switch (e.Tool) { case VillageTools.Default: VillageEnd = e.FirstVillage; //SetMorale(); SetTimes(); break; case VillageTools.Distance: VillageStart = e.FirstVillage; SetTimes(); break; } } private void World_Loaded(object sender, EventArgs e) { // dispose existing Distance buttons if (_items != null) { for (int i = 0; i < _items.Count; i++) { var ctl = _items[i]; if (ctl != null) { ctl.Dispose(); } } } // Add all units _items = new List<DistanceControl>(); float lastSpeed = 0; foreach (Unit unit in WorldUnits.Default) { if (unit.Speed != lastSpeed) { var ctl = new DistanceControl(this, unit); Controls.Add(ctl); _items.Add(ctl); } lastSpeed = unit.Speed; } SetSize(); // load default bullseye from settings /*if (World.Default.Settings.BullsEye != null) { _villageStart = World.Default.Settings.BullsEye; }*/ } #endregion #region Commented Morale /*private void SetMorale() { int morale = 0; if (!VillageEnd.HasPlayer) morale = 100; else if (World.Default.Settings.You.PlayerSelected) { if (VillageEnd.Player != World.Default.Settings.You.Player) { } } if (morale == 0) { _moraleButton.Text = "???"; _moraleButton.ForeColor = System.Drawing.Color.Black; } else { _moraleButton.Text = morale.ToString(); if (morale < 60) _moraleButton.ForeColor = System.Drawing.Color.Red; else _moraleButton.ForeColor = System.Drawing.Color.Green; } }*/ #endregion #region Private Implementation /// <summary> /// Sets the time for all Distance buttons /// </summary> private void SetTimes() { foreach (DistanceControl distance in _items) { distance.ShowTime(_villageStart, _villageEnd, _speed); } } #endregion #region Public Methods /// <summary> /// Sets the size of the collection to fit the Distance buttons /// </summary> public void SetSize() { int width = TravelWidth; if (CurrentSpeed == ShowDistanceEnum.TravelTime || CurrentSpeed == ShowDistanceEnum.TravelTime2) width = TimeWidth; Size = new System.Drawing.Size((width + 3) * _items.Count + _speedButton.Width + 2, 21); } #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.Reflection; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Internal.Reflection.Augments; //================================================================================================================== // Dependency note: // This class must depend only on the CustomAttribute properties that return IEnumerable<CustomAttributeData>. // All of the other custom attribute api route back here so calls to them will cause an infinite recursion. //================================================================================================================== namespace Internal.Reflection.Extensions.NonPortable { internal static class CustomAttributeInheritanceRules { //============================================================================================================================== // Api helpers: Computes the effective set of custom attributes for various Reflection elements and returns them // as CustomAttributeData objects. //============================================================================================================================== public static IEnumerable<CustomAttributeData> GetMatchingCustomAttributes(this Assembly element, Type optionalAttributeTypeFilter, bool skipTypeValidation = false) { return AssemblyCustomAttributeSearcher.Default.GetMatchingCustomAttributes(element, optionalAttributeTypeFilter, inherit: false, skipTypeValidation: skipTypeValidation); } public static IEnumerable<CustomAttributeData> GetMatchingCustomAttributes(this Module element, Type optionalAttributeTypeFilter, bool skipTypeValidation = false) { return ModuleCustomAttributeSearcher.Default.GetMatchingCustomAttributes(element, optionalAttributeTypeFilter, inherit: false, skipTypeValidation: skipTypeValidation); } public static IEnumerable<CustomAttributeData> GetMatchingCustomAttributes(this ParameterInfo element, Type optionalAttributeTypeFilter, bool inherit, bool skipTypeValidation = false) { return ParameterCustomAttributeSearcher.Default.GetMatchingCustomAttributes(element, optionalAttributeTypeFilter, inherit, skipTypeValidation: skipTypeValidation); } public static IEnumerable<CustomAttributeData> GetMatchingCustomAttributes(this MemberInfo element, Type optionalAttributeTypeFilter, bool inherit, bool skipTypeValidation = false) { { TypeInfo typeInfo = element as TypeInfo; if (typeInfo != null) return TypeCustomAttributeSearcher.Default.GetMatchingCustomAttributes(typeInfo, optionalAttributeTypeFilter, inherit, skipTypeValidation: skipTypeValidation); } { ConstructorInfo constructorInfo = element as ConstructorInfo; if (constructorInfo != null) return ConstructorCustomAttributeSearcher.Default.GetMatchingCustomAttributes(constructorInfo, optionalAttributeTypeFilter, inherit: false, skipTypeValidation: skipTypeValidation); } { MethodInfo methodInfo = element as MethodInfo; if (methodInfo != null) return MethodCustomAttributeSearcher.Default.GetMatchingCustomAttributes(methodInfo, optionalAttributeTypeFilter, inherit, skipTypeValidation: skipTypeValidation); } { FieldInfo fieldInfo = element as FieldInfo; if (fieldInfo != null) return FieldCustomAttributeSearcher.Default.GetMatchingCustomAttributes(fieldInfo, optionalAttributeTypeFilter, inherit: false, skipTypeValidation: skipTypeValidation); } { PropertyInfo propertyInfo = element as PropertyInfo; if (propertyInfo != null) return PropertyCustomAttributeSearcher.Default.GetMatchingCustomAttributes(propertyInfo, optionalAttributeTypeFilter, inherit, skipTypeValidation: skipTypeValidation); } { EventInfo eventInfo = element as EventInfo; if (eventInfo != null) return EventCustomAttributeSearcher.Default.GetMatchingCustomAttributes(eventInfo, optionalAttributeTypeFilter, inherit, skipTypeValidation: skipTypeValidation); } if (element == null) throw new ArgumentNullException(); throw new NotSupportedException(); // Shouldn't get here. } //============================================================================================================================== // Searcher class for Assemblies. //============================================================================================================================== private sealed class AssemblyCustomAttributeSearcher : CustomAttributeSearcher<Assembly> { protected sealed override IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(Assembly element) { return element.CustomAttributes; } public static readonly AssemblyCustomAttributeSearcher Default = new AssemblyCustomAttributeSearcher(); } //============================================================================================================================== // Searcher class for Modules. //============================================================================================================================== private sealed class ModuleCustomAttributeSearcher : CustomAttributeSearcher<Module> { protected sealed override IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(Module element) { return element.CustomAttributes; } public static readonly ModuleCustomAttributeSearcher Default = new ModuleCustomAttributeSearcher(); } //============================================================================================================================== // Searcher class for TypeInfos. //============================================================================================================================== private sealed class TypeCustomAttributeSearcher : CustomAttributeSearcher<TypeInfo> { protected sealed override IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(TypeInfo element) { return element.CustomAttributes; } public sealed override TypeInfo GetParent(TypeInfo e) { Type baseType = e.BaseType; if (baseType == null) return null; // Optimization: We shouldn't have any public inheritable attributes on Object or ValueType so don't bother scanning this one. // Since many types derive directly from Object, this should a lot of type. if (baseType.Equals(CommonRuntimeTypes.Object) || baseType.Equals(CommonRuntimeTypes.ValueType)) return null; return baseType.GetTypeInfo(); } public static readonly TypeCustomAttributeSearcher Default = new TypeCustomAttributeSearcher(); } //============================================================================================================================== // Searcher class for FieldInfos. //============================================================================================================================== private sealed class FieldCustomAttributeSearcher : CustomAttributeSearcher<FieldInfo> { protected sealed override IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(FieldInfo element) { return element.CustomAttributes; } public static readonly FieldCustomAttributeSearcher Default = new FieldCustomAttributeSearcher(); } //============================================================================================================================== // Searcher class for ConstructorInfos. //============================================================================================================================== private sealed class ConstructorCustomAttributeSearcher : CustomAttributeSearcher<ConstructorInfo> { protected sealed override IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(ConstructorInfo element) { return element.CustomAttributes; } public static readonly ConstructorCustomAttributeSearcher Default = new ConstructorCustomAttributeSearcher(); } //============================================================================================================================== // Searcher class for MethodInfos. //============================================================================================================================== private sealed class MethodCustomAttributeSearcher : CustomAttributeSearcher<MethodInfo> { protected sealed override IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(MethodInfo element) { return element.CustomAttributes; } public sealed override MethodInfo GetParent(MethodInfo e) { return ReflectionAugments.ReflectionCoreCallbacks.GetImplicitlyOverriddenBaseClassMethod(e); } public static readonly MethodCustomAttributeSearcher Default = new MethodCustomAttributeSearcher(); } //============================================================================================================================== // Searcher class for PropertyInfos. //============================================================================================================================== private sealed class PropertyCustomAttributeSearcher : CustomAttributeSearcher<PropertyInfo> { protected sealed override IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(PropertyInfo element) { return element.CustomAttributes; } public sealed override PropertyInfo GetParent(PropertyInfo e) { return ReflectionAugments.ReflectionCoreCallbacks.GetImplicitlyOverriddenBaseClassProperty(e); } public static readonly PropertyCustomAttributeSearcher Default = new PropertyCustomAttributeSearcher(); } //============================================================================================================================== // Searcher class for EventInfos. //============================================================================================================================== private sealed class EventCustomAttributeSearcher : CustomAttributeSearcher<EventInfo> { protected sealed override IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(EventInfo element) { return element.CustomAttributes; } public sealed override EventInfo GetParent(EventInfo e) { return ReflectionAugments.ReflectionCoreCallbacks.GetImplicitlyOverriddenBaseClassEvent(e); } public static readonly EventCustomAttributeSearcher Default = new EventCustomAttributeSearcher(); } //============================================================================================================================== // Searcher class for ParameterInfos. //============================================================================================================================== private sealed class ParameterCustomAttributeSearcher : CustomAttributeSearcher<ParameterInfo> { protected sealed override IEnumerable<CustomAttributeData> GetDeclaredCustomAttributes(ParameterInfo element) { return element.CustomAttributes; } public sealed override ParameterInfo GetParent(ParameterInfo e) { MethodInfo method = e.Member as MethodInfo; if (method == null) return null; // This is a constructor parameter. MethodInfo methodParent = new MethodCustomAttributeSearcher().GetParent(method); if (methodParent == null) return null; return methodParent.GetParameters()[e.Position]; } public static readonly ParameterCustomAttributeSearcher Default = new ParameterCustomAttributeSearcher(); } } }
// 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.Globalization; using System.Runtime.InteropServices; using System.DirectoryServices; using System.Text; using System.Net; namespace System.DirectoryServices.AccountManagement { #pragma warning disable 618 // Have not migrated to v4 transparency yet [System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)] #pragma warning restore 618 internal class SidList { internal SidList(List<Byte[]> sidListByteFormat) : this(sidListByteFormat, null, null) { } internal SidList(List<Byte[]> sidListByteFormat, string target, NetCred credentials) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: processing {0} ByteFormat SIDs", sidListByteFormat.Count); GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: Targetting {0} ", (target != null) ? target : "local store"); // Build the list of SIDs to resolve IntPtr hUser = IntPtr.Zero; int sidCount = sidListByteFormat.Count; IntPtr[] pSids = new IntPtr[sidCount]; for (int i = 0; i < sidCount; i++) { pSids[i] = Utils.ConvertByteArrayToIntPtr(sidListByteFormat[i]); } try { if (credentials != null) { Utils.BeginImpersonation(credentials, out hUser); } TranslateSids(target, pSids); } finally { if (hUser != IntPtr.Zero) Utils.EndImpersonation(hUser); } } internal SidList(UnsafeNativeMethods.SID_AND_ATTR[] sidAndAttr) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "SidList", "SidList: processing {0} Sid+Attr SIDs", sidAndAttr.Length); // Build the list of SIDs to resolve int sidCount = sidAndAttr.Length; IntPtr[] pSids = new IntPtr[sidCount]; for (int i = 0; i < sidCount; i++) { pSids[i] = sidAndAttr[i].pSid; } TranslateSids(null, pSids); } protected void TranslateSids(string target, IntPtr[] pSids) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: processing {0} SIDs", pSids.Length); // if there are no SIDs to translate return if (pSids.Length == 0) { return; } // Build the list of SIDs to resolve int sidCount = pSids.Length; // Translate the SIDs in bulk IntPtr pOA = IntPtr.Zero; IntPtr pPolicyHandle = IntPtr.Zero; IntPtr pDomains = IntPtr.Zero; UnsafeNativeMethods.LSA_TRUST_INFORMATION[] domains; IntPtr pNames = IntPtr.Zero; UnsafeNativeMethods.LSA_TRANSLATED_NAME[] names; try { // // Get the policy handle // UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES oa = new UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES(); pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES))); Marshal.StructureToPtr(oa, pOA, false); int err = 0; if (target == null) { err = UnsafeNativeMethods.LsaOpenPolicy( IntPtr.Zero, pOA, 0x800, // POLICY_LOOKUP_NAMES ref pPolicyHandle); } else { // Build an entry. Note that LSA_UNICODE_STRING.length is in bytes, // while PtrToStringUni expects a length in characters. UnsafeNativeMethods.LSA_UNICODE_STRING_Managed lsaTargetString = new UnsafeNativeMethods.LSA_UNICODE_STRING_Managed(); lsaTargetString.buffer = target; lsaTargetString.length = (ushort)(target.Length * 2); lsaTargetString.maximumLength = lsaTargetString.length; IntPtr lsaTargetPr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_UNICODE_STRING))); try { Marshal.StructureToPtr(lsaTargetString, lsaTargetPr, false); err = UnsafeNativeMethods.LsaOpenPolicy( lsaTargetPr, pOA, 0x800, // POLICY_LOOKUP_NAMES ref pPolicyHandle); } finally { if (lsaTargetPr != IntPtr.Zero) { UnsafeNativeMethods.LSA_UNICODE_STRING lsaTargetUnmanagedPtr = (UnsafeNativeMethods.LSA_UNICODE_STRING)Marshal.PtrToStructure(lsaTargetPr, typeof(UnsafeNativeMethods.LSA_UNICODE_STRING)); if (lsaTargetUnmanagedPtr.buffer != IntPtr.Zero) { Marshal.FreeHGlobal(lsaTargetUnmanagedPtr.buffer); lsaTargetUnmanagedPtr.buffer = IntPtr.Zero; } Marshal.FreeHGlobal(lsaTargetPr); } } } if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: couldn't get policy handle, err={0}", err); throw new PrincipalOperationException(String.Format(CultureInfo.CurrentCulture, SR.AuthZErrorEnumeratingGroups, SafeNativeMethods.LsaNtStatusToWinError(err))); } Debug.Assert(pPolicyHandle != IntPtr.Zero); // // Translate the SIDs // err = UnsafeNativeMethods.LsaLookupSids( pPolicyHandle, sidCount, pSids, out pDomains, out pNames); // ignore error STATUS_SOME_NOT_MAPPED = 0x00000107 and // STATUS_NONE_MAPPED = 0xC0000073 if (err != 0 && err != 263 && err != -1073741709) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: LsaLookupSids failed, err={0}", err); throw new PrincipalOperationException(String.Format(CultureInfo.CurrentCulture, SR.AuthZErrorEnumeratingGroups, SafeNativeMethods.LsaNtStatusToWinError(err))); } // // Get the group names in managed form // names = new UnsafeNativeMethods.LSA_TRANSLATED_NAME[sidCount]; IntPtr pCurrentName = pNames; for (int i = 0; i < sidCount; i++) { names[i] = (UnsafeNativeMethods.LSA_TRANSLATED_NAME) Marshal.PtrToStructure(pCurrentName, typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME)); pCurrentName = new IntPtr(pCurrentName.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRANSLATED_NAME))); } // // Get the domain names in managed form // // Extract LSA_REFERENCED_DOMAIN_LIST.Entries UnsafeNativeMethods.LSA_REFERENCED_DOMAIN_LIST referencedDomains = (UnsafeNativeMethods.LSA_REFERENCED_DOMAIN_LIST)Marshal.PtrToStructure(pDomains, typeof(UnsafeNativeMethods.LSA_REFERENCED_DOMAIN_LIST)); int domainCount = referencedDomains.entries; // Extract LSA_REFERENCED_DOMAIN_LIST.Domains, by iterating over the array and marshalling // each native LSA_TRUST_INFORMATION into a managed LSA_TRUST_INFORMATION. domains = new UnsafeNativeMethods.LSA_TRUST_INFORMATION[domainCount]; IntPtr pCurrentDomain = referencedDomains.domains; for (int i = 0; i < domainCount; i++) { domains[i] = (UnsafeNativeMethods.LSA_TRUST_INFORMATION)Marshal.PtrToStructure(pCurrentDomain, typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION)); pCurrentDomain = new IntPtr(pCurrentDomain.ToInt64() + Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_TRUST_INFORMATION))); } GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthZSet", "SidList: got {0} groups in {1} domains", sidCount, domainCount); // // Build the list of entries // Debug.Assert(names.Length == sidCount); for (int i = 0; i < names.Length; i++) { UnsafeNativeMethods.LSA_TRANSLATED_NAME name = names[i]; // Build an entry. Note that LSA_UNICODE_STRING.length is in bytes, // while PtrToStringUni expects a length in characters. SidListEntry entry = new SidListEntry(); Debug.Assert(name.name.length % 2 == 0); entry.name = Marshal.PtrToStringUni(name.name.buffer, name.name.length / 2); // Get the domain associated with this name Debug.Assert(name.domainIndex < domains.Length); if (name.domainIndex >= 0) { UnsafeNativeMethods.LSA_TRUST_INFORMATION domain = domains[name.domainIndex]; Debug.Assert(domain.name.length % 2 == 0); entry.sidIssuerName = Marshal.PtrToStringUni(domain.name.buffer, domain.name.length / 2); } entry.pSid = pSids[i]; _entries.Add(entry); } // Sort the list so they are oriented by the issuer name. // this.entries.Sort( new SidListComparer()); } finally { if (pDomains != IntPtr.Zero) UnsafeNativeMethods.LsaFreeMemory(pDomains); if (pNames != IntPtr.Zero) UnsafeNativeMethods.LsaFreeMemory(pNames); if (pPolicyHandle != IntPtr.Zero) UnsafeNativeMethods.LsaClose(pPolicyHandle); if (pOA != IntPtr.Zero) Marshal.FreeHGlobal(pOA); } } private List<SidListEntry> _entries = new List<SidListEntry>(); public SidListEntry this[int index] { get { return _entries[index]; } } public int Length { get { return _entries.Count; } } public void RemoveAt(int index) { _entries[index].Dispose(); _entries.RemoveAt(index); } public void Clear() { foreach (SidListEntry sl in _entries) sl.Dispose(); _entries.Clear(); } } /****** class SidListComparer : IComparer<SidListEntry> { public int Compare(SidListEntry entry1, SidListEntry entry2) { return ( string.Compare( entry1.sidIssuerName, entry2.sidIssuerName, true, CultureInfo.InvariantCulture)); } } ********/ internal class SidListEntry : IDisposable { public IntPtr pSid = IntPtr.Zero; public string name; public string sidIssuerName; // // IDisposable // [System.Security.SecurityCritical] public virtual void Dispose() { if (pSid != IntPtr.Zero) { Marshal.FreeHGlobal(pSid); pSid = IntPtr.Zero; } } } }
// 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.IO; using System.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class PublicKeyTests { private static PublicKey GetTestRsaKey() { using (var cert = new X509Certificate2(TestData.MsCertificate)) { return cert.PublicKey; } } private static PublicKey GetTestDsaKey() { using (var cert = new X509Certificate2(TestData.DssCer)) { return cert.PublicKey; } } [Fact] public static void TestOid_RSA() { PublicKey pk = GetTestRsaKey(); Assert.Equal("1.2.840.113549.1.1.1", pk.Oid.Value); } [Fact] public static void TestOid_DSA() { PublicKey pk = GetTestDsaKey(); Assert.Equal("1.2.840.10040.4.1", pk.Oid.Value); } [Fact] public static void TestEncodedKeyValue_RSA() { byte[] expectedPublicKey = ( "3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb" + "407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb" + "137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bba" + "b95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1" + "109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd" + "2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c425" + "2e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b2801" + "84b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec643" + "0b950005b14f6571c50203010001").HexToByteArray(); PublicKey pk = GetTestRsaKey(); Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData); } [Fact] public static void TestEncodedKeyValue_DSA() { byte[] expectedPublicKey = ( "028180089a43f439b924bef3529d8d6206d1fca56a55caf52b41d6ce371ebf07" + "bda132c8eadc040007fcf4da06c1f30504ebd8a77d301f5a4702f01f0d2a0707" + "ac1da38dd3251883286e12456234da62eda0df5fe2fa07cd5b16f3638becca77" + "86312da7d3594a4bb14e353884da0e9aecb86e3c9bdb66fca78ea85e1cc3f2f8" + "bf0963").HexToByteArray(); PublicKey pk = GetTestDsaKey(); Assert.Equal(expectedPublicKey, pk.EncodedKeyValue.RawData); } [Fact] public static void TestEncodedParameters_RSA() { PublicKey pk = GetTestRsaKey(); // RSA has no key parameters, so the answer is always // DER:NULL (type 0x05, length 0x00) Assert.Equal(new byte[] { 0x05, 0x00 }, pk.EncodedParameters.RawData); } [Fact] public static void TestEncodedParameters_DSA() { byte[] expectedParameters = ( "3082011F02818100871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180" + "511D0DCEB8B979285708C800FC10CB15337A4AC1A48ED31394072015A7A6B525" + "986B49E5E1139737A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA4" + "1E8F0763AA613E29C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DF" + "B33C44D2F2DBE819021500E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D02" + "818100859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481" + "584413E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310F" + "EFD518AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0" + "DAFDA079BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D" + "05431D").HexToByteArray(); PublicKey pk = GetTestDsaKey(); Assert.Equal(expectedParameters, pk.EncodedParameters.RawData); } [Fact] public static void TestKey_RSA() { using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { RSA rsa = cert.GetRSAPublicKey(); RSAParameters rsaParameters = rsa.ExportParameters(false); byte[] expectedModulus = ( "E8AF5CA2200DF8287CBC057B7FADEEEB76AC28533F3ADB407DB38E33E6573FA5" + "51153454A5CFB48BA93FA837E12D50ED35164EEF4D7ADB137688B02CF0595CA9" + "EBE1D72975E41B85279BF3F82D9E41362B0B40FBBE3BBAB95C759316524BCA33" + "C537B0F3EB7EA8F541155C08651D2137F02CBA220B10B1109D772285847C4FB9" + "1B90B0F5A3FE8BF40C9A4EA0F5C90A21E2AAE3013647FD2F826A8103F5A935DC" + "94579DFB4BD40E82DB388F12FEE3D67A748864E162C4252E2AAE9D181F0E1EB6" + "C2AF24B40E50BCDE1C935C49A679B5B6DBCEF9707B280184B82A29CFBFA90505" + "E1E00F714DFDAD5C238329EBC7C54AC8E82784D37EC6430B950005B14F6571C5").HexToByteArray(); byte[] expectedExponent = new byte[] { 0x01, 0x00, 0x01 }; Assert.Equal(expectedModulus, rsaParameters.Modulus); Assert.Equal(expectedExponent, rsaParameters.Exponent); } } [Fact] public static void TestKey_RSA384_ValidatesSignature() { byte[] signature = { 0x79, 0xD9, 0x3C, 0xBF, 0x54, 0xFA, 0x55, 0x8C, 0x44, 0xC3, 0xC3, 0x83, 0x85, 0xBB, 0x78, 0x44, 0xCD, 0x0F, 0x5A, 0x8E, 0x71, 0xC9, 0xC2, 0x68, 0x68, 0x0A, 0x33, 0x93, 0x19, 0x37, 0x02, 0x06, 0xE2, 0xF7, 0x67, 0x97, 0x3C, 0x67, 0xB3, 0xF4, 0x11, 0xE0, 0x6E, 0xD2, 0x22, 0x75, 0xE7, 0x7C, }; byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.Rsa384CertificatePemBytes)) using (RSA rsa = cert.GetRSAPublicKey()) { Assert.True(rsa.VerifyData(helloBytes, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)); } } [Fact] public static void TestECDsaPublicKey() { byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(384, publicKey.KeySize); // The public key should be unable to sign. Assert.ThrowsAny<CryptographicException>(() => publicKey.SignData(helloBytes, HashAlgorithmName.SHA256)); } } [Fact] public static void TestECDsaPublicKey_ValidatesSignature() { // This signature was produced as the output of ECDsaCng.SignData with the same key // on .NET 4.6. Ensure it is verified here as a data compatibility test. // // Note that since ECDSA signatures contain randomness as an input, this value is unlikely // to be reproduced by another equivalent program. byte[] existingSignature = { // r: 0x7E, 0xD7, 0xEF, 0x46, 0x04, 0x92, 0x61, 0x27, 0x9F, 0xC9, 0x1B, 0x7B, 0x8A, 0x41, 0x6A, 0xC6, 0xCF, 0xD4, 0xD4, 0xD1, 0x73, 0x05, 0x1F, 0xF3, 0x75, 0xB2, 0x13, 0xFA, 0x82, 0x2B, 0x55, 0x11, 0xBE, 0x57, 0x4F, 0x20, 0x07, 0x24, 0xB7, 0xE5, 0x24, 0x44, 0x33, 0xC3, 0xB6, 0x8F, 0xBC, 0x1F, // s: 0x48, 0x57, 0x25, 0x39, 0xC0, 0x84, 0xB9, 0x0E, 0xDA, 0x32, 0x35, 0x16, 0xEF, 0xA0, 0xE2, 0x34, 0x35, 0x7E, 0x10, 0x38, 0xA5, 0xE4, 0x8B, 0xD3, 0xFC, 0xE7, 0x60, 0x25, 0x4E, 0x63, 0xF7, 0xDB, 0x7C, 0xBF, 0x18, 0xD6, 0xD3, 0x49, 0xD0, 0x93, 0x08, 0xC5, 0xAA, 0xA6, 0xE5, 0xFD, 0xD0, 0x96, }; byte[] helloBytes = Encoding.ASCII.GetBytes("Hello"); using (var cert = new X509Certificate2(TestData.ECDsa384Certificate)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { Assert.Equal(384, publicKey.KeySize); bool isSignatureValid = publicKey.VerifyData(helloBytes, existingSignature, HashAlgorithmName.SHA256); Assert.True(isSignatureValid, "isSignatureValid"); } } [Fact] public static void TestECDsaPublicKey_NonSignatureCert() { using (var cert = new X509Certificate2(TestData.EccCert_KeyAgreement)) using (ECDsa publicKey = cert.GetECDsaPublicKey()) { // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); // But, due to KeyUsage, it shouldn't be used for ECDSA. Assert.Null(publicKey); } } [Fact] public static void TestECDsa224PublicKey() { using (var cert = new X509Certificate2(TestData.ECDsa224Certificate)) { // It is an Elliptic Curve Cryptography public key. Assert.Equal("1.2.840.10045.2.1", cert.PublicKey.Oid.Value); ECDsa ecdsa; try { ecdsa = cert.GetECDsaPublicKey(); } catch (CryptographicException) { // Windows 7, Windows 8, CentOS. return; } // Other Unix using (ecdsa) { byte[] data = ByteUtils.AsciiBytes("Hello"); byte[] signature = ( // r "8ede5053d546d35c1aba829bca3ecf493eb7a73f751548bd4cf2ad10" + // s "5e3da9d359001a6be18e2b4e49205e5219f30a9daeb026159f41b9de").HexToByteArray(); Assert.True(ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA1)); } } } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void TestKey_ECDsaCng256() { TestKey_ECDsaCng(TestData.ECDsa256Certificate, TestData.ECDsaCng256PublicKey); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void TestKey_ECDsaCng384() { TestKey_ECDsaCng(TestData.ECDsa384Certificate, TestData.ECDsaCng384PublicKey); } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void TestKey_ECDsaCng521() { TestKey_ECDsaCng(TestData.ECDsa521Certificate, TestData.ECDsaCng521PublicKey); } private static void TestKey_ECDsaCng(byte[] certBytes, TestData.ECDsaCngKeyValues expected) { #if !NETNATIVE using (X509Certificate2 cert = new X509Certificate2(certBytes)) { ECDsaCng e = (ECDsaCng)(cert.GetECDsaPublicKey()); CngKey k = e.Key; byte[] blob = k.Export(CngKeyBlobFormat.EccPublicBlob); using (BinaryReader br = new BinaryReader(new MemoryStream(blob))) { int magic = br.ReadInt32(); int cbKey = br.ReadInt32(); Assert.Equal(expected.QX.Length, cbKey); byte[] qx = br.ReadBytes(cbKey); byte[] qy = br.ReadBytes(cbKey); Assert.Equal<byte>(expected.QX, qx); Assert.Equal<byte>(expected.QY, qy); } } #endif //!NETNATIVE } } }
//*************************************************** //* This file was generated by tool //* SharpKit //* At: 29/08/2012 03:59:42 p.m. //*************************************************** using SharpKit.JavaScript; namespace Ext.view { #region AbstractView /// <inheritdocs /> /// <summary> /// <p><strong>NOTE</strong> This is a private utility class for internal use by the framework. Don't rely on its existence.</p><p>This is an abstract superclass and should not be used directly. Please see <see cref="Ext.view.View">Ext.view.View</see>.</p> /// </summary> [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)] public partial class AbstractView : Ext.Component, Ext.util.Bindable { /// <summary> /// Set this to true to ignore refresh events on the bound store. This is useful if /// you wish to provide custom transition animations via a plugin /// Defaults to: <c>false</c> /// </summary> public bool blockRefresh; /// <summary> /// True to defer emptyText being applied until the store's first load. /// Defaults to: <c>true</c> /// </summary> public bool deferEmptyText; /// <summary> /// Defaults to true to defer the initial refresh of the view. /// This allows the View to execute its render and initial layout more quickly because the process will not be encumbered /// by the expensive update of the view structure. /// <b>Important: </b>Be aware that this will mean that the View's item elements will not be available immediately upon render, so /// <i>selection</i> may not take place at render time. To access a View's item elements as soon as possible, use the <see cref="Ext.view.AbstractViewEvents.viewready">viewready</see> event. /// Or set <c>deferInitialrefresh</c> to false, but this will be at the cost of slower rendering. /// Defaults to: <c>true</c> /// </summary> public bool deferInitialRefresh; /// <summary> /// True to disable selection within the DataView. This configuration will lock the selection model /// that the DataView uses. /// </summary> public bool disableSelection; /// <summary> /// The text to display in the view when there is no data to display. /// Note that when using local data the emptyText will not be displayed unless you set /// the deferEmptyText option to false. /// Defaults to: <c>&quot;&quot;</c> /// </summary> public JsString emptyText; /// <summary> /// Specifies the class to be assigned to each element in the view when used in conjunction with the /// itemTpl configuration. /// Defaults to: <c>&quot;x-dataview-item&quot;</c> /// </summary> public JsString itemCls; /// <summary> /// This is a required setting. A simple CSS selector (e.g. div.some-class or /// span:first-child) that will be used to determine what nodes this DataView will be /// working with. The itemSelector is used to map DOM nodes to records. As such, there should /// only be one root level element that matches the selector for each record. /// </summary> public JsString itemSelector; /// <summary> /// The inner portion of the item template to be rendered. Follows an XTemplate /// structure and will be placed inside of a tpl. /// </summary> public object itemTpl; /// <summary> /// False to disable a load mask from displaying while the view is loading. This can also be a /// Ext.LoadMask configuration object. /// Defaults to: <c>true</c> /// </summary> public object loadMask; /// <summary> /// The CSS class to apply to the loading message element. Defaults to Ext.LoadMask.prototype.msgCls "x-mask-loading". /// </summary> public JsString loadingCls; /// <summary> /// If specified, gives an explicit height for the data view when it is showing the loadingText, /// if that is specified. This is useful to prevent the view's height from collapsing to zero when the /// loading mask is applied and there are no other contents in the data view. /// </summary> public JsNumber loadingHeight; /// <summary> /// A string to display during data load operations. If specified, this text will be /// displayed in a loading div and the view's contents will be cleared while loading, otherwise the view's /// contents will continue to display normally until the new data is loaded and the contents are replaced. /// Defaults to: <c>&quot;Loading...&quot;</c> /// </summary> public JsString loadingText; /// <summary> /// Whether or not to use the loading message. /// Defaults to: <c>true</c> /// </summary> public bool loadingUseMsg; /// <summary> /// True to allow selection of more than one item at a time, false to allow selection of only a single item /// at a time or no selection at all, depending on the value of singleSelect. /// Defaults to: <c>false</c> /// <p>This cfg has been <strong>deprecated</strong> since 4.1.1</p> /// <p>Use <see cref="Ext.selection.ModelConfig.mode">Ext.selection.Model.mode</see> 'MULTI' instead.</p> /// </summary> public bool multiSelect; /// <summary> /// A CSS class to apply to each item in the view on mouseover. /// Setting this will automatically set trackOver to true. /// </summary> public JsString overItemCls; /// <summary> /// =false /// True to preserve scroll position across refresh operations. /// Defaults to: <c>false</c> /// </summary> public bool preserveScrollOnRefresh; /// <summary> /// A CSS class to apply to each selected item in the view. /// Defaults to: <c>&quot;x-item-selected&quot;</c> /// </summary> public JsString selectedItemCls; /// <summary> /// True to enable multiselection by clicking on multiple items without requiring the user to hold Shift or Ctrl, /// false to force the user to hold Ctrl or Shift to select more than on item. /// Defaults to: <c>false</c> /// <p>This cfg has been <strong>deprecated</strong> since 4.1.1</p> /// <p>Use <see cref="Ext.selection.ModelConfig.mode">Ext.selection.Model.mode</see> 'SIMPLE' instead.</p> /// </summary> public bool simpleSelect; /// <summary> /// Allows selection of exactly one item at a time. As this is the default selection mode anyway, this config /// is completely ignored. /// <p>This cfg has been <strong>removed</strong> since 4.1.1</p> /// <p>Use <see cref="Ext.selection.ModelConfig.mode">Ext.selection.Model.mode</see> 'SINGLE' instead.</p> /// </summary> public bool singleSelect; /// <summary> /// The Ext.data.Store to bind this DataView to. /// </summary> public Ext.data.Store store; /// <summary> /// When true the overItemCls will be applied to rows when hovered over. /// This in return will also cause highlightitem and /// unhighlightitem events to be fired. /// Enabled automatically when the <see cref="Ext.view.AbstractViewConfig.overItemCls">overItemCls</see> config is set. /// Defaults to: <c>false</c> /// </summary> public bool trackOver; /// <summary> /// Changes the data store bound to this view and refreshes it. /// </summary> /// <param name="store"><p>The store to bind to this view</p> /// </param> public void bindStore(Ext.data.Store store){} /// <summary> /// Binds listeners for this component to the store. By default it will add /// anything bound by the getStoreListeners method, however it can be overridden /// in a subclass to provide any more complicated handling. /// </summary> /// <param name="store"><p>The store to bind to</p> /// </param> public virtual void bindStoreListeners(Ext.data.AbstractStore store){} /// <summary> /// Deselects all selected records. /// <p>This method has been <strong>deprecated</strong> since 4.0</p> /// <p>Use <see cref="Ext.selection.Model.deselectAll">Ext.selection.Model.deselectAll</see> instead.</p> /// </summary> public void clearSelections(){} /// <summary> /// Function which can be overridden which returns the data object passed to this /// DataView's template to render the whole DataView. /// This is usually an Array of data objects, each element of which is processed by an /// <see cref="Ext.XTemplate">XTemplate</see> which uses <tt>'&lt;tpl for="."&gt;'</tt> to iterate over its supplied /// data object as an Array. However, <i>named</i> properties may be placed into the data object to /// provide non-repeating data such as headings, totals etc. /// </summary> /// <param name="records"><p>An Array of <see cref="Ext.data.Model">Ext.data.Model</see>s to be rendered into the DataView.</p> /// </param> /// <param name="startIndex"><p>the index number of the Record being prepared for rendering.</p> /// </param> /// <returns> /// <span><see cref="Object">Object</see>[]</span><div><p>An Array of data objects to be processed by a repeating XTemplate. May also /// contain <i>named</i> properties.</p> /// </div> /// </returns> public object[] collectData(JsArray<Ext.data.Model> records, JsNumber startIndex){return null;} /// <summary> /// Deselects a record instance by record instance or index. /// </summary> /// <param name="records"><p>An array of records or an index</p> /// </param> /// <param name="suppressEvent"><p>Set to false to not fire a deselect event</p> /// </param> public void deselect(object records, object suppressEvent=null){} /// <summary> /// Perform the first refresh of the View from a newly bound store. /// This is called when this View has been sized for the first time. /// </summary> /// <param name="store"> /// </param> private void doFirstRefresh(object store){} /// <summary> /// Returns the template node the passed child belongs to, or null if it doesn't belong to one. /// </summary> /// <param name="node"> /// </param> /// <returns> /// <span>HTMLElement</span><div><p>The template node</p> /// </div> /// </returns> public JsObject findItemByChild(object node){return null;} /// <summary> /// Returns the template node by the Ext.EventObject or null if it is not found. /// </summary> /// <param name="e"> /// </param> public void findTargetByEvent(EventObject e){} /// <summary> /// Gets a template node. /// </summary> /// <param name="nodeInfo"><p>An HTMLElement template node, index of a template node, /// the id of a template node or the record associated with the node.</p> /// </param> /// <returns> /// <span>HTMLElement</span><div><p>The node or null if it wasn't found</p> /// </div> /// </returns> public JsObject getNode(object nodeInfo){return null;} /// <summary> /// Parameters<li><span>record</span> : <see cref="Object">Object</see><div> /// </div></li> /// </summary> /// <param name="record"> /// </param> private void getNodeByRecord(object record){} /// <summary> /// Gets a range nodes. /// </summary> /// <param name="start"><p>The index of the first node in the range</p> /// </param> /// <param name="end"><p>The index of the last node in the range</p> /// </param> /// <returns> /// <span>HTMLElement[]</span><div><p>An array of nodes</p> /// </div> /// </returns> public JsObject[] getNodes(object start=null, object end=null){return null;} /// <summary> /// Gets a record from a node /// </summary> /// <param name="node"><p>The node to evaluate</p> /// </param> /// <returns> /// <span><see cref="Ext.data.Model">Ext.data.Model</see></span><div><p>record The <see cref="Ext.data.Model">Ext.data.Model</see> object</p> /// </div> /// </returns> public Ext.data.Model getRecord(object node){return null;} /// <summary> /// Gets an array of the records from an array of nodes /// </summary> /// <param name="nodes"><p>The nodes to evaluate</p> /// </param> /// <returns> /// <span><see cref="Ext.data.Model">Ext.data.Model</see>[]</span><div><p>records The <see cref="Ext.data.Model">Ext.data.Model</see> objects</p> /// </div> /// </returns> public Ext.data.Model[] getRecords(object nodes){return null;} /// <summary> /// Gets the currently selected nodes. /// </summary> /// <returns> /// <span>HTMLElement[]</span><div><p>An array of HTMLElements</p> /// </div> /// </returns> public JsObject[] getSelectedNodes(){return null;} /// <summary> /// Gets an array of the selected records /// <p>This method has been <strong>deprecated</strong> since 4.0</p> /// <p>Use <see cref="Ext.selection.Model.getSelection">Ext.selection.Model.getSelection</see> instead.</p> /// </summary> /// <returns> /// <span><see cref="Ext.data.Model">Ext.data.Model</see>[]</span><div><p>An array of <see cref="Ext.data.Model">Ext.data.Model</see> objects</p> /// </div> /// </returns> public Ext.data.Model[] getSelectedRecords(){return null;} /// <summary> /// Gets the number of selected nodes. /// <p>This method has been <strong>deprecated</strong> since 4.0</p> /// <p>Use <see cref="Ext.selection.Model.getCount">Ext.selection.Model.getCount</see> instead.</p> /// </summary> /// <returns> /// <span><see cref="Number">Number</see></span><div><p>The node count</p> /// </div> /// </returns> public JsNumber getSelectionCount(){return null;} /// <summary> /// Gets the selection model for this view. /// </summary> /// <returns> /// <span><see cref="Ext.selection.Model">Ext.selection.Model</see></span><div><p>The selection model</p> /// </div> /// </returns> public Ext.selection.Model getSelectionModel(){return null;} /// <summary> /// Returns the store associated with this DataView. /// </summary> /// <returns> /// <span><see cref="Ext.data.Store">Ext.data.Store</see></span><div><p>The store</p> /// </div> /// </returns> public virtual Ext.data.Store getStore(){return null;} /// <summary> /// Gets the listeners to bind to a new store. /// </summary> /// <returns> /// <span><see cref="Object">Object</see></span><div><p>The listeners to be bound to the store in object literal form. The scope /// may be omitted, it is assumed to be the current instance.</p> /// </div> /// </returns> public virtual object getStoreListeners(){return null;} /// <summary> /// Finds the index of the passed node. /// </summary> /// <param name="nodeInfo"><p>An HTMLElement template node, index of a template node, the id of a template node /// or a record associated with a node.</p> /// </param> /// <returns> /// <span><see cref="Number">Number</see></span><div><p>The index of the node or -1</p> /// </div> /// </returns> public JsNumber indexOf(object nodeInfo){return null;} /// <summary> /// Returns true if the passed node is selected, else false. /// </summary> /// <param name="node"><p>The node, node index or record to check</p> /// </param> /// <returns> /// <span><see cref="bool">Boolean</see></span><div><p>True if selected, else false</p> /// </div> /// </returns> public bool isSelected(object node){return false;} /// <summary> /// Template method, it is called when a new store is bound /// to the current instance. /// </summary> /// <param name="store"><p>The store being bound</p> /// </param> /// <param name="initial"><p>True if this store is being bound as initialization of the instance.</p> /// </param> public virtual void onBindStore(Ext.data.AbstractStore store, bool initial){} /// <summary> /// Calls this.refresh if this.blockRefresh is not true /// </summary> private void onDataRefresh(){} /// <summary> /// Template method, it is called when an existing store is unbound /// from the current instance. /// </summary> /// <param name="store"><p>The store being unbound</p> /// </param> /// <param name="initial"><p>True if this store is being bound as initialization of the instance.</p> /// </param> public virtual void onUnbindStore(Ext.data.AbstractStore store, bool initial){} /// <summary> /// Function which can be overridden to provide custom formatting for each Record that is used by this /// DataView's template to render each node. /// </summary> /// <param name="data"><p>The raw data object that was used to create the Record.</p> /// </param> /// <param name="recordIndex"><p>the index number of the Record being prepared for rendering.</p> /// </param> /// <param name="record"><p>The Record being prepared for rendering.</p> /// </param> /// <returns> /// <span><see cref="Array">Array</see>/<see cref="Object">Object</see></span><div><p>The formatted data in a format expected by the internal <see cref="Ext.view.AbstractViewConfig.tpl">template</see>'s overwrite() method. /// (either an array if your params are numeric (i.e. {0}) or an object (i.e. {foo: 'bar'}))</p> /// </div> /// </returns> public object prepareData(object data, JsNumber recordIndex, Ext.data.Model record){return null;} /// <summary> /// Refreshes the view by reloading the data from the store and re-rendering the template. /// </summary> public void refresh(){} /// <summary> /// Refreshes an individual node's data from the store. /// </summary> /// <param name="index"><p>The item's data index in the store</p> /// </param> public void refreshNode(JsNumber index){} /// <summary> /// Called by the framework when the view is refreshed, or when rows are added or deleted. /// These operations may cause the view's dimensions to change, and if the owning container /// is shrinkwrapping this view, then the layout must be updated to accommodate these new dimensions. /// </summary> private void refreshSize(){} /// <summary> /// Restores the scrollState. /// Must be used in conjunction with saveScrollState /// </summary> private void restoreScrollState(){} /// <summary> /// Saves the scrollState in a private variable. Must be used in conjunction with restoreScrollState. /// </summary> private void saveScrollState(){} /// <summary> /// Selects a record instance by record instance or index. /// <p>This method has been <strong>deprecated</strong> since 4.0</p> /// <p>Use <see cref="Ext.selection.Model.select">Ext.selection.Model.select</see> instead.</p> /// </summary> /// <param name="records"><p>An array of records or an index</p> /// </param> /// <param name="keepExisting"> /// </param> /// <param name="suppressEvent"><p>Set to false to not fire a select event</p> /// </param> public void select(object records, bool keepExisting, object suppressEvent=null){} /// <summary> /// Unbinds listeners from this component to the store. By default it will remove /// anything bound by the bindStoreListeners method, however it can be overridden /// in a subclass to provide any more complicated handling. /// </summary> /// <param name="store"><p>The store to unbind from</p> /// </param> public virtual void unbindStoreListeners(Ext.data.AbstractStore store){} /// <summary> /// Binds a store to this instance. /// </summary> public virtual void bindStore(object store=null, object initial=null){} public AbstractView(AbstractViewConfig config){} public AbstractView(){} public AbstractView(params object[] args){} } #endregion #region AbstractViewConfig /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class AbstractViewConfig : Ext.ComponentConfig { /// <summary> /// Set this to true to ignore refresh events on the bound store. This is useful if /// you wish to provide custom transition animations via a plugin /// Defaults to: <c>false</c> /// </summary> public bool blockRefresh; /// <summary> /// True to defer emptyText being applied until the store's first load. /// Defaults to: <c>true</c> /// </summary> public bool deferEmptyText; /// <summary> /// Defaults to true to defer the initial refresh of the view. /// This allows the View to execute its render and initial layout more quickly because the process will not be encumbered /// by the expensive update of the view structure. /// <b>Important: </b>Be aware that this will mean that the View's item elements will not be available immediately upon render, so /// <i>selection</i> may not take place at render time. To access a View's item elements as soon as possible, use the <see cref="Ext.view.AbstractViewEvents.viewready">viewready</see> event. /// Or set <c>deferInitialrefresh</c> to false, but this will be at the cost of slower rendering. /// Defaults to: <c>true</c> /// </summary> public bool deferInitialRefresh; /// <summary> /// True to disable selection within the DataView. This configuration will lock the selection model /// that the DataView uses. /// </summary> public bool disableSelection; /// <summary> /// The text to display in the view when there is no data to display. /// Note that when using local data the emptyText will not be displayed unless you set /// the deferEmptyText option to false. /// Defaults to: <c>&quot;&quot;</c> /// </summary> public JsString emptyText; /// <summary> /// Specifies the class to be assigned to each element in the view when used in conjunction with the /// itemTpl configuration. /// Defaults to: <c>&quot;x-dataview-item&quot;</c> /// </summary> public JsString itemCls; /// <summary> /// This is a required setting. A simple CSS selector (e.g. div.some-class or /// span:first-child) that will be used to determine what nodes this DataView will be /// working with. The itemSelector is used to map DOM nodes to records. As such, there should /// only be one root level element that matches the selector for each record. /// </summary> public JsString itemSelector; /// <summary> /// The inner portion of the item template to be rendered. Follows an XTemplate /// structure and will be placed inside of a tpl. /// </summary> public object itemTpl; /// <summary> /// False to disable a load mask from displaying while the view is loading. This can also be a /// Ext.LoadMask configuration object. /// Defaults to: <c>true</c> /// </summary> public object loadMask; /// <summary> /// The CSS class to apply to the loading message element. Defaults to Ext.LoadMask.prototype.msgCls "x-mask-loading". /// </summary> public JsString loadingCls; /// <summary> /// If specified, gives an explicit height for the data view when it is showing the loadingText, /// if that is specified. This is useful to prevent the view's height from collapsing to zero when the /// loading mask is applied and there are no other contents in the data view. /// </summary> public JsNumber loadingHeight; /// <summary> /// A string to display during data load operations. If specified, this text will be /// displayed in a loading div and the view's contents will be cleared while loading, otherwise the view's /// contents will continue to display normally until the new data is loaded and the contents are replaced. /// Defaults to: <c>&quot;Loading...&quot;</c> /// </summary> public JsString loadingText; /// <summary> /// Whether or not to use the loading message. /// Defaults to: <c>true</c> /// </summary> public bool loadingUseMsg; /// <summary> /// True to allow selection of more than one item at a time, false to allow selection of only a single item /// at a time or no selection at all, depending on the value of singleSelect. /// Defaults to: <c>false</c> /// <p>This cfg has been <strong>deprecated</strong> since 4.1.1</p> /// <p>Use <see cref="Ext.selection.ModelConfig.mode">Ext.selection.Model.mode</see> 'MULTI' instead.</p> /// </summary> public bool multiSelect; /// <summary> /// A CSS class to apply to each item in the view on mouseover. /// Setting this will automatically set trackOver to true. /// </summary> public JsString overItemCls; /// <summary> /// =false /// True to preserve scroll position across refresh operations. /// Defaults to: <c>false</c> /// </summary> public bool preserveScrollOnRefresh; /// <summary> /// A CSS class to apply to each selected item in the view. /// Defaults to: <c>&quot;x-item-selected&quot;</c> /// </summary> public JsString selectedItemCls; /// <summary> /// True to enable multiselection by clicking on multiple items without requiring the user to hold Shift or Ctrl, /// false to force the user to hold Ctrl or Shift to select more than on item. /// Defaults to: <c>false</c> /// <p>This cfg has been <strong>deprecated</strong> since 4.1.1</p> /// <p>Use <see cref="Ext.selection.ModelConfig.mode">Ext.selection.Model.mode</see> 'SIMPLE' instead.</p> /// </summary> public bool simpleSelect; /// <summary> /// Allows selection of exactly one item at a time. As this is the default selection mode anyway, this config /// is completely ignored. /// <p>This cfg has been <strong>removed</strong> since 4.1.1</p> /// <p>Use <see cref="Ext.selection.ModelConfig.mode">Ext.selection.Model.mode</see> 'SINGLE' instead.</p> /// </summary> public bool singleSelect; /// <summary> /// The Ext.data.Store to bind this DataView to. /// </summary> public Ext.data.Store store; /// <summary> /// When true the overItemCls will be applied to rows when hovered over. /// This in return will also cause highlightitem and /// unhighlightitem events to be fired. /// Enabled automatically when the <see cref="Ext.view.AbstractViewConfig.overItemCls">overItemCls</see> config is set. /// Defaults to: <c>false</c> /// </summary> public bool trackOver; public AbstractViewConfig(params object[] args){} } #endregion #region AbstractViewEvents /// <inheritdocs /> [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)] public partial class AbstractViewEvents : Ext.ComponentEvents { /// <summary> /// Fires before the view is refreshed /// </summary> /// <param name="this"><p>The DataView object</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void beforerefresh(Ext.view.View @this, object eOpts){} /// <summary> /// Fires when the nodes associated with an recordset have been added to the underlying store /// </summary> /// <param name="records"><p>The model instance</p> /// </param> /// <param name="index"><p>The index at which the set of record/nodes starts</p> /// </param> /// <param name="node"><p>The node that has just been updated</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void itemadd(JsArray<Ext.data.Model> records, object index, object node, object eOpts){} /// <summary> /// Fires when the node associated with an individual record is removed /// </summary> /// <param name="record"><p>The model instance</p> /// </param> /// <param name="index"><p>The index of the record/node</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void itemremove(Ext.data.Model record, object index, object eOpts){} /// <summary> /// Fires when the node associated with an individual record is updated /// </summary> /// <param name="record"><p>The model instance</p> /// </param> /// <param name="index"><p>The index of the record/node</p> /// </param> /// <param name="node"><p>The node that has just been updated</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void itemupdate(Ext.data.Model record, object index, object node, object eOpts){} /// <summary> /// Fires when the view is refreshed /// </summary> /// <param name="this"><p>The DataView object</p> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void refresh(Ext.view.View @this, object eOpts){} /// <summary> /// Fires when the View's item elements representing Store items has been rendered. If the deferInitialRefresh flag /// was set (and it is true by default), this will be after initial render, and no items will be available /// for selection until this event fires. /// </summary> /// <param name="this"> /// </param> /// <param name="eOpts"><p>The options object passed to <see cref="Ext.util.Observable.addListener">Ext.util.Observable.addListener</see>.</p> /// </param> public void viewready(Ext.view.View @this, object eOpts){} public AbstractViewEvents(params object[] args){} } #endregion }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SwAddin.cs" company=""> // Airgas 2016 // </copyright> // <summary> // Saves a PDF copy of a drawing. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Windows.Forms.VisualStyles; namespace SavePDF { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.Win32; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using SolidWorks.Interop.swpublished; using SolidWorksTools; using SolidWorksTools.File; using Attribute = System.Attribute; using Environment = System.Environment; /// <summary> /// Saves a PDF copy of a drawing. /// </summary> /// [Guid("6dee52ef-da6a-4782-a482-2ecbdb284e98"), ComVisible(true)] [Guid("353B343A-427E-4438-97EE-847C6223151A")] [ComVisible(true)] [SwAddin(Description = "Saves a PDF when you save a drawing", Title = "SavePDF", LoadAtStartup = true)] public class SwAddin : ISwAddin { #region Constants /// <summary> /// The main cmd group id. /// </summary> public const int MainCmdGroupId = 1; /// <summary> /// The main item i d 1. /// </summary> public const int MainItemId1 = 0; /// <summary> /// The description value name. /// </summary> private const string DescriptionValueName = "AppendDescription"; /// <summary> /// The location value name. /// </summary> private const string LocationValueName = "PDFLocation"; /// <summary> /// The options key name. /// </summary> private const string OptionsKeyName = "Software\\Airgas Inc\\SavePDF"; /// <summary> /// The revision value name. /// </summary> private const string RevisionValueName = "AppendRevision"; /// <summary> /// The show pdf value name. /// </summary> private const string ShowPdfValueName = "ShowPDF"; /// <summary> /// The show pdf value name. /// </summary> private const string RemovePrevValueName = "RemovePrevious"; /// <summary> /// The save on close value name. /// </summary> private const string SaveOnCloseValueName = "SaveOnClose"; #endregion #region Fields /// <summary> /// The sw event ptr. /// </summary> private SldWorks solidworksEventPtr; /// <summary> /// The addin id. /// </summary> private int addinId; /// <summary> /// The i bmp. /// </summary> private BitmapHandler iBmp; /// <summary> /// The open docs. /// </summary> private Hashtable openDocs = new Hashtable(); /// <summary> /// The ppage. /// </summary> private UserPMPage ppage; #endregion #region Public Properties /// <summary> /// Gets or sets a value indicating whether append description. /// </summary> public bool AppendDescription { get; set; } /// <summary> /// Gets or sets a value indicating whether append revision. /// </summary> public bool AppendRevision { get; set; } // Public Properties /// <summary> /// Gets the cmd mgr. /// </summary> public ICommandManager CmdMgr { get; private set; } /// <summary> /// Gets the open docs. /// </summary> public Hashtable OpenDocs { get { return this.openDocs; } } /// <summary> /// Gets or sets the pdf location. /// </summary> public string PDFLocation { get; set; } /// <summary> /// Gets or sets a value indicating whether show pdf. /// </summary> public bool ShowPDF { get; set; } /// <summary> /// Gets the sw app. /// </summary> public ISldWorks SwApp { get; private set; } public bool SaveOnClose { get; set; } public bool RemovePrevious { get; set; } #endregion #region Public Methods and Operators /// <summary> /// The register function. /// </summary> /// <param name="t"> /// The t. /// </param> [ComRegisterFunction] public static void RegisterFunction(Type t) { Type type = typeof(SwAddin); SwAddinAttribute solidworksAttribute = type.GetCustomAttributes(false).OfType<SwAddinAttribute>().Select(attr => attr).FirstOrDefault(); try { RegistryKey hklm = Registry.LocalMachine; RegistryKey hkcu = Registry.CurrentUser; string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID + "}"; RegistryKey addinkey = hklm.CreateSubKey(keyname); addinkey.SetValue(null, 0); addinkey.SetValue("Description", solidworksAttribute.Description); addinkey.SetValue("Title", solidworksAttribute.Title); keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID + "}"; addinkey = hkcu.CreateSubKey(keyname); addinkey.SetValue(null, Convert.ToInt32(solidworksAttribute.LoadAtStartup), RegistryValueKind.DWord); } catch (NullReferenceException nl) { Console.WriteLine("There was a problem registering this dll: SWattr is null. \n\"" + nl.Message + "\""); MessageBox.Show("There was a problem registering this dll: SWattr is null.\n\"" + nl.Message + "\""); } catch (Exception e) { Console.WriteLine(e.Message); MessageBox.Show("There was a problem registering the function: \n\"" + e.Message + "\""); } } /// <summary> /// The unregister function. /// </summary> /// <param name="t"> /// The t. /// </param> [ComUnregisterFunction] public static void UnregisterFunction(Type t) { try { RegistryKey hklm = Registry.LocalMachine; RegistryKey hkcu = Registry.CurrentUser; string keyname = "SOFTWARE\\SolidWorks\\Addins\\{" + t.GUID + "}"; hklm.DeleteSubKey(keyname); keyname = "Software\\SolidWorks\\AddInsStartup\\{" + t.GUID + "}"; hkcu.DeleteSubKey(keyname); } catch (NullReferenceException nl) { Console.WriteLine("There was a problem unregistering this dll: " + nl.Message); MessageBox.Show("There was a problem unregistering this dll: \n\"" + nl.Message + "\""); } catch (Exception e) { Console.WriteLine("There was a problem unregistering this dll: " + e.Message); MessageBox.Show("There was a problem unregistering this dll: \n\"" + e.Message + "\""); } } /// <summary> /// The add command mgr. /// </summary> public void AddCommandMgr() { if (this.iBmp == null) { this.iBmp = new BitmapHandler(); } const string Title = "Save PDF"; const string ToolTip = "Save PDF"; int[] docTypes = { (int)swDocumentTypes_e.swDocASSEMBLY, (int)swDocumentTypes_e.swDocDRAWING, (int)swDocumentTypes_e.swDocPART }; Assembly thisAssembly = Assembly.GetAssembly(this.GetType()); int cmdGroupErr = 0; bool ignorePrevious = false; object registryIDs; // get the ID information stored in the registry bool getDataResult = this.CmdMgr.GetGroupDataFromRegistry(MainCmdGroupId, out registryIDs); int[] knownIDs = { MainItemId1 }; if (getDataResult) { if (!this.CompareIDs((int[])registryIDs, knownIDs)) { // if the IDs don't match, reset the commandGroup ignorePrevious = true; } } ICommandGroup cmdGroup = this.CmdMgr.CreateCommandGroup2( MainCmdGroupId, Title, ToolTip, "", -1, ignorePrevious, ref cmdGroupErr); cmdGroup.LargeIconList = this.iBmp.CreateFileFromResourceBitmap("SavePDF.ToolbarLarge.bmp", thisAssembly); cmdGroup.SmallIconList = this.iBmp.CreateFileFromResourceBitmap("SavePDF.ToolbarSmall.bmp", thisAssembly); const int menuToolbarOption = (int)(swCommandItemType_e.swMenuItem | swCommandItemType_e.swToolbarItem); int cmdIndex0 = cmdGroup.AddCommandItem2( "Save PDF", -1, "Save PDF Options", "Save PDF Options", 0, "ShowPMP", "EnablePMP", MainItemId1, menuToolbarOption); cmdGroup.HasToolbar = true; cmdGroup.HasMenu = true; cmdGroup.Activate(); foreach (int type in docTypes) { CommandTab cmdTab = this.CmdMgr.GetCommandTab(type, Title); if (cmdTab != null & !getDataResult | ignorePrevious) { // if tab exists, but we have ignored the registry info (or changed command group ID), re-create the tab. Otherwise the ids won't matchup and the tab will be blank bool res = this.CmdMgr.RemoveCommandTab(cmdTab); cmdTab = null; } // if cmdTab is null, must be first load (possibly after reset), add the commands to the tabs if (cmdTab == null) { cmdTab = this.CmdMgr.AddCommandTab(type, Title); CommandTabBox cmdBox = cmdTab.AddCommandTabBox(); var cmdIDs = new int[1]; var textType = new int[1]; cmdIDs[0] = cmdGroup.CommandID[cmdIndex0]; textType[0] = (int)swCommandTabButtonTextDisplay_e.swCommandTabButton_TextHorizontal; cmdBox.AddCommands(cmdIDs, textType); } } thisAssembly = null; } /// <summary> /// The add pmp. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool AddPMP() { this.ppage = new UserPMPage(this); return true; } /// <summary> /// The attach event handlers. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool AttachEventHandlers() { this.AttachSwEvents(); // Listen for events on all currently open docs this.AttachEventsToAllDocuments(); return true; } /// <summary> /// The attach events to all documents. /// </summary> public void AttachEventsToAllDocuments() { var modDoc = (ModelDoc2)this.SwApp.GetFirstDocument(); while (modDoc != null) { if (!this.openDocs.Contains(modDoc)) { this.AttachModelDocEventHandler(modDoc); } else if (this.openDocs.Contains(modDoc)) { bool connected = false; var docHandler = (DocumentEventHandler)this.openDocs[modDoc]; if (docHandler != null) { connected = docHandler.ConnectModelViews(); } } modDoc = (ModelDoc2)modDoc.GetNext(); } } /// <summary> /// The attach model doc event handler. /// </summary> /// <param name="modDoc"> /// The mod doc. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool AttachModelDocEventHandler(ModelDoc2 modDoc) { if (modDoc == null) { return false; } DocumentEventHandler docHandler = null; if (!this.openDocs.Contains(modDoc)) { switch (modDoc.GetType()) { case (int)swDocumentTypes_e.swDocPART: { docHandler = new PartEventHandler(modDoc, this); break; } case (int)swDocumentTypes_e.swDocASSEMBLY: { docHandler = new AssemblyEventHandler(modDoc, this); break; } case (int)swDocumentTypes_e.swDocDRAWING: { docHandler = new DrawingEventHandler(modDoc, this); break; } default: { return false; // Unsupported document type } } docHandler.AttachEventHandlers(); this.openDocs.Add(modDoc, docHandler); } return true; } /// <summary> /// The compare i ds. /// </summary> /// <param name="storedIDs"> /// The stored i ds. /// </param> /// <param name="addinIDs"> /// The addin i ds. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool CompareIDs(int[] storedIDs, int[] addinIDs) { var storedList = new List<int>(storedIDs); var addinList = new List<int>(addinIDs); addinList.Sort(); storedList.Sort(); if (addinList.Count != storedList.Count) { return false; } for (int i = 0; i < addinList.Count; i++) { if (addinList[i] != storedList[i]) { return false; } } return true; } /// <summary> /// The connect to sw. /// </summary> /// <param name="ThisSW"> /// The this sw. /// </param> /// <param name="cookie"> /// The cookie. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool ConnectToSW(object ThisSW, int cookie) { this.SwApp = (ISldWorks)ThisSW; this.addinId = cookie; // Setup callbacks this.SwApp.SetAddinCallbackInfo(0, this, this.addinId); this.CmdMgr = this.SwApp.GetCommandManager(cookie); this.AddCommandMgr(); #region Setup the Event Handlers this.solidworksEventPtr = (SldWorks)this.SwApp; this.openDocs = new Hashtable(); this.AttachEventHandlers(); #endregion this.ReadOptions(); #region Setup Property Manager this.AddPMP(); #endregion return true; } /// <summary> /// The detach event handlers. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool DetachEventHandlers() { this.DetachSwEvents(); // Close events on all currently open docs DocumentEventHandler docHandler; int numKeys = this.openDocs.Count; var keys = new object[numKeys]; // Remove all document event handlers this.openDocs.Keys.CopyTo(keys, 0); foreach (ModelDoc2 key in keys) { docHandler = (DocumentEventHandler)this.openDocs[key]; docHandler.DetachEventHandlers(); // This also removes the pair from the hash docHandler = null; } return true; } /// <summary> /// The detach model event handler. /// </summary> /// <param name="modDoc"> /// The mod doc. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool DetachModelEventHandler(ModelDoc2 modDoc) { DocumentEventHandler docHandler; docHandler = (DocumentEventHandler)this.openDocs[modDoc]; this.openDocs.Remove(modDoc); modDoc = null; docHandler = null; return true; } /// <summary> /// The disconnect from sw. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool DisconnectFromSW() { this.RemoveCommandMgr(); this.RemovePMP(); this.DetachEventHandlers(); Marshal.ReleaseComObject(this.CmdMgr); this.CmdMgr = null; Marshal.ReleaseComObject(this.SwApp); this.SwApp = null; // The addin _must_ call GC.Collect() here in order to retrieve all managed code pointers GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); return true; } /// <summary> /// The enable pmp. /// </summary> /// <returns> /// The <see cref="int"/>. /// </returns> public int EnablePMP() { if (this.SwApp.ActiveDoc != null) { return 1; } return 0; } // Events /// <summary> /// The on doc change. /// </summary> /// <returns> /// The <see cref="int"/>. /// </returns> public int OnDocChange() { return 0; } /// <summary> /// The on doc load. /// </summary> /// <param name="docTitle"> /// The doc title. /// </param> /// <param name="docPath"> /// The doc path. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> public int OnDocLoad(string docTitle, string docPath) { return 0; } /// <summary> /// The on file new. /// </summary> /// <param name="newDoc"> /// The new doc. /// </param> /// <param name="docType"> /// The doc type. /// </param> /// <param name="templateName"> /// The template name. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> public int OnFileNew(object newDoc, int docType, string templateName) { this.AttachEventsToAllDocuments(); return 0; } /// <summary> /// The on model change. /// </summary> /// <returns> /// The <see cref="int"/>. /// </returns> public int OnModelChange() { return 0; } /// <summary> /// The read options. /// </summary> public void ReadOptions() { try { RegistryKey hkcu = Registry.CurrentUser; RegistryKey optionsKey = hkcu.OpenSubKey(OptionsKeyName, true) ?? hkcu.CreateSubKey(OptionsKeyName); this.PDFLocation = (string) optionsKey.GetValue( LocationValueName, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); this.AppendRevision = Convert.ToBoolean(optionsKey.GetValue(RevisionValueName, true)); this.AppendDescription = Convert.ToBoolean(optionsKey.GetValue(DescriptionValueName, true)); this.ShowPDF = Convert.ToBoolean(optionsKey.GetValue(ShowPdfValueName, false)); this.RemovePrevious = Convert.ToBoolean(optionsKey.GetValue(RemovePrevValueName, false)); //this.SaveOnClose = Convert.ToBoolean(optionsKey.GetValue(SaveOnCloseValueName, false)); this.SaveOnClose = true; } catch (Exception nl) { MessageBox.Show("There was a problem reading the options: \n\"" + nl.Message + "\""); } } /// <summary> /// The remove command mgr. /// </summary> public void RemoveCommandMgr() { this.iBmp.Dispose(); this.CmdMgr.RemoveCommandGroup(MainCmdGroupId); } /// <summary> /// The remove pmp. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool RemovePMP() { this.ppage = null; return true; } /// <summary> /// The show pmp. /// </summary> public void ShowPMP() { if (this.ppage != null) { this.ppage.Show(); } } /// <summary> /// The write options. /// </summary> public void WriteOptions() { try { RegistryKey hkcu = Registry.CurrentUser; RegistryKey optionsKey = hkcu.OpenSubKey(OptionsKeyName, true) ?? hkcu.CreateSubKey(OptionsKeyName); optionsKey.SetValue(LocationValueName, this.PDFLocation, RegistryValueKind.String); optionsKey.SetValue(RevisionValueName, this.AppendRevision, RegistryValueKind.DWord); optionsKey.SetValue(DescriptionValueName, this.AppendDescription, RegistryValueKind.DWord); optionsKey.SetValue(ShowPdfValueName, this.ShowPDF, RegistryValueKind.DWord); optionsKey.SetValue(SaveOnCloseValueName, this.SaveOnClose, RegistryValueKind.DWord); optionsKey.SetValue(RemovePrevValueName, this.RemovePrevious, RegistryValueKind.DWord); } catch (Exception nl) { MessageBox.Show("There was a problem writing the options: \n\"" + nl.Message + "\""); } } #endregion #region Methods /// <summary> /// The attach sw events. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> private bool AttachSwEvents() { try { this.solidworksEventPtr.ActiveDocChangeNotify += this.OnDocChange; this.solidworksEventPtr.DocumentLoadNotify2 += this.OnDocLoad; this.solidworksEventPtr.FileNewNotify2 += this.OnFileNew; this.solidworksEventPtr.ActiveModelDocChangeNotify += this.OnModelChange; this.solidworksEventPtr.FileOpenPostNotify += this.FileOpenPostNotify; return true; } catch (Exception e) { Console.WriteLine(e.Message); return false; } } /// <summary> /// The detach sw events. /// </summary> /// <returns> /// The <see cref="bool"/>. /// </returns> private bool DetachSwEvents() { try { this.solidworksEventPtr.ActiveDocChangeNotify -= this.OnDocChange; this.solidworksEventPtr.DocumentLoadNotify2 -= this.OnDocLoad; this.solidworksEventPtr.FileNewNotify2 -= this.OnFileNew; this.solidworksEventPtr.ActiveModelDocChangeNotify -= this.OnModelChange; this.solidworksEventPtr.FileOpenPostNotify -= this.FileOpenPostNotify; return true; } catch (Exception e) { Console.WriteLine(e.Message); return false; } } /// <summary> /// The file open post notify. /// </summary> /// <param name="FileName"> /// The file name. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> private int FileOpenPostNotify(string FileName) { this.AttachEventsToAllDocuments(); return 0; } #endregion } }
// Keep this file CodeMaid organised and cleaned using ClosedXML.Excel.CalcEngine.Exceptions; using System; using System.Collections.Generic; using System.Linq; namespace ClosedXML.Excel.CalcEngine.Functions { internal static class Lookup { public static void Register(CalcEngine ce) { //ce.RegisterFunction("ADDRESS", , Address); // Returns a reference as text to a single cell in a worksheet //ce.RegisterFunction("AREAS", , Areas); // Returns the number of areas in a reference //ce.RegisterFunction("CHOOSE", , Choose); // Chooses a value from a list of values //ce.RegisterFunction("COLUMN", , Column); // Returns the column number of a reference //ce.RegisterFunction("COLUMNS", , Columns); // Returns the number of columns in a reference //ce.RegisterFunction("FORMULATEXT", , Formulatext); // Returns the formula at the given reference as text //ce.RegisterFunction("GETPIVOTDATA", , Getpivotdata); // Returns data stored in a PivotTable report ce.RegisterFunction("HLOOKUP", 3, 4, Hlookup); // Looks in the top row of an array and returns the value of the indicated cell ce.RegisterFunction("HYPERLINK", 1, 2, Hyperlink); // Creates a shortcut or jump that opens a document stored on a network server, an intranet, or the Internet ce.RegisterFunction("INDEX", 2, 4, Index); // Uses an index to choose a value from a reference or array //ce.RegisterFunction("INDIRECT", , Indirect); // Returns a reference indicated by a text value //ce.RegisterFunction("LOOKUP", , Lookup); // Looks up values in a vector or array ce.RegisterFunction("MATCH", 2, 3, Match); // Looks up values in a reference or array //ce.RegisterFunction("OFFSET", , Offset); // Returns a reference offset from a given reference //ce.RegisterFunction("ROW", , Row); // Returns the row number of a reference //ce.RegisterFunction("ROWS", , Rows); // Returns the number of rows in a reference //ce.RegisterFunction("RTD", , Rtd); // Retrieves real-time data from a program that supports COM automation //ce.RegisterFunction("TRANSPOSE", , Transpose); // Returns the transpose of an array ce.RegisterFunction("VLOOKUP", 3, 4, Vlookup); // Looks in the first column of an array and moves across the row to return the value of a cell } private static IXLRange ExtractRange(Expression expression) { if (!(expression is XObjectExpression objectExpression)) throw new NoValueAvailableException("Parameter has to be a valid range"); if (!(objectExpression.Value is CellRangeReference cellRangeReference)) throw new NoValueAvailableException("lookup_array has to be a range"); var range = cellRangeReference.Range; return range; } private static object Hlookup(List<Expression> p) { var lookup_value = p[0]; var range = ExtractRange(p[1]); var row_index_num = (int)p[2]; var range_lookup = p.Count < 4 || p[3] is EmptyValueExpression || (bool)(p[3]); if (row_index_num < 1) throw new CellReferenceException("Row index has to be positive"); if (row_index_num > range.RowCount()) throw new CellReferenceException("Row index has to be positive"); IXLRangeColumn matching_column; matching_column = range.FindColumn(c => !c.Cell(1).IsEmpty() && new Expression(c.Cell(1).Value).CompareTo(lookup_value) == 0); if (range_lookup && matching_column == null) { var first_column = range.FirstColumn().ColumnNumber(); var number_of_columns_in_range = range.ColumnsUsed().Count(); matching_column = range.FindColumn(c => { var column_index_in_range = c.ColumnNumber() - first_column + 1; if (column_index_in_range < number_of_columns_in_range && !c.Cell(1).IsEmpty() && new Expression(c.Cell(1).Value).CompareTo(lookup_value) <= 0 && !c.ColumnRight().Cell(1).IsEmpty() && new Expression(c.ColumnRight().Cell(1).Value).CompareTo(lookup_value) > 0) return true; else if (column_index_in_range == number_of_columns_in_range && !c.Cell(1).IsEmpty() && new Expression(c.Cell(1).Value).CompareTo(lookup_value) <= 0) return true; else return false; }); } if (matching_column == null) throw new NoValueAvailableException("No matches found."); return matching_column .Cell(row_index_num) .Value; } private static object Hyperlink(List<Expression> p) { String address = p[0]; String toolTip = p.Count == 2 ? p[1] : String.Empty; return new XLHyperlink(address, toolTip); } private static object Index(List<Expression> p) { // This is one of the few functions that is "overloaded" var range = ExtractRange(p[0]); if (range.ColumnCount() > 1 && range.RowCount() > 1) { var row_num = (int)p[1]; var column_num = (int)p[2]; if (row_num > range.RowCount()) throw new CellReferenceException("Out of bound row number"); if (column_num > range.ColumnCount()) throw new CellReferenceException("Out of bound column number"); return range.Row(row_num).Cell(column_num).Value; } else if (p.Count == 2) { var cellOffset = (int)p[1]; if (cellOffset > range.RowCount() * range.ColumnCount()) throw new CellReferenceException(); return range.Cells().ElementAt(cellOffset - 1).Value; } else { int column_num = 1; int row_num = 1; if (!(p[1] is EmptyValueExpression)) row_num = (int)p[1]; if (!(p[2] is EmptyValueExpression)) column_num = (int)p[2]; var rangeIsRow = range.RowCount() == 1; if (rangeIsRow && row_num > 1) throw new CellReferenceException(); if (!rangeIsRow && column_num > 1) throw new CellReferenceException(); if (row_num > range.RowCount()) throw new CellReferenceException("Out of bound row number"); if (column_num > range.ColumnCount()) throw new CellReferenceException("Out of bound column number"); return range.Row(row_num).Cell(column_num).Value; } } private static object Match(List<Expression> p) { var lookup_value = p[0]; var range = ExtractRange(p[1]); int match_type = 1; if (p.Count > 2) match_type = Math.Sign((int)p[2]); if (range.ColumnCount() != 1 && range.RowCount() != 1) throw new CellValueException("Range has to be 1-dimensional"); Predicate<int> lookupPredicate = null; switch (match_type) { case 0: lookupPredicate = i => i == 0; break; case 1: lookupPredicate = i => i <= 0; break; case -1: lookupPredicate = i => i >= 0; break; default: throw new NoValueAvailableException("Invalid match_type"); } IXLCell foundCell = null; if (match_type == 0) foundCell = range .CellsUsed(XLCellsUsedOptions.Contents, c => lookupPredicate.Invoke(new Expression(c.Value).CompareTo(lookup_value))) .FirstOrDefault(); else { object previousValue = null; foundCell = range .CellsUsed(XLCellsUsedOptions.Contents) .TakeWhile(c => { var currentCellExpression = new Expression(c.Value); if (previousValue != null) { // When match_type != 0, we have to assume that the order of the items being search is ascending or descending var previousValueExpression = new Expression(previousValue); if (!lookupPredicate.Invoke(previousValueExpression.CompareTo(currentCellExpression))) return false; } previousValue = c.Value; return lookupPredicate.Invoke(currentCellExpression.CompareTo(lookup_value)); }) .LastOrDefault(); } if (foundCell == null) throw new NoValueAvailableException(); var firstCell = range.FirstCell(); return (foundCell.Address.ColumnNumber - firstCell.Address.ColumnNumber + 1) * (foundCell.Address.RowNumber - firstCell.Address.RowNumber + 1); } private static object Vlookup(List<Expression> p) { var lookup_value = p[0]; var range = ExtractRange(p[1]); var col_index_num = (int)p[2]; var range_lookup = p.Count < 4 || p[3] is EmptyValueExpression || (bool)(p[3]); if (col_index_num < 1) throw new CellReferenceException("Column index has to be positive"); if (col_index_num > range.ColumnCount()) throw new CellReferenceException("Colum index must be smaller or equal to the number of columns in the table array"); IXLRangeRow matching_row; try { matching_row = range.FindRow(r => !r.Cell(1).IsEmpty() && new Expression(r.Cell(1).Value).CompareTo(lookup_value) == 0); } catch (Exception ex) { throw new NoValueAvailableException("No matches found", ex); } if (range_lookup && matching_row == null) { var first_row = range.FirstRow().RowNumber(); var number_of_rows_in_range = range.RowsUsed().Count(); matching_row = range.FindRow(r => { var row_index_in_range = r.RowNumber() - first_row + 1; if (row_index_in_range < number_of_rows_in_range && !r.Cell(1).IsEmpty() && new Expression(r.Cell(1).Value).CompareTo(lookup_value) <= 0 && !r.RowBelow().Cell(1).IsEmpty() && new Expression(r.RowBelow().Cell(1).Value).CompareTo(lookup_value) > 0) return true; else if (row_index_in_range == number_of_rows_in_range && !r.Cell(1).IsEmpty() && new Expression(r.Cell(1).Value).CompareTo(lookup_value) <= 0) return true; else return false; }); } if (matching_row == null) throw new NoValueAvailableException("No matches found."); return matching_row .Cell(col_index_num) .Value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Runtime.CompilerServices; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace System.Runtime.InteropServices { [Flags] public enum McgInterfaceFlags : byte { None = 0x00, isIInspectable = 0x01, // this interface derives from IInspectable isDelegate = 0x02, // this entry is for a WinRT delegate type, ItfType is the type of a managed delegate type isInternal = 0x04, useSharedCCW = 0x08, // this entry uses shared ccwVTable + thunk function SharedCCWMask = 0xF8, useSharedCCW_IVector = 0x08, // 4-bit shared ccw index: 16 max, 8 used useSharedCCW_IVectorView = 0x18, useSharedCCW_IIterable = 0x28, useSharedCCW_IIterator = 0x38, useSharedCCW_AsyncOperationCompletedHandler = 0x48, useSharedCCW_IVectorBlittable = 0x58, useSharedCCW_IVectorViewBlittable = 0x68, useSharedCCW_IIteratorBlittable = 0x78, } [Flags] public enum McgClassFlags : int { None = 0, /// <summary> /// This represents the types MarshalingBehavior. /// </summary> MarshalingBehavior_Inhibit = 1, MarshalingBehavior_Free = 2, MarshalingBehavior_Standard = 3, MarshalingBehavior_Mask = 3, /// <summary> /// GCPressureRange /// </summary> GCPressureRange_WinRT_Default = 1 << 2, GCPressureRange_WinRT_Low = 2 << 2, GCPressureRange_WinRT_Medium = 3 << 2, GCPressureRange_WinRT_High = 4 << 2, GCPressureRange_Mask = 7 << 2, /// <summary> /// Either a WinRT value type, or a projected class type /// In either case, it is not a __ComObject and we can't create it using CreateComObject /// </summary> NotComObject = 32, /// <summary> /// This type is sealed /// </summary> IsSealed = 64, /// <summary> /// This type is a WinRT type and we'll return Kind=Metadata in type name marshalling /// </summary> IsWinRT = 128 } /// <summary> /// Per-native-interface information generated by MCG /// </summary> [CLSCompliant(false)] public struct McgInterfaceData // 36 bytes on 32-bit platforms { /// <summary> /// NOTE: Managed debugger depends on field name: "FixupItfType" and field type must be FixupRuntimeTypeHandle /// Update managed debugger whenever field name/field type is changed. /// See CordbObjectValue::WalkPtrAndTypeData in debug\dbi\values.cpp /// </summary> public FixupRuntimeTypeHandle FixupItfType; // 1 pointer // Optional fields(FixupDispatchClassType and FixupDynamicAdapterClassType) public FixupRuntimeTypeHandle FixupDispatchClassType; // 1 pointer, around 80% usage public FixupRuntimeTypeHandle FixupDynamicAdapterClassType; // 1 pointer, around 20% usage public RuntimeTypeHandle ItfType { get { return FixupItfType.RuntimeTypeHandle; } set { FixupItfType = new FixupRuntimeTypeHandle(value); } } public RuntimeTypeHandle DispatchClassType { get { return FixupDispatchClassType.RuntimeTypeHandle; } } public RuntimeTypeHandle DynamicAdapterClassType { get { return FixupDynamicAdapterClassType.RuntimeTypeHandle; } } // Fixed fields public Guid ItfGuid; // 16 bytes /// <summary> /// NOTE: Managed debugger depends on field name: "Flags" and field type must be an enum type /// Update managed debugger whenever field name/field type is changed. /// See CordbObjectValue::WalkPtrAndTypeData in debug\dbi\values.cpp /// </summary> public McgInterfaceFlags Flags; // 1 byte /// <summary> /// Whether this type is a IInspectable type /// </summary> internal bool IsIInspectable { get { return (Flags & McgInterfaceFlags.isIInspectable) != McgInterfaceFlags.None; } } internal bool IsIInspectableOrDelegate { get { return (Flags & (McgInterfaceFlags.isIInspectable | McgInterfaceFlags.isDelegate)) != McgInterfaceFlags.None; } } public short MarshalIndex; // 2 bytes: Index into InterfaceMarshalData array for shared CCW, also used for internal module sequential type index // Optional fields(CcwVtable) // TODO fyuan define larger McgInterfaceData for merging interop code (shared CCW, default eventhandler) public IntPtr CcwVtable; // 1 pointer, around 20-40% usage public IntPtr DelegateInvokeStub; // only used for RCW delegate } [CLSCompliant(false)] public struct McgGenericArgumentMarshalInfo // Marshal information for generic argument T { // sizeOf(T) public uint ElementSize; // Class Type Handle for sealed T winrt class public FixupRuntimeTypeHandle FixupElementClassType; // Interface Type Handle for T interface type public FixupRuntimeTypeHandle FixupElementInterfaceType; // Type Handle for IAsyncOperation<T> public FixupRuntimeTypeHandle FixupAsyncOperationType; // Type Handle for Iterator<T> public FixupRuntimeTypeHandle FixupIteratorType; // Type Handle for VectorView<T> public FixupRuntimeTypeHandle FixupVectorViewType; public RuntimeTypeHandle AsyncOperationType { get { return FixupAsyncOperationType.RuntimeTypeHandle; } } public RuntimeTypeHandle ElementClassType { get { return FixupElementClassType.RuntimeTypeHandle; } } public RuntimeTypeHandle ElementInterfaceType { get { return FixupElementInterfaceType.RuntimeTypeHandle; } } public RuntimeTypeHandle IteratorType { get { return FixupIteratorType.RuntimeTypeHandle; } } public RuntimeTypeHandle VectorViewType { get { return FixupVectorViewType.RuntimeTypeHandle; } } } /// <summary> /// Per-WinRT-class information generated by MCG. This is used for TypeName marshalling and for /// CreateComObject. For the TypeName marshalling case, we have Nullable<T> / KeyValuePair<K,V> value /// classes as the ClassType field and WinRT names like Windows.Foundation.IReference`1<blah> in the name /// field. These entries are filtered out by CreateComObject using the Flags field. /// </summary> [CLSCompliant(false)] public struct McgClassData { public FixupRuntimeTypeHandle FixupClassType; // FixupRuntimeTypeHandle for type in CLR (projected) view public RuntimeTypeHandle ClassType // RuntimeTypeHandle of FixupRuntimeTypeHandle { get { return FixupClassType.RuntimeTypeHandle; } } public McgClassFlags Flags; // Flags (whether it is a ComObject, whether it can be boxed, etc) internal GCPressureRange GCPressureRange { get { switch (Flags & McgClassFlags.GCPressureRange_Mask) { case McgClassFlags.GCPressureRange_WinRT_Default: return GCPressureRange.WinRT_Default; case McgClassFlags.GCPressureRange_WinRT_Low: return GCPressureRange.WinRT_Low; case McgClassFlags.GCPressureRange_WinRT_Medium: return GCPressureRange.WinRT_Medium; case McgClassFlags.GCPressureRange_WinRT_High: return GCPressureRange.WinRT_High; default: return GCPressureRange.None; } } } internal ComMarshalingType MarshalingType { get { switch (Flags & McgClassFlags.MarshalingBehavior_Mask) { case McgClassFlags.MarshalingBehavior_Inhibit: return ComMarshalingType.Inhibit; case McgClassFlags.MarshalingBehavior_Free: return ComMarshalingType.Free; case McgClassFlags.MarshalingBehavior_Standard: return ComMarshalingType.Standard; default: return ComMarshalingType.Unknown; } } } /// <summary> /// The type handle for its base class /// /// There are two ways to access base class: RuntimeTypeHandle or Index /// Ideally we want to use typehandle for everything - but DR throws it away and breaks the inheritance chain /// - therefore we would only use index for "same module" and type handle for "cross module" /// /// Code Pattern: /// if (BaseClassIndex >=0) { // same module } /// else if(!BaseClassType.Equals(default(RuntimeTypeHandle)) { // cross module} /// else { // it doesn't have base} /// </summary> public FixupRuntimeTypeHandle FixupBaseClassType; // FixupRuntimeTypeHandle for Base class type in CLR (projected) view public RuntimeTypeHandle BaseClassType // RuntimeTypeHandle of BaseClass { get { return FixupBaseClassType.RuntimeTypeHandle; } } public short BaseClassIndex; // Index to the base class; /// <summary> /// The type handle for its default Interface /// The comment above for BaseClassType applies for DefaultInterface as well /// </summary> public FixupRuntimeTypeHandle FixupDefaultInterfaceType; // FixupRuntimeTypeHandle for DefaultInterface type in CLR (projected) view public RuntimeTypeHandle DefaultInterfaceType // RuntimeTypeHandle of DefaultInterface { get { return FixupDefaultInterfaceType.RuntimeTypeHandle; } } public short DefaultInterfaceIndex; // Index to the default interface } [CLSCompliant(false)] public struct McgHashcodeVerifyEntry { public FixupRuntimeTypeHandle FixupTypeHandle; public RuntimeTypeHandle TypeHandle { get { return FixupTypeHandle.RuntimeTypeHandle; } } public uint HashCode; } /// <summary> /// Mcg data used for boxing /// Boxing refers to IReference/IReferenceArray boxing, as well as projection support when marshalling /// IInspectable, such as IKeyValuePair, System.Uri, etc. /// So this supports boxing in a broader sense that it supports WinRT type <-> native type projection /// There are 3 cases: /// 1. IReference<T> / IReferenceArray<T>. It is boxed to a managed wrapper and unboxed either from the wrapper or from native IReference/IReferenceArray RCW (through unboxing stub) /// 2. IKeyValuePair<K, V>. Very similiar to #1 except that it does not have propertyType /// 3. All other cases, including System.Uri, NotifyCollectionChangedEventArgs, etc. They go through boxing stub and unboxing stub. /// /// NOTE: Even though this struct doesn't have a name in itself, there is a parallel array /// m_boxingDataNameMap that holds the corresponding class names for each boxing data /// </summary> [CLSCompliant(false)] public struct McgBoxingData { /// <summary> /// The target type that triggers the boxing. Used in search /// </summary> public FixupRuntimeTypeHandle FixupManagedClassType; /// <summary> /// HIDDEN /// This is actually saved in m_boxingDataNameMap /// The runtime class name that triggers the unboxing. Used in search. /// </summary> /// public string Name; /// <summary> /// A managed wrapper for IReference/IReferenceArray/IKeyValuePair boxing /// We create the wrapper directly instead of going through a boxing stub. This saves us some /// disk space (300+ boxing stub in a typical app), but we need to see whether this trade off /// makes sense long term. /// </summary> public FixupRuntimeTypeHandle FixupCLRBoxingWrapperType; public RuntimeTypeHandle ManagedClassType { get { return FixupManagedClassType.RuntimeTypeHandle; } } public RuntimeTypeHandle CLRBoxingWrapperType { get { return FixupCLRBoxingWrapperType.RuntimeTypeHandle; } } /// <summary> /// General boxing stub - boxing an managed object instance into a native object instance (RCW) /// This is used for special cases where managed wrappers aren't suitable, mainly for projected types /// such as System.Uri. /// /// Prototype: /// object Boxing_Stub(object target) /// </summary> public IntPtr BoxingStub; /// <summary> /// General unboxing stub - unbox a native object instance (RCW) into a managed object (interestingly, /// can be boxed in the managed sense) /// /// object UnboxingStub(object target) /// </summary> public IntPtr UnboxingStub; /// <summary> /// Corresponding PropertyType /// Only used when boxing into a managed wrapper - because it is only meaningful in IReference /// & IReferenceArray /// </summary> public short PropertyType; } /// <summary> /// This information is separate from the McgClassData[] /// as its captures the types which are not imported by the MCG. /// </summary> [CLSCompliant(false)] public struct McgTypeNameMarshalingData { public FixupRuntimeTypeHandle FixupClassType; public RuntimeTypeHandle ClassType { get { return FixupClassType.RuntimeTypeHandle; } } } public enum McgStructMarshalFlags { None, /// <summary> /// This struct has invalid layout information, most likely because it is marked LayoutKind.Auto /// </summary> HasInvalidLayout } [CLSCompliant(false)] public struct McgStructMarshalData { public FixupRuntimeTypeHandle FixupSafeStructType; public FixupRuntimeTypeHandle FixupUnsafeStructType; public RuntimeTypeHandle SafeStructType { get { return FixupSafeStructType.RuntimeTypeHandle; } } public RuntimeTypeHandle UnsafeStructType { get { return FixupUnsafeStructType.RuntimeTypeHandle; } } public IntPtr MarshalStub; public IntPtr UnmarshalStub; public IntPtr DestroyStructureStub; public McgStructMarshalFlags Flags; /// <summary> /// This struct has invalid layout information, most likely because it is marked LayoutKind.Auto /// We'll throw exception when this struct is getting marshalled /// </summary> internal bool HasInvalidLayout { get { return (Flags & McgStructMarshalFlags.HasInvalidLayout) != 0; } } public int FieldOffsetStartIndex; // start index to its field offset data public int NumOfFields; // number of fields } [CLSCompliant(false)] public struct McgUnsafeStructFieldOffsetData { public uint Offset; // offset value in bytes } /// <summary> /// Base class for KeyValuePairImpl<T> /// </summary> public abstract class BoxedKeyValuePair : IManagedWrapper { // Called by public object McgModule.Box(object obj, int boxingIndex) after allocating instance public abstract object Initialize(object val); public abstract object GetTarget(); } /// <summary> /// Supports unboxing managed wrappers such as ReferenceImpl / KeyValuePair /// </summary> public interface IManagedWrapper { object GetTarget(); } /// <summary> /// Base class for ReferenceImpl<T>/ReferenceArrayImpl<T> /// </summary> public class BoxedValue : IManagedWrapper { protected object m_data; // boxed value protected short m_type; // Windows.Foundation.PropertyType protected bool m_unboxed; // false if T ReferenceImpl<T>.m_value needs to be unboxed from m_data when needed public BoxedValue(object val, int type) { m_data = val; m_type = (short)type; } // Called by public object Box(object obj, int boxingIndex) after allocating instance // T ReferenceImpl<T>.m_value needs to be unboxed from m_data when needed virtual public void Initialize(object val, int type) { m_data = val; m_type = (short)type; } public object GetTarget() { return m_data; } public override string ToString() { if (m_data != null) { return m_data.ToString(); } else { return "null"; } } } /// <summary> /// Entries for WinRT classes that MCG didn't see in user code /// We need to make sure when we are marshalling these types, we need to hand out the closest match /// For example, if MCG only sees DependencyObject but native is passing MatrixTransform, we need /// to give user the next best thing - dependencyObject, so that user can cast it to DependencyObject /// /// MatrixTransform -> DependencyObject /// </summary> [CLSCompliant(false)] public struct McgAdditionalClassData { public int ClassDataIndex; // Pointing to the "next best" class (DependencyObject, for example) public FixupRuntimeTypeHandle FixupClassType; // Pointing to the "next best" class (DependencyObject, for example) public RuntimeTypeHandle ClassType { get { return FixupClassType.RuntimeTypeHandle; } } } /// <summary> /// Maps from an ICollection or IReadOnlyCollection type to the corresponding entries in m_interfaceTypeInfo /// for IList, IDictionary, IReadOnlyList, IReadOnlyDictionary /// </summary> [CLSCompliant(false)] public struct McgCollectionData { public FixupRuntimeTypeHandle FixupCollectionType; public RuntimeTypeHandle CollectionType { get { return FixupCollectionType.RuntimeTypeHandle; } } public FixupRuntimeTypeHandle FixupFirstType; public RuntimeTypeHandle FirstType { get { return FixupFirstType.RuntimeTypeHandle; } } public FixupRuntimeTypeHandle FixupSecondType; public RuntimeTypeHandle SecondType { get { return FixupSecondType.RuntimeTypeHandle; } } } /// <summary> /// Captures data for each P/invoke delegate type we decide to import /// </summary> [CLSCompliant(false)] public struct McgPInvokeDelegateData { /// <summary> /// Type of the delegate /// </summary> public FixupRuntimeTypeHandle FixupDelegate; public RuntimeTypeHandle Delegate { get { return FixupDelegate.RuntimeTypeHandle; } } /// <summary> /// The stub called from thunk that does the marshalling when calling managed delegate (as a function /// pointer) from native code /// </summary> public IntPtr ReverseStub; /// <summary> /// The stub called from thunk that does the marshalling when calling managed open static delegate (as a function /// pointer) from native code /// </summary> public IntPtr ReverseOpenStaticDelegateStub; /// <summary> /// This creates a delegate wrapper class that wraps the native function pointer and allows managed /// code to call it /// </summary> public IntPtr ForwardDelegateCreationStub; } /// <summary> /// Base class for all 'wrapper' classes that wraps a native function pointer /// The forward delegates (that wraps native function pointers) points to derived Invoke method of this /// class, and the Invoke method would implement the marshalling and making the call /// </summary> public abstract class NativeFunctionPointerWrapper { public NativeFunctionPointerWrapper(IntPtr nativeFunctionPointer) { m_nativeFunctionPointer = nativeFunctionPointer; } IntPtr m_nativeFunctionPointer; public IntPtr NativeFunctionPointer { get { return m_nativeFunctionPointer; } } } [CLSCompliant(false)] public struct McgCCWFactoryInfoEntry { public FixupRuntimeTypeHandle FixupFactoryType; public RuntimeTypeHandle FactoryType { get { return FixupFactoryType.RuntimeTypeHandle; } } } /// <summary> /// Static per-type CCW information /// </summary> [CLSCompliant(false)] public struct CCWTemplateData { /// <summary> /// RuntimeTypeHandle of the class that this CCWTemplateData is for /// </summary> public FixupRuntimeTypeHandle FixupClassType; public RuntimeTypeHandle ClassType { get { return FixupClassType.RuntimeTypeHandle; } } /// <summary> /// The type handle for its base class (that is also a managed type) /// /// There are two ways to access base class: RuntimeTypeHandle or Index /// Ideally we want to use typehandle for everything - but DR throws it away and breaks the inheritance chain /// - therefore we would only use index for "same module" and type handle for "cross module" /// /// Code Pattern: /// if (ParentCCWTemplateIndex >=0) { // same module } /// else if(!BaseClassType.Equals(default(RuntimeTypeHandle)) { // cross module} /// else { // it doesn't have base} /// </summary> public FixupRuntimeTypeHandle FixupBaseType; public RuntimeTypeHandle BaseType { get { return FixupBaseType.RuntimeTypeHandle; } } /// <summary> /// The index of the CCWTemplateData for its base class (that is also a managed type) /// < 0 if does not exist or there are multiple module involved(use its BaseType property instead) /// </summary> public int ParentCCWTemplateIndex; /// <summary> /// The beginning index of list of supported interface /// NOTE: The list for this specific type only, excluding base classes /// </summary> public int SupportedInterfaceListBeginIndex; /// <summary> /// The total number of supported interface /// NOTE: The list for this specific type only, excluding base classes /// </summary> public int NumberOfSupportedInterface; /// <summary> /// Whether this CCWTemplateData belongs to a WinRT type /// Typically this only happens when we import a managed class that implements a WinRT type and /// we'll import the base WinRT type as CCW template too, as a way to capture interfaces in the class /// hierarchy and also know which are the ones implemented by managed class /// </summary> public bool IsWinRTType; } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type bool with 4 columns and 4 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct bmat4 : IReadOnlyList<bool>, IEquatable<bmat4> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public bool m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public bool m01; /// <summary> /// Column 0, Rows 2 /// </summary> [DataMember] public bool m02; /// <summary> /// Column 0, Rows 3 /// </summary> [DataMember] public bool m03; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public bool m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public bool m11; /// <summary> /// Column 1, Rows 2 /// </summary> [DataMember] public bool m12; /// <summary> /// Column 1, Rows 3 /// </summary> [DataMember] public bool m13; /// <summary> /// Column 2, Rows 0 /// </summary> [DataMember] public bool m20; /// <summary> /// Column 2, Rows 1 /// </summary> [DataMember] public bool m21; /// <summary> /// Column 2, Rows 2 /// </summary> [DataMember] public bool m22; /// <summary> /// Column 2, Rows 3 /// </summary> [DataMember] public bool m23; /// <summary> /// Column 3, Rows 0 /// </summary> [DataMember] public bool m30; /// <summary> /// Column 3, Rows 1 /// </summary> [DataMember] public bool m31; /// <summary> /// Column 3, Rows 2 /// </summary> [DataMember] public bool m32; /// <summary> /// Column 3, Rows 3 /// </summary> [DataMember] public bool m33; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public bmat4(bool m00, bool m01, bool m02, bool m03, bool m10, bool m11, bool m12, bool m13, bool m20, bool m21, bool m22, bool m23, bool m30, bool m31, bool m32, bool m33) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; } /// <summary> /// Constructs this matrix from a bmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = false; this.m03 = false; this.m10 = m.m10; this.m11 = m.m11; this.m12 = false; this.m13 = false; this.m20 = false; this.m21 = false; this.m22 = true; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a bmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = false; this.m03 = false; this.m10 = m.m10; this.m11 = m.m11; this.m12 = false; this.m13 = false; this.m20 = m.m20; this.m21 = m.m21; this.m22 = true; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a bmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = false; this.m03 = false; this.m10 = m.m10; this.m11 = m.m11; this.m12 = false; this.m13 = false; this.m20 = m.m20; this.m21 = m.m21; this.m22 = true; this.m23 = false; this.m30 = m.m30; this.m31 = m.m31; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a bmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = false; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = false; this.m20 = false; this.m21 = false; this.m22 = true; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a bmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = false; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = false; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a bmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = false; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = false; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; this.m23 = false; this.m30 = m.m30; this.m31 = m.m31; this.m32 = m.m32; this.m33 = true; } /// <summary> /// Constructs this matrix from a bmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; this.m20 = false; this.m21 = false; this.m22 = true; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a bmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; this.m23 = m.m23; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a bmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; this.m23 = m.m23; this.m30 = m.m30; this.m31 = m.m31; this.m32 = m.m32; this.m33 = m.m33; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bvec2 c0, bvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = false; this.m03 = false; this.m10 = c1.x; this.m11 = c1.y; this.m12 = false; this.m13 = false; this.m20 = false; this.m21 = false; this.m22 = true; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bvec2 c0, bvec2 c1, bvec2 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = false; this.m03 = false; this.m10 = c1.x; this.m11 = c1.y; this.m12 = false; this.m13 = false; this.m20 = c2.x; this.m21 = c2.y; this.m22 = true; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bvec2 c0, bvec2 c1, bvec2 c2, bvec2 c3) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = false; this.m03 = false; this.m10 = c1.x; this.m11 = c1.y; this.m12 = false; this.m13 = false; this.m20 = c2.x; this.m21 = c2.y; this.m22 = true; this.m23 = false; this.m30 = c3.x; this.m31 = c3.y; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bvec3 c0, bvec3 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = false; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = false; this.m20 = false; this.m21 = false; this.m22 = true; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bvec3 c0, bvec3 c1, bvec3 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = false; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = false; this.m20 = c2.x; this.m21 = c2.y; this.m22 = c2.z; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bvec3 c0, bvec3 c1, bvec3 c2, bvec3 c3) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = false; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = false; this.m20 = c2.x; this.m21 = c2.y; this.m22 = c2.z; this.m23 = false; this.m30 = c3.x; this.m31 = c3.y; this.m32 = c3.z; this.m33 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bvec4 c0, bvec4 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = c0.w; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = c1.w; this.m20 = false; this.m21 = false; this.m22 = true; this.m23 = false; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bvec4 c0, bvec4 c1, bvec4 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = c0.w; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = c1.w; this.m20 = c2.x; this.m21 = c2.y; this.m22 = c2.z; this.m23 = c2.w; this.m30 = false; this.m31 = false; this.m32 = false; this.m33 = true; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public bmat4(bvec4 c0, bvec4 c1, bvec4 c2, bvec4 c3) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = c0.w; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = c1.w; this.m20 = c2.x; this.m21 = c2.y; this.m22 = c2.z; this.m23 = c2.w; this.m30 = c3.x; this.m31 = c3.y; this.m32 = c3.z; this.m33 = c3.w; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public bool[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 }, { m20, m21, m22, m23 }, { m30, m31, m32, m33 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public bool[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public bvec4 Column0 { get { return new bvec4(m00, m01, m02, m03); } set { m00 = value.x; m01 = value.y; m02 = value.z; m03 = value.w; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public bvec4 Column1 { get { return new bvec4(m10, m11, m12, m13); } set { m10 = value.x; m11 = value.y; m12 = value.z; m13 = value.w; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public bvec4 Column2 { get { return new bvec4(m20, m21, m22, m23); } set { m20 = value.x; m21 = value.y; m22 = value.z; m23 = value.w; } } /// <summary> /// Gets or sets the column nr 3 /// </summary> public bvec4 Column3 { get { return new bvec4(m30, m31, m32, m33); } set { m30 = value.x; m31 = value.y; m32 = value.z; m33 = value.w; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public bvec4 Row0 { get { return new bvec4(m00, m10, m20, m30); } set { m00 = value.x; m10 = value.y; m20 = value.z; m30 = value.w; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public bvec4 Row1 { get { return new bvec4(m01, m11, m21, m31); } set { m01 = value.x; m11 = value.y; m21 = value.z; m31 = value.w; } } /// <summary> /// Gets or sets the row nr 2 /// </summary> public bvec4 Row2 { get { return new bvec4(m02, m12, m22, m32); } set { m02 = value.x; m12 = value.y; m22 = value.z; m32 = value.w; } } /// <summary> /// Gets or sets the row nr 3 /// </summary> public bvec4 Row3 { get { return new bvec4(m03, m13, m23, m33); } set { m03 = value.x; m13 = value.y; m23 = value.z; m33 = value.w; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static bmat4 Zero { get; } = new bmat4(false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false); /// <summary> /// Predefined all-ones matrix /// </summary> public static bmat4 Ones { get; } = new bmat4(true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true); /// <summary> /// Predefined identity matrix /// </summary> public static bmat4 Identity { get; } = new bmat4(true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<bool> GetEnumerator() { yield return m00; yield return m01; yield return m02; yield return m03; yield return m10; yield return m11; yield return m12; yield return m13; yield return m20; yield return m21; yield return m22; yield return m23; yield return m30; yield return m31; yield return m32; yield return m33; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (4 x 4 = 16). /// </summary> public int Count => 16; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public bool this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m02; case 3: return m03; case 4: return m10; case 5: return m11; case 6: return m12; case 7: return m13; case 8: return m20; case 9: return m21; case 10: return m22; case 11: return m23; case 12: return m30; case 13: return m31; case 14: return m32; case 15: return m33; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m02 = value; break; case 3: this.m03 = value; break; case 4: this.m10 = value; break; case 5: this.m11 = value; break; case 6: this.m12 = value; break; case 7: this.m13 = value; break; case 8: this.m20 = value; break; case 9: this.m21 = value; break; case 10: this.m22 = value; break; case 11: this.m23 = value; break; case 12: this.m30 = value; break; case 13: this.m31 = value; break; case 14: this.m32 = value; break; case 15: this.m33 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public bool this[int col, int row] { get { return this[col * 4 + row]; } set { this[col * 4 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(bmat4 rhs) => ((((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13)))) && (((m20.Equals(rhs.m20) && m21.Equals(rhs.m21)) && (m22.Equals(rhs.m22) && m23.Equals(rhs.m23))) && ((m30.Equals(rhs.m30) && m31.Equals(rhs.m31)) && (m32.Equals(rhs.m32) && m33.Equals(rhs.m33))))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is bmat4 && Equals((bmat4) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(bmat4 lhs, bmat4 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(bmat4 lhs, bmat4 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((((((((((((((((((m00.GetHashCode()) * 2) ^ m01.GetHashCode()) * 2) ^ m02.GetHashCode()) * 2) ^ m03.GetHashCode()) * 2) ^ m10.GetHashCode()) * 2) ^ m11.GetHashCode()) * 2) ^ m12.GetHashCode()) * 2) ^ m13.GetHashCode()) * 2) ^ m20.GetHashCode()) * 2) ^ m21.GetHashCode()) * 2) ^ m22.GetHashCode()) * 2) ^ m23.GetHashCode()) * 2) ^ m30.GetHashCode()) * 2) ^ m31.GetHashCode()) * 2) ^ m32.GetHashCode()) * 2) ^ m33.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public bmat4 Transposed => new bmat4(m00, m10, m20, m30, m01, m11, m21, m31, m02, m12, m22, m32, m03, m13, m23, m33); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public bool MinElement => ((((m00 && m01) && (m02 && m03)) && ((m10 && m11) && (m12 && m13))) && (((m20 && m21) && (m22 && m23)) && ((m30 && m31) && (m32 && m33)))); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public bool MaxElement => ((((m00 || m01) || (m02 || m03)) || ((m10 || m11) || (m12 || m13))) || (((m20 || m21) || (m22 || m23)) || ((m30 || m31) || (m32 || m33)))); /// <summary> /// Returns true if all component are true. /// </summary> public bool All => ((((m00 && m01) && (m02 && m03)) && ((m10 && m11) && (m12 && m13))) && (((m20 && m21) && (m22 && m23)) && ((m30 && m31) && (m32 && m33)))); /// <summary> /// Returns true if any component is true. /// </summary> public bool Any => ((((m00 || m01) || (m02 || m03)) || ((m10 || m11) || (m12 || m13))) || (((m20 || m21) || (m22 || m23)) || ((m30 || m31) || (m32 || m33)))); /// <summary> /// Executes a component-wise &amp;&amp;. (sorry for different overload but &amp;&amp; cannot be overloaded directly) /// </summary> public static bmat4 operator&(bmat4 lhs, bmat4 rhs) => new bmat4(lhs.m00 && rhs.m00, lhs.m01 && rhs.m01, lhs.m02 && rhs.m02, lhs.m03 && rhs.m03, lhs.m10 && rhs.m10, lhs.m11 && rhs.m11, lhs.m12 && rhs.m12, lhs.m13 && rhs.m13, lhs.m20 && rhs.m20, lhs.m21 && rhs.m21, lhs.m22 && rhs.m22, lhs.m23 && rhs.m23, lhs.m30 && rhs.m30, lhs.m31 && rhs.m31, lhs.m32 && rhs.m32, lhs.m33 && rhs.m33); /// <summary> /// Executes a component-wise ||. (sorry for different overload but || cannot be overloaded directly) /// </summary> public static bmat4 operator|(bmat4 lhs, bmat4 rhs) => new bmat4(lhs.m00 || rhs.m00, lhs.m01 || rhs.m01, lhs.m02 || rhs.m02, lhs.m03 || rhs.m03, lhs.m10 || rhs.m10, lhs.m11 || rhs.m11, lhs.m12 || rhs.m12, lhs.m13 || rhs.m13, lhs.m20 || rhs.m20, lhs.m21 || rhs.m21, lhs.m22 || rhs.m22, lhs.m23 || rhs.m23, lhs.m30 || rhs.m30, lhs.m31 || rhs.m31, lhs.m32 || rhs.m32, lhs.m33 || rhs.m33); } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using FluentAssertions.Execution; namespace FluentAssertions.Collections { /// <summary> /// Contains a number of methods to assert that an <see cref="IEnumerable{T}"/> is in the expectation state. /// </summary> public class SelfReferencingCollectionAssertions<T, TAssertions> : CollectionAssertions<IEnumerable<T>, TAssertions> where TAssertions : SelfReferencingCollectionAssertions<T, TAssertions> { public SelfReferencingCollectionAssertions(IEnumerable<T> actualValue) { if (actualValue != null) { Subject = actualValue; } } /// <summary> /// Asserts that the number of items in the collection matches the supplied <paramref name="expected" /> amount. /// </summary> /// <param name="expected">The expected number of items in the collection.</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="reasonArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndConstraint<TAssertions> HaveCount(int expected, string because = "", params object[] reasonArgs) { if (ReferenceEquals(Subject, null)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} to contain {0} item(s){reason}, but found <null>.", expected); } int actualCount = Subject.Count(); Execute.Assertion .ForCondition(actualCount == expected) .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} to contain {0} item(s){reason}, but found {1}.", expected, actualCount); return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Asserts that the number of items in the collection matches a condition stated by the <paramref name="countPredicate"/>. /// </summary> /// <param name="countPredicate">A predicate that yields the number of items that is expected to be in the collection.</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="reasonArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndConstraint<TAssertions> HaveCount(Expression<Func<int, bool>> countPredicate, string because = "", params object[] reasonArgs) { if (countPredicate == null) { throw new NullReferenceException("Cannot compare collection count against a <null> predicate."); } if (ReferenceEquals(Subject, null)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} to contain {0} items{reason}, but found {1}.", countPredicate.Body, Subject); } Func<int, bool> compiledPredicate = countPredicate.Compile(); int actualCount = Subject.Count(); if (!compiledPredicate(actualCount)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} {0} to have a count {1}{reason}, but count is {2}.", Subject, countPredicate.Body, actualCount); } return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Expects the current collection to contain all the same elements in the same order as the collection identified by /// <paramref name="elements" />. Elements are compared using their <see cref="T.Equals(T)" /> method. /// </summary> /// <param name="elements">A params array with the expected elements.</param> public AndConstraint<TAssertions> Equal(params T[] elements) { return Equal(elements, String.Empty); } /// <summary> /// Asserts that two collections contain the same items in the same order, where equality is determined using a /// predicate. /// </summary> /// <param name="expectation"> /// The collection to compare the subject with. /// </param> /// <param name="predicate"> /// A predicate the is used to determine whether two objects should be treated as equal. /// </param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])"/> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="reasonArgs"> /// Zero or more objects to format using the placeholders in <see cref="because"/>. /// </param> public AndConstraint<TAssertions> Equal( IEnumerable<T> expectation, Func<T, T, bool> predicate, string because = "", params object[] reasonArgs) { AssertSubjectEquality(expectation, predicate, because, reasonArgs); return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Asserts that the collection contains the specified item. /// </summary> /// <param name="expected">The expectation item.</param> /// <param name="because"> /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not /// start with the word <i>because</i>, it is prepended to the message. /// </param> /// <param name="reasonArgs"> /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders. /// </param> public AndWhichConstraint<TAssertions, T> Contain(T expected, string because = "", params object[] reasonArgs) { if (ReferenceEquals(Subject, null)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} to contain {0}{reason}, but found {1}.", expected, Subject); } if (!Subject.Contains(expected)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} {0} to contain {1}{reason}.", Subject, expected); } return new AndWhichConstraint<TAssertions, T>((TAssertions) this, Subject.Where( item => EqualityComparer<T>.Default.Equals(item, expected))); } /// <summary> /// Asserts that the collection contains some extra items in addition to the original items. /// </summary> /// <param name="expectedItemsList">An <see cref="IEnumerable{T}"/> of expectation items.</param> /// <param name="additionalExpectedItems">Additional items that are expectation to be contained by the collection.</param> public AndConstraint<TAssertions> Contain(IEnumerable<T> expectedItemsList, params T [] additionalExpectedItems) { var list = new List<T>(expectedItemsList); list.AddRange(additionalExpectedItems); return Contain((IEnumerable)list); } /// <summary> /// Asserts that the collection contains at least one item that matches the predicate. /// </summary> /// <param name="predicate">A predicate to match the items in the collection against.</param> /// <param name="because"> /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not /// start with the word <i>because</i>, it is prepended to the message. /// </param> /// <param name="reasonArgs"> /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders. /// </param> public AndWhichConstraint<TAssertions, T> Contain(Expression<Func<T, bool>> predicate, string because = "", params object[] reasonArgs) { if (ReferenceEquals(Subject, null)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} to contain {0}{reason}, but found {1}.", predicate.Body, Subject); } Func<T, bool> func = predicate.Compile(); Execute.Assertion .ForCondition(Subject.Any(func)) .BecauseOf(because, reasonArgs) .FailWith("{context:Collection} {0} should have an item matching {1}{reason}.", Subject, predicate.Body); return new AndWhichConstraint<TAssertions, T>((TAssertions)this, Subject.Where(func)); } /// <summary> /// Asserts that the collection only contains items that match a predicate. /// </summary> /// <param name="predicate">A predicate to match the items in the collection against.</param> /// <param name="because"> /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not /// start with the word <i>because</i>, it is prepended to the message. /// </param> /// <param name="reasonArgs"> /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders. /// </param> public AndConstraint<TAssertions> OnlyContain( Expression<Func<T, bool>> predicate, string because = "", params object[] reasonArgs) { Func<T, bool> compiledPredicate = predicate.Compile(); Execute.Assertion .ForCondition(Subject.Any()) .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} to contain only items matching {0}{reason}, but the collection is empty.", predicate.Body); IEnumerable<T> mismatchingItems = Subject.Where(item => !compiledPredicate(item)); if (mismatchingItems.Any()) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} to contain only items matching {0}{reason}, but {1} do(es) not match.", predicate.Body, mismatchingItems); } return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Asserts that the collection does not contain any items that match the predicate. /// </summary> /// <param name="predicate">A predicate to match the items in the collection against.</param> /// <param name="because"> /// A formatted phrase explaining why the assertion should be satisfied. If the phrase does not /// start with the word <i>because</i>, it is prepended to the message. /// </param> /// <param name="reasonArgs"> /// Zero or more values to use for filling in any <see cref="string.Format(string,object[])"/> compatible placeholders. /// </param> public AndConstraint<TAssertions> NotContain(Expression<Func<T, bool>> predicate, string because = "", params object[] reasonArgs) { if (ReferenceEquals(Subject, null)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} not to contain {0}{reason}, but found {1}.", predicate.Body, Subject); } if (Subject.Any(item => predicate.Compile()(item))) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("{context:Collection} {0} should not have any items matching {1}{reason}.", Subject, predicate.Body); } return new AndConstraint<TAssertions>((TAssertions)this); } /// <summary> /// Expects the current collection to contain only a single item. /// </summary> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="reasonArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndWhichConstraint<TAssertions, T> ContainSingle(string because = "", params object[] reasonArgs) { if (ReferenceEquals(Subject, null)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} to contain a single item but found <null>."); } if (Subject.Count() != 1) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith("Expected {context:collection} to contain a single item."); } return new AndWhichConstraint<TAssertions, T>((TAssertions)this, Subject.Single()); } /// <summary> /// Expects the current collection to contain only a single item matching the specified <paramref name="predicate"/>. /// </summary> /// <param name="predicate">The predicate that will be used to find the matching items.</param> /// <param name="because"> /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion /// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="reasonArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public AndWhichConstraint<TAssertions, T> ContainSingle(Expression<Func<T, bool>> predicate, string because = "", params object[] reasonArgs) { string expectationPrefix = string.Format("Expected {{context:collection}} to contain a single item matching {0}{{reason}}, ", predicate.Body); if (ReferenceEquals(Subject, null)) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith(expectationPrefix + "but found {0}.", Subject); } T[] actualItems = Subject.ToArray(); Execute.Assertion .ForCondition(actualItems.Any()) .BecauseOf(because, reasonArgs) .FailWith(expectationPrefix + "but the collection is empty."); T[] matchingElements = actualItems.Where(predicate.Compile()).ToArray(); int count = matchingElements.Count(); if (count == 0) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith(expectationPrefix + "but no such item was found."); } else if (count > 1) { Execute.Assertion .BecauseOf(because, reasonArgs) .FailWith(expectationPrefix + "but " + count + " such items were found."); } else { // Exactly 1 item was expected } return new AndWhichConstraint<TAssertions, T>((TAssertions) this, matchingElements); } } }
using System; using System.Collections.Generic; namespace EmergeTk.Model.Providers { public class MockDataProvider : IDataProvider { Random rand = new Random (); Dictionary<Type, Dictionary<int, AbstractRecord>> db = new Dictionary<Type, Dictionary<int, AbstractRecord>> (); public MockDataProvider () { } #region IDataProvider implementation public object ExecuteScalar (string sql) { return null; } public System.Collections.Generic.List<int> ExecuteVectorInt (string sql) { return null; } public void ExecuteNonQuery (string sql) { } public void ExecuteReader (string sql, ReaderDelegate r) { } public System.Data.DataTable ExecuteDataTable (string sql) { return null; } public System.Data.DataSet ExecuteDataSet (string sql) { return null; } System.Data.DataSet IDataProvider.ExecuteDataSet (string sql, System.Data.IDataParameter[] parms) { return null; } public System.Data.IDataParameter CreateParameter () { return null; } public IRecordList<T> Load<T> () where T : AbstractRecord, new () { return new RecordList<T> (); } IRecordList<T> IDataProvider.Load<T> (System.Collections.Generic.List<int> ids) { return new RecordList<T> (); } IRecordList<T> IDataProvider.Load<T> (params SortInfo[] sortInfos) { return new RecordList<T> (); } IRecordList<T> IDataProvider.Load<T> (params FilterInfo[] filterInfos) { return new RecordList<T> (); } IRecordList<T> IDataProvider.Load<T> (FilterInfo[] filterInfos, SortInfo[] sortInfos) { return new RecordList<T> (); } IRecordList<T> IDataProvider.Load<T> (string whereClause, string orderByClause) { return new RecordList<T> (); } IRecordList<T> IDataProvider.Load<T> (string whereClause, string orderByClause, string selectColumns) { return new RecordList<T> (); } public Type GetTypeForId (int id) { return null; } public int RowCount<T> () where T : AbstractRecord, new() { return 0; } int nextId = 1; public int GetNewId (string typeName) { return nextId++; } public int GetLatestVersion (AbstractRecord r) { return 0; } int IDataProvider.GetLatestVersion (string modelName, int id) { return 0; } public System.Data.Common.DbConnection CreateNewConnection () { return null; } public void Save (AbstractRecord record, bool SaveChildren) { ((IDataProvider)this).Save (record, SaveChildren, false, null); } void IDataProvider.Save (AbstractRecord record, bool SaveChildren, bool IncrementVersion, System.Data.Common.DbConnection conn) { Type t = record.GetType(); if (!db.ContainsKey(t)) db [t] = new Dictionary<int, AbstractRecord> (); record.EnsureId (); db[t][record.Id] = record; } public void SaveSingleRelation (string childTableName, string parent_id, string child_id) { } public void RemoveRelations (string childTableName, string ObjectId) { } public void RemoveSingleRelation (string childTableName, string parent_id, string child_id) { } public void Delete (AbstractRecord r) { Type t = r.GetType(); if (!db.ContainsKey(t)) db [t] = new Dictionary<int, AbstractRecord> (); if (db[t].ContainsKey (r.Id)) db[t].Remove (r.Id); } public void SynchronizeModel (Type t) { } public void SynchronizeModelType<T> () where T :AbstractRecord, new () { } public string GetSqlType (DataType dt) { return null; } public void CreateTable (Type modelType, string tableName) { } public string GetSqlTypeFromType (ColumnInfo col, string tableName) { return null; } public void CreateChildTable (string tableName, ColumnInfo col) { } public bool TableExists (string name) { return true; } public bool TableExistsNoCache (string name) { return true; } public System.Collections.Generic.List<string> ColumnList (string tableName) { return null; } public System.Collections.Generic.List<string> TableList () { return null; } public System.Data.DataTable GetColumnTable (string tableName) { return null; } public string GenerateAddColStatement (ColumnInfo col, string table) { return null; } public string GenerateRemoveColStatement (string col, string table) { return null; } public string GenerateFixColTypeStatement (ColumnInfo col, string table) { return null; } public string CheckIdColumn (string table) { return null; } public string GenerateAddIdColStatement (string table) { return null; } public string GenerateModifyIdColStatement (string table) { return null; } public string GenerateAddTableStatement (Type addTable) { return null; } public string GenerateAddChildTableStatement (string tableName, bool isDerived) { return null; } public string GetCommentCharacter () { return null; } public string BuildWhereClause (FilterInfo[] filters) { return null; } public string GetIdentityColumn () { return null; } public string EscapeEntity (string entity) { return null; } public bool Synchronizing { get { return false; } } public bool OutOfSync { get { 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. // NOTE: This is a generated file - do not manually edit! #pragma warning disable 649 using System; using System.IO; using System.Collections.Generic; using System.Reflection; using Internal.NativeFormat; using Debug = System.Diagnostics.Debug; namespace Internal.Metadata.NativeFormat { internal static partial class MdBinaryReader { public static unsafe uint Read(this NativeReader reader, uint offset, out BooleanCollection values) { values = new BooleanCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Boolean)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out CharCollection values) { values = new CharCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Char)); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out StringCollection values) { values = new StringCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out ByteCollection values) { values = new ByteCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Byte)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out SByteCollection values) { values = new SByteCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(SByte)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out Int16Collection values) { values = new Int16Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Int16)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out UInt16Collection values) { values = new UInt16Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(UInt16)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out Int32Collection values) { values = new Int32Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Int32)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out UInt32Collection values) { values = new UInt32Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(UInt32)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out Int64Collection values) { values = new Int64Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Int64)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out UInt64Collection values) { values = new UInt64Collection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(UInt64)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out SingleCollection values) { values = new SingleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Single)); return offset; } // Read public static unsafe uint Read(this NativeReader reader, uint offset, out DoubleCollection values) { values = new DoubleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); offset = checked(offset + count * sizeof(Double)); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out AssemblyFlags value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (AssemblyFlags)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out AssemblyHashAlgorithm value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (AssemblyHashAlgorithm)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out CallingConventions value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (CallingConventions)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out EventAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (EventAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FieldAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (FieldAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FixedArgumentAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (FixedArgumentAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out GenericParameterAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (GenericParameterAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out GenericParameterKind value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (GenericParameterKind)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (MethodAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodImplAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (MethodImplAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (MethodSemanticsAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamedArgumentMemberKind value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (NamedArgumentMemberKind)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ParameterAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (ParameterAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PInvokeAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (PInvokeAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PropertyAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (PropertyAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeAttributes value) { uint ivalue; offset = reader.DecodeUnsigned(offset, out ivalue); value = (TypeAttributes)ivalue; return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out HandleCollection values) { values = new HandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ArraySignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ArraySignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ByReferenceSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ByReferenceSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantBooleanArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantBooleanArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantBooleanValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantBooleanValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantBoxedEnumValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantBoxedEnumValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantByteArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantByteArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantByteValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantByteValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantCharArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantCharArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantCharValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantCharValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantDoubleArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantDoubleArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantDoubleValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantDoubleValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantHandleArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantHandleArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt16ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt16ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt16ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt16ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt32ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt32ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt32ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt32ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt64ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt64ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantInt64ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantInt64ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantReferenceValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantReferenceValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantSByteArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantSByteArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantSByteValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantSByteValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantSingleArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantSingleArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantSingleValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantSingleValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantStringArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantStringArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantStringValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantStringValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt16ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt16ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt16ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt16ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt32ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt32ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt32ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt32ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt64ArrayHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt64ArrayHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ConstantUInt64ValueHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ConstantUInt64ValueHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out CustomAttributeHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new CustomAttributeHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out EventHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new EventHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FieldHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new FieldHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FieldSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new FieldSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FixedArgumentHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new FixedArgumentHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FunctionPointerSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new FunctionPointerSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out GenericParameterHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new GenericParameterHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MemberReferenceHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MemberReferenceHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodImplHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodImplHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodInstantiationHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodInstantiationHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodSemanticsHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodTypeVariableSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new MethodTypeVariableSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ModifiedTypeHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ModifiedTypeHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamedArgumentHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new NamedArgumentHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamespaceDefinitionHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new NamespaceDefinitionHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamespaceReferenceHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new NamespaceReferenceHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ParameterHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ParameterHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PointerSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new PointerSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PropertyHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new PropertyHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PropertySignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new PropertySignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out QualifiedFieldHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new QualifiedFieldHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out QualifiedMethodHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new QualifiedMethodHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out SZArraySignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new SZArraySignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ScopeDefinitionHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ScopeDefinitionHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ScopeReferenceHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new ScopeReferenceHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeDefinitionHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeDefinitionHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeForwarderHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeForwarderHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeInstantiationSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeInstantiationSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeReferenceHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeReferenceHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeSpecificationHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeSpecificationHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeVariableSignatureHandle handle) { uint value; offset = reader.DecodeUnsigned(offset, out value); handle = new TypeVariableSignatureHandle((int)value); handle._Validate(); return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FixedArgumentHandleCollection values) { values = new FixedArgumentHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamedArgumentHandleCollection values) { values = new NamedArgumentHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsHandleCollection values) { values = new MethodSemanticsHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out CustomAttributeHandleCollection values) { values = new CustomAttributeHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ParameterHandleCollection values) { values = new ParameterHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out GenericParameterHandleCollection values) { values = new GenericParameterHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeDefinitionHandleCollection values) { values = new TypeDefinitionHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out TypeForwarderHandleCollection values) { values = new TypeForwarderHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out NamespaceDefinitionHandleCollection values) { values = new NamespaceDefinitionHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodHandleCollection values) { values = new MethodHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out FieldHandleCollection values) { values = new FieldHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out PropertyHandleCollection values) { values = new PropertyHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out EventHandleCollection values) { values = new EventHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out MethodImplHandleCollection values) { values = new MethodImplHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read public static uint Read(this NativeReader reader, uint offset, out ScopeDefinitionHandleCollection values) { values = new ScopeDefinitionHandleCollection(reader, offset); uint count; offset = reader.DecodeUnsigned(offset, out count); for (uint i = 0; i < count; ++i) { offset = reader.SkipInteger(offset); } return offset; } // Read } // MdBinaryReader } // Internal.Metadata.NativeFormat
using System.Collections.Generic; using System.Windows.Forms; using System.Linq; using Sce.Atf.Adaptation; using Sce.Atf.Dom; using Sce.Atf.Controls; using Sce.Atf.Applications; using System.Drawing; using Sce.Atf; namespace SettingsEditor { public class DocumentControl : UserControl { public DocumentControl( Editor editor ) { m_editor = editor; //m_treeControl = new TreeControl() //{ // ImageList = ResourceUtil.GetImageList16(), // StateImageList = ResourceUtil.GetImageList16() // //LabelEditMode = TreeControl.LabelEditModes.EditOnF2 //}; //m_treeControl.Dock = DockStyle.Fill; //m_treeControl.ShowRoot = true; //m_treeControlAdapter = new TreeControlAdapter(m_treeControl); //TreeView treeView = RootNode.As<TreeView>(); //treeView.Schema = schema; //m_treeControlAdapter.TreeView = treeView; ////foreach ( Struct group in RootNode.Children.AsIEnumerable<Struct>() ) //foreach( Struct group in RootNode.Subtree.AsIEnumerable<Struct>() ) //{ // if ( group.Expanded ) // m_treeControlAdapter.Expand( group ); //} //m_treeControl.MouseUp += treeControl_MouseUp; ////m_treeControl.MouseDoubleClick += m_treeControl_MouseDoubleClick; //m_treeControl.NodeExpandedChanged += m_treeControl_NodeExpandedChanged; ////m_treeControl.NodeLabelEdited += m_treeControl_NodeLabelEdited; //m_treeControlAdapter.LastHitChanged += treeControlAdapter_LastHitChanged; m_filteredTreeControlEditor = new FilteredTreeControlEditor( editor.CommandService ); m_filteredTreeControlEditor.Control.Dock = DockStyle.Fill; //m_filteredTreeControlEditor.TreeView = new FilteredTreeView( treeView, m_filteredTreeControlEditor.DefaultFilter ); //m_filteredTreeControlEditor.TreeView = new FilteredTreeView( treeView, CustomFilter ); m_filteredTreeControlEditor.TreeControl.NodeExpandedChanged += m_treeControl_NodeExpandedChanged; //foreach ( Struct group in RootNode.Subtree.AsIEnumerable<Struct>() ) //{ // if ( group.Expanded ) // m_filteredTreeControlEditor.TreeControlAdapter.Expand( group ); //} m_filteredTreeControlEditor.SearchInputUI.Updated += SearchInputUI_Updated; m_propertyGrid = new Sce.Atf.Controls.PropertyEditing.PropertyGrid(); m_propertyGrid.PropertySorting = Sce.Atf.Controls.PropertyEditing.PropertySorting.Categorized; m_propertyGrid.Dock = DockStyle.Fill; //m_propertyGrid.Bind( root.As<DocumentEditingContext>() ); m_splitContainer = new SplitContainer(); m_splitContainer.Text = "Split Container"; //m_splitContainer.Panel1.Controls.Add( m_treeControl ); m_splitContainer.Panel1.Controls.Add( m_filteredTreeControlEditor.Control ); m_splitContainer.Panel2.Controls.Add( m_propertyGrid ); m_splitContainer.Dock = DockStyle.Fill; Dock = DockStyle.Fill; Controls.Add( m_splitContainer ); } public void Setup( DomNode root, Schema schema ) { RootNode = root; //Schema = schema; RootNode.AttributeChanged += RootNode_AttributeChanged; TreeView treeView = RootNode.As<TreeView>(); m_filteredTreeControlEditor.TreeView = new FilteredTreeView( treeView, CustomFilter ); foreach ( Struct group in RootNode.Subtree.AsIEnumerable<Struct>() ) { if ( group.Expanded ) m_filteredTreeControlEditor.TreeControlAdapter.Expand( group ); } m_propertyGrid.Bind( root.As<DocumentEditingContext>() ); } private void SearchInputUI_Updated( object sender, System.EventArgs e ) { // we're filling property editor's search bar while typing in tree's search bar // this is to further narrow search so user can quicker find what he's after // it's kind of hack, setting only m_propertyGrid.PropertyGridView.FilterPattern // will filter properly, but filling search bar is more intuitive // because user will see what's actually happening // to set this search text box we need to find it among other controls // PropertyGrid doesn't expose any API to do it directly // foreach ( ToolStripItem tsi in m_propertyGrid.ToolStrip.Items ) { if ( tsi is ToolStripAutoFitTextBox ) { ToolStripAutoFitTextBox t = tsi as ToolStripAutoFitTextBox; t.Text = m_filteredTreeControlEditor.SearchInputUI.SearchPattern; m_propertyGrid.PropertyGridView.FilterPattern = m_filteredTreeControlEditor.SearchInputUI.SearchPattern; break; } } } /// <summary> /// Callback to determine if an item in the tree is filtered in (return true) or out</summary> /// <param name="item">Item tested for filtering</param> /// <returns>True if filtered in, false if filtered out</returns> private bool CustomFilter( object item ) { // filter first tries to match group name and if failed checks all settings // DomNode dn = item.As<DomNode>(); SettingGroup group = dn.Type.GetTag<SettingGroup>(); if ( group != null ) { if ( m_filteredTreeControlEditor.SearchInputUI.IsNullOrEmpty() || m_filteredTreeControlEditor.SearchInputUI.Matches( group.Name ) ) { return true; } foreach( Setting sett in group.Settings ) { if ( m_filteredTreeControlEditor.SearchInputUI.IsNullOrEmpty() || m_filteredTreeControlEditor.SearchInputUI.Matches( sett.Name ) ) { return true; } } return false; } return true; // Don't filter anything if the context doesn't implement IItemView } private void RootNode_AttributeChanged( object sender, AttributeEventArgs e ) { Document document = RootNode.As<Document>(); Struct group = e.DomNode.As<Struct>(); if ( group != null && e.AttributeInfo.Equivalent( document.Schema.structType.expandedAttribute ) ) { if ( group.Expanded ) //m_treeControlAdapter.Expand( group ); m_filteredTreeControlEditor.TreeControlAdapter.Expand( group ); else //m_treeControlAdapter.Collapse( group ); m_filteredTreeControlEditor.TreeControlAdapter.Collapse( group ); } } private void m_treeControl_NodeExpandedChanged( object sender, TreeControl.NodeEventArgs e ) { Struct group = e.Node.Tag.As<Struct>(); if ( group != null && group.Expanded != e.Node.Expanded ) { ITransactionContext transactionContext = RootNode.As<ITransactionContext>(); transactionContext.DoTransaction( delegate { group.Expanded = e.Node.Expanded; }, e.Node.Expanded ? "Struct expanded" : "Struct collapsed" ); } } //void m_treeControl_NodeLabelEdited( object sender, TreeControl.NodeEventArgs e ) //{ // Preset preset = e.Node.Tag.As<Preset>(); // Group group = preset.Group; // ITransactionContext transactionContext = RootNode.As<ITransactionContext>(); // transactionContext.DoTransaction( // delegate // { // preset.Name = e.Node.Label; // //if (group.SelectedPreset == preset) // // group.SelectedPreset = preset; // }, string.Format( "Preset name: '{0}' -> '{1}'", preset.Name, e.Node.Label ) ); //} private void treeControlAdapter_LastHitChanged( object sender, System.EventArgs e ) { //DocumentEditingContext editingContext = RootNode.Cast<DocumentEditingContext>(); //editingContext.SetInsertionParent( m_treeControlAdapter.LastHit ); } //private void treeControl_MouseUp( object sender, MouseEventArgs e ) //{ // if ( e.Button == MouseButtons.Right ) // { // IEnumerable<object> commands = // m_editor.ContextMenuCommandProviders.GetCommands( m_treeControlAdapter.TreeView, m_treeControlAdapter.LastHit ); // Point screenPoint = m_treeControl.PointToScreen( new Point( e.X, e.Y ) ); // m_editor.CommandService.RunContextMenu( commands, screenPoint ); // } //} //void m_treeControl_MouseDoubleClick( object sender, MouseEventArgs e ) //{ // Preset preset = m_treeControlAdapter.LastHit.As<Preset>(); // if (preset != null) // { // Group group = preset.Group; // //Preset prevPreset = group.SelectedPreset; // Preset prevPreset = group.SelectedPresetRef; // if (prevPreset != preset) // { // ITransactionContext transactionContext = RootNode.As<ITransactionContext>(); // transactionContext.DoTransaction( // delegate // { // //group.SelectedPreset = preset; // group.SelectedPresetRef = preset; // }, "Active preset: " + ((prevPreset != null) ? prevPreset.Name : "null") + " -> " + preset.Name ); // //// refreshing group causes selection to change and effectively clears it leaving property editor empty // //// // //m_treeControlAdapter.Refresh( prevPreset ); // //m_treeControlAdapter.Refresh( preset ); // } // } //} public void Rebind() { System.Diagnostics.Debug.WriteLine( "DocumentControl.Rebind" ); m_propertyGrid.Bind( null ); m_propertyGrid.Bind( RootNode.As<DocumentEditingContext>() ); } /// <summary> /// Selects DomNode in tree control. This is really hacky way to do it. /// We need to remap DomNode to TreeControl.Node, don't know any better way to do it. /// </summary> /// <param name="domNode">Group or Preset to select</param> public void SetSelectedDomNode( DomNode domNode ) { //var paths = m_treeControlAdapter.GetPaths( domNode ); var paths = m_filteredTreeControlEditor.TreeControlAdapter.GetPaths( domNode ); var list = paths.ToList(); if ( list.Count > 0 ) { //TreeControl.Node n = m_treeControlAdapter.ExpandPath( list[0] ); TreeControl.Node n = m_filteredTreeControlEditor.TreeControlAdapter.ExpandPath( list[0] ); //m_treeControl.SetSelection( n ); m_filteredTreeControlEditor.TreeControl.SetSelection( n ); } } public DomNode RootNode { get; set; } //public Schema Schema { get; set; } public ControlInfo ControlInfo { get; set; } //private TreeControl m_treeControl; //private TreeControlAdapter m_treeControlAdapter; private FilteredTreeControlEditor m_filteredTreeControlEditor; private readonly SplitContainer m_splitContainer; private readonly Sce.Atf.Controls.PropertyEditing.PropertyGrid m_propertyGrid; private Editor m_editor; } }
namespace HelixToolkit.Wpf.SharpDX { using System.Linq; using System.Collections.ObjectModel; using global::SharpDX; public class PhongMaterialCollection : ObservableCollection<PhongMaterial> { public PhongMaterialCollection() { Add(PhongMaterials.Black); Add(PhongMaterials.BlackPlastic); Add(PhongMaterials.BlackRubber); Add(PhongMaterials.Blue); Add(PhongMaterials.Brass); Add(PhongMaterials.Bronze); Add(PhongMaterials.Chrome); Add(PhongMaterials.Copper); Add(PhongMaterials.DefaultVRML); Add(PhongMaterials.Emerald); Add(PhongMaterials.Glass); Add(PhongMaterials.Gold); Add(PhongMaterials.Green); Add(PhongMaterials.Indigo); Add(PhongMaterials.Jade); Add(PhongMaterials.LightGray); Add(PhongMaterials.MediumGray); Add(PhongMaterials.Obsidian); Add(PhongMaterials.Orange); Add(PhongMaterials.Pearl); Add(PhongMaterials.Pewter); Add(PhongMaterials.PolishedBronze); Add(PhongMaterials.PolishedCopper); Add(PhongMaterials.PolishedGold); Add(PhongMaterials.PolishedSilver); Add(PhongMaterials.Red); Add(PhongMaterials.Ruby); Add(PhongMaterials.Silver); Add(PhongMaterials.Turquoise); Add(PhongMaterials.Violet); Add(PhongMaterials.White); Add(PhongMaterials.Yellow); } } /// <summary> /// /// </summary> public static class PhongMaterials { public static PhongMaterialCollection Materials { get; private set; } public static PhongMaterial GetMaterial(string materialName) { var mat = Materials.FirstOrDefault(x => x.Name == materialName); return mat != null ? mat : PhongMaterials.DefaultVRML; } static PhongMaterials() { Materials = new PhongMaterialCollection(); } public static Color4 ToColor(double r, double g, double b, double a = 1.0) { //return new Color4((float)r, (float)g, (float)b, (float)a); return System.Windows.Media.Color.FromScRgb((float)a, (float)r, (float)g, (float)b).ToColor4(); } // factory public static readonly PhongMaterial Red = new PhongMaterial { Name = "Red", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = Color.Red, SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial Blue = new PhongMaterial { Name = "Blue", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = Color.Blue, SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial Green = new PhongMaterial { Name = "Green", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = Color.Green, SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial Orange = new PhongMaterial { Name = "Orange", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = ToColor(0.992157, 0.513726, 0.0, 1.0), SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial BlanchedAlmond = new PhongMaterial { Name = "BlanchedAlmond", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = Color.BlanchedAlmond, SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial Bisque = new PhongMaterial { Name = "Bisque", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = Color.Bisque, SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial Yellow = new PhongMaterial { Name = "Yellow", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = ToColor(1.0, 0.964706, 0.0, 1.0), SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial Indigo = new PhongMaterial { Name = "Indigo", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = ToColor(0.0980392, 0.0, 0.458824, 1.0), SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial Violet = new PhongMaterial { Name = "Violet", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = ToColor(0.635294, 0.0, 1.0, 1.0), SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial White = new PhongMaterial { Name = "White", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = ToColor(0.992157, 0.992157, 0.992157, 1.0), SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial PureWhite = new PhongMaterial { Name = "PureWhite", AmbientColor = ToColor(1, 1, 1, 1.0), DiffuseColor = ToColor(1, 1, 1, 1.0), SpecularColor = ToColor(0.0, 0.0, 0.0, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 1000000f, }.Clone(); public static readonly PhongMaterial Black = new PhongMaterial { Name = "Black", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial Gray = new PhongMaterial { Name = "Gray", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = ToColor(0.254902, 0.254902, 0.254902, 1.0), SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial MediumGray = new PhongMaterial { Name = "MediumGray", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = ToColor(0.454902, 0.454902, 0.454902, 1.0), SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial LightGray = new PhongMaterial { Name = "LightGray", AmbientColor = ToColor(0.1, 0.1, 0.1, 1.0), DiffuseColor = ToColor(0.682353, 0.682353, 0.682353, 1.0), SpecularColor = ToColor(0.0225, 0.0225, 0.0225, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 12.8f, }.Clone(); // Materials from: http://globe3d.sourceforge.net/g3d_html/gl-materials__ads.htm public static readonly PhongMaterial Glass = new PhongMaterial { Name = "Glass", AmbientColor = ToColor(0.0, 0.0, 0.0, 1.0), DiffuseColor = ToColor(0.588235, 0.670588, 0.729412, 1.0), SpecularColor = ToColor(0.9, 0.9, 0.9, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 96.0f, }.Clone(); public static readonly PhongMaterial Brass = new PhongMaterial { Name = "Brass", AmbientColor = ToColor(0.329412, 0.223529, 0.027451, 1.0), DiffuseColor = ToColor(0.780392, 0.568627, 0.113725, 1.0), SpecularColor = ToColor(0.992157, 0.941176, 0.807843, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 27.8974f, }.Clone(); public static readonly PhongMaterial Bronze = new PhongMaterial { Name = "Bronze", AmbientColor = ToColor(0.2125, 0.1275, 0.054, 1.0), DiffuseColor = ToColor(0.714, 0.4284, 0.18144, 1.0), SpecularColor = ToColor(0.393548, 0.271906, 0.166721, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 25.6f, }.Clone(); public static readonly PhongMaterial PolishedBronze = new PhongMaterial { Name = "PolishedBronze", AmbientColor = ToColor(0.25, 0.148, 0.06475, 1.0), DiffuseColor = ToColor(0.4, 0.2368, 0.1036, 1.0), SpecularColor = ToColor(0.774597, 0.458561, 0.200621, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 76.8f, }.Clone(); public static readonly PhongMaterial Chrome = new PhongMaterial { Name = "Chrome", AmbientColor = ToColor(0.25f, 0.25f, 0.25f, 1.0f), DiffuseColor = ToColor(0.4f, 0.4f, 0.4f, 1.0f), SpecularColor = ToColor(0.774597f, 0.774597f, 0.774597f, 1.0f), EmissiveColor = ToColor(0f, 0f, 0f, 0f), SpecularShininess = 76.8f, }.Clone(); public static readonly PhongMaterial Copper = new PhongMaterial { Name = "Copper", AmbientColor = ToColor(0.19125, 0.0735, 0.0225, 1.0), DiffuseColor = ToColor(0.7038, 0.27048, 0.0828, 1.0), SpecularColor = ToColor(0.256777, 0.137622, 0.086014, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial PolishedCopper = new PhongMaterial { Name = "PolishedCopper", AmbientColor = ToColor(0.2295, 0.08825, 0.0275, 1.0), DiffuseColor = ToColor(0.5508, 0.2118, 0.066, 1.0), SpecularColor = ToColor(0.580594, 0.223257, 0.0695701, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 51.2f, }.Clone(); public static readonly PhongMaterial Gold = new PhongMaterial { Name = "Gold", AmbientColor = ToColor(0.24725, 0.1995, 0.0745, 1.0), DiffuseColor = ToColor(0.75164, 0.60648, 0.22648, 1.0), SpecularColor = ToColor(0.628281, 0.555802, 0.366065, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 51.2f, }.Clone(); public static readonly PhongMaterial PolishedGold = new PhongMaterial { Name = "PolishedGold", AmbientColor = ToColor(0.24725, 0.2245, 0.0645, 1.0), DiffuseColor = ToColor(0.34615, 0.3143, 0.0903, 1.0), SpecularColor = ToColor(0.797357, 0.723991, 0.208006, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 83.2f, }.Clone(); public static readonly PhongMaterial Pewter = new PhongMaterial { Name = "Pewter", AmbientColor = ToColor(0.105882, 0.058824, 0.113725, 1.0), DiffuseColor = ToColor(0.427451, 0.470588, 0.541176, 1.0), SpecularColor = ToColor(0.333333, 0.333333, 0.521569, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 9.84615f, }.Clone(); public static readonly PhongMaterial Silver = new PhongMaterial { Name = "Silver", AmbientColor = ToColor(0.19225, 0.19225, 0.19225, 1.0), DiffuseColor = ToColor(0.50754, 0.50754, 0.50754, 1.0), SpecularColor = ToColor(0.508273, 0.508273, 0.508273, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 51.2f, }.Clone(); public static readonly PhongMaterial PolishedSilver = new PhongMaterial { Name = "PolishedSilver", AmbientColor = ToColor(0.23125, 0.23125, 0.23125, 1.0), DiffuseColor = ToColor(0.2775, 0.2775, 0.2775, 1.0), SpecularColor = ToColor(0.773911, 0.773911, 0.773911, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 89.6f, }.Clone(); public static readonly PhongMaterial Emerald = new PhongMaterial { Name = "Emerald", AmbientColor = ToColor(0.0215, 0.1745, 0.0215, 0.55), DiffuseColor = ToColor(0.07568, 0.61424, 0.07568, 0.55), SpecularColor = ToColor(0.633, 0.727811, 0.633, 0.55), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 76.8f, }.Clone(); public static readonly PhongMaterial Jade = new PhongMaterial { Name = "Jade", AmbientColor = ToColor(0.135, 0.2225, 0.1575, 0.95), DiffuseColor = ToColor(0.54, 0.89, 0.63, 0.95), SpecularColor = ToColor(0.316228, 0.316228, 0.316228, 0.95), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial Obsidian = new PhongMaterial { Name = "Obsidian", AmbientColor = ToColor(0.05375, 0.05, 0.06625, 0.82), DiffuseColor = ToColor(0.18275, 0.17, 0.22525, 0.82), SpecularColor = ToColor(0.332741, 0.328634, 0.346435, 0.82), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 38.4f, }.Clone(); public static readonly PhongMaterial Pearl = new PhongMaterial { Name = "Pearl", AmbientColor = ToColor(0.25, 0.20725, 0.20725, 0.922), DiffuseColor = ToColor(1.0, 0.829, 0.829, 0.922), SpecularColor = ToColor(0.296648, 0.296648, 0.296648, 0.922), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 11.264f, }.Clone(); public static readonly PhongMaterial Ruby = new PhongMaterial { Name = "Ruby", AmbientColor = ToColor(0.1745, 0.01175, 0.01175, 0.55), DiffuseColor = ToColor(0.61424, 0.04136, 0.04136, 0.55), SpecularColor = ToColor(0.727811, 0.626959, 0.626959, 0.55), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 76.8f, }.Clone(); public static readonly PhongMaterial Turquoise = new PhongMaterial { Name = "Turquoise", AmbientColor = ToColor(0.1, 0.18725, 0.1745, 0.8), DiffuseColor = ToColor(0.396, 0.74151, 0.69102, 0.8), SpecularColor = ToColor(0.297254, 0.30829, 0.306678, 0.8), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 12.8f, }.Clone(); public static readonly PhongMaterial BlackPlastic = new PhongMaterial { Name = "BlackPlastic", AmbientColor = ToColor(0.0, 0.0, 0.0, 1.0), DiffuseColor = ToColor(0.01, 0.01, 0.01, 1.0), SpecularColor = ToColor(0.50, 0.50, 0.50, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 32f, }.Clone(); public static readonly PhongMaterial BlackRubber = new PhongMaterial { Name = "BlackRubber", AmbientColor = ToColor(0.02, 0.02, 0.02, 1.0), DiffuseColor = ToColor(0.01, 0.01, 0.01, 1.0), SpecularColor = ToColor(0.4, 0.4, 0.4, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 0.0), SpecularShininess = 10f, }.Clone(); public static readonly PhongMaterial DefaultVRML = new PhongMaterial { Name = "DefaultVRML", AmbientColor = ToColor(0.2, 0.2, 0.2, 1.0), DiffuseColor = ToColor(0.8, 0.8, 0.8, 1.0), SpecularColor = ToColor(0.0, 0.0, 0.0, 1.0), EmissiveColor = ToColor(0.0, 0.0, 0.0, 1.0), SpecularShininess = 25.6f, }.Clone(); } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Net.NetworkInformation { public enum DuplicateAddressDetectionState { Deprecated = 3, Duplicate = 2, Invalid = 0, Preferred = 4, Tentative = 1, } public abstract partial class GatewayIPAddressInformation { protected GatewayIPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } } public partial class GatewayIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.IEnumerable { protected internal GatewayIPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.GatewayIPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.GatewayIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.GatewayIPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.GatewayIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.GatewayIPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class IcmpV4Statistics { protected IcmpV4Statistics() { } public abstract long AddressMaskRepliesReceived { get; } public abstract long AddressMaskRepliesSent { get; } public abstract long AddressMaskRequestsReceived { get; } public abstract long AddressMaskRequestsSent { get; } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long SourceQuenchesReceived { get; } public abstract long SourceQuenchesSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } public abstract long TimestampRepliesReceived { get; } public abstract long TimestampRepliesSent { get; } public abstract long TimestampRequestsReceived { get; } public abstract long TimestampRequestsSent { get; } } public abstract partial class IcmpV6Statistics { protected IcmpV6Statistics() { } public abstract long DestinationUnreachableMessagesReceived { get; } public abstract long DestinationUnreachableMessagesSent { get; } public abstract long EchoRepliesReceived { get; } public abstract long EchoRepliesSent { get; } public abstract long EchoRequestsReceived { get; } public abstract long EchoRequestsSent { get; } public abstract long ErrorsReceived { get; } public abstract long ErrorsSent { get; } public abstract long MembershipQueriesReceived { get; } public abstract long MembershipQueriesSent { get; } public abstract long MembershipReductionsReceived { get; } public abstract long MembershipReductionsSent { get; } public abstract long MembershipReportsReceived { get; } public abstract long MembershipReportsSent { get; } public abstract long MessagesReceived { get; } public abstract long MessagesSent { get; } public abstract long NeighborAdvertisementsReceived { get; } public abstract long NeighborAdvertisementsSent { get; } public abstract long NeighborSolicitsReceived { get; } public abstract long NeighborSolicitsSent { get; } public abstract long PacketTooBigMessagesReceived { get; } public abstract long PacketTooBigMessagesSent { get; } public abstract long ParameterProblemsReceived { get; } public abstract long ParameterProblemsSent { get; } public abstract long RedirectsReceived { get; } public abstract long RedirectsSent { get; } public abstract long RouterAdvertisementsReceived { get; } public abstract long RouterAdvertisementsSent { get; } public abstract long RouterSolicitsReceived { get; } public abstract long RouterSolicitsSent { get; } public abstract long TimeExceededMessagesReceived { get; } public abstract long TimeExceededMessagesSent { get; } } public abstract partial class IPAddressInformation { protected IPAddressInformation() { } public abstract System.Net.IPAddress Address { get; } public abstract bool IsDnsEligible { get; } public abstract bool IsTransient { get; } } public partial class IPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.IEnumerable { internal IPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.IPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.IPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.IPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.IPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.IPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class IPGlobalProperties { protected IPGlobalProperties() { } public abstract string DhcpScopeName { get; } public abstract string DomainName { get; } public abstract string HostName { get; } public abstract bool IsWinsProxy { get; } public abstract System.Net.NetworkInformation.NetBiosNodeType NodeType { get; } public virtual System.IAsyncResult BeginGetUnicastAddresses(System.AsyncCallback callback, object state) { throw null; } public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection EndGetUnicastAddresses(System.IAsyncResult asyncResult) { throw null; } public abstract System.Net.NetworkInformation.TcpConnectionInformation[] GetActiveTcpConnections(); public abstract System.Net.IPEndPoint[] GetActiveTcpListeners(); public abstract System.Net.IPEndPoint[] GetActiveUdpListeners(); public abstract System.Net.NetworkInformation.IcmpV4Statistics GetIcmpV4Statistics(); public abstract System.Net.NetworkInformation.IcmpV6Statistics GetIcmpV6Statistics(); public static System.Net.NetworkInformation.IPGlobalProperties GetIPGlobalProperties() { throw null; } public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv4GlobalStatistics(); public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv6GlobalStatistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv4Statistics(); public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv6Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv4Statistics(); public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv6Statistics(); public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection GetUnicastAddresses() { throw null; } public virtual System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection> GetUnicastAddressesAsync() { throw null; } } public abstract partial class IPGlobalStatistics { protected IPGlobalStatistics() { } public abstract int DefaultTtl { get; } public abstract bool ForwardingEnabled { get; } public abstract int NumberOfInterfaces { get; } public abstract int NumberOfIPAddresses { get; } public abstract int NumberOfRoutes { get; } public abstract long OutputPacketRequests { get; } public abstract long OutputPacketRoutingDiscards { get; } public abstract long OutputPacketsDiscarded { get; } public abstract long OutputPacketsWithNoRoute { get; } public abstract long PacketFragmentFailures { get; } public abstract long PacketReassembliesRequired { get; } public abstract long PacketReassemblyFailures { get; } public abstract long PacketReassemblyTimeout { get; } public abstract long PacketsFragmented { get; } public abstract long PacketsReassembled { get; } public abstract long ReceivedPackets { get; } public abstract long ReceivedPacketsDelivered { get; } public abstract long ReceivedPacketsDiscarded { get; } public abstract long ReceivedPacketsForwarded { get; } public abstract long ReceivedPacketsWithAddressErrors { get; } public abstract long ReceivedPacketsWithHeadersErrors { get; } public abstract long ReceivedPacketsWithUnknownProtocol { get; } } public abstract partial class IPInterfaceProperties { protected IPInterfaceProperties() { } public abstract System.Net.NetworkInformation.IPAddressInformationCollection AnycastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DhcpServerAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection DnsAddresses { get; } public abstract string DnsSuffix { get; } public abstract System.Net.NetworkInformation.GatewayIPAddressInformationCollection GatewayAddresses { get; } public abstract bool IsDnsEnabled { get; } public abstract bool IsDynamicDnsEnabled { get; } public abstract System.Net.NetworkInformation.MulticastIPAddressInformationCollection MulticastAddresses { get; } public abstract System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastAddresses { get; } public abstract System.Net.NetworkInformation.IPAddressCollection WinsServersAddresses { get; } public abstract System.Net.NetworkInformation.IPv4InterfaceProperties GetIPv4Properties(); public abstract System.Net.NetworkInformation.IPv6InterfaceProperties GetIPv6Properties(); } public abstract partial class IPInterfaceStatistics { protected IPInterfaceStatistics() { } public abstract long BytesReceived { get; } public abstract long BytesSent { get; } public abstract long IncomingPacketsDiscarded { get; } public abstract long IncomingPacketsWithErrors { get; } public abstract long IncomingUnknownProtocolPackets { get; } public abstract long NonUnicastPacketsReceived { get; } public abstract long NonUnicastPacketsSent { get; } public abstract long OutgoingPacketsDiscarded { get; } public abstract long OutgoingPacketsWithErrors { get; } public abstract long OutputQueueLength { get; } public abstract long UnicastPacketsReceived { get; } public abstract long UnicastPacketsSent { get; } } public abstract partial class IPv4InterfaceProperties { protected IPv4InterfaceProperties() { } public abstract int Index { get; } public abstract bool IsAutomaticPrivateAddressingActive { get; } public abstract bool IsAutomaticPrivateAddressingEnabled { get; } public abstract bool IsDhcpEnabled { get; } public abstract bool IsForwardingEnabled { get; } public abstract int Mtu { get; } public abstract bool UsesWins { get; } } public abstract partial class IPv4InterfaceStatistics { protected IPv4InterfaceStatistics() { } public abstract long BytesReceived { get; } public abstract long BytesSent { get; } public abstract long IncomingPacketsDiscarded { get; } public abstract long IncomingPacketsWithErrors { get; } public abstract long IncomingUnknownProtocolPackets { get; } public abstract long NonUnicastPacketsReceived { get; } public abstract long NonUnicastPacketsSent { get; } public abstract long OutgoingPacketsDiscarded { get; } public abstract long OutgoingPacketsWithErrors { get; } public abstract long OutputQueueLength { get; } public abstract long UnicastPacketsReceived { get; } public abstract long UnicastPacketsSent { get; } } public abstract partial class IPv6InterfaceProperties { protected IPv6InterfaceProperties() { } public abstract int Index { get; } public abstract int Mtu { get; } public virtual long GetScopeId(System.Net.NetworkInformation.ScopeLevel scopeLevel) { throw null; } } public abstract partial class MulticastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected MulticastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class MulticastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.IEnumerable { protected internal MulticastIPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.MulticastIPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.MulticastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.MulticastIPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.MulticastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.MulticastIPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public enum NetBiosNodeType { Broadcast = 1, Hybrid = 8, Mixed = 4, Peer2Peer = 2, Unknown = 0, } public delegate void NetworkAddressChangedEventHandler(object sender, System.EventArgs e); public delegate void NetworkAvailabilityChangedEventHandler(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e); public partial class NetworkAvailabilityEventArgs : System.EventArgs { internal NetworkAvailabilityEventArgs() { } public bool IsAvailable { get { throw null; } } } public partial class NetworkChange { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public NetworkChange() { } public static event System.Net.NetworkInformation.NetworkAddressChangedEventHandler NetworkAddressChanged { add { } remove { } } public static event System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { } remove { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public static void RegisterNetworkChange(System.Net.NetworkInformation.NetworkChange nc) { } } public partial class NetworkInformationException : System.ComponentModel.Win32Exception { public NetworkInformationException() { } public NetworkInformationException(int errorCode) { } protected NetworkInformationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { } public override int ErrorCode { get { throw null; } } } public abstract partial class NetworkInterface { protected NetworkInterface() { } public virtual string Description { get { throw null; } } public virtual string Id { get { throw null; } } public static int IPv6LoopbackInterfaceIndex { get { throw null; } } public virtual bool IsReceiveOnly { get { throw null; } } public static int LoopbackInterfaceIndex { get { throw null; } } public virtual string Name { get { throw null; } } public virtual System.Net.NetworkInformation.NetworkInterfaceType NetworkInterfaceType { get { throw null; } } public virtual System.Net.NetworkInformation.OperationalStatus OperationalStatus { get { throw null; } } public virtual long Speed { get { throw null; } } public virtual bool SupportsMulticast { get { throw null; } } public static System.Net.NetworkInformation.NetworkInterface[] GetAllNetworkInterfaces() { throw null; } public virtual System.Net.NetworkInformation.IPInterfaceProperties GetIPProperties() { throw null; } public virtual System.Net.NetworkInformation.IPInterfaceStatistics GetIPStatistics() { throw null; } public virtual System.Net.NetworkInformation.IPv4InterfaceStatistics GetIPv4Statistics() { throw null; } public static bool GetIsNetworkAvailable() { throw null; } public virtual System.Net.NetworkInformation.PhysicalAddress GetPhysicalAddress() { throw null; } public virtual bool Supports(System.Net.NetworkInformation.NetworkInterfaceComponent networkInterfaceComponent) { throw null; } } public enum NetworkInterfaceComponent { IPv4 = 0, IPv6 = 1, } public enum NetworkInterfaceType { AsymmetricDsl = 94, Atm = 37, BasicIsdn = 20, Ethernet = 6, Ethernet3Megabit = 26, FastEthernetFx = 69, FastEthernetT = 62, Fddi = 15, GenericModem = 48, GigabitEthernet = 117, HighPerformanceSerialBus = 144, IPOverAtm = 114, Isdn = 63, Loopback = 24, MultiRateSymmetricDsl = 143, Ppp = 23, PrimaryIsdn = 21, RateAdaptDsl = 95, Slip = 28, SymmetricDsl = 96, TokenRing = 9, Tunnel = 131, Unknown = 1, VeryHighSpeedDsl = 97, Wireless80211 = 71, Wman = 237, Wwanpp = 243, Wwanpp2 = 244, } public enum OperationalStatus { Dormant = 5, Down = 2, LowerLayerDown = 7, NotPresent = 6, Testing = 3, Unknown = 4, Up = 1, } public partial class PhysicalAddress { public static readonly System.Net.NetworkInformation.PhysicalAddress None; public PhysicalAddress(byte[] address) { } public override bool Equals(object comparand) { throw null; } public byte[] GetAddressBytes() { throw null; } public override int GetHashCode() { throw null; } public static System.Net.NetworkInformation.PhysicalAddress Parse(string address) { throw null; } public override string ToString() { throw null; } } public enum PrefixOrigin { Dhcp = 3, Manual = 1, Other = 0, RouterAdvertisement = 4, WellKnown = 2, } public enum ScopeLevel { Admin = 4, Global = 14, Interface = 1, Link = 2, None = 0, Organization = 8, Site = 5, Subnet = 3, } public enum SuffixOrigin { LinkLayerAddress = 4, Manual = 1, OriginDhcp = 3, Other = 0, Random = 5, WellKnown = 2, } public abstract partial class TcpConnectionInformation { protected TcpConnectionInformation() { } public abstract System.Net.IPEndPoint LocalEndPoint { get; } public abstract System.Net.IPEndPoint RemoteEndPoint { get; } public abstract System.Net.NetworkInformation.TcpState State { get; } } public enum TcpState { Closed = 1, CloseWait = 8, Closing = 9, DeleteTcb = 12, Established = 5, FinWait1 = 6, FinWait2 = 7, LastAck = 10, Listen = 2, SynReceived = 4, SynSent = 3, TimeWait = 11, Unknown = 0, } public abstract partial class TcpStatistics { protected TcpStatistics() { } public abstract long ConnectionsAccepted { get; } public abstract long ConnectionsInitiated { get; } public abstract long CumulativeConnections { get; } public abstract long CurrentConnections { get; } public abstract long ErrorsReceived { get; } public abstract long FailedConnectionAttempts { get; } public abstract long MaximumConnections { get; } public abstract long MaximumTransmissionTimeout { get; } public abstract long MinimumTransmissionTimeout { get; } public abstract long ResetConnections { get; } public abstract long ResetsSent { get; } public abstract long SegmentsReceived { get; } public abstract long SegmentsResent { get; } public abstract long SegmentsSent { get; } } public abstract partial class UdpStatistics { protected UdpStatistics() { } public abstract long DatagramsReceived { get; } public abstract long DatagramsSent { get; } public abstract long IncomingDatagramsDiscarded { get; } public abstract long IncomingDatagramsWithErrors { get; } public abstract int UdpListeners { get; } } public abstract partial class UnicastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation { protected UnicastIPAddressInformation() { } public abstract long AddressPreferredLifetime { get; } public abstract long AddressValidLifetime { get; } public abstract long DhcpLeaseLifetime { get; } public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; } public abstract System.Net.IPAddress IPv4Mask { get; } public virtual int PrefixLength { get { throw null; } } public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; } public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; } } public partial class UnicastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.IEnumerable { protected internal UnicastIPAddressInformationCollection() { } public virtual int Count { get { throw null; } } public virtual bool IsReadOnly { get { throw null; } } public virtual System.Net.NetworkInformation.UnicastIPAddressInformation this[int index] { get { throw null; } } public virtual void Add(System.Net.NetworkInformation.UnicastIPAddressInformation address) { } public virtual void Clear() { } public virtual bool Contains(System.Net.NetworkInformation.UnicastIPAddressInformation address) { throw null; } public virtual void CopyTo(System.Net.NetworkInformation.UnicastIPAddressInformation[] array, int offset) { } public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation> GetEnumerator() { throw null; } public virtual bool Remove(System.Net.NetworkInformation.UnicastIPAddressInformation address) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Operations; namespace IronPython.Compiler { public delegate object CallTarget0(); internal static class PythonCallTargets { public static object OriginalCallTargetN(PythonFunction function, params object[] args) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object[], object>)function.__code__.Target)(function, args); } #region Generated Python Lazy Call Targets // *** BEGIN GENERATED CODE *** // generated by function: gen_lazy_call_targets from: generate_calls.py public static object OriginalCallTarget0(PythonFunction function) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object>)function.__code__.Target)(function); } public static object OriginalCallTarget1(PythonFunction function, object arg0) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object>)function.__code__.Target)(function, arg0); } public static object OriginalCallTarget2(PythonFunction function, object arg0, object arg1) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object>)function.__code__.Target)(function, arg0, arg1); } public static object OriginalCallTarget3(PythonFunction function, object arg0, object arg1, object arg2) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2); } public static object OriginalCallTarget4(PythonFunction function, object arg0, object arg1, object arg2, object arg3) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3); } public static object OriginalCallTarget5(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4); } public static object OriginalCallTarget6(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5); } public static object OriginalCallTarget7(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6); } public static object OriginalCallTarget8(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } public static object OriginalCallTarget9(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } public static object OriginalCallTarget10(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } public static object OriginalCallTarget11(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } public static object OriginalCallTarget12(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } public static object OriginalCallTarget13(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } public static object OriginalCallTarget14(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } public static object OriginalCallTarget15(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) { function.__code__.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.__code__.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } // *** END GENERATED CODE *** #endregion public const int MaxArgs = 15; internal static Type GetPythonTargetType(bool wrapper, int parameters, out Delegate originalTarget) { if (!wrapper) { switch (parameters) { #region Generated Python Call Target Switch // *** BEGIN GENERATED CODE *** // generated by function: gen_python_switch from: generate_calls.py case 0: originalTarget = (Func<PythonFunction, object>)OriginalCallTarget0; return typeof(Func<PythonFunction, object>); case 1: originalTarget = (Func<PythonFunction, object, object>)OriginalCallTarget1; return typeof(Func<PythonFunction, object, object>); case 2: originalTarget = (Func<PythonFunction, object, object, object>)OriginalCallTarget2; return typeof(Func<PythonFunction, object, object, object>); case 3: originalTarget = (Func<PythonFunction, object, object, object, object>)OriginalCallTarget3; return typeof(Func<PythonFunction, object, object, object, object>); case 4: originalTarget = (Func<PythonFunction, object, object, object, object, object>)OriginalCallTarget4; return typeof(Func<PythonFunction, object, object, object, object, object>); case 5: originalTarget = (Func<PythonFunction, object, object, object, object, object, object>)OriginalCallTarget5; return typeof(Func<PythonFunction, object, object, object, object, object, object>); case 6: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object>)OriginalCallTarget6; return typeof(Func<PythonFunction, object, object, object, object, object, object, object>); case 7: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object>)OriginalCallTarget7; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object>); case 8: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object>)OriginalCallTarget8; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object>); case 9: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget9; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>); case 10: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget10; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>); case 11: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget11; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>); case 12: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget12; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 13: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget13; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 14: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget14; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 15: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget15; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); // *** END GENERATED CODE *** #endregion } } originalTarget = (Func<PythonFunction, object[], object>)OriginalCallTargetN; return typeof(Func<PythonFunction, object[], object>); } } internal class PythonFunctionRecursionCheckN { private readonly Func<PythonFunction, object[], object> _target; public PythonFunctionRecursionCheckN(Func<PythonFunction, object[], object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object[] args) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, args); } finally { PythonOps.FunctionPopFrame(); } } } #region Generated Python Recursion Enforcement // *** BEGIN GENERATED CODE *** // generated by function: gen_recursion_checks from: generate_calls.py internal class PythonFunctionRecursionCheck0 { private readonly Func<PythonFunction, object> _target; public PythonFunctionRecursionCheck0(Func<PythonFunction, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck1 { private readonly Func<PythonFunction, object, object> _target; public PythonFunctionRecursionCheck1(Func<PythonFunction, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck2 { private readonly Func<PythonFunction, object, object, object> _target; public PythonFunctionRecursionCheck2(Func<PythonFunction, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck3 { private readonly Func<PythonFunction, object, object, object, object> _target; public PythonFunctionRecursionCheck3(Func<PythonFunction, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck4 { private readonly Func<PythonFunction, object, object, object, object, object> _target; public PythonFunctionRecursionCheck4(Func<PythonFunction, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck5 { private readonly Func<PythonFunction, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck5(Func<PythonFunction, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck6 { private readonly Func<PythonFunction, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck6(Func<PythonFunction, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck7 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck7(Func<PythonFunction, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck8 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck8(Func<PythonFunction, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck9 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck9(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck10 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck10(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck11 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck11(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck12 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck12(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck13 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck13(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck14 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck14(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck15 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck15(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } finally { PythonOps.FunctionPopFrame(); } } } // *** END GENERATED CODE *** #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; namespace Microsoft.Scripting.Utils { public static class TypeUtils { public static bool IsNested(this Type t) { return t.DeclaringType != null; } internal static Type GetNonNullableType(this Type type) => IsNullableType(type) ? type.GetGenericArguments()[0] : type; internal static Type GetNullableType(this Type type) { Debug.Assert(type != null, "type cannot be null"); if (type.IsValueType && !IsNullableType(type)) { return typeof(Nullable<>).MakeGenericType(type); } return type; } internal static bool IsNullableType(this Type type) => type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); internal static bool IsBool(this Type type) => GetNonNullableType(type) == typeof(bool); internal static bool IsNumeric(this Type type) { type = GetNonNullableType(type); if (!type.IsEnum) { return IsNumeric(type.GetTypeCode()); } return false; } internal static bool IsNumeric(TypeCode typeCode) { switch (typeCode) { case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Double: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; } return false; } internal static bool IsArithmetic(this Type type) { type = GetNonNullableType(type); if (!type.IsEnum) { switch (type.GetTypeCode()) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Double: case TypeCode.Single: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; } } return false; } internal static bool IsUnsignedInt(this Type type) { type = GetNonNullableType(type); if (!type.IsEnum) { switch (type.GetTypeCode()) { case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return true; } } return false; } internal static bool IsIntegerOrBool(this Type type) { type = GetNonNullableType(type); if (!type.IsEnum) { switch (type.GetTypeCode()) { case TypeCode.Int64: case TypeCode.Int32: case TypeCode.Int16: case TypeCode.UInt64: case TypeCode.UInt32: case TypeCode.UInt16: case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: return true; } } return false; } internal static bool CanAssign(Type to, Expression from) { if (CanAssign(to, from.Type)) return true; if (to.IsValueType && to.IsGenericType && to.GetGenericTypeDefinition() == typeof(Nullable<>) && ConstantCheck.Check(from, null)) { return true; } return false; } internal static bool CanAssign(Type to, Type from) { if (to == from) { return true; } // Reference types if (!to.IsValueType && !from.IsValueType) { if (to.IsAssignableFrom(from)) { return true; } // Arrays can be assigned if they have same rank and assignable element types. if (to.IsArray && from.IsArray && to.GetArrayRank() == from.GetArrayRank() && CanAssign(to.GetElementType(), from.GetElementType())) { return true; } } return false; } internal static bool IsGeneric(Type type) => type.ContainsGenericParameters || type.IsGenericTypeDefinition; internal static bool CanCompareToNull(Type type) { // This is a bit too conservative. return !type.IsValueType; } /// <summary> /// Returns a numerical code of the size of a type. All types get both a horizontal /// and vertical code. Types that are lower in both dimensions have implicit conversions /// to types that are higher in both dimensions. /// </summary> internal static bool GetNumericConversionOrder(TypeCode code, out int x, out int y) { // implicit conversions: // 0 1 2 3 4 // 0: U1 -> U2 -> U4 -> U8 // | | | // v v v // 1: I1 -> I2 -> I4 -> I8 // | | // v v // 2: R4 -> R8 switch (code) { case TypeCode.Byte: x = 0; y = 0; break; case TypeCode.UInt16: x = 1; y = 0; break; case TypeCode.UInt32: x = 2; y = 0; break; case TypeCode.UInt64: x = 3; y = 0; break; case TypeCode.SByte: x = 0; y = 1; break; case TypeCode.Int16: x = 1; y = 1; break; case TypeCode.Int32: x = 2; y = 1; break; case TypeCode.Int64: x = 3; y = 1; break; case TypeCode.Single: x = 1; y = 2; break; case TypeCode.Double: x = 2; y = 2; break; default: x = y = 0; return false; } return true; } internal static bool IsImplicitlyConvertible(int fromX, int fromY, int toX, int toY) { return fromX <= toX && fromY <= toY; } internal static bool HasBuiltinEquality(Type left, Type right) { // Reference type can be compared to interfaces if (left.IsInterface && !right.IsValueType || right.IsInterface && !left.IsValueType) { return true; } // Reference types compare if they are assignable if (!left.IsValueType && !right.IsValueType) { if (CanAssign(left, right) || CanAssign(right, left)) { return true; } } // Nullable<T> vs null if (NullVsNullable(left, right) || NullVsNullable(right, left)) { return true; } if (left != right) { return false; } if (left == typeof(bool) || IsNumeric(left) || left.IsEnum) { return true; } return false; } private static bool NullVsNullable(Type left, Type right) { return IsNullableType(left) && right == typeof(DynamicNull); } // keep in sync with System.Core version internal static bool AreEquivalent(Type t1, Type t2) { #if FEATURE_TYPE_EQUIVALENCE return t1 == t2 || t1.IsEquivalentTo(t2); #else return t1 == t2; #endif } // keep in sync with System.Core version internal static bool AreReferenceAssignable(Type dest, Type src) { // WARNING: This actually implements "Is this identity assignable and/or reference assignable?" if (dest == src) { return true; } if (!dest.IsValueType && !src.IsValueType && AreAssignable(dest, src)) { return true; } return false; } // keep in sync with System.Core version internal static bool AreAssignable(Type dest, Type src) { if (dest == src) { return true; } if (dest.IsAssignableFrom(src)) { return true; } if (dest.IsArray && src.IsArray && dest.GetArrayRank() == src.GetArrayRank() && AreReferenceAssignable(dest.GetElementType(), src.GetElementType())) { return true; } if (src.IsArray && dest.IsGenericType && (dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IList<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>)) && dest.GetGenericArguments()[0] == src.GetElementType()) { return true; } return false; } // keep in sync with System.Core version internal static Type GetConstantType(Type type) { // If it's a visible type, we're done if (type.IsVisible) { return type; } // Get the visible base type Type bt = type; do { bt = bt.BaseType; } while (!bt.IsVisible); // If it's one of the known reflection types, // return the known type. if (bt == typeof(Type) || bt == typeof(ConstructorInfo) || bt == typeof(EventInfo) || bt == typeof(FieldInfo) || bt == typeof(MethodInfo) || bt == typeof(PropertyInfo)) { return bt; } // else return the original type return type; } internal static bool IsConvertible(Type type) { type = GetNonNullableType(type); if (type.IsEnum) { return true; } switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Char: return true; default: return false; } } internal static bool IsFloatingPoint(Type type) { type = GetNonNullableType(type); switch (type.GetTypeCode()) { case TypeCode.Single: case TypeCode.Double: return true; default: return false; } } #if FEATURE_COM public static readonly Type ComObjectType = typeof(object).Assembly.GetType("System.__ComObject"); public static bool IsComObjectType(Type/*!*/ type) { return ComObjectType?.IsAssignableFrom(type) ?? false; } // we can't use System.Runtime.InteropServices.Marshal.IsComObject(obj) since it doesn't work in partial trust public static bool IsComObject(object obj) { #if NETCOREAPP || NETSTANDARD return obj != null && Marshal.IsComObject(obj); #else return obj != null && IsComObjectType(obj.GetType()); #endif } #else public static bool IsComObjectType(Type/*!*/ type) { return false; } public static bool IsComObject(object obj) { return false; } #endif } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Family Invoice Allocations Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class STSBDataSet : EduHubDataSet<STSB> { /// <inheritdoc /> public override string Name { get { return "STSB"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal STSBDataSet(EduHubContext Context) : base(Context) { Index_FAMILY = new Lazy<NullDictionary<string, IReadOnlyList<STSB>>>(() => this.ToGroupedNullDictionary(i => i.FAMILY)); Index_SKEY = new Lazy<Dictionary<string, IReadOnlyList<STSB>>>(() => this.ToGroupedDictionary(i => i.SKEY)); Index_SPLIT_ITEM = new Lazy<NullDictionary<string, IReadOnlyList<STSB>>>(() => this.ToGroupedNullDictionary(i => i.SPLIT_ITEM)); Index_TID = new Lazy<Dictionary<int, STSB>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="STSB" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="STSB" /> fields for each CSV column header</returns> internal override Action<STSB, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<STSB, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "SKEY": mapper[i] = (e, v) => e.SKEY = v; break; case "FAMILY": mapper[i] = (e, v) => e.FAMILY = v; break; case "PERCENTAGE": mapper[i] = (e, v) => e.PERCENTAGE = v == null ? (short?)null : short.Parse(v); break; case "SPLIT_ITEM": mapper[i] = (e, v) => e.SPLIT_ITEM = v; break; case "ITEM_TYPE": mapper[i] = (e, v) => e.ITEM_TYPE = v; break; case "SPLIT_ITEM_SU": mapper[i] = (e, v) => e.SPLIT_ITEM_SU = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="STSB" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="STSB" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="STSB" /> entities</param> /// <returns>A merged <see cref="IEnumerable{STSB}"/> of entities</returns> internal override IEnumerable<STSB> ApplyDeltaEntities(IEnumerable<STSB> Entities, List<STSB> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.SKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.SKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<STSB>>> Index_FAMILY; private Lazy<Dictionary<string, IReadOnlyList<STSB>>> Index_SKEY; private Lazy<NullDictionary<string, IReadOnlyList<STSB>>> Index_SPLIT_ITEM; private Lazy<Dictionary<int, STSB>> Index_TID; #endregion #region Index Methods /// <summary> /// Find STSB by FAMILY field /// </summary> /// <param name="FAMILY">FAMILY value used to find STSB</param> /// <returns>List of related STSB entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STSB> FindByFAMILY(string FAMILY) { return Index_FAMILY.Value[FAMILY]; } /// <summary> /// Attempt to find STSB by FAMILY field /// </summary> /// <param name="FAMILY">FAMILY value used to find STSB</param> /// <param name="Value">List of related STSB entities</param> /// <returns>True if the list of related STSB entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByFAMILY(string FAMILY, out IReadOnlyList<STSB> Value) { return Index_FAMILY.Value.TryGetValue(FAMILY, out Value); } /// <summary> /// Attempt to find STSB by FAMILY field /// </summary> /// <param name="FAMILY">FAMILY value used to find STSB</param> /// <returns>List of related STSB entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STSB> TryFindByFAMILY(string FAMILY) { IReadOnlyList<STSB> value; if (Index_FAMILY.Value.TryGetValue(FAMILY, out value)) { return value; } else { return null; } } /// <summary> /// Find STSB by SKEY field /// </summary> /// <param name="SKEY">SKEY value used to find STSB</param> /// <returns>List of related STSB entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STSB> FindBySKEY(string SKEY) { return Index_SKEY.Value[SKEY]; } /// <summary> /// Attempt to find STSB by SKEY field /// </summary> /// <param name="SKEY">SKEY value used to find STSB</param> /// <param name="Value">List of related STSB entities</param> /// <returns>True if the list of related STSB entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySKEY(string SKEY, out IReadOnlyList<STSB> Value) { return Index_SKEY.Value.TryGetValue(SKEY, out Value); } /// <summary> /// Attempt to find STSB by SKEY field /// </summary> /// <param name="SKEY">SKEY value used to find STSB</param> /// <returns>List of related STSB entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STSB> TryFindBySKEY(string SKEY) { IReadOnlyList<STSB> value; if (Index_SKEY.Value.TryGetValue(SKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find STSB by SPLIT_ITEM field /// </summary> /// <param name="SPLIT_ITEM">SPLIT_ITEM value used to find STSB</param> /// <returns>List of related STSB entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STSB> FindBySPLIT_ITEM(string SPLIT_ITEM) { return Index_SPLIT_ITEM.Value[SPLIT_ITEM]; } /// <summary> /// Attempt to find STSB by SPLIT_ITEM field /// </summary> /// <param name="SPLIT_ITEM">SPLIT_ITEM value used to find STSB</param> /// <param name="Value">List of related STSB entities</param> /// <returns>True if the list of related STSB entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySPLIT_ITEM(string SPLIT_ITEM, out IReadOnlyList<STSB> Value) { return Index_SPLIT_ITEM.Value.TryGetValue(SPLIT_ITEM, out Value); } /// <summary> /// Attempt to find STSB by SPLIT_ITEM field /// </summary> /// <param name="SPLIT_ITEM">SPLIT_ITEM value used to find STSB</param> /// <returns>List of related STSB entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STSB> TryFindBySPLIT_ITEM(string SPLIT_ITEM) { IReadOnlyList<STSB> value; if (Index_SPLIT_ITEM.Value.TryGetValue(SPLIT_ITEM, out value)) { return value; } else { return null; } } /// <summary> /// Find STSB by TID field /// </summary> /// <param name="TID">TID value used to find STSB</param> /// <returns>Related STSB entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STSB FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find STSB by TID field /// </summary> /// <param name="TID">TID value used to find STSB</param> /// <param name="Value">Related STSB entity</param> /// <returns>True if the related STSB entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out STSB Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find STSB by TID field /// </summary> /// <param name="TID">TID value used to find STSB</param> /// <returns>Related STSB entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STSB TryFindByTID(int TID) { STSB value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a STSB table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STSB]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[STSB]( [TID] int IDENTITY NOT NULL, [SKEY] varchar(10) NOT NULL, [FAMILY] varchar(10) NULL, [PERCENTAGE] smallint NULL, [SPLIT_ITEM] varchar(10) NULL, [ITEM_TYPE] varchar(1) NULL, [SPLIT_ITEM_SU] varchar(5) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [STSB_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [STSB_Index_FAMILY] ON [dbo].[STSB] ( [FAMILY] ASC ); CREATE CLUSTERED INDEX [STSB_Index_SKEY] ON [dbo].[STSB] ( [SKEY] ASC ); CREATE NONCLUSTERED INDEX [STSB_Index_SPLIT_ITEM] ON [dbo].[STSB] ( [SPLIT_ITEM] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STSB]') AND name = N'STSB_Index_FAMILY') ALTER INDEX [STSB_Index_FAMILY] ON [dbo].[STSB] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STSB]') AND name = N'STSB_Index_SPLIT_ITEM') ALTER INDEX [STSB_Index_SPLIT_ITEM] ON [dbo].[STSB] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STSB]') AND name = N'STSB_Index_TID') ALTER INDEX [STSB_Index_TID] ON [dbo].[STSB] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STSB]') AND name = N'STSB_Index_FAMILY') ALTER INDEX [STSB_Index_FAMILY] ON [dbo].[STSB] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STSB]') AND name = N'STSB_Index_SPLIT_ITEM') ALTER INDEX [STSB_Index_SPLIT_ITEM] ON [dbo].[STSB] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STSB]') AND name = N'STSB_Index_TID') ALTER INDEX [STSB_Index_TID] ON [dbo].[STSB] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STSB"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="STSB"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STSB> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[STSB] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the STSB data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STSB data set</returns> public override EduHubDataSetDataReader<STSB> GetDataSetDataReader() { return new STSBDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the STSB data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STSB data set</returns> public override EduHubDataSetDataReader<STSB> GetDataSetDataReader(List<STSB> Entities) { return new STSBDataReader(new EduHubDataSetLoadedReader<STSB>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class STSBDataReader : EduHubDataSetDataReader<STSB> { public STSBDataReader(IEduHubDataSetReader<STSB> Reader) : base (Reader) { } public override int FieldCount { get { return 10; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // SKEY return Current.SKEY; case 2: // FAMILY return Current.FAMILY; case 3: // PERCENTAGE return Current.PERCENTAGE; case 4: // SPLIT_ITEM return Current.SPLIT_ITEM; case 5: // ITEM_TYPE return Current.ITEM_TYPE; case 6: // SPLIT_ITEM_SU return Current.SPLIT_ITEM_SU; case 7: // LW_DATE return Current.LW_DATE; case 8: // LW_TIME return Current.LW_TIME; case 9: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // FAMILY return Current.FAMILY == null; case 3: // PERCENTAGE return Current.PERCENTAGE == null; case 4: // SPLIT_ITEM return Current.SPLIT_ITEM == null; case 5: // ITEM_TYPE return Current.ITEM_TYPE == null; case 6: // SPLIT_ITEM_SU return Current.SPLIT_ITEM_SU == null; case 7: // LW_DATE return Current.LW_DATE == null; case 8: // LW_TIME return Current.LW_TIME == null; case 9: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // SKEY return "SKEY"; case 2: // FAMILY return "FAMILY"; case 3: // PERCENTAGE return "PERCENTAGE"; case 4: // SPLIT_ITEM return "SPLIT_ITEM"; case 5: // ITEM_TYPE return "ITEM_TYPE"; case 6: // SPLIT_ITEM_SU return "SPLIT_ITEM_SU"; case 7: // LW_DATE return "LW_DATE"; case 8: // LW_TIME return "LW_TIME"; case 9: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "SKEY": return 1; case "FAMILY": return 2; case "PERCENTAGE": return 3; case "SPLIT_ITEM": return 4; case "ITEM_TYPE": return 5; case "SPLIT_ITEM_SU": return 6; case "LW_DATE": return 7; case "LW_TIME": return 8; case "LW_USER": return 9; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2010, Nathan Brown // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using FluentMigrator.Expressions; using FluentMigrator.Runner; using FluentMigrator.Runner.Announcers; using FluentMigrator.Runner.Generators.SqlServer; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.Processors.Firebird; using FluentMigrator.Runner.Processors.MySql; using FluentMigrator.Runner.Processors.Postgres; using FluentMigrator.Runner.Processors.SQLite; using FluentMigrator.Runner.Processors.SqlServer; using FluentMigrator.Tests.Integration.Migrations; using FluentMigrator.Tests.Integration.Migrations.Tagged; using FluentMigrator.Tests.Unit; using FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass3; using Moq; using NUnit.Framework; using NUnit.Should; namespace FluentMigrator.Tests.Integration { [TestFixture] [Category("Integration")] public class MigrationRunnerTests : IntegrationTestBase { private IRunnerContext _runnerContext; [SetUp] public void SetUp() { _runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = "FluentMigrator.Tests.Integration.Migrations" }; } [Test] public void CanRunMigration() { ExecuteWithSupportedProcessors(processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.TableExists(null, "TestTable").ShouldBeTrue(); // This is a hack until MigrationVersionRunner and MigrationRunner are refactored and merged together //processor.CommitTransaction(); runner.Down(new TestCreateAndDropTableMigration()); processor.TableExists(null, "TestTable").ShouldBeFalse(); }); } [Test] public void CanSilentlyFail() { try { var processorOptions = new Mock<IMigrationProcessorOptions>(); processorOptions.SetupGet(x => x.PreviewOnly).Returns(false); var processor = new Mock<IMigrationProcessor>(); processor.Setup(x => x.Process(It.IsAny<CreateForeignKeyExpression>())).Throws(new Exception("Error")); processor.Setup(x => x.Process(It.IsAny<DeleteForeignKeyExpression>())).Throws(new Exception("Error")); processor.Setup(x => x.Options).Returns(processorOptions.Object); var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor.Object) { SilentlyFail = true }; runner.Up(new TestForeignKeySilentFailure()); runner.CaughtExceptions.Count.ShouldBeGreaterThan(0); runner.Down(new TestForeignKeySilentFailure()); runner.CaughtExceptions.Count.ShouldBeGreaterThan(0); } finally { ExecuteWithSupportedProcessors(processor => { MigrationRunner testRunner = SetupMigrationRunner(processor); testRunner.RollbackToVersion(0); }, false); } } [Test] public void CanApplyForeignKeyConvention() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestForeignKeyNamingConvention()); processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue(); runner.Down(new TestForeignKeyNamingConvention()); processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeFalse(); }, false, typeof(SQLiteProcessor)); } [Test] public void CanApplyForeignKeyConventionWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestForeignKeyNamingConventionWithSchema()); processor.ConstraintExists("TestSchema", "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue(); runner.Down(new TestForeignKeyNamingConventionWithSchema()); }, false, new []{typeof(SQLiteProcessor), typeof(FirebirdProcessor)}); } [Test] public void CanApplyIndexConvention() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestIndexNamingConvention()); processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeTrue(); processor.TableExists(null, "Users").ShouldBeTrue(); runner.Down(new TestIndexNamingConvention()); processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeFalse(); processor.TableExists(null, "Users").ShouldBeFalse(); }); } [Test] public void CanApplyIndexConventionWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestIndexNamingConventionWithSchema()); processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeTrue(); processor.TableExists("TestSchema", "Users").ShouldBeTrue(); runner.Down(new TestIndexNamingConventionWithSchema()); processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeFalse(); processor.TableExists("TestSchema", "Users").ShouldBeFalse(); }); } [Test] public void CanCreateAndDropIndex() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Up(new TestCreateAndDropIndexMigration()); processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeTrue(); runner.Down(new TestCreateAndDropIndexMigration()); processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigration()); processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse(); //processor.CommitTransaction(); }); } [Test] public void CanCreateAndDropIndexWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Up(new TestCreateAndDropIndexMigrationWithSchema()); processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeTrue(); runner.Down(new TestCreateAndDropIndexMigrationWithSchema()); processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse(); runner.Down(new TestCreateSchema()); //processor.CommitTransaction(); }, false, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] public void CanRenameTable() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.TableExists(null, "TestTable2").ShouldBeTrue(); runner.Up(new TestRenameTableMigration()); processor.TableExists(null, "TestTable2").ShouldBeFalse(); processor.TableExists(null, "TestTable'3").ShouldBeTrue(); runner.Down(new TestRenameTableMigration()); processor.TableExists(null, "TestTable'3").ShouldBeFalse(); processor.TableExists(null, "TestTable2").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigration()); processor.TableExists(null, "TestTable2").ShouldBeFalse(); //processor.CommitTransaction(); }); } [Test] public void CanRenameTableWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue(); runner.Up(new TestRenameTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse(); processor.TableExists("TestSchema", "TestTable'3").ShouldBeTrue(); runner.Down(new TestRenameTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable'3").ShouldBeFalse(); processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse(); runner.Down(new TestCreateSchema()); //processor.CommitTransaction(); }); } [Test] public void CanRenameColumn() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue(); runner.Up(new TestRenameColumnMigration()); processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse(); processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeTrue(); runner.Down(new TestRenameColumnMigration()); processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeFalse(); processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigration()); processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse(); }, true, typeof(SQLiteProcessor)); } [Test] public void CanRenameColumnWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue(); runner.Up(new TestRenameColumnMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse(); processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeTrue(); runner.Down(new TestRenameColumnMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeFalse(); processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse(); runner.Down(new TestCreateSchema()); }, true, typeof(SQLiteProcessor), typeof(FirebirdProcessor)); } [Test] public void CanLoadMigrations() { ExecuteWithSupportedProcessors(processor => { var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(TestMigration).Namespace, }; var runner = new MigrationRunner(typeof(MigrationRunnerTests).Assembly, runnerContext, processor); //runner.Processor.CommitTransaction(); runner.MigrationLoader.LoadMigrations().ShouldNotBeNull(); }); } [Test] public void CanLoadVersion() { ExecuteWithSupportedProcessors(processor => { var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(TestMigration).Namespace, }; var runner = new MigrationRunner(typeof(TestMigration).Assembly, runnerContext, processor); //runner.Processor.CommitTransaction(); runner.VersionLoader.VersionInfo.ShouldNotBeNull(); }); } [Test] public void CanRunMigrations() { ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(false); runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue(); runner.VersionLoader.VersionInfo.HasAppliedMigration(2).ShouldBeTrue(); runner.VersionLoader.VersionInfo.HasAppliedMigration(3).ShouldBeTrue(); runner.VersionLoader.VersionInfo.HasAppliedMigration(4).ShouldBeTrue(); runner.VersionLoader.VersionInfo.HasAppliedMigration(5).ShouldBeTrue(); runner.VersionLoader.VersionInfo.Latest().ShouldBe(5); runner.RollbackToVersion(0, false); }); } [Test] public void CanMigrateASpecificVersion() { ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); try { runner.MigrateUp(1, false); runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue(); processor.TableExists(null, "Users").ShouldBeTrue(); } finally { runner.RollbackToVersion(0, false); } }); } [Test] public void CanMigrateASpecificVersionDown() { try { ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(1, false); runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue(); processor.TableExists(null, "Users").ShouldBeTrue(); MigrationRunner testRunner = SetupMigrationRunner(processor); testRunner.MigrateDown(0, false); testRunner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeFalse(); processor.TableExists(null, "Users").ShouldBeFalse(); }, false, typeof(SQLiteProcessor)); } finally { ExecuteWithSupportedProcessors(processor => { MigrationRunner testRunner = SetupMigrationRunner(processor); testRunner.RollbackToVersion(0, false); }, false); } } [Test] public void RollbackAllShouldRemoveVersionInfoTable() { ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(2); processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeTrue(); }); ExecuteWithSupportedProcessors(processor => { MigrationRunner runner = SetupMigrationRunner(processor); runner.RollbackToVersion(0); processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeFalse(); }); } [Test] public void MigrateUpWithSqlServerProcessorShouldCommitItsTransaction() { if (!IntegrationTestOptions.SqlServer2008.IsEnabled) return; var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString); var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory()); MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(); try { processor.WasCommitted.ShouldBeTrue(); } finally { CleanupTestSqlServerDatabase(connection, processor); } } [Test] public void MigrateUpSpecificVersionWithSqlServerProcessorShouldCommitItsTransaction() { if (!IntegrationTestOptions.SqlServer2008.IsEnabled) return; var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString); var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory()); MigrationRunner runner = SetupMigrationRunner(processor); runner.MigrateUp(1); try { processor.WasCommitted.ShouldBeTrue(); } finally { CleanupTestSqlServerDatabase(connection, processor); } } [Test] public void MigrateUpWithTaggedMigrationsShouldOnlyApplyMatchedMigrations() { ExecuteWithSupportedProcessors(processor => { var assembly = typeof(TenantATable).Assembly; var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(TenantATable).Namespace, Tags = new[] { "TenantA" } }; var runner = new MigrationRunner(assembly, runnerContext, processor); try { runner.MigrateUp(false); processor.TableExists(null, "TenantATable").ShouldBeTrue(); processor.TableExists(null, "NormalTable").ShouldBeTrue(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeTrue(); } finally { runner.RollbackToVersion(0); } }); } [Test] public void MigrateUpWithTaggedMigrationsAndUsingMultipleTagsShouldOnlyApplyMatchedMigrations() { ExecuteWithSupportedProcessors(processor => { var assembly = typeof(TenantATable).Assembly; var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(TenantATable).Namespace, Tags = new[] { "TenantA", "TenantB" } }; var runner = new MigrationRunner(assembly, runnerContext, processor); try { runner.MigrateUp(false); processor.TableExists(null, "TenantATable").ShouldBeFalse(); processor.TableExists(null, "NormalTable").ShouldBeTrue(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeTrue(); } finally { new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0); } }); } [Test] public void MigrateDownWithDifferentTagsToMigrateUpShouldApplyMatchedMigrations() { var assembly = typeof(TenantATable).Assembly; var migrationsNamespace = typeof(TenantATable).Namespace; var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = migrationsNamespace, }; // Excluded SqliteProcessor as it errors on DB cleanup (RollbackToVersion). ExecuteWithSupportedProcessors(processor => { try { runnerContext.Tags = new[] { "TenantA" }; new MigrationRunner(assembly, runnerContext, processor).MigrateUp(false); processor.TableExists(null, "TenantATable").ShouldBeTrue(); processor.TableExists(null, "NormalTable").ShouldBeTrue(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeTrue(); runnerContext.Tags = new[] { "TenantB" }; new MigrationRunner(assembly, runnerContext, processor).MigrateDown(0, false); processor.TableExists(null, "TenantATable").ShouldBeTrue(); processor.TableExists(null, "NormalTable").ShouldBeFalse(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeFalse(); } finally { runnerContext.Tags = new[] { "TenantA" }; new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0, false); } }, true, typeof(SQLiteProcessor)); } [Test] public void VersionInfoCreationScriptsOnlyGeneratedOnceInPreviewMode() { if (!IntegrationTestOptions.SqlServer2008.IsEnabled) return; var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString); var processorOptions = new ProcessorOptions { PreviewOnly = true }; var outputSql = new StringWriter(); var announcer = new TextWriterAnnouncer(outputSql){ ShowSql = true }; var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), announcer, processorOptions, new SqlServerDbFactory()); try { var asm = typeof(MigrationRunnerTests).Assembly; var runnerContext = new RunnerContext(announcer) { Namespace = "FluentMigrator.Tests.Integration.Migrations", PreviewOnly = true }; var runner = new MigrationRunner(asm, runnerContext, processor); runner.MigrateUp(1, false); processor.CommitTransaction(); string schemaName = new TestVersionTableMetaData().SchemaName; var schemaAndTableName = string.Format("\\[{0}\\]\\.\\[{1}\\]", schemaName, TestVersionTableMetaData.TABLENAME); var outputSqlString = outputSql.ToString(); var createSchemaMatches = new Regex(string.Format("CREATE SCHEMA \\[{0}\\]", schemaName)).Matches(outputSqlString).Count; var createTableMatches = new Regex("CREATE TABLE " + schemaAndTableName).Matches(outputSqlString).Count; var createIndexMatches = new Regex("CREATE UNIQUE CLUSTERED INDEX \\[" + TestVersionTableMetaData.UNIQUEINDEXNAME + "\\] ON " + schemaAndTableName).Matches(outputSqlString).Count; var alterTableMatches = new Regex("ALTER TABLE " + schemaAndTableName).Matches(outputSqlString).Count; System.Console.WriteLine(outputSqlString); createSchemaMatches.ShouldBe(1); createTableMatches.ShouldBe(1); alterTableMatches.ShouldBe(1); createIndexMatches.ShouldBe(1); } finally { CleanupTestSqlServerDatabase(connection, processor); } } [Test] public void MigrateUpWithTaggedMigrationsShouldNotApplyAnyMigrationsIfNoTagsParameterIsPassedIntoTheRunner() { ExecuteWithSupportedProcessors(processor => { var assembly = typeof(TenantATable).Assembly; var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(TenantATable).Namespace }; var runner = new MigrationRunner(assembly, runnerContext, processor); try { runner.MigrateUp(false); processor.TableExists(null, "TenantATable").ShouldBeFalse(); processor.TableExists(null, "NormalTable").ShouldBeTrue(); processor.TableExists(null, "TenantBTable").ShouldBeFalse(); processor.TableExists(null, "TenantAandBTable").ShouldBeFalse(); } finally { runner.RollbackToVersion(0); } }); } [Test] public void ValidateVersionOrderShouldDoNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration() { // Using SqlServer instead of SqlLite as versions not deleted from VersionInfo table when using Sqlite. var excludedProcessors = new[] { typeof(SQLiteProcessor), typeof(MySqlProcessor), typeof(PostgresProcessor) }; var assembly = typeof(User).Assembly; var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace }; var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace }; try { ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor); migrationRunner.MigrateUp(3); }, false, excludedProcessors); ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor); Assert.DoesNotThrow(migrationRunner.ValidateVersionOrder); }, false, excludedProcessors); } finally { ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor); migrationRunner.RollbackToVersion(0); }, true, excludedProcessors); } } [Test] public void ValidateVersionOrderShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanLatestAppliedMigration() { // Using SqlServer instead of SqlLite as versions not deleted from VersionInfo table when using Sqlite. var excludedProcessors = new[] { typeof(SQLiteProcessor), typeof(MySqlProcessor), typeof(PostgresProcessor) }; var assembly = typeof(User).Assembly; var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace }; var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace }; VersionOrderInvalidException caughtException = null; try { ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor); migrationRunner.MigrateUp(); }, false, excludedProcessors); ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor); migrationRunner.ValidateVersionOrder(); }, false, excludedProcessors); } catch (VersionOrderInvalidException ex) { caughtException = ex; } finally { ExecuteWithSupportedProcessors(processor => { var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor); migrationRunner.RollbackToVersion(0); }, true, excludedProcessors); } caughtException.ShouldNotBeNull(); caughtException.InvalidMigrations.Count().ShouldBe(1); var keyValuePair = caughtException.InvalidMigrations.First(); keyValuePair.Key.ShouldBe(200909060935); keyValuePair.Value.Migration.ShouldBeOfType<UserEmail>(); } [Test] public void CanCreateSequence() { ExecuteWithSqlServer2012( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSequence()); processor.SequenceExists(null, "TestSequence"); runner.Down(new TestCreateSequence()); processor.SequenceExists(null, "TestSequence").ShouldBeFalse(); }, true); } [Test] public void CanCreateSequenceWithSchema() { Action<IMigrationProcessor> action = processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSequence()); processor.SequenceExists("TestSchema", "TestSequence"); runner.Down(new TestCreateSequence()); processor.SequenceExists("TestSchema", "TestSequence").ShouldBeFalse(); }; ExecuteWithSqlServer2012( action,true); ExecuteWithPostgres(action, IntegrationTestOptions.Postgres, true); } [Test] public void CanAlterColumnWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue(); processor.DefaultValueExists("TestSchema", "TestTable", "Name", "Anonymous").ShouldBeTrue(); runner.Up(new TestAlterColumnWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue(); runner.Down(new TestAlterColumnWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] public void CanAlterTableWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse(); runner.Up(new TestAlterTableWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeTrue(); runner.Down(new TestAlterTableWithSchema()); processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] public void CanAlterTablesSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.TableExists("TestSchema", "TestTable").ShouldBeTrue(); runner.Up(new TestAlterSchema()); processor.TableExists("NewSchema", "TestTable").ShouldBeTrue(); runner.Down(new TestAlterSchema()); processor.TableExists("TestSchema", "TestTable").ShouldBeTrue(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] public void CanCreateUniqueConstraint() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse(); runner.Up(new TestCreateUniqueConstraint()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeTrue(); runner.Down(new TestCreateUniqueConstraint()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigration()); }, true, typeof(SQLiteProcessor)); } [Test] public void CanCreateUniqueConstraintWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse(); runner.Up(new TestCreateUniqueConstraintWithSchema()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeTrue(); runner.Down(new TestCreateUniqueConstraintWithSchema()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] public void CanInsertData() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); DataSet ds = processor.ReadTableData(null, "TestTable"); ds.Tables[0].Rows.Count.ShouldBe(1); ds.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigration()); }, true, new[] { typeof(SQLiteProcessor) }); } [Test] public void CanInsertDataWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); DataSet ds = processor.ReadTableData("TestSchema", "TestTable"); ds.Tables[0].Rows.Count.ShouldBe(1); ds.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] public void CanUpdateData() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); runner.Up(new TestUpdateData()); DataSet upDs = processor.ReadTableData("TestSchema", "TestTable"); upDs.Tables[0].Rows.Count.ShouldBe(1); upDs.Tables[0].Rows[0][1].ShouldBe("Updated"); runner.Down(new TestUpdateData()); DataSet downDs = processor.ReadTableData("TestSchema", "TestTable"); downDs.Tables[0].Rows.Count.ShouldBe(1); downDs.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] public void CanDeleteData() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); runner.Up(new TestDeleteData()); DataSet upDs = processor.ReadTableData(null, "TestTable"); upDs.Tables[0].Rows.Count.ShouldBe(0); runner.Down(new TestDeleteData()); DataSet downDs = processor.ReadTableData(null, "TestTable"); downDs.Tables[0].Rows.Count.ShouldBe(1); downDs.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigration()); }, true, new[] { typeof(SQLiteProcessor) }); } [Test] public void CanDeleteDataWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); runner.Up(new TestDeleteDataWithSchema()); DataSet upDs = processor.ReadTableData("TestSchema", "TestTable"); upDs.Tables[0].Rows.Count.ShouldBe(0); runner.Down(new TestDeleteDataWithSchema()); DataSet downDs = processor.ReadTableData("TestSchema", "TestTable"); downDs.Tables[0].Rows.Count.ShouldBe(1); downDs.Tables[0].Rows[0][1].ShouldBe("Test"); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor), typeof(FirebirdProcessor) }); } [Test] public void CanReverseCreateIndex() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); runner.Up(new TestCreateIndexWithReversing()); processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeTrue(); runner.Down(new TestCreateIndexWithReversing()); processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor) }); } [Test] public void CanReverseCreateUniqueConstraint() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateAndDropTableMigration()); runner.Up(new TestCreateUniqueConstraintWithReversing()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeTrue(); runner.Down(new TestCreateUniqueConstraintWithReversing()); processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigration()); }, true, new[] { typeof(SQLiteProcessor) }); } [Test] public void CanReverseCreateUniqueConstraintWithSchema() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestCreateSchema()); runner.Up(new TestCreateAndDropTableMigrationWithSchema()); runner.Up(new TestCreateUniqueConstraintWithSchemaWithReversing()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeTrue(); runner.Down(new TestCreateUniqueConstraintWithSchemaWithReversing()); processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse(); runner.Down(new TestCreateAndDropTableMigrationWithSchema()); runner.Down(new TestCreateSchema()); }, true, new[] { typeof(SQLiteProcessor) }); } [Test] public void CanExecuteSql() { ExecuteWithSupportedProcessors( processor => { var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor); runner.Up(new TestExecuteSql()); runner.Down(new TestExecuteSql()); }, true, new[] { typeof(FirebirdProcessor) }); } private static MigrationRunner SetupMigrationRunner(IMigrationProcessor processor) { Assembly asm = typeof(MigrationRunnerTests).Assembly; var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = "FluentMigrator.Tests.Integration.Migrations" }; return new MigrationRunner(asm, runnerContext, processor); } private static void CleanupTestSqlServerDatabase(SqlConnection connection, SqlServerProcessor origProcessor) { if (origProcessor.WasCommitted) { connection.Close(); var cleanupProcessor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory()); MigrationRunner cleanupRunner = SetupMigrationRunner(cleanupProcessor); cleanupRunner.RollbackToVersion(0); } else { origProcessor.RollbackTransaction(); } } } internal class TestForeignKeyNamingConvention : Migration { public override void Up() { Create.Table("Users") .WithColumn("UserId").AsInt32().Identity().PrimaryKey() .WithColumn("GroupId").AsInt32().NotNullable() .WithColumn("UserName").AsString(32).NotNullable() .WithColumn("Password").AsString(32).NotNullable(); Create.Table("Groups") .WithColumn("GroupId").AsInt32().Identity().PrimaryKey() .WithColumn("Name").AsString(32).NotNullable(); Create.ForeignKey().FromTable("Users").ForeignColumn("GroupId").ToTable("Groups").PrimaryColumn("GroupId"); } public override void Down() { Delete.Table("Users"); Delete.Table("Groups"); } } internal class TestIndexNamingConvention : Migration { public override void Up() { Create.Table("Users") .WithColumn("UserId").AsInt32().Identity().PrimaryKey() .WithColumn("GroupId").AsInt32().NotNullable() .WithColumn("UserName").AsString(32).NotNullable() .WithColumn("Password").AsString(32).NotNullable(); Create.Index().OnTable("Users").OnColumn("GroupId").Ascending(); } public override void Down() { Delete.Index("IX_Users_GroupId").OnTable("Users").OnColumn("GroupId"); Delete.Table("Users"); } } internal class TestForeignKeySilentFailure : Migration { public override void Up() { Create.Table("Users") .WithColumn("UserId").AsInt32().Identity().PrimaryKey() .WithColumn("GroupId").AsInt32().NotNullable() .WithColumn("UserName").AsString(32).NotNullable() .WithColumn("Password").AsString(32).NotNullable(); Create.Table("Groups") .WithColumn("GroupId").AsInt32().Identity().PrimaryKey() .WithColumn("Name").AsString(32).NotNullable(); Create.ForeignKey("FK_Foo").FromTable("Users").ForeignColumn("GroupId").ToTable("Groups").PrimaryColumn("GroupId"); } public override void Down() { Delete.ForeignKey("FK_Foo").OnTable("Users"); Delete.Table("Users"); Delete.Table("Groups"); } } internal class TestCreateAndDropTableMigration : Migration { public override void Up() { Create.Table("TestTable") .WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity() .WithColumn("Name").AsString(255).NotNullable().WithDefaultValue("Anonymous"); Create.Table("TestTable2") .WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity() .WithColumn("Name").AsString(255).Nullable() .WithColumn("TestTableId").AsInt32().NotNullable(); Create.Index("ix_Name").OnTable("TestTable2").OnColumn("Name").Ascending() .WithOptions().NonClustered(); Create.Column("Name2").OnTable("TestTable2").AsBoolean().Nullable(); Create.ForeignKey("fk_TestTable2_TestTableId_TestTable_Id") .FromTable("TestTable2").ForeignColumn("TestTableId") .ToTable("TestTable").PrimaryColumn("Id"); Insert.IntoTable("TestTable").Row(new { Name = "Test" }); } public override void Down() { Delete.Table("TestTable2"); Delete.Table("TestTable"); } } internal class TestRenameTableMigration : AutoReversingMigration { public override void Up() { Rename.Table("TestTable2").To("TestTable'3"); } } internal class TestRenameColumnMigration : AutoReversingMigration { public override void Up() { Rename.Column("Name").OnTable("TestTable2").To("Name'3"); } } internal class TestCreateAndDropIndexMigration : Migration { public override void Up() { Create.Index("IX_TestTable_Name").OnTable("TestTable").OnColumn("Name"); } public override void Down() { Delete.Index("IX_TestTable_Name").OnTable("TestTable"); } } internal class TestForeignKeyNamingConventionWithSchema : Migration { public override void Up() { Create.Schema("TestSchema"); Create.Table("Users") .InSchema("TestSchema") .WithColumn("UserId").AsInt32().Identity().PrimaryKey() .WithColumn("GroupId").AsInt32().NotNullable() .WithColumn("UserName").AsString(32).NotNullable() .WithColumn("Password").AsString(32).NotNullable(); Create.Table("Groups") .InSchema("TestSchema") .WithColumn("GroupId").AsInt32().Identity().PrimaryKey() .WithColumn("Name").AsString(32).NotNullable(); Create.ForeignKey().FromTable("Users").InSchema("TestSchema").ForeignColumn("GroupId").ToTable("Groups").InSchema("TestSchema").PrimaryColumn("GroupId"); } public override void Down() { Delete.Table("Users").InSchema("TestSchema"); Delete.Table("Groups").InSchema("TestSchema"); Delete.Schema("TestSchema"); } } internal class TestIndexNamingConventionWithSchema : Migration { public override void Up() { Create.Schema("TestSchema"); Create.Table("Users") .InSchema("TestSchema") .WithColumn("UserId").AsInt32().Identity().PrimaryKey() .WithColumn("GroupId").AsInt32().NotNullable() .WithColumn("UserName").AsString(32).NotNullable() .WithColumn("Password").AsString(32).NotNullable(); Create.Index().OnTable("Users").InSchema("TestSchema").OnColumn("GroupId").Ascending(); } public override void Down() { Delete.Index("IX_Users_GroupId").OnTable("Users").InSchema("TestSchema").OnColumn("GroupId"); Delete.Table("Users").InSchema("TestSchema"); Delete.Schema("TestSchema"); } } internal class TestCreateAndDropTableMigrationWithSchema : Migration { public override void Up() { Create.Table("TestTable") .InSchema("TestSchema") .WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity() .WithColumn("Name").AsString(255).NotNullable().WithDefaultValue("Anonymous"); Create.Table("TestTable2") .InSchema("TestSchema") .WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity() .WithColumn("Name").AsString(255).Nullable() .WithColumn("TestTableId").AsInt32().NotNullable(); Create.Index("ix_Name").OnTable("TestTable2").InSchema("TestSchema").OnColumn("Name").Ascending() .WithOptions().NonClustered(); Create.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsString(10).Nullable(); Create.ForeignKey("fk_TestTable2_TestTableId_TestTable_Id") .FromTable("TestTable2").InSchema("TestSchema").ForeignColumn("TestTableId") .ToTable("TestTable").InSchema("TestSchema").PrimaryColumn("Id"); Insert.IntoTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test" }); } public override void Down() { Delete.Table("TestTable2").InSchema("TestSchema"); Delete.Table("TestTable").InSchema("TestSchema"); } } internal class TestRenameTableMigrationWithSchema : AutoReversingMigration { public override void Up() { Rename.Table("TestTable2").InSchema("TestSchema").To("TestTable'3"); } } internal class TestRenameColumnMigrationWithSchema : AutoReversingMigration { public override void Up() { Rename.Column("Name").OnTable("TestTable2").InSchema("TestSchema").To("Name'3"); } } internal class TestCreateAndDropIndexMigrationWithSchema : Migration { public override void Up() { Create.Index("IX_TestTable_Name").OnTable("TestTable").InSchema("TestSchema").OnColumn("Name"); } public override void Down() { Delete.Index("IX_TestTable_Name").OnTable("TestTable").InSchema("TestSchema"); } } internal class TestCreateSchema : Migration { public override void Up() { Create.Schema("TestSchema"); } public override void Down() { Delete.Schema("TestSchema"); } } internal class TestCreateSequence : Migration { public override void Up() { Create.Sequence("TestSequence").StartWith(1).IncrementBy(1).MinValue(0).MaxValue(1000).Cycle().Cache(10); } public override void Down() { Delete.Sequence("TestSequence"); } } internal class TestCreateSequenceWithSchema : Migration { public override void Up() { Create.Sequence("TestSequence").InSchema("TestSchema").StartWith(1).IncrementBy(1).MinValue(0).MaxValue(1000).Cycle().Cache(10); } public override void Down() { Delete.Sequence("TestSequence").InSchema("TestSchema"); } } internal class TestAlterColumnWithSchema: Migration { public override void Up() { Alter.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsAnsiString(100).Nullable(); } public override void Down() { Alter.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsString(10).Nullable(); } } internal class TestAlterTableWithSchema : Migration { public override void Up() { Alter.Table("TestTable2").InSchema("TestSchema").AddColumn("NewColumn").AsInt32().WithDefaultValue(1); } public override void Down() { Delete.Column("NewColumn").FromTable("TestTable2").InSchema("TestSchema"); } } internal class TestAlterSchema : Migration { public override void Up() { Create.Schema("NewSchema"); Alter.Table("TestTable").InSchema("TestSchema").ToSchema("NewSchema"); } public override void Down() { Alter.Table("TestTable").InSchema("NewSchema").ToSchema("TestSchema"); Delete.Schema("NewSchema"); } } internal class TestCreateUniqueConstraint : Migration { public override void Up() { Create.UniqueConstraint("TestUnique").OnTable("TestTable2").Column("Name"); } public override void Down() { Delete.UniqueConstraint("TestUnique").FromTable("TestTable2"); } } internal class TestCreateUniqueConstraintWithSchema : Migration { public override void Up() { Create.UniqueConstraint("TestUnique").OnTable("TestTable2").WithSchema("TestSchema").Column("Name"); } public override void Down() { Delete.UniqueConstraint("TestUnique").FromTable("TestTable2").InSchema("TestSchema"); } } internal class TestUpdateData : Migration { public override void Up() { Update.Table("TestTable").InSchema("TestSchema").Set(new { Name = "Updated" }).AllRows(); } public override void Down() { Update.Table("TestTable").InSchema("TestSchema").Set(new { Name = "Test" }).AllRows(); } } internal class TestDeleteData : Migration { public override void Up() { Delete.FromTable("TestTable").Row(new { Name = "Test" }); } public override void Down() { Insert.IntoTable("TestTable").Row(new { Name = "Test" }); } } internal class TestDeleteDataWithSchema :Migration { public override void Up() { Delete.FromTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test"}); } public override void Down() { Insert.IntoTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test" }); } } internal class TestCreateIndexWithReversing : AutoReversingMigration { public override void Up() { Create.Index().OnTable("TestTable2").InSchema("TestSchema").OnColumn("Name2").Ascending(); } } internal class TestCreateUniqueConstraintWithReversing : AutoReversingMigration { public override void Up() { Create.UniqueConstraint("TestUnique").OnTable("TestTable2").Column("Name"); } } internal class TestCreateUniqueConstraintWithSchemaWithReversing : AutoReversingMigration { public override void Up() { Create.UniqueConstraint("TestUnique").OnTable("TestTable2").WithSchema("TestSchema").Column("Name"); } } internal class TestExecuteSql : Migration { public override void Up() { Execute.Sql("select 1"); } public override void Down() { Execute.Sql("select 2"); } } }
// // 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.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operations for managing Products. /// </summary> internal partial class ProductsOperations : IServiceOperations<ApiManagementClient>, IProductsOperations { /// <summary> /// Initializes a new instance of the ProductsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ProductsOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Create new product. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='parameters'> /// Required. Create or update parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateAsync(string resourceGroupName, string serviceName, string pid, ProductCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (pid == null) { throw new ArgumentNullException("pid"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ProductContract == null) { throw new ArgumentNullException("parameters.ProductContract"); } if (parameters.ProductContract.Name == null) { throw new ArgumentNullException("parameters.ProductContract.Name"); } if (parameters.ProductContract.Name.Length > 300) { throw new ArgumentOutOfRangeException("parameters.ProductContract.Name"); } // 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("serviceName", serviceName); tracingParameters.Add("pid", pid); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", 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.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/products/"; url = url + Uri.EscapeDataString(pid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject productCreateParametersValue = new JObject(); requestDoc = productCreateParametersValue; if (parameters.ProductContract.IdPath != null) { productCreateParametersValue["id"] = parameters.ProductContract.IdPath; } productCreateParametersValue["name"] = parameters.ProductContract.Name; if (parameters.ProductContract.Description != null) { productCreateParametersValue["description"] = parameters.ProductContract.Description; } if (parameters.ProductContract.Terms != null) { productCreateParametersValue["terms"] = parameters.ProductContract.Terms; } if (parameters.ProductContract.SubscriptionRequired != null) { productCreateParametersValue["subscriptionRequired"] = parameters.ProductContract.SubscriptionRequired.Value; } if (parameters.ProductContract.ApprovalRequired != null) { productCreateParametersValue["approvalRequired"] = parameters.ProductContract.ApprovalRequired.Value; } if (parameters.ProductContract.SubscriptionsLimit != null) { productCreateParametersValue["subscriptionsLimit"] = parameters.ProductContract.SubscriptionsLimit.Value; } productCreateParametersValue["state"] = parameters.ProductContract.State.ToString(); requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // 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.Created && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete product. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='deleteSubscriptions'> /// Required. Delete existing subscriptions to the product ot not. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string pid, string etag, bool deleteSubscriptions, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (pid == null) { throw new ArgumentNullException("pid"); } if (etag == null) { throw new ArgumentNullException("etag"); } // 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("serviceName", serviceName); tracingParameters.Add("pid", pid); tracingParameters.Add("etag", etag); tracingParameters.Add("deleteSubscriptions", deleteSubscriptions); TracingAdapter.Enter(invocationId, this, "DeleteAsync", 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.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/products/"; url = url + Uri.EscapeDataString(pid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); queryParameters.Add("deleteSubscriptions=" + Uri.EscapeDataString(deleteSubscriptions.ToString().ToLower())); 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.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // 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 && statusCode != HttpStatusCode.NoContent) { 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 AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get specific product. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Get Product operation response details. /// </returns> public async Task<ProductGetResponse> GetAsync(string resourceGroupName, string serviceName, string pid, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (pid == null) { throw new ArgumentNullException("pid"); } // 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("serviceName", serviceName); tracingParameters.Add("pid", pid); TracingAdapter.Enter(invocationId, this, "GetAsync", 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.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/products/"; url = url + Uri.EscapeDataString(pid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); 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 ProductGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProductGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ProductContract valueInstance = new ProductContract(); result.Value = valueInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); valueInstance.IdPath = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); valueInstance.Name = nameInstance; } JToken descriptionValue = responseDoc["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); valueInstance.Description = descriptionInstance; } JToken termsValue = responseDoc["terms"]; if (termsValue != null && termsValue.Type != JTokenType.Null) { string termsInstance = ((string)termsValue); valueInstance.Terms = termsInstance; } JToken subscriptionRequiredValue = responseDoc["subscriptionRequired"]; if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null) { bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue); valueInstance.SubscriptionRequired = subscriptionRequiredInstance; } JToken approvalRequiredValue = responseDoc["approvalRequired"]; if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null) { bool approvalRequiredInstance = ((bool)approvalRequiredValue); valueInstance.ApprovalRequired = approvalRequiredInstance; } JToken subscriptionsLimitValue = responseDoc["subscriptionsLimit"]; if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null) { int subscriptionsLimitInstance = ((int)subscriptionsLimitValue); valueInstance.SubscriptionsLimit = subscriptionsLimitInstance; } JToken stateValue = responseDoc["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true)); valueInstance.State = stateInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List all products. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='query'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Products operation response details. /// </returns> public async Task<ProductListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // 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("serviceName", serviceName); tracingParameters.Add("query", query); TracingAdapter.Enter(invocationId, this, "ListAsync", 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.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/products"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); List<string> odataFilter = new List<string>(); if (query != null && query.Filter != null) { odataFilter.Add(Uri.EscapeDataString(query.Filter)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (query != null && query.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString())); } if (query != null && query.Skip != null) { queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString())); } 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 ProductListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProductListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ProductPaged resultInstance = new ProductPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ProductContract productContractInstance = new ProductContract(); resultInstance.Values.Add(productContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); productContractInstance.IdPath = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); productContractInstance.Name = nameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); productContractInstance.Description = descriptionInstance; } JToken termsValue = valueValue["terms"]; if (termsValue != null && termsValue.Type != JTokenType.Null) { string termsInstance = ((string)termsValue); productContractInstance.Terms = termsInstance; } JToken subscriptionRequiredValue = valueValue["subscriptionRequired"]; if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null) { bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue); productContractInstance.SubscriptionRequired = subscriptionRequiredInstance; } JToken approvalRequiredValue = valueValue["approvalRequired"]; if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null) { bool approvalRequiredInstance = ((bool)approvalRequiredValue); productContractInstance.ApprovalRequired = approvalRequiredInstance; } JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"]; if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null) { int subscriptionsLimitInstance = ((int)subscriptionsLimitValue); productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true)); productContractInstance.State = stateInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// List all products. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Products operation response details. /// </returns> public async Task<ProductListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; 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 ProductListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ProductListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ProductPaged resultInstance = new ProductPaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ProductContract productContractInstance = new ProductContract(); resultInstance.Values.Add(productContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); productContractInstance.IdPath = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); productContractInstance.Name = nameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); productContractInstance.Description = descriptionInstance; } JToken termsValue = valueValue["terms"]; if (termsValue != null && termsValue.Type != JTokenType.Null) { string termsInstance = ((string)termsValue); productContractInstance.Terms = termsInstance; } JToken subscriptionRequiredValue = valueValue["subscriptionRequired"]; if (subscriptionRequiredValue != null && subscriptionRequiredValue.Type != JTokenType.Null) { bool subscriptionRequiredInstance = ((bool)subscriptionRequiredValue); productContractInstance.SubscriptionRequired = subscriptionRequiredInstance; } JToken approvalRequiredValue = valueValue["approvalRequired"]; if (approvalRequiredValue != null && approvalRequiredValue.Type != JTokenType.Null) { bool approvalRequiredInstance = ((bool)approvalRequiredValue); productContractInstance.ApprovalRequired = approvalRequiredInstance; } JToken subscriptionsLimitValue = valueValue["subscriptionsLimit"]; if (subscriptionsLimitValue != null && subscriptionsLimitValue.Type != JTokenType.Null) { int subscriptionsLimitInstance = ((int)subscriptionsLimitValue); productContractInstance.SubscriptionsLimit = subscriptionsLimitInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { ProductStateContract stateInstance = ((ProductStateContract)Enum.Parse(typeof(ProductStateContract), ((string)stateValue), true)); productContractInstance.State = stateInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update product. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='pid'> /// Required. Identifier of the product. /// </param> /// <param name='parameters'> /// Required. Update parameters. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> UpdateAsync(string resourceGroupName, string serviceName, string pid, ProductUpdateParameters parameters, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (pid == null) { throw new ArgumentNullException("pid"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name != null && parameters.Name.Length > 300) { throw new ArgumentOutOfRangeException("parameters.Name"); } if (etag == null) { throw new ArgumentNullException("etag"); } // 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("serviceName", serviceName); tracingParameters.Add("pid", pid); tracingParameters.Add("parameters", parameters); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "UpdateAsync", 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.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/products/"; url = url + Uri.EscapeDataString(pid); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-07-07"); 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 = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject productUpdateParametersValue = new JObject(); requestDoc = productUpdateParametersValue; if (parameters.Name != null) { productUpdateParametersValue["name"] = parameters.Name; } if (parameters.Description != null) { productUpdateParametersValue["description"] = parameters.Description; } if (parameters.Terms != null) { productUpdateParametersValue["terms"] = parameters.Terms; } if (parameters.SubscriptionRequired != null) { productUpdateParametersValue["subscriptionRequired"] = parameters.SubscriptionRequired.Value; } if (parameters.ApprovalRequired != null) { productUpdateParametersValue["approvalRequired"] = parameters.ApprovalRequired.Value; } if (parameters.SubscriptionsLimit != null) { productUpdateParametersValue["subscriptionsLimit"] = parameters.SubscriptionsLimit.Value; } if (parameters.State != null) { productUpdateParametersValue["state"] = parameters.State.Value.ToString(); } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // 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 && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); 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(); } } } } }
/* Copyright (c) 2006-2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ using System; using System.Collections; using System.Text; using System.Xml; using Google.GData.Client; namespace Google.GData.Extensions { /// <summary> /// A place (such as an event location) associated with the containing entity. The type of /// the association is determined by the rel attribute; the details of the location are /// contained in an embedded or linked-to Contact entry. /// A gd:where element is more general than a gd:geoPt element. The former identifies a place /// using a text description and/or a Contact entry, while the latter identifies a place /// using a specific geographic location. /// Properties /// Property Type Description /// @label? xs:string Specifies a user-readable label to distinguish this location from other locations. /// @rel? xs:string Specifies the relationship between the containing entity and the contained location. Possible values /// (see below) are defined by other elements. For example, gd:when defines http://schemas.google.com/g/2005#event. /// @valueString? xs:string A simple string value that can be used as a representation of this location. /// gd:entryLink? entryLink Entry representing location details. This entry should implement the Contact kind. /// rel values /// Value Description /// http://schemas.google.com/g/2005#event or not specified Place where the enclosing event takes place. /// http://schemas.google.com/g/2005#event.alternate A secondary location. For example, a remote /// site with a videoconference link to the main site. /// http://schemas.google.com/g/2005#event.parking A nearby parking lot. /// </summary> public class Where : IExtensionElementFactory { /// <summary> /// Relation type. Describes the meaning of this location. /// </summary> public class RelType { /// <summary> /// The standard relationship EVENT_ALTERNATE /// </summary> public const string EVENT = null; /// <summary> /// the alternate EVENT location /// </summary> public const string EVENT_ALTERNATE = BaseNameTable.gNamespacePrefix + "event.alternate"; /// <summary> /// the parking location /// </summary> public const string EVENT_PARKING = BaseNameTable.gNamespacePrefix + "event.parking"; } /// <summary> /// Constructs an empty Where instance /// </summary> public Where() { } /// <summary> /// default constructor, takes 3 parameters /// </summary> /// <param name="value">the valueString property value</param> /// <param name="label">label property value</param> /// <param name="rel">default for the Rel property value</param> public Where(String rel, String label, String value) { this.Rel = rel; this.Label = label; this.ValueString = value; } private string rel; private string label; private string valueString; private EntryLink entryLink; /// <summary> /// Rel property accessor /// </summary> public string Rel { get { return rel; } set { rel = value; } } /// <summary> /// User-readable label that identifies this location. /// </summary> public string Label { get { return label; } set { label = value; } } /// <summary> /// String description of the event places. /// </summary> public string ValueString { get { return valueString; } set { valueString = value; } } /// <summary> /// Nested entry (optional). /// </summary> public EntryLink EntryLink { get { return entryLink; } set { entryLink = value; } } #region overloaded from IExtensionElementFactory ////////////////////////////////////////////////////////////////////// /// <summary>Parses an xml node to create a Where object.</summary> /// <param name="node">the node to parse node</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created Where object</returns> ////////////////////////////////////////////////////////////////////// public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { Tracing.TraceCall(); Where where = null; if (node != null) { object localname = node.LocalName; if (localname.Equals(this.XmlName) == false || node.NamespaceURI.Equals(this.XmlNameSpace) == false) { return null; } } where = new Where(); if (node != null) { if (node.Attributes != null) { if (node.Attributes[GDataParserNameTable.XmlAttributeRel] != null) { where.Rel = node.Attributes[GDataParserNameTable.XmlAttributeRel].Value; } if (node.Attributes[GDataParserNameTable.XmlAttributeLabel] != null) { where.Label = node.Attributes[GDataParserNameTable.XmlAttributeLabel].Value; } if (node.Attributes[GDataParserNameTable.XmlAttributeValueString] != null) { where.ValueString = node.Attributes[GDataParserNameTable.XmlAttributeValueString].Value; } } if (node.HasChildNodes) { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == GDataParserNameTable.XmlEntryLinkElement) { if (where.EntryLink == null) { where.EntryLink = EntryLink.ParseEntryLink(childNode, parser); } else { throw new ArgumentException("Only one entryLink is allowed inside the g:where"); } } } } } return where; } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlName { get { return GDataParserNameTable.XmlWhereElement; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlNameSpace { get { return BaseNameTable.gNamespace; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlPrefix { get { return BaseNameTable.gDataPrefix; } } #endregion #region overloaded for persistence /// <summary> /// Persistence method for the Where object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { if (Utilities.IsPersistable(this.Label) || Utilities.IsPersistable(this.Rel) || Utilities.IsPersistable(this.ValueString) || entryLink != null) { writer.WriteStartElement(BaseNameTable.gDataPrefix, XmlName, BaseNameTable.gNamespace); if (Utilities.IsPersistable(this.Label)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeLabel, this.Label); } if (Utilities.IsPersistable(this.Rel)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeRel, this.Rel); } if (Utilities.IsPersistable(this.ValueString)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeValueString, this.valueString); } if (entryLink != null) { entryLink.Save(writer); } writer.WriteEndElement(); } } #endregion } }
/* * 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 OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Framework.Interfaces { // option flags for NPCs public enum NPCOptionsFlags : int { None = 0x00, // no flags (max restriction) AllowNotOwned = 0x01, // allow NPCs to be created not Owned AllowSenseAsAvatar = 0x02, // allow NPCs to set to be sensed as Avatars AllowCloneOtherAvatars = 0x04, // allow NPCs to created cloning a avatar in region NoNPCGroup = 0x08 // NPCs will have no group title, otherwise will have "- NPC -" } /// <summary> /// Temporary interface. More methods to come at some point to make NPCs /// more object oriented rather than controlling purely through module /// level interface calls (e.g. sit/stand). /// </summary> public interface INPC { /// <summary> /// Should this NPC be sensed by LSL sensors as an 'agent' /// (interpreted here to mean a normal user) rather than an OpenSim /// specific NPC extension? /// </summary> bool SenseAsAgent { get; } } public interface INPCModule { /// <summary> /// Create an NPC /// </summary> /// <param name="firstname"></param> /// <param name="lastname"></param> /// <param name="position"></param> /// <param name="senseAsAgent"> /// Make the NPC show up as an agent on LSL sensors. The default is /// that they show up as the NPC type instead, but this is currently /// an OpenSim-only extension. /// </param> /// <param name="scene"></param> /// <param name="appearance"> /// The avatar appearance to use for the new NPC. /// </param> /// <returns> /// The UUID of the ScenePresence created. UUID.Zero if there was a /// failure. /// </returns> UUID CreateNPC(string firstname, string lastname, Vector3 position, UUID owner, bool senseAsAgent, Scene scene, AvatarAppearance appearance); /// <summary> /// Create an NPC with a user-supplied agentID /// </summary> /// <param name="firstname"></param> /// <param name="lastname"></param> /// <param name="position"></param> /// <param name="agentID"></param> /// The desired agent ID /// <param name="owner"></param> /// <param name="senseAsAgent"> /// Make the NPC show up as an agent on LSL sensors. The default is /// that they show up as the NPC type instead, but this is currently /// an OpenSim-only extension. /// </param> /// <param name="scene"></param> /// <param name="appearance"> /// The avatar appearance to use for the new NPC. /// </param> /// <returns> /// The UUID of the ScenePresence created. UUID.Zero if there was a /// failure. /// </returns> UUID CreateNPC(string firstname, string lastname, Vector3 position, UUID agentID, UUID owner, bool senseAsAgent, Scene scene, AvatarAppearance appearance); /// <summary> /// Check if the agent is an NPC. /// </summary> /// <param name="agentID"></param> /// <param name="scene"></param> /// <returns> /// True if the agent is an NPC in the given scene. False otherwise. /// </returns> bool IsNPC(UUID agentID, Scene scene); /// <summary> /// Get the NPC. /// </summary> /// <remarks> /// This is not currently complete - manipulation of NPCs still occurs /// through the region interface. /// </remarks> /// <param name="agentID"></param> /// <param name="scene"></param> /// <returns>The NPC. null if it does not exist.</returns> INPC GetNPC(UUID agentID, Scene scene); /// <summary> /// Check if the caller has permission to manipulate the given NPC. /// </summary> /// <remarks> /// A caller has permission if /// * An NPC exists with the given npcID. /// * The caller UUID given is UUID.Zero. /// * The avatar is unowned (owner is UUID.Zero). /// * The avatar is owned and the owner and callerID match. /// * The avatar is owned and the callerID matches its agentID. /// </remarks> /// <param name="av"></param> /// <param name="callerID"></param> /// <returns>true if they do, false if they don't.</returns> /// <param name="npcID"></param> /// <param name="callerID"></param> /// <returns> /// true if they do, false if they don't or if there's no NPC with the /// given ID. /// </returns> bool CheckPermissions(UUID npcID, UUID callerID); /// <summary> /// Set the appearance for an NPC. /// </summary> /// <param name="agentID"></param> /// <param name="appearance"></param> /// <param name="scene"></param> /// <returns> /// True if the operation succeeded, false if there was no such agent /// or the agent was not an NPC. /// </returns> bool SetNPCAppearance(UUID agentID, AvatarAppearance appearance, Scene scene); /// <summary> /// Move an NPC to a target over time. /// </summary> /// <param name="agentID">The UUID of the NPC</param> /// <param name="scene"></param> /// <param name="pos"></param> /// <param name="noFly"> /// If true, then the avatar will attempt to walk to the location even /// if it's up in the air. This is to allow walking on prims. /// </param> /// <param name="landAtTarget"> /// If true and the avatar is flying when it reaches the target, land. /// </param> name="running"> /// If true, NPC moves with running speed. /// <returns> /// True if the operation succeeded, false if there was no such agent /// or the agent was not an NPC. /// </returns> bool MoveToTarget(UUID agentID, Scene scene, Vector3 pos, bool noFly, bool landAtTarget, bool running); /// <summary> /// Stop the NPC's current movement. /// </summary> /// <param name="agentID">The UUID of the NPC</param> /// <param name="scene"></param> /// <returns> /// True if the operation succeeded, false if there was no such agent /// or the agent was not an NPC. /// </returns> bool StopMoveToTarget(UUID agentID, Scene scene); /// <summary> /// Get the NPC to say something. /// </summary> /// <param name="agentID">The UUID of the NPC</param> /// <param name="scene"></param> /// <param name="text"></param> /// <returns> /// True if the operation succeeded, false if there was no such agent /// or the agent was not an NPC. /// </returns> bool Say(UUID agentID, Scene scene, string text); /// <summary> /// Get the NPC to say something. /// </summary> /// <param name="agentID">The UUID of the NPC</param> /// <param name="scene"></param> /// <param name="text"></param> /// <param name="channel"></param> /// <returns> /// True if the operation succeeded, false if there was no such agent /// or the agent was not an NPC. /// </returns> bool Say(UUID agentID, Scene scene, string text, int channel); /// <summary> /// Get the NPC to shout something. /// </summary> /// <param name="agentID">The UUID of the NPC</param> /// <param name="scene"></param> /// <param name="text"></param> /// <param name="channel"></param> /// <returns> /// True if the operation succeeded, false if there was no such agent /// or the agent was not an NPC. /// </returns> bool Shout(UUID agentID, Scene scene, string text, int channel); /// <summary> /// Get the NPC to whisper something. /// </summary> /// <param name="agentID">The UUID of the NPC</param> /// <param name="scene"></param> /// <param name="text"></param> /// <param name="channel"></param> /// <returns> /// True if the operation succeeded, false if there was no such agent /// or the agent was not an NPC. /// </returns> bool Whisper(UUID agentID, Scene scene, string text, int channel); /// <summary> /// Sit the NPC. /// </summary> /// <param name="agentID"></param> /// <param name="partID"></param> /// <param name="scene"></param> /// <returns>true if the sit succeeded, false if not</returns> bool Sit(UUID agentID, UUID partID, Scene scene); /// <summary> /// Stand a sitting NPC. /// </summary> /// <param name="agentID"></param> /// <param name="scene"></param> /// <returns>true if the stand succeeded, false if not</returns> bool Stand(UUID agentID, Scene scene); /// <summary> /// Get the NPC to touch an object. /// </summary> /// <param name="agentID"></param> /// <param name="partID"></param> /// <returns> /// true if the touch is actually attempted, false if not. /// </returns> bool Touch(UUID agentID, UUID partID); /// <summary> /// Delete an NPC. /// </summary> /// <param name="agentID">The UUID of the NPC</param> /// <param name="scene"></param> /// <returns> /// True if the operation succeeded, false if there was no such agent /// or the agent was not an NPC. /// </returns> bool DeleteNPC(UUID agentID, Scene scene); /// <summary> /// Get the owner of a NPC /// </summary> /// <param name="agentID">The UUID of the NPC</param> /// <returns> /// UUID of owner if the NPC exists, UUID.Zero if there was no such /// agent, the agent is unowned or the agent was not an NPC. /// </returns> UUID GetOwner(UUID agentID); NPCOptionsFlags NPCOptionFlags {get;} } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; namespace Aurora.Framework { public struct ContactPoint { public float PenetrationDepth; public Vector3 Position; public Vector3 SurfaceNormal; public ActorTypes Type; public ContactPoint(Vector3 position, Vector3 surfaceNormal, float penetrationDepth, ActorTypes type) { Type = type; Position = position; SurfaceNormal = surfaceNormal; PenetrationDepth = penetrationDepth; } } public class CollisionEventUpdate : EventArgs { // Raising the event on the object, so don't need to provide location.. further up the tree knows that info. public bool Cleared; public Dictionary<uint, ContactPoint> m_objCollisionList = new Dictionary<uint, ContactPoint>(); public CollisionEventUpdate(Dictionary<uint, ContactPoint> objCollisionList) { m_objCollisionList = objCollisionList; } public CollisionEventUpdate() { m_objCollisionList = new Dictionary<uint, ContactPoint>(); } public void addCollider(uint localID, ContactPoint contact) { Cleared = false; /*ContactPoint oldCol; if(!m_objCollisionList.TryGetValue(localID, out oldCol)) { */ lock (m_objCollisionList) m_objCollisionList[localID] = contact; /*} else { if(oldCol.PenetrationDepth < contact.PenetrationDepth) lock(m_objCollisionList) m_objCollisionList[localID] = contact; }*/ } /// <summary> /// Reset all the info about this collider /// </summary> public void Clear() { Cleared = true; lock (m_objCollisionList) m_objCollisionList.Clear(); } public CollisionEventUpdate Copy() { CollisionEventUpdate c = new CollisionEventUpdate(); lock (m_objCollisionList) { foreach (KeyValuePair<uint, ContactPoint> kvp in m_objCollisionList) c.m_objCollisionList.Add(kvp.Key, kvp.Value); } return c; } } public delegate void PositionUpdate(Vector3 position); public delegate void VelocityUpdate(Vector3 velocity); public delegate void OrientationUpdate(Quaternion orientation); public enum ActorTypes { Unknown = 0, Agent = 1, Prim = 2, Ground = 3, Water = 4 } public abstract class PhysicsCharacter : PhysicsActor { public abstract bool IsJumping { get; } public abstract float SpeedModifier { get; set; } public abstract bool IsPreJumping { get; } public virtual void AddMovementForce(Vector3 force) { } public virtual void SetMovementForce(Vector3 force) { } public delegate bool checkForRegionCrossing(); public event checkForRegionCrossing OnCheckForRegionCrossing; public virtual bool CheckForRegionCrossing() { // Make a temporary copy of the event to avoid possibility of // a race condition if the last subscriber unsubscribes // immediately after the null check and before the event is raised. checkForRegionCrossing handler = OnCheckForRegionCrossing; if (handler != null) return handler(); return false; } } public abstract class PhysicsObject : PhysicsActor { public virtual void link(PhysicsObject obj) { } public virtual void delink() { } public virtual bool LinkSetIsColliding { get; set; } public virtual void LockAngularMotion(Vector3 axis) { } public virtual PrimitiveBaseShape Shape { set { if (value == null) throw new ArgumentNullException("value"); } } public abstract bool Selected { set; } public abstract void CrossingFailure(); public virtual void SetMaterial(int material, bool forceMaterialSettings) { } // set never appears to be called public virtual int VehicleType { get { return 0; } set { return; } } public virtual void VehicleFloatParam(int param, float value) { } public virtual void VehicleVectorParam(int param, Vector3 value) { } public virtual void VehicleRotationParam(int param, Quaternion rotation) { } public virtual void VehicleFlags(int param, bool remove) { } public virtual void SetCameraPos(Quaternion CameraRotation) { } public virtual bool BuildingRepresentation { get; set; } public virtual bool BlockPhysicalReconstruction { get; set; } //set never appears to be called public virtual bool VolumeDetect { get { return false; } set { return; } } public abstract Vector3 Acceleration { get; } public abstract void AddAngularForce(Vector3 force, bool pushforce); public virtual void ClearVelocity() { } public event BlankHandler OnPhysicalRepresentationChanged; public void FirePhysicalRepresentationChanged() { if (OnPhysicalRepresentationChanged != null) OnPhysicalRepresentationChanged(); } } public abstract class PhysicsActor { // disable warning: public events #pragma warning disable 67 public delegate void RequestTerseUpdate(); public delegate void CollisionUpdate(EventArgs e); public delegate void OutOfBounds(Vector3 pos); public event RequestTerseUpdate OnRequestTerseUpdate; public event RequestTerseUpdate OnSignificantMovement; public event RequestTerseUpdate OnPositionAndVelocityUpdate; public event CollisionUpdate OnCollisionUpdate; public event OutOfBounds OnOutOfBounds; #pragma warning restore 67 public abstract Vector3 Size { get; set; } public abstract uint LocalID { get; set; } public UUID UUID { get; set; } public virtual void RequestPhysicsterseUpdate() { // Make a temporary copy of the event to avoid possibility of // a race condition if the last subscriber unsubscribes // immediately after the null check and before the event is raised. RequestTerseUpdate handler = OnRequestTerseUpdate; if (handler != null) handler(); } public virtual void RaiseOutOfBounds(Vector3 pos) { // Make a temporary copy of the event to avoid possibility of // a race condition if the last subscriber unsubscribes // immediately after the null check and before the event is raised. OutOfBounds handler = OnOutOfBounds; if (handler != null) handler(pos); } public virtual void SendCollisionUpdate(EventArgs e) { CollisionUpdate handler = OnCollisionUpdate; if (handler != null) handler(e); } public virtual bool SubscribedToCollisions() { return OnCollisionUpdate != null; } public virtual void TriggerSignificantMovement() { //Call significant movement RequestTerseUpdate significantMovement = OnSignificantMovement; if (significantMovement != null) significantMovement(); } public virtual void TriggerMovementUpdate() { //Call significant movement RequestTerseUpdate movementUpdate = OnPositionAndVelocityUpdate; if (movementUpdate != null) movementUpdate(); } public abstract Vector3 Position { get; set; } public abstract float Mass { get; } public abstract Vector3 Force { get; set; } public abstract Vector3 CenterOfMass { get; } public abstract Vector3 Velocity { get; set; } public abstract Vector3 Torque { get; set; } public abstract float CollisionScore { get; set; } public abstract Quaternion Orientation { get; set; } public abstract int PhysicsActorType { get; } public abstract bool IsPhysical { get; set; } public abstract bool Flying { get; set; } public abstract bool SetAlwaysRun { get; set; } public abstract bool ThrottleUpdates { get; set; } public abstract bool IsColliding { get; set; } public abstract bool FloatOnWater { set; } public abstract Vector3 RotationalVelocity { get; set; } public abstract float Buoyancy { get; set; } public abstract void AddForce(Vector3 force, bool pushforce); public abstract void SubscribeEvents(int ms); public abstract void UnSubscribeEvents(); public abstract bool SubscribedEvents(); public abstract void SendCollisions(); public abstract void AddCollisionEvent(uint localID, ContactPoint contact); public virtual void ForceSetVelocity(Vector3 velocity) { } public virtual void ForceSetPosition(Vector3 position) { } } public class NullObjectPhysicsActor : PhysicsObject { public override Vector3 Position { get { return Vector3.Zero; } set { return; } } public override bool SetAlwaysRun { get { return false; } set { return; } } public override uint LocalID { get { return 0; } set { return; } } public override bool Selected { set { return; } } public override float Buoyancy { get { return 0f; } set { return; } } public override bool FloatOnWater { set { return; } } public override Vector3 Size { get { return Vector3.Zero; } set { return; } } public override float Mass { get { return 0f; } } public override Vector3 Force { get { return Vector3.Zero; } set { return; } } public override Vector3 CenterOfMass { get { return Vector3.Zero; } } public override Vector3 Velocity { get { return Vector3.Zero; } set { return; } } public override Vector3 Torque { get { return Vector3.Zero; } set { return; } } public override float CollisionScore { get { return 0f; } set { } } public override Quaternion Orientation { get { return Quaternion.Identity; } set { } } public override Vector3 Acceleration { get { return Vector3.Zero; } } public override bool IsPhysical { get { return false; } set { return; } } public override bool Flying { get { return false; } set { return; } } public override bool ThrottleUpdates { get { return false; } set { return; } } public override bool IsColliding { get { return false; } set { return; } } public override int PhysicsActorType { get { return (int) ActorTypes.Ground; } } public override Vector3 RotationalVelocity { get { return Vector3.Zero; } set { return; } } public override void CrossingFailure() { } public override void AddForce(Vector3 force, bool pushforce) { } public override void AddAngularForce(Vector3 force, bool pushforce) { } public override void SubscribeEvents(int ms) { } public override void UnSubscribeEvents() { } public override bool SubscribedEvents() { return false; } public override void SendCollisions() { } public override void AddCollisionEvent(uint CollidedWith, ContactPoint contact) { } } public class NullCharacterPhysicsActor : PhysicsCharacter { public override bool IsJumping { get { return false; } } public override bool IsPreJumping { get { return false; } } public override float SpeedModifier { get { return 1.0f; } set { } } public override Vector3 Position { get { return Vector3.Zero; } set { return; } } public override bool SetAlwaysRun { get { return false; } set { return; } } public override uint LocalID { get { return 0; } set { return; } } public override float Buoyancy { get { return 0f; } set { return; } } public override bool FloatOnWater { set { return; } } public override Vector3 Size { get { return Vector3.Zero; } set { return; } } public override float Mass { get { return 0f; } } public override Vector3 Force { get { return Vector3.Zero; } set { return; } } public override Vector3 CenterOfMass { get { return Vector3.Zero; } } public override Vector3 Velocity { get { return Vector3.Zero; } set { return; } } public override Vector3 Torque { get { return Vector3.Zero; } set { return; } } public override float CollisionScore { get { return 0f; } set { } } public override Quaternion Orientation { get { return Quaternion.Identity; } set { } } public override bool IsPhysical { get { return false; } set { return; } } public override bool Flying { get { return false; } set { return; } } public override bool ThrottleUpdates { get { return false; } set { return; } } public override bool IsColliding { get { return false; } set { return; } } public override int PhysicsActorType { get { return (int) ActorTypes.Unknown; } } public override Vector3 RotationalVelocity { get { return Vector3.Zero; } set { return; } } public override void AddForce(Vector3 force, bool pushforce) { } public override void SubscribeEvents(int ms) { } public override void UnSubscribeEvents() { } public override bool SubscribedEvents() { return false; } public override void SendCollisions() { } public override void AddCollisionEvent(uint CollidedWith, ContactPoint contact) { } } }
using System; using System.Collections.ObjectModel; using System.Linq; using System.Collections.Generic; namespace ExportExtensionCommon { #region TVIModel /// In order to implement a tree view in SIIE one needs to implement an instance of the /// TreeViewItemModel (TVIModel). A TVIModel must /// * Maintain the Name attribute to hold the string to be displayed at a tree node /// * Maintain all information needed to work with that node /// It is serialized so the information maintained may coexist in workable form and /// as a serialized form, e.g. DirectoryInfo + FullPathName. Note that the xml serializer /// is being used. Only public properties are serialized. /// public abstract class TVIModel { // This is used to identify the node public string Id { get; set; } // The name as shown in the tree and identifying this node public string DisplayName { get; set; } // Depth in the tree, starts from 0 public int Depth { get; set; } // Indicates whether this node can be expanded public virtual bool IsFolder { get; set; } = true; // The icon to be displayed for this node public virtual string Icon { get { return IsFolder ? "Folder" : "Default"; } } // Return all children for the current node public abstract List<TVIModel> GetChildren(); // String use to concatenate two nodes in the final display string, e.g. "/" or "\" or "->" public virtual string GetPathConcatenationString() { return "/"; } // Name of node type, e.g. "File system folder"; is used for error message public abstract string GetTypeName(); // Pathname is the Name of all nodes concatenated by the concatenation string public enum Pathtype { Id, DisplayName }; public virtual string GetPath(List<TVIModel> path, Pathtype pt) { string result = string.Empty; foreach (TVIModel node in path) result += (pt == Pathtype.DisplayName? node.DisplayName : node.Id) + GetPathConcatenationString(); return result; } // Compare two names. Overwrite if e.g. name is case insensitive public virtual bool IsSame(string id) { return Id == id; } public abstract TVIModel Clone(); } #endregion #region SIEETreeView /// The SIEETreeView is the anchor of the tree. /// And it is also the type of the Children member. public class SIEETreeView : ObservableCollection<TVIViewModel> { public SIEEViewModel Vm { get; set; } public SIEETreeView(SIEEViewModel vm) { this.Vm = vm; } public void AddItem(TVIViewModel item) { this.Add(item); item.Vm = Vm; item.Children.Vm = Vm; } // Open the tree view according to the serialzed path. // Expands all nodes on the way public TVIViewModel InitializeTree(List<string> serializedPath, Type modelType) { if (serializedPath == null) return null; SIEETreeView currentTree = this; TVIViewModel currItem = null; try { for (int i = 0; i != serializedPath.Count; i++) { TVIModel tvim = (TVIModel)TVIViewModel.deSerialize(serializedPath[i], modelType); currItem = currentTree.findChild(tvim.Id); if (currItem == null) throw new Exception(tvim.DisplayName + " not found"); currItem.IsExpanded = true; currItem.IsSelected = true; currentTree = currItem.Children; } } catch (Exception e) { string errMsg = "No items in tree view"; string title = "Error"; if (this.Count() > 0) { TVIModel someModel = this[0].Tvim; errMsg = "Could not locate " + someModel.GetTypeName() + ". Reason:\n" + e.Message; title = "Navigate to " + someModel.GetTypeName(); } SIEEMessageBox.Show(errMsg, title, System.Windows.MessageBoxImage.Error ); } return currItem; } // Find the node in the tree starting at the current node // Expand tree if necessary public TVIViewModel FindNodeInTree(string idPath) { if (this.Count() == 0) return null; string concatString = this[0].Tvim.GetPathConcatenationString(); string[] tokens = idPath.Split(new[] { concatString }, StringSplitOptions.None); TVIViewModel currNode = null; SIEETreeView currTree = this; for (int i = 0; i != tokens.Length; i++) { if (tokens[i] == string.Empty) continue; currNode = currTree.findChild(tokens[i]); if (currNode == null) return null; currNode.IsExpanded = true; currTree = currNode.Children; } return currNode; } // Find direct child private TVIViewModel findChild(string childId) { foreach (TVIViewModel child in this) if (child.Tvim.IsSame(childId)) return child; return null; } } #endregion #region Tree view: Item view model /// Base class for all ViewModel classes displayed by TreeViewItems. /// This acts as an adapter between a raw data object and a TreeViewItem. public class TVIViewModel : ModelBase { #region Construction static readonly TVIViewModel DummyChild = new TVIViewModel(); // This list can be extended when using the tree static Dictionary<string, string> IconMap = new Dictionary<string, string>() { { "Folder", "pack://application:,,,/ExportExtensionCommon.Base;component/Resources/folder.png" }, { "Default", "pack://application:,,,/ExportExtensionCommon.Base;component/Resources/document.png" }, }; public TVIViewModel(TVIModel model, TVIViewModel parent, bool lazyLoadChildren) { Tvim = model; this.parent = parent; Tvim.Depth = parent == null ? 0 : parent.Tvim.Depth + 1; children = new SIEETreeView(null); if (lazyLoadChildren && Tvim.IsFolder) children.Add(DummyChild); } // This is used to create the DummyChild instance. private TVIViewModel() { } //public void SetAsParent() { parent = null; } #endregion #region Properties private TVIModel tvim; public TVIModel Tvim { get { return tvim; } set { SetField(ref tvim, value); RaisePropertyChanged("DisplayName"); } } public SIEEViewModel Vm { get; set; } = null; public string DisplayName { get { return Tvim.DisplayName; } } /// Returns the logical child items of this object. readonly SIEETreeView children; public SIEETreeView Children { get { return children; } } /// Returns true if this object's Children have not yet been populated. public bool HasDummyChild { get { return this.Children.Count == 1 && this.Children[0] == DummyChild; } } /// Gets/sets whether the TreeViewItem /// associated with this object is expanded. bool isExpanded; public bool IsExpanded { get { return isExpanded; } set { SetField(ref isExpanded, value); // Expand all the way up to the root. if (isExpanded && parent != null) parent.IsExpanded = true; // Lazy load the child items, if necessary. if (this.HasDummyChild) { this.Children.Remove(DummyChild); this.LoadChildren(); } } } /// Gets/sets whether the TreeViewItem /// associated with this object is selected. bool isSelected; public bool IsSelected { get { return isSelected; } set { SetField(ref isSelected, value); } } private TVIViewModel parent; public TVIViewModel Parent { get { return parent; } } public string Icon { get { return IconMap[Tvim != null && IconMap.ContainsKey(Tvim.Icon)? Tvim.Icon : "Folder"]; } } #endregion #region Functions protected void LoadChildren() { if (Vm != null) Vm.IsRunning = true; try { foreach (TVIModel child in Tvim.GetChildren()) Children.AddItem(new TVIViewModel(child.Clone(), this, true)); } finally { if (Vm != null) Vm.IsRunning = false; } } // Recursive function to create forward path to current node public List<TVIModel> GetPath() { List<TVIModel> result; if (Parent == null) { result = new List<TVIModel>(); result.Add(Tvim); return result; } result = Parent.GetPath(); result.Add(Tvim); return result; } //public string GetIdPath() //{ // return Tvim.GetPath(GetPath(), TVIModel.Pathtype.Id); //} public string GetDisplayNamePath() { return Tvim.GetPath(GetPath(), TVIModel.Pathtype.DisplayName); } public List<string> GetSerializedPath() { List<string> result; if (Parent == null) { result = new List<string>(); result.Add(serialize(Tvim)); return result; } result = Parent.GetSerializedPath(); result.Add(serialize(Tvim)); return result; } public static TVIModel GetSelectedItem(List<string> serializedFolderPath, Type modelType) { if (serializedFolderPath.Count == 0) return null; return deSerialize(serializedFolderPath.Last(), modelType) as TVIModel; } public static string serialize(object o) { return Serializer.SerializeToXmlString(o, System.Text.Encoding.Unicode); } public static object deSerialize(string s, Type t) { return Serializer.DeserializeFromXmlString(s, t, System.Text.Encoding.Unicode); } #endregion } #endregion }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. 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. *******************************************************************************/ // // Novell.Directory.Ldap.LdapSearchResults.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap { /// <summary> An LdapSearchResults object is returned from a synchronous search /// operation. It provides access to all results received during the /// operation (entries and exceptions). /// /// </summary> /// <seealso cref="LdapConnection.Search"> /// </seealso> public class LdapSearchResults { /// <summary> Returns a count of the items in the search result. /// /// Returns a count of the entries and exceptions remaining in the object. /// If the search was submitted with a batch size greater than zero, /// getCount reports the number of results received so far but not enumerated /// with next(). If batch size equals zero, getCount reports the number of /// items received, since the application thread blocks until all results are /// received. /// /// </summary> /// <returns> The number of items received but not retrieved by the application /// </returns> virtual public int Count { get { int qCount = queue.MessageAgent.Count; return entryCount - entryIndex + referenceCount - referenceIndex + qCount; } } /// <summary> Returns the latest server controls returned by the server /// in the context of this search request, or null /// if no server controls were returned. /// /// </summary> /// <returns> The server controls returned with the search request, or null /// if none were returned. /// </returns> virtual public LdapControl[] ResponseControls { get { return controls; } } /// <summary> Collects batchSize elements from an LdapSearchQueue message /// queue and places them in a Vector. /// /// If the last message from the server, /// the result message, contains an error, it will be stored in the Vector /// for nextElement to process. (although it does not increment the search /// result count) All search result entries will be placed in the Vector. /// If a null is returned from getResponse(), it is likely that the search /// was abandoned. /// /// </summary> /// <returns> true if all search results have been placed in the vector. /// </returns> private bool BatchOfResults { get { LdapMessage msg; // <=batchSize so that we can pick up the result-done message for (int i = 0; i < batchSize; ) { try { if ((msg = queue.getResponse()) != null) { // Only save controls if there are some LdapControl[] ctls = msg.Controls; if (ctls != null) { controls = ctls; } if (msg is LdapSearchResult) { // Search Entry System.Object entry = ((LdapSearchResult) msg).Entry; entries.Add(entry); i++; entryCount++; } else if (msg is LdapSearchResultReference) { // Search Ref System.String[] refs = ((LdapSearchResultReference) msg).Referrals; if (cons.ReferralFollowing) { // referralConn = conn.chaseReferral(queue, cons, msg, refs, 0, true, referralConn); } else { references.Add(refs); referenceCount++; } } else { // LdapResponse LdapResponse resp = (LdapResponse) msg; int resultCode = resp.ResultCode; // Check for an embedded exception if (resp.hasException()) { // Fake it, results in an exception when msg read resultCode = LdapException.CONNECT_ERROR; } if ((resultCode == LdapException.REFERRAL) && cons.ReferralFollowing) { // Following referrals // referralConn = conn.chaseReferral(queue, cons, resp, resp.Referrals, 0, false, referralConn); } else if (resultCode != LdapException.SUCCESS) { // Results in an exception when message read entries.Add(resp); entryCount++; } // We are done only when we have read all messages // including those received from following referrals int[] msgIDs = queue.MessageIDs; if (msgIDs.Length == 0) { // Release referral exceptions // conn.releaseReferralConnections(referralConn); return true; // search completed } else { } continue; } } else { // We get here if the connection timed out // we have no responses, no message IDs and no exceptions LdapException e = new LdapException(null, LdapException.Ldap_TIMEOUT, (System.String) null); entries.Add(e); break; } } catch (LdapException e) { // Hand exception off to user entries.Add(e); } continue; } return false; // search not completed } } private System.Collections.ArrayList entries; // Search entries private int entryCount; // # Search entries in vector private int entryIndex; // Current position in vector private System.Collections.ArrayList references; // Search Result References private int referenceCount; // # Search Result Reference in vector private int referenceIndex; // Current position in vector private int batchSize; // Application specified batch size private bool completed = false; // All entries received private LdapControl[] controls = null; // Last set of controls private LdapSearchQueue queue; private static System.Object nameLock; // protect resultsNum private static int resultsNum = 0; // used for debug private System.String name; // used for debug private LdapConnection conn; // LdapConnection which started search private LdapSearchConstraints cons; // LdapSearchConstraints for search private System.Collections.ArrayList referralConn = null; // Referral Connections /// <summary> Constructs a queue object for search results. /// /// </summary> /// <param name="conn">The LdapConnection which initiated the search /// /// </param> /// <param name="queue">The queue for the search results. /// /// </param> /// <param name="cons">The LdapSearchConstraints associated with this search /// </param> /* package */ internal LdapSearchResults(LdapConnection conn, LdapSearchQueue queue, LdapSearchConstraints cons) { // setup entry Vector this.conn = conn; this.cons = cons; int batchSize = cons.BatchSize; int vectorIncr = (batchSize == 0)?64:0; entries = new System.Collections.ArrayList((batchSize == 0)?64:batchSize); entryCount = 0; entryIndex = 0; // setup search reference Vector references = new System.Collections.ArrayList(5); referenceCount = 0; referenceIndex = 0; this.queue = queue; this.batchSize = (batchSize == 0)?System.Int32.MaxValue:batchSize; return ; } /// <summary> Reports if there are more search results. /// /// </summary> /// <returns> true if there are more search results. /// </returns> public virtual bool hasMore() { bool ret = false; if ((entryIndex < entryCount) || (referenceIndex < referenceCount)) { // we have data ret = true; } else if (completed == false) { // reload the Vector by getting more results resetVectors(); ret = (entryIndex < entryCount) || (referenceIndex < referenceCount); } return ret; } /* * If both of the vectors are empty, get more data for them. */ private void resetVectors() { // If we're done, no further checking needed if (completed) { return ; } // Checks if we have run out of references if ((referenceIndex != 0) && (referenceIndex >= referenceCount)) { SupportClass.SetSize(references, 0); referenceCount = 0; referenceIndex = 0; } // Checks if we have run out of entries if ((entryIndex != 0) && (entryIndex >= entryCount)) { SupportClass.SetSize(entries, 0); entryCount = 0; entryIndex = 0; } // If no data at all, must reload enumeration if ((referenceIndex == 0) && (referenceCount == 0) && (entryIndex == 0) && (entryCount == 0)) { completed = BatchOfResults; } return ; } /// <summary> Returns the next result as an LdapEntry. /// /// If automatic referral following is disabled or if a referral /// was not followed, next() will throw an LdapReferralException /// when the referral is received. /// /// </summary> /// <returns> The next search result as an LdapEntry. /// /// </returns> /// <exception> LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> /// <exception> LdapReferralException A referral was received and not /// followed. /// </exception> public virtual LdapEntry next() { if (completed && (entryIndex >= entryCount) && (referenceIndex >= referenceCount)) { throw new System.ArgumentOutOfRangeException("LdapSearchResults.next() no more results"); } // Check if the enumeration is empty and must be reloaded resetVectors(); System.Object element = null; // Check for Search References & deliver to app as they come in // We only get here if not following referrals/references if (referenceIndex < referenceCount) { System.String[] refs = (System.String[]) (references[referenceIndex++]); LdapReferralException rex = new LdapReferralException(ExceptionMessages.REFERENCE_NOFOLLOW); rex.setReferrals(refs); throw rex; } else if (entryIndex < entryCount) { // Check for Search Entries and the Search Result element = entries[entryIndex++]; if (element is LdapResponse) { // Search done w/bad status if (((LdapResponse) element).hasException()) { LdapResponse lr = (LdapResponse) element; ReferralInfo ri = lr.ActiveReferral; if (ri != null) { // Error attempting to follow a search continuation reference LdapReferralException rex = new LdapReferralException(ExceptionMessages.REFERENCE_ERROR, lr.Exception); rex.setReferrals(ri.ReferralList); rex.FailedReferral = ri.ReferralUrl.ToString(); throw rex; } } // Throw an exception if not success ((LdapResponse) element).chkResultCode(); } else if (element is LdapException) { throw (LdapException) element; } } else { // If not a Search Entry, Search Result, or search continuation // we are very confused. // LdapSearchResults.next(): No entry found & request is not complete throw new LdapException(ExceptionMessages.REFERRAL_LOCAL, new System.Object[]{"next"}, LdapException.LOCAL_ERROR, (System.String) null); } return (LdapEntry) element; } /// <summary> Cancels the search request and clears the message and enumeration.</summary> /*package*/ internal virtual void Abandon() { // first, remove message ID and timer and any responses in the queue queue.MessageAgent.AbandonAll(); // next, clear out enumeration resetVectors(); completed = true; } static LdapSearchResults() { nameLock = new System.Object(); } } }
// Copyright (c) 2007, LShift Ltd. <query@lshift.net> // Copyright (c) 2007, Tony Garnock-Jones <tonyg@kcbbs.gen.nz> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Linq; namespace com.rabbitmq.tools.ndocproc { public class NDocProc { public static void Main(string[] args_array) { new NDocProc(new ArrayList(args_array)); } public void Banner() { foreach (string s in new string[] { "NDocProc.exe -- .NET XML documentation processor", "Copyright (c) 2007, LShift Ltd. <query@lshift.net>", "Copyright (c) 2007, Tony Garnock-Jones <tonyg@kcbbs.gen.nz>", "===========================================================================" }) { Console.Out.WriteLine(s); } } public void Usage() { Console.Error.WriteLine("Usage: ndocproc [options] <destdir> <xmlfile> [<xmlfile> [...]]"); Console.Error.WriteLine(" where each option can be:"); Console.Error.WriteLine(" /nonpublic include non-public members"); Console.Error.WriteLine(" /nogoogledtypes suppress \"I'm feeling lucky\" links"); Console.Error.WriteLine(" /suppress:<namespace> suppress analysis of items in <namespace>"); Environment.Exit(1); } public void HandleOption(string opt) { if (opt == "/nonpublic") { includeNonpublic = true; } else if (opt == "/nogoogledtypes") { googleNonlocalTypes = false; } else if (opt.StartsWith("/suppress:")) { string ns = opt.Substring(10); suppressedNamespaces[ns] = ns; Log("Suppressing namespace "+ns); } } public NDocProc(ArrayList args) { Banner(); while (args.Count > 0 && IsOptionName((string)args[0])) { HandleOption((string) args[0]); args.RemoveAt(0); } if (args.Count < 2) { Usage(); } this.destdir = (string) args[0]; args.RemoveAt(0); Directory.CreateDirectory(destdir); foreach (string xmlFilename in args) { Load(xmlFilename); } Reflect(); Generate(); } private static bool IsOptionName(string s) { return (s.StartsWith("/no") || s.StartsWith("/suppress")); } /////////////////////////////////////////////////////////////////////////// public string destdir; public IDictionary<string, Assembly> assemblies = new Dictionary<string, Assembly>(); public IDictionary<string, XmlNode> members = new Dictionary<string, XmlNode>(); public IDictionary<string, ArrayList> namespaces = new Dictionary<string, ArrayList>(); public IDictionary<string, Type> types = new Dictionary<string, Type>(); public IDictionary<Type, ArrayList> knownSubtypes = new Dictionary<Type, ArrayList>(); public IDictionary<string, string> suppressedNamespaces = new Dictionary<string, string>(); public bool includeNonpublic = false; public bool googleNonlocalTypes = true; public void Log(object message) { Console.Error.WriteLine("* " + message); } public string FullPath(string leaf) { return Path.Combine(destdir, leaf); } public XmlWriter OpenOut(string leaf) { string path = FullPath(leaf); Log("Creating " + path); XmlTextWriter w = new XmlTextWriter(path, Encoding.UTF8); w.Formatting = Formatting.Indented; return w; } public string MakeAssemblyPath(string assemblyName) { return assemblyName + ".dll"; } public Assembly LoadAssembly(string xmlFilename, string assemblyPath) { try { return Assembly.LoadFrom(assemblyPath); } catch (FileNotFoundException) { return Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(xmlFilename), assemblyPath)); } } public void Load(string xmlFilename) { Log("Loading XML "+xmlFilename); XmlDocument d = new XmlDocument(); d.Load(xmlFilename); foreach (XmlNode assemblyNode in d.SelectNodes("/doc/assembly")) { string assemblyName = assemblyNode.SelectSingleNode("name").InnerText; Assembly a; if (!assemblies.ContainsKey(assemblyName)) { string assemblyPath = MakeAssemblyPath(assemblyName); Log("Loading Assembly "+assemblyPath); a = LoadAssembly(xmlFilename, assemblyPath); assemblies[assemblyName] = a; } else { a = (Assembly) assemblies[assemblyName]; } } foreach (XmlNode memberNode in d.SelectNodes("//member")) { members[memberNode.SelectSingleNode("@name").InnerText] = memberNode; } } public sealed class MemberInfoNameComparer: IComparer { int IComparer.Compare(Object a, Object b) { return ((string) ((MemberInfo) a).Name).CompareTo(((MemberInfo) b).Name); } } public void AddKnownSubtype(Type _base, Type derived) { if (_base != null) { if (!knownSubtypes.ContainsKey(_base)) { knownSubtypes[_base] = new ArrayList(); } ((ArrayList) knownSubtypes[_base]).Add(derived); } } public string Namespace(Type t) { return (t.Namespace != null) ? t.Namespace : ""; } public void Reflect() { foreach (var entry in assemblies) { var a = entry.Value; foreach (Type t in a.GetTypes()) { if (!namespaces.ContainsKey(Namespace(t))) { namespaces[Namespace(t)] = new ArrayList(); } ((ArrayList) namespaces[Namespace(t)]).Add(t); types[t.FullName] = t; } } foreach (var entry in types) { Type t = (Type) entry.Value; AddKnownSubtype(t.BaseType, t); foreach (Type i in GetDirectInterfaces(t)) { AddKnownSubtype(i, t); } } } public Type[] GetDirectInterfaces(Type t) { if (t.BaseType == null) { return t.GetInterfaces(); } else { Type[] baseInterfaces = t.BaseType.GetInterfaces(); return t.FindInterfaces(new TypeFilter(InterfaceRejector), baseInterfaces); } } // I find it fascinating that after so many decades of support // for closures, we're still stuck in a C-style mentality of // passing function-pointer that take an explicit context // argument rather than a proper closure object. public static bool InterfaceRejector(Type candidate, Object criteria) { Type[] interfacesToReject = (Type[]) criteria; foreach (Type t in interfacesToReject) { if (candidate.Equals(t)) return false; } return true; } public ICollection Sorted(ICollection other, IComparer cmp) { ArrayList result = new ArrayList(other); result.Sort(cmp); return result; } public SortedDictionary<K, V> Sorted<K, V>(IDictionary<K, V> other, IComparer<K> cmp) { return new SortedDictionary<K, V>(other, cmp); } public bool NotSuppressed(string nsName) { return !suppressedNamespaces.ContainsKey(nsName); } public void GenerateConfig() { XmlWriter w = OpenOut("config.xml"); w.WriteStartDocument(); w.WriteStartElement("options"); w.WriteStartElement("option"); w.WriteAttributeString("googlenonlocaltypes", googleNonlocalTypes ? "true" : "false"); w.WriteEndElement(); w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); w.Close(); } public void Generate() { GenerateConfig(); XmlWriter w = OpenOut("index.xml"); w.WriteStartDocument(); w.WriteStartElement("index"); w.WriteStartElement("namespaces"); foreach (var entry in Sorted(namespaces, StringComparer.InvariantCulture)) { string namespaceName = (string) entry.Key; if (NotSuppressed(namespaceName)) { w.WriteStartElement("namespace"); w.WriteAttributeString("name", namespaceName); WriteItemDocs(w, "N:"+namespaceName, "summary"); w.WriteEndElement(); } } w.WriteEndElement(); w.WriteStartElement("types"); foreach (var entry in Sorted(types, StringComparer.InvariantCulture)) { Type t = (Type) entry.Value; if (NotSuppressed(Namespace(t))) { w.WriteStartElement("typedoc"); GenerateTypeRef(w, t); WriteItemDocs(w, t, "summary"); w.WriteEndElement(); } } w.WriteEndElement(); w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); w.Close(); var typesToIterate = types.Values.ToList<Type>(); typesToIterate.RemoveAll(t => t.FullName.Contains("<")); foreach (Type t in typesToIterate) { if (NotSuppressed(Namespace(t))) { GenerateTypePage(t); } } foreach (var entry in namespaces) { string nsName = (string) entry.Key; if (NotSuppressed(nsName)) { GenerateNamespacePage(nsName, (ArrayList) entry.Value); } } } public void GenerateTypePage(Type t) { var filename = "type-" + t.FullName + ".xml"; Console.WriteLine("Generating page for type {0} at {1}", t.FullName, filename); XmlWriter w = OpenOut(filename); w.WriteStartDocument(); w.WriteStartElement("typedef"); WriteItemAttributes(w, t); GenerateTypeRef(w, t, true); Type[] nestedTypes = t.GetNestedTypes(LiberalFlags); if (nestedTypes.Length > 0) { w.WriteStartElement("nestedtypes"); foreach (Type nested in nestedTypes) { GenerateTypeRef(w, nested); } w.WriteEndElement(); } w.WriteStartElement("extends"); if (t.BaseType != null) { w.WriteStartElement("class"); GenerateTypeRef(w, t.BaseType); w.WriteEndElement(); } foreach (Type i in Sorted(GetDirectInterfaces(t), new MemberInfoNameComparer())) { w.WriteStartElement("interface"); GenerateTypeRef(w, i); w.WriteEndElement(); } w.WriteEndElement(); w.WriteStartElement("known-subtypes"); if (knownSubtypes.ContainsKey(t)) { ArrayList sts = (ArrayList) knownSubtypes[t]; sts.Sort(new TypeComparer()); foreach (Type st in sts) { GenerateTypeRef(w, st); } } w.WriteEndElement(); WriteItemDocs(w, t); w.WriteStartElement("members"); foreach (FieldInfo fi in Sorted(t.GetFields(LiberalFlags), new MemberInfoNameComparer())) { GenerateFieldDoc(w, fi); } foreach (PropertyInfo pi in Sorted(t.GetProperties(LiberalFlags), new MemberInfoNameComparer())) { GeneratePropertyDoc(w, pi); } foreach (EventInfo ei in Sorted(t.GetEvents(LiberalFlags), new MemberInfoNameComparer())) { GenerateEventDoc(w, ei); } var mbs = Sorted(t.GetConstructors(LiberalFlags), new MemberInfoNameComparer()); foreach (MethodBase mi in mbs) { Console.WriteLine("\tProcessing method {0}", mi.Name); GenerateMethodDoc(w, mi); } foreach (MethodBase mi in Sorted(t.GetMethods(LiberalFlags), new MemberInfoNameComparer())) { GenerateMethodDoc(w, mi); } w.WriteEndElement(); w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); w.Close(); } public string GenericBaseName(string n) { return n.Split(new char[1] {'`'})[0]; } public string MaybeInnerFullName(Type t) { return (t.FullName == null ? t.Name : t.FullName).Replace("+", "."); } public string ConcatNamespace(Type ptBase, string suffix) { if (ptBase.Namespace != null) { return ptBase.Namespace + "." + suffix; } else { return suffix; } } public void AppendTypeName(StringBuilder sb, Type pt) { if (pt.IsGenericParameter) { if (pt.DeclaringMethod != null) { sb.Append("``"); } else { sb.Append("`"); } sb.Append(pt.GenericParameterPosition); } else { if (pt.IsGenericType) { Type ptBase = pt.GetGenericTypeDefinition(); // Match bugs in csc's documentation output. // A generic type A.X+Y`1 comes out A.Y{T} // A nongeneric type A.X+Y comes out A.X.Y sb.Append(ConcatNamespace(ptBase, GenericBaseName(ptBase.Name))); Type[] ptArgs = pt.GetGenericArguments(); if (ptArgs.Length > 0) { sb.Append("{"); bool needComma = false; foreach (Type ptArg in ptArgs) { if (needComma) { sb.Append(","); } needComma = true; AppendTypeName(sb, ptArg); } sb.Append("}"); } } else { sb.Append(GenericBaseName(MaybeInnerFullName(pt))); } } } public string MethodFullName(MethodBase mi, string shortName) { StringBuilder sb = new StringBuilder(); sb.Append(MaybeInnerFullName(mi.DeclaringType) + "." + shortName); if (mi.ContainsGenericParameters && !mi.IsConstructor) { int genArgCount = mi.GetGenericArguments().Length; if (genArgCount > 0) { sb.Append("``"); sb.Append(genArgCount); } } bool needComma = false; foreach (ParameterInfo pi in mi.GetParameters()) { if (needComma) { sb.Append(","); } else { sb.Append("("); needComma = true; } if (pi.IsOut || pi.ParameterType.IsByRef) { AppendTypeName(sb, pi.ParameterType.GetElementType()); sb.Append("@"); } else { AppendTypeName(sb, pi.ParameterType); } } if (needComma) { sb.Append(")"); } return sb.ToString(); } public string MemberFullName(MemberInfo mi) { if (mi is Type) { Type t = (Type) mi; return MaybeInnerFullName(t); } else if (mi is MethodInfo) { return MethodFullName((MethodBase) mi, mi.Name); } else if (mi is ConstructorInfo) { return MethodFullName((MethodBase) mi, "#ctor"); } else { return MaybeInnerFullName(mi.DeclaringType) + "." + mi.Name; } } public void GenerateMethodDoc(XmlWriter w, MethodBase mi) { w.WriteStartElement("method"); WriteItemAttributes(w, mi); GenerateGenericArguments(w, mi); if (mi is MethodInfo) { w.WriteStartElement("returns"); GenerateTypeRef(w, ((MethodInfo) mi).ReturnType); w.WriteEndElement(); } else if (mi is ConstructorInfo) { w.WriteStartElement("constructor"); w.WriteEndElement(); } else { throw new Exception("Unsupported MethodBase: " + mi); } w.WriteStartElement("parameters"); foreach (ParameterInfo pi in mi.GetParameters()) { w.WriteStartElement("parameter"); w.WriteAttributeString("name", pi.Name); w.WriteAttributeString("input", pi.IsIn ? "true" : "false"); w.WriteAttributeString("output", pi.IsOut ? "true" : "false"); w.WriteAttributeString("reference", ((!pi.IsOut) && pi.ParameterType.IsByRef) ? "true" : "false"); w.WriteAttributeString("position", pi.Position.ToString()); if (pi.IsOut || pi.ParameterType.IsByRef) { GenerateTypeRef(w, pi.ParameterType.GetElementType()); } else { GenerateTypeRef(w, pi.ParameterType); } w.WriteEndElement(); } w.WriteEndElement(); WriteItemDocs(w, mi); w.WriteEndElement(); } public void GenerateFieldDoc(XmlWriter w, FieldInfo fi) { w.WriteStartElement("field"); WriteItemAttributes(w, fi); GenerateTypeRef(w, fi.FieldType); WriteItemDocs(w, fi); w.WriteEndElement(); } public void GeneratePropertyDoc(XmlWriter w, PropertyInfo pi) { w.WriteStartElement("property"); WriteItemAttributes(w, pi); GenerateTypeRef(w, pi.PropertyType); WriteItemDocs(w, pi); if (pi.CanRead) { w.WriteStartElement("getter"); WriteItemAttributes(w, pi.GetGetMethod(true)); w.WriteEndElement(); } if (pi.CanWrite) { w.WriteStartElement("setter"); WriteItemAttributes(w, pi.GetSetMethod(true)); w.WriteEndElement(); } w.WriteEndElement(); } public void GenerateEventDoc(XmlWriter w, EventInfo ei) { w.WriteStartElement("event"); WriteItemAttributes(w, ei); GenerateTypeRef(w, ei.EventHandlerType); WriteItemDocs(w, ei); w.WriteEndElement(); } public sealed class TypeComparer: IComparer { int IComparer.Compare(Object a, Object b) { return ((Type) a).FullName.CompareTo(((Type) b).FullName); } } public void GenerateNamespacePage(string namespaceName, ArrayList types) { types.Sort(new TypeComparer()); XmlWriter w = OpenOut("namespace-"+namespaceName+".xml"); w.WriteStartDocument(); w.WriteStartElement("namespace"); w.WriteAttributeString("name", namespaceName); WriteItemDocs(w, "N:"+namespaceName); foreach (Type t in Sorted(types, new MemberInfoNameComparer())) { w.WriteStartElement("typedoc"); GenerateTypeRef(w, t); WriteItemDocs(w, t, "summary"); w.WriteEndElement(); } w.WriteEndElement(); w.WriteEndDocument(); w.Flush(); w.Close(); } public void WriteItemAttributes(XmlWriter w, MemberInfo mi) { w.WriteAttributeString("anchor", KeyForMember(mi)); w.WriteAttributeString("leaf", (mi is ConstructorInfo) ? GenericBaseName(mi.DeclaringType.Name) : GenericBaseName(mi.Name)); w.WriteAttributeString("fullname", MemberFullName(mi)); w.WriteAttributeString("namespace", (mi is Type) ? Namespace((Type) mi) : Namespace(mi.DeclaringType)); if (mi is Type) { Type x = (Type) mi; if (x.IsAbstract) { w.WriteAttributeString("abstract", "true"); } if (x.IsClass) { w.WriteAttributeString("class", "true"); } if (x.IsEnum) { w.WriteAttributeString("enum", "true"); } if (x.IsGenericParameter) { w.WriteAttributeString("generictypeparameter", "true"); w.WriteAttributeString("genericparameterposition", x.GenericParameterPosition.ToString()); } if (x.IsGenericType) { w.WriteAttributeString("generictype", "true"); } if (x.IsGenericTypeDefinition) { w.WriteAttributeString("generictypedefinition", "true"); } if (x.IsInterface) { w.WriteAttributeString("interface", "true"); } if (x.IsPublic) { w.WriteAttributeString("public", "true"); } if (x.IsSpecialName) { w.WriteAttributeString("specialname", "true"); } if (x.IsValueType) { w.WriteAttributeString("valuetype", "true"); } // if (x.IsVisible) { w.WriteAttributeString("visible", "true"); } } else if (mi is FieldInfo) { FieldInfo x = (FieldInfo) mi; if (x.IsAssembly) { w.WriteAttributeString("assembly", "true"); } if (x.IsFamily) { w.WriteAttributeString("family", "true"); } if (x.IsInitOnly) { w.WriteAttributeString("initonly", "true"); } if (x.IsLiteral) { w.WriteAttributeString("literal", "true"); } if (x.IsPrivate) { w.WriteAttributeString("private", "true"); } if (x.IsPublic) { w.WriteAttributeString("public", "true"); } if (x.IsSpecialName) { w.WriteAttributeString("specialname", "true"); } if (x.IsStatic) { w.WriteAttributeString("static", "true"); } } else if (mi is PropertyInfo) { PropertyInfo x = (PropertyInfo) mi; if (x.IsSpecialName) { w.WriteAttributeString("specialname", "true"); } } else if (mi is EventInfo) { EventInfo x = (EventInfo) mi; if (x.IsMulticast) { w.WriteAttributeString("multicast", "true"); } if (x.IsSpecialName) { w.WriteAttributeString("specialname", "true"); } } else if (mi is MethodBase) { MethodBase x = (MethodBase) mi; if (x.IsAbstract) { w.WriteAttributeString("abstract", "true"); } if (x.IsAssembly) { w.WriteAttributeString("assembly", "true"); } if (x.IsConstructor) { w.WriteAttributeString("constructor", "true"); } if (x.IsFamily) { w.WriteAttributeString("family", "true"); } if (x.IsFinal) { w.WriteAttributeString("final", "true"); } if (x.IsPrivate) { w.WriteAttributeString("private", "true"); } if (x.IsPublic) { w.WriteAttributeString("public", "true"); } if (x.IsSpecialName) { w.WriteAttributeString("specialname", "true"); } if (x.IsStatic) { w.WriteAttributeString("static", "true"); } if (x.IsVirtual) { w.WriteAttributeString("virtual", "true"); } } } public string KeyForMember(MemberInfo mi) { if (mi is FieldInfo) return "F:" + MemberFullName(mi); if (mi is PropertyInfo) return "P:" + MemberFullName(mi); if (mi is EventInfo) return "E:" + MemberFullName(mi); if (mi is MethodBase) return "M:" + MemberFullName(mi); if (mi is Type) return "T:" + MemberFullName(mi); throw new Exception("Unsupported member kind: " + mi.ToString() + ", " + mi.GetType().ToString()); } public void WriteItemDocs(XmlWriter w, MemberInfo mi) { String key = KeyForMember(mi); WriteItemDocs(w, key); } public void WriteItemDocs(XmlWriter w, MemberInfo mi, string subsetSpec) { String key = KeyForMember(mi); WriteItemDocs(w, key, subsetSpec); } public void WriteItemDocs(XmlWriter w, string key) { WriteItemDocs(w, key, "*"); } public void WriteItemDocs(XmlWriter w, string key, string subsetSpec) { w.WriteStartElement("doc"); if (members.ContainsKey(key)) { XmlNode node = (XmlNode) members[key]; foreach (XmlNode n in node.SelectNodes(subsetSpec)) { w.WriteRaw(n.OuterXml); } } w.WriteEndElement(); } public bool IsIndirect(Type t) { return t.IsArray || t.IsByRef; } public bool IsLocal(Type t) { Type pt = t.IsGenericType ? t.GetGenericTypeDefinition() : t; return (types.ContainsKey(pt.FullName) && NotSuppressed(Namespace(pt))) || (IsIndirect(pt) && IsLocal(pt.GetElementType())); } public void GenerateGenericArguments(XmlWriter w, Type t, bool emitTypeConstraints) { Type[] genericArguments = t.GetGenericArguments(); int outerGenericArgumentCount = (t.DeclaringType == null) ? 0 : t.DeclaringType.GetGenericArguments().Length; GenerateGenericArguments(w, genericArguments, outerGenericArgumentCount, emitTypeConstraints); } public void GenerateGenericArguments(XmlWriter w, MethodBase mi) { if (mi.ContainsGenericParameters && !mi.IsConstructor) { GenerateGenericArguments(w, mi.GetGenericArguments(), 0, false); } } public void GenerateGenericArguments(XmlWriter w, Type[] genericArguments, int startOffset, bool emitTypeConstraints) { bool needEndElement = false; for (int i = startOffset; i < genericArguments.Length; i++) { Type genericArgument = genericArguments[i]; if (!needEndElement) { w.WriteStartElement("genericarguments"); needEndElement = true; } GenerateTypeRef(w, genericArgument, emitTypeConstraints); } if (needEndElement) { w.WriteEndElement(); } } public void GenerateTypeRef(XmlWriter w, Type t) { GenerateTypeRef(w, t, false); } public void GenerateTypeRef(XmlWriter w, Type t, bool emitTypeConstraints) { GenerateTypeRef(w, t, "", emitTypeConstraints); } public void GenerateTypeRef(XmlWriter w, Type t, string referenceChain, bool emitTypeConstraints) { if (t.IsArray) { GenerateTypeRef(w, t.GetElementType(), referenceChain + "A", emitTypeConstraints); return; } else if (t.IsByRef) { GenerateTypeRef(w, t.GetElementType(), referenceChain + "R", emitTypeConstraints); return; } Type baseType = t.IsGenericType ? t.GetGenericTypeDefinition() : t; w.WriteStartElement("type"); w.WriteAttributeString("name", baseType.FullName); w.WriteAttributeString("referenceChain", referenceChain); w.WriteAttributeString("leaf", GenericBaseName(baseType.Name)); w.WriteAttributeString("namespace", Namespace(baseType)); w.WriteAttributeString("local", t.IsGenericParameter ? "genericparameter" : IsLocal(t) ? "true" : "false"); w.WriteAttributeString("generictype", t.IsGenericType ? "true" : "false"); w.WriteAttributeString("generictypedefinition", t.IsGenericTypeDefinition ? "true" : "false"); w.WriteAttributeString("genericparameter", t.IsGenericParameter ? "true" : "false"); if (t.IsGenericParameter) { if (t.DeclaringMethod != null) { w.WriteAttributeString("methodgenericparameter", "true"); } w.WriteAttributeString("genericparameterposition", t.GenericParameterPosition.ToString()); if (emitTypeConstraints) { GenerateTypeConstraints(w, t); } } else { if (t.DeclaringType != null) { w.WriteStartElement("declaringtype"); GenerateTypeRef(w, t.DeclaringType); w.WriteEndElement(); } } GenerateGenericArguments(w, t, emitTypeConstraints); w.WriteEndElement(); } public void GenerateTypeConstraints(XmlWriter w, Type t) { w.WriteStartElement("typeconstraints"); GenericParameterAttributes gpa = t.GenericParameterAttributes; if ((gpa & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { w.WriteElementString("notnullablevaluetype", ""); } if ((gpa & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { w.WriteElementString("referencetype", ""); } Type[] typeConstraints = t.GetGenericParameterConstraints(); if (typeConstraints.Length > 0) { foreach (Type constraint in typeConstraints) { GenerateTypeRef(w, constraint); } } if ((gpa & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { w.WriteElementString("defaultconstructor", ""); } w.WriteEndElement(); } public BindingFlags LiberalFlags { get { BindingFlags f = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly; if (includeNonpublic) { f = f | BindingFlags.NonPublic; } return f; } } } }
namespace EIDSS.RAM.QueryBuilder { partial class QuerySearchObjectInfo { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(QuerySearchObjectInfo)); this.splitContainer = new DevExpress.XtraEditors.SplitContainerControl(); this.QuerySearchFilter = new DevExpress.XtraEditors.FilterControl(); this.lblFilter = new DevExpress.XtraEditors.LabelControl(); this.txtFilterText = new DevExpress.XtraEditors.MemoEdit(); this.gcSelectedField = new DevExpress.XtraGrid.GridControl(); this.gvSelectedField = new DevExpress.XtraGrid.Views.Grid.GridView(); this.colQuerySearchField = new DevExpress.XtraGrid.Columns.GridColumn(); this.colShow = new DevExpress.XtraGrid.Columns.GridColumn(); this.chShow = new DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit(); this.gcolTypeImage = new DevExpress.XtraGrid.Columns.GridColumn(); this.imTypeImage = new DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox(); this.colFieldCaption = new DevExpress.XtraGrid.Columns.GridColumn(); this.btnRemoveAll = new DevExpress.XtraEditors.SimpleButton(); this.btnRemove = new DevExpress.XtraEditors.SimpleButton(); this.btnAddAll = new DevExpress.XtraEditors.SimpleButton(); this.btnAdd = new DevExpress.XtraEditors.SimpleButton(); this.lblSelectedField = new DevExpress.XtraEditors.LabelControl(); this.lblAvailableField = new DevExpress.XtraEditors.LabelControl(); this.grcQueryObjectFiltration = new DevExpress.XtraEditors.GroupControl(); this.navSearchFields = new DevExpress.XtraNavBar.NavBarControl(); this.grpSearchFields = new DevExpress.XtraNavBar.NavBarGroup(); this.navSearchFieldsContainer = new DevExpress.XtraNavBar.NavBarGroupControlContainer(); this.imlbcAvailableField = new DevExpress.XtraEditors.ImageListBoxControl(); this.ttcAvailableField = new DevExpress.Utils.ToolTipController(this.components); this.cbFilterByDiagnosis = new DevExpress.XtraEditors.LookUpEdit(); this.lblFilterByDiagnosis = new DevExpress.XtraEditors.LabelControl(); this.splitFields = new DevExpress.XtraEditors.SplitterControl(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).BeginInit(); this.splitContainer.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.txtFilterText.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gcSelectedField)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gvSelectedField)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.chShow)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.imTypeImage)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.grcQueryObjectFiltration)).BeginInit(); this.grcQueryObjectFiltration.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.navSearchFields)).BeginInit(); this.navSearchFields.SuspendLayout(); this.navSearchFieldsContainer.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.imlbcAvailableField)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.cbFilterByDiagnosis.Properties)).BeginInit(); this.SuspendLayout(); // // splitContainer // this.splitContainer.Appearance.Options.UseFont = true; this.splitContainer.AppearanceCaption.Options.UseFont = true; this.splitContainer.CollapsePanel = DevExpress.XtraEditors.SplitCollapsePanel.Panel2; resources.ApplyResources(this.splitContainer, "splitContainer"); this.splitContainer.FixedPanel = DevExpress.XtraEditors.SplitFixedPanel.Panel2; this.splitContainer.Horizontal = false; this.splitContainer.Name = "splitContainer"; this.splitContainer.Panel1.Appearance.Options.UseFont = true; this.splitContainer.Panel1.AppearanceCaption.Options.UseFont = true; this.splitContainer.Panel1.Controls.Add(this.QuerySearchFilter); this.splitContainer.Panel1.Controls.Add(this.lblFilter); this.splitContainer.Panel1.MinSize = 100; this.splitContainer.Panel2.Appearance.Options.UseFont = true; this.splitContainer.Panel2.AppearanceCaption.Options.UseFont = true; this.splitContainer.Panel2.Controls.Add(this.txtFilterText); this.splitContainer.Panel2.MinSize = 40; resources.ApplyResources(this.splitContainer.Panel2, "splitContainer.Panel2"); this.splitContainer.SplitterPosition = 75; this.splitContainer.SplitGroupPanelCollapsed += new DevExpress.XtraEditors.SplitGroupPanelCollapsedEventHandler(this.splitContainer_SplitGroupPanelCollapsed); // // QuerySearchFilter // resources.ApplyResources(this.QuerySearchFilter, "QuerySearchFilter"); this.QuerySearchFilter.Appearance.Options.UseFont = true; this.QuerySearchFilter.AppearanceTreeLine.Options.UseFont = true; this.QuerySearchFilter.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Flat; this.QuerySearchFilter.Cursor = System.Windows.Forms.Cursors.Arrow; this.QuerySearchFilter.Name = "QuerySearchFilter"; // // lblFilter // resources.ApplyResources(this.lblFilter, "lblFilter"); this.lblFilter.Name = "lblFilter"; // // txtFilterText // resources.ApplyResources(this.txtFilterText, "txtFilterText"); this.txtFilterText.Name = "txtFilterText"; this.txtFilterText.Properties.Appearance.Options.UseFont = true; this.txtFilterText.Properties.AppearanceDisabled.BackColor = ((System.Drawing.Color)(resources.GetObject("txtFilterText.Properties.AppearanceDisabled.BackColor"))); this.txtFilterText.Properties.AppearanceDisabled.Options.UseBackColor = true; this.txtFilterText.Properties.AppearanceDisabled.Options.UseFont = true; this.txtFilterText.Properties.AppearanceFocused.Options.UseFont = true; this.txtFilterText.Properties.AppearanceReadOnly.BackColor = ((System.Drawing.Color)(resources.GetObject("txtFilterText.Properties.AppearanceReadOnly.BackColor"))); this.txtFilterText.Properties.AppearanceReadOnly.Options.UseBackColor = true; this.txtFilterText.Properties.AppearanceReadOnly.Options.UseFont = true; this.txtFilterText.Properties.ReadOnly = true; this.txtFilterText.Tag = "{R}"; // // gcSelectedField // resources.ApplyResources(this.gcSelectedField, "gcSelectedField"); this.gcSelectedField.EmbeddedNavigator.Appearance.Options.UseFont = true; this.gcSelectedField.MainView = this.gvSelectedField; this.gcSelectedField.Name = "gcSelectedField"; this.gcSelectedField.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] { this.chShow, this.imTypeImage}); this.gcSelectedField.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gvSelectedField}); // // gvSelectedField // this.gvSelectedField.ActiveFilterEnabled = false; this.gvSelectedField.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.colQuerySearchField, this.colShow, this.gcolTypeImage, this.colFieldCaption}); this.gvSelectedField.GridControl = this.gcSelectedField; this.gvSelectedField.Name = "gvSelectedField"; this.gvSelectedField.OptionsCustomization.AllowColumnMoving = false; this.gvSelectedField.OptionsCustomization.AllowFilter = false; this.gvSelectedField.OptionsCustomization.AllowGroup = false; this.gvSelectedField.OptionsCustomization.AllowSort = false; this.gvSelectedField.OptionsNavigation.AutoFocusNewRow = true; this.gvSelectedField.OptionsView.ShowColumnHeaders = false; this.gvSelectedField.OptionsView.ShowDetailButtons = false; this.gvSelectedField.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never; this.gvSelectedField.OptionsView.ShowGroupExpandCollapseButtons = false; this.gvSelectedField.OptionsView.ShowGroupPanel = false; this.gvSelectedField.OptionsView.ShowHorzLines = false; this.gvSelectedField.OptionsView.ShowIndicator = false; this.gvSelectedField.OptionsView.ShowVertLines = false; this.gvSelectedField.RowCellClick += new DevExpress.XtraGrid.Views.Grid.RowCellClickEventHandler(this.gvSelectedField_RowCellClick); // // colQuerySearchField // resources.ApplyResources(this.colQuerySearchField, "colQuerySearchField"); this.colQuerySearchField.FieldName = "idfQuerySearchField"; this.colQuerySearchField.Name = "colQuerySearchField"; // // colShow // resources.ApplyResources(this.colShow, "colShow"); this.colShow.ColumnEdit = this.chShow; this.colShow.FieldName = "blnShow"; this.colShow.Name = "colShow"; this.colShow.OptionsColumn.AllowMove = false; this.colShow.OptionsColumn.AllowSize = false; this.colShow.OptionsColumn.ShowInCustomizationForm = false; // // chShow // this.chShow.Appearance.Options.UseFont = true; this.chShow.AppearanceDisabled.Options.UseFont = true; this.chShow.AppearanceFocused.Options.UseFont = true; this.chShow.AppearanceReadOnly.Options.UseFont = true; resources.ApplyResources(this.chShow, "chShow"); this.chShow.Name = "chShow"; // // gcolTypeImage // resources.ApplyResources(this.gcolTypeImage, "gcolTypeImage"); this.gcolTypeImage.ColumnEdit = this.imTypeImage; this.gcolTypeImage.FieldName = "TypeImageIndex"; this.gcolTypeImage.Name = "gcolTypeImage"; this.gcolTypeImage.OptionsColumn.AllowEdit = false; this.gcolTypeImage.OptionsColumn.AllowMove = false; this.gcolTypeImage.OptionsColumn.AllowSize = false; this.gcolTypeImage.OptionsColumn.ShowInCustomizationForm = false; this.gcolTypeImage.OptionsColumn.TabStop = false; // // imTypeImage // resources.ApplyResources(this.imTypeImage, "imTypeImage"); this.imTypeImage.Name = "imTypeImage"; this.imTypeImage.ShowDropDown = DevExpress.XtraEditors.Controls.ShowDropDown.Never; // // colFieldCaption // resources.ApplyResources(this.colFieldCaption, "colFieldCaption"); this.colFieldCaption.FieldName = "FieldCaption"; this.colFieldCaption.Name = "colFieldCaption"; this.colFieldCaption.OptionsColumn.AllowEdit = false; this.colFieldCaption.OptionsColumn.AllowMove = false; this.colFieldCaption.OptionsColumn.AllowShowHide = false; this.colFieldCaption.OptionsColumn.ShowInCustomizationForm = false; // // btnRemoveAll // this.btnRemoveAll.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("btnRemoveAll.Appearance.Font"))); this.btnRemoveAll.Appearance.Options.UseFont = true; this.btnRemoveAll.ImageIndex = 3; resources.ApplyResources(this.btnRemoveAll, "btnRemoveAll"); this.btnRemoveAll.Name = "btnRemoveAll"; this.btnRemoveAll.Tag = "FixFont"; this.btnRemoveAll.Click += new System.EventHandler(this.btnRemoveAll_Click); // // btnRemove // this.btnRemove.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("btnRemove.Appearance.Font"))); this.btnRemove.Appearance.Options.UseFont = true; resources.ApplyResources(this.btnRemove, "btnRemove"); this.btnRemove.Name = "btnRemove"; this.btnRemove.Tag = "FixFont"; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // btnAddAll // this.btnAddAll.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("btnAddAll.Appearance.Font"))); this.btnAddAll.Appearance.Options.UseFont = true; this.btnAddAll.ImageIndex = 2; resources.ApplyResources(this.btnAddAll, "btnAddAll"); this.btnAddAll.Name = "btnAddAll"; this.btnAddAll.Tag = "FixFont"; this.btnAddAll.Click += new System.EventHandler(this.btnAddAll_Click); // // btnAdd // this.btnAdd.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("btnAdd.Appearance.Font"))); this.btnAdd.Appearance.Options.UseFont = true; this.btnAdd.ImageIndex = 0; this.btnAdd.ImageLocation = DevExpress.XtraEditors.ImageLocation.MiddleCenter; resources.ApplyResources(this.btnAdd, "btnAdd"); this.btnAdd.Name = "btnAdd"; this.btnAdd.Tag = "FixFont"; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // lblSelectedField // resources.ApplyResources(this.lblSelectedField, "lblSelectedField"); this.lblSelectedField.Name = "lblSelectedField"; // // lblAvailableField // resources.ApplyResources(this.lblAvailableField, "lblAvailableField"); this.lblAvailableField.Name = "lblAvailableField"; // // grcQueryObjectFiltration // this.grcQueryObjectFiltration.Appearance.Options.UseFont = true; this.grcQueryObjectFiltration.AppearanceCaption.Options.UseFont = true; this.grcQueryObjectFiltration.Controls.Add(this.splitContainer); resources.ApplyResources(this.grcQueryObjectFiltration, "grcQueryObjectFiltration"); this.grcQueryObjectFiltration.MinimumSize = new System.Drawing.Size(240, 248); this.grcQueryObjectFiltration.Name = "grcQueryObjectFiltration"; // // navSearchFields // this.navSearchFields.ActiveGroup = this.grpSearchFields; this.navSearchFields.Appearance.Background.Options.UseFont = true; this.navSearchFields.Appearance.Button.Options.UseFont = true; this.navSearchFields.Appearance.ButtonDisabled.Options.UseFont = true; this.navSearchFields.Appearance.ButtonHotTracked.Options.UseFont = true; this.navSearchFields.Appearance.ButtonPressed.Options.UseFont = true; this.navSearchFields.Appearance.GroupBackground.Options.UseFont = true; this.navSearchFields.Appearance.GroupHeader.Options.UseFont = true; this.navSearchFields.Appearance.GroupHeaderActive.Options.UseFont = true; this.navSearchFields.Appearance.GroupHeaderHotTracked.Options.UseFont = true; this.navSearchFields.Appearance.GroupHeaderPressed.Options.UseFont = true; this.navSearchFields.Appearance.Hint.Options.UseFont = true; this.navSearchFields.Appearance.Item.Options.UseFont = true; this.navSearchFields.Appearance.ItemActive.Options.UseFont = true; this.navSearchFields.Appearance.ItemDisabled.Options.UseFont = true; this.navSearchFields.Appearance.ItemHotTracked.Options.UseFont = true; this.navSearchFields.Appearance.ItemPressed.Options.UseFont = true; this.navSearchFields.Appearance.LinkDropTarget.Options.UseFont = true; this.navSearchFields.Appearance.NavigationPaneHeader.Options.UseFont = true; this.navSearchFields.Appearance.NavPaneContentButton.Options.UseFont = true; this.navSearchFields.Appearance.NavPaneContentButtonHotTracked.Options.UseFont = true; this.navSearchFields.Appearance.NavPaneContentButtonPressed.Options.UseFont = true; this.navSearchFields.Appearance.NavPaneContentButtonReleased.Options.UseFont = true; this.navSearchFields.ContentButtonHint = null; this.navSearchFields.Controls.Add(this.navSearchFieldsContainer); resources.ApplyResources(this.navSearchFields, "navSearchFields"); this.navSearchFields.Groups.AddRange(new DevExpress.XtraNavBar.NavBarGroup[] { this.grpSearchFields}); this.navSearchFields.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Office2003; this.navSearchFields.Name = "navSearchFields"; this.navSearchFields.NavigationPaneOverflowPanelUseSmallImages = false; this.navSearchFields.OptionsNavPane.ExpandedWidth = ((int)(resources.GetObject("resource.ExpandedWidth"))); this.navSearchFields.OptionsNavPane.ShowOverflowPanel = false; this.navSearchFields.OptionsNavPane.ShowSplitter = false; this.navSearchFields.ShowGroupHint = false; this.navSearchFields.View = new DevExpress.XtraNavBar.ViewInfo.SkinNavigationPaneViewInfoRegistrator(); // // grpSearchFields // resources.ApplyResources(this.grpSearchFields, "grpSearchFields"); this.grpSearchFields.ControlContainer = this.navSearchFieldsContainer; this.grpSearchFields.Expanded = true; this.grpSearchFields.GroupClientHeight = 308; this.grpSearchFields.GroupStyle = DevExpress.XtraNavBar.NavBarGroupStyle.ControlContainer; this.grpSearchFields.Name = "grpSearchFields"; this.grpSearchFields.NavigationPaneVisible = false; // // navSearchFieldsContainer // this.navSearchFieldsContainer.Controls.Add(this.imlbcAvailableField); this.navSearchFieldsContainer.Controls.Add(this.gcSelectedField); this.navSearchFieldsContainer.Controls.Add(this.btnRemoveAll); this.navSearchFieldsContainer.Controls.Add(this.lblAvailableField); this.navSearchFieldsContainer.Controls.Add(this.btnRemove); this.navSearchFieldsContainer.Controls.Add(this.btnAddAll); this.navSearchFieldsContainer.Controls.Add(this.lblSelectedField); this.navSearchFieldsContainer.Controls.Add(this.btnAdd); this.navSearchFieldsContainer.Controls.Add(this.cbFilterByDiagnosis); this.navSearchFieldsContainer.Controls.Add(this.lblFilterByDiagnosis); this.navSearchFieldsContainer.Name = "navSearchFieldsContainer"; resources.ApplyResources(this.navSearchFieldsContainer, "navSearchFieldsContainer"); // // imlbcAvailableField // resources.ApplyResources(this.imlbcAvailableField, "imlbcAvailableField"); this.imlbcAvailableField.HorizontalScrollbar = true; this.imlbcAvailableField.Name = "imlbcAvailableField"; this.imlbcAvailableField.ToolTipController = this.ttcAvailableField; this.imlbcAvailableField.SelectedIndexChanged += new System.EventHandler(this.imlbcAvailableField_SelectedIndexChanged); this.imlbcAvailableField.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.imlbcAvailableField_MouseDoubleClick); this.imlbcAvailableField.MouseLeave += new System.EventHandler(this.imlbcAvailableField_MouseLeave); this.imlbcAvailableField.MouseMove += new System.Windows.Forms.MouseEventHandler(this.imlbcAvailableField_MouseMove); // // ttcAvailableField // this.ttcAvailableField.CloseOnClick = DevExpress.Utils.DefaultBoolean.True; this.ttcAvailableField.InitialDelay = 1000; this.ttcAvailableField.ReshowDelay = 200; // // cbFilterByDiagnosis // resources.ApplyResources(this.cbFilterByDiagnosis, "cbFilterByDiagnosis"); this.cbFilterByDiagnosis.Name = "cbFilterByDiagnosis"; this.cbFilterByDiagnosis.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("cbFilterByDiagnosis.Properties.Buttons"))))}); this.cbFilterByDiagnosis.Properties.NullText = resources.GetString("cbFilterByDiagnosis.Properties.NullText"); this.cbFilterByDiagnosis.EditValueChanged += new System.EventHandler(this.cbFilterByDiagnosis_EditValueChanged); // // lblFilterByDiagnosis // resources.ApplyResources(this.lblFilterByDiagnosis, "lblFilterByDiagnosis"); this.lblFilterByDiagnosis.Name = "lblFilterByDiagnosis"; // // splitFields // resources.ApplyResources(this.splitFields, "splitFields"); this.splitFields.Name = "splitFields"; this.splitFields.TabStop = false; // // QuerySearchObjectInfo // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.grcQueryObjectFiltration); this.Controls.Add(this.splitFields); this.Controls.Add(this.navSearchFields); this.KeyFieldName = "idfQuerySearchObject"; this.MinHeight = 300; this.Name = "QuerySearchObjectInfo"; this.ObjectName = "QuerySearchObject"; this.TableName = "tasQuerySearchObject"; this.OnBeforePost += new System.EventHandler(this.QuerySearchObjectInfo_OnBeforePost); this.OnAfterPost += new System.EventHandler(this.QuerySearchObjectInfo_OnAfterPost); this.AfterLoadData += new System.EventHandler(this.QuerySearchObjectInfo_AfterLoadData); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).EndInit(); this.splitContainer.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.txtFilterText.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gcSelectedField)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gvSelectedField)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.chShow)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.imTypeImage)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.grcQueryObjectFiltration)).EndInit(); this.grcQueryObjectFiltration.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.navSearchFields)).EndInit(); this.navSearchFields.ResumeLayout(false); this.navSearchFieldsContainer.ResumeLayout(false); this.navSearchFieldsContainer.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.imlbcAvailableField)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.cbFilterByDiagnosis.Properties)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraEditors.SimpleButton btnRemoveAll; private DevExpress.XtraEditors.SimpleButton btnRemove; private DevExpress.XtraEditors.SimpleButton btnAddAll; private DevExpress.XtraEditors.SimpleButton btnAdd; private DevExpress.XtraEditors.LabelControl lblSelectedField; private DevExpress.XtraEditors.LabelControl lblAvailableField; private DevExpress.XtraEditors.GroupControl grcQueryObjectFiltration; private DevExpress.XtraEditors.LabelControl lblFilter; private DevExpress.XtraGrid.GridControl gcSelectedField; private DevExpress.XtraGrid.Views.Grid.GridView gvSelectedField; private DevExpress.XtraGrid.Columns.GridColumn colShow; private DevExpress.XtraGrid.Columns.GridColumn colQuerySearchField; private DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit chShow; private DevExpress.XtraGrid.Columns.GridColumn colFieldCaption; private DevExpress.XtraEditors.FilterControl QuerySearchFilter; private DevExpress.XtraEditors.MemoEdit txtFilterText; private DevExpress.XtraNavBar.NavBarControl navSearchFields; private DevExpress.XtraNavBar.NavBarGroup grpSearchFields; private DevExpress.XtraNavBar.NavBarGroupControlContainer navSearchFieldsContainer; private DevExpress.XtraEditors.SplitContainerControl splitContainer; private DevExpress.XtraEditors.SplitterControl splitFields; private DevExpress.XtraEditors.ImageListBoxControl imlbcAvailableField; private DevExpress.XtraGrid.Columns.GridColumn gcolTypeImage; private DevExpress.XtraEditors.Repository.RepositoryItemImageComboBox imTypeImage; private DevExpress.Utils.ToolTipController ttcAvailableField; private DevExpress.XtraEditors.LookUpEdit cbFilterByDiagnosis; private DevExpress.XtraEditors.LabelControl lblFilterByDiagnosis; } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // IndexedWhereQueryOperator.cs // // <OWNER>[....]</OWNER> // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// A variant of the Where operator that supplies element index while performing the /// filtering operation. This requires cooperation with partitioning and merging to /// guarantee ordering is preserved. /// /// </summary> /// <typeparam name="TInputOutput"></typeparam> internal sealed class IndexedWhereQueryOperator<TInputOutput> : UnaryQueryOperator<TInputOutput, TInputOutput> { // Predicate function. Used to filter out non-matching elements during execution. private Func<TInputOutput, int, bool> m_predicate; private bool m_prematureMerge = false; // Whether to prematurely merge the input of this operator. private bool m_limitsParallelism = false; // Whether this operator limits parallelism //--------------------------------------------------------------------------------------- // Initializes a new where operator. // // Arguments: // child - the child operator or data source from which to pull data // predicate - a delegate representing the predicate function // // Assumptions: // predicate must be non null. // internal IndexedWhereQueryOperator(IEnumerable<TInputOutput> child, Func<TInputOutput, int, bool> predicate) :base(child) { Contract.Assert(child != null, "child data source cannot be null"); Contract.Assert(predicate != null, "need a filter function"); m_predicate = predicate; // In an indexed Select, elements must be returned in the order in which // indices were assigned. m_outputOrdered = true; InitOrdinalIndexState(); } private void InitOrdinalIndexState() { OrdinalIndexState childIndexState = Child.OrdinalIndexState; if (ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct)) { m_prematureMerge = true; m_limitsParallelism = childIndexState != OrdinalIndexState.Shuffled; } SetOrdinalIndexState(OrdinalIndexState.Increasing); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TInputOutput> Open( QuerySettings settings, bool preferStriping) { QueryResults<TInputOutput> childQueryResults = Child.Open(settings, preferStriping); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TInputOutput, TKey> inputStream, IPartitionedStreamRecipient<TInputOutput> recipient, bool preferStriping, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; // If the index is not correct, we need to reindex. PartitionedStream<TInputOutput, int> inputStreamInt; if (m_prematureMerge) { ListQueryResults<TInputOutput> listResults = ExecuteAndCollectResults(inputStream, partitionCount, Child.OutputOrdered, preferStriping, settings); inputStreamInt = listResults.GetPartitionedStream(); } else { Contract.Assert(typeof(TKey) == typeof(int)); inputStreamInt = (PartitionedStream<TInputOutput, int>)(object)inputStream; } // Since the index is correct, the type of the index must be int PartitionedStream<TInputOutput, int> outputStream = new PartitionedStream<TInputOutput, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new IndexedWhereQueryOperatorEnumerator(inputStreamInt[i], m_predicate, settings.CancellationState.MergedCancellationToken); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { IEnumerable<TInputOutput> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.Where(m_predicate); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return m_limitsParallelism; } } //----------------------------------------------------------------------------------- // An enumerator that implements the filtering logic. // private class IndexedWhereQueryOperatorEnumerator : QueryOperatorEnumerator<TInputOutput, int> { private readonly QueryOperatorEnumerator<TInputOutput, int> m_source; // The data source to enumerate. private readonly Func<TInputOutput, int, bool> m_predicate; // The predicate used for filtering. private CancellationToken m_cancellationToken; private Shared<int> m_outputLoopCount; //----------------------------------------------------------------------------------- // Instantiates a new enumerator. // internal IndexedWhereQueryOperatorEnumerator(QueryOperatorEnumerator<TInputOutput, int> source, Func<TInputOutput, int, bool> predicate, CancellationToken cancellationToken) { Contract.Assert(source != null); Contract.Assert(predicate != null); m_source = source; m_predicate = predicate; m_cancellationToken = cancellationToken; } //----------------------------------------------------------------------------------- // Moves to the next matching element in the underlying data stream. // internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey) { Contract.Assert(m_predicate != null, "expected a compiled operator"); // Iterate through the input until we reach the end of the sequence or find // an element matching the predicate. if (m_outputLoopCount == null) m_outputLoopCount = new Shared<int>(0); while (m_source.MoveNext(ref currentElement, ref currentKey)) { if ((m_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(m_cancellationToken); if (m_predicate(currentElement, currentKey)) { return true; } } return false; } protected override void Dispose(bool disposing) { Contract.Assert(m_source != null); m_source.Dispose(); } } } }
// 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 gcsv = Google.Cloud.Scheduler.V1; using sys = System; namespace Google.Cloud.Scheduler.V1 { /// <summary>Resource name for the <c>Topic</c> resource.</summary> public sealed partial class TopicName : gax::IResourceName, sys::IEquatable<TopicName> { /// <summary>The possible contents of <see cref="TopicName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/topics/{topic}</c>.</summary> ProjectTopic = 1, } private static gax::PathTemplate s_projectTopic = new gax::PathTemplate("projects/{project}/topics/{topic}"); /// <summary>Creates a <see cref="TopicName"/> 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="TopicName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static TopicName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TopicName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TopicName"/> with the pattern <c>projects/{project}/topics/{topic}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TopicName"/> constructed from the provided ids.</returns> public static TopicName FromProjectTopic(string projectId, string topicId) => new TopicName(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern /// <c>projects/{project}/topics/{topic}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c> /// . /// </returns> public static string Format(string projectId, string topicId) => FormatProjectTopic(projectId, topicId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern /// <c>projects/{project}/topics/{topic}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c> /// . /// </returns> public static string FormatProjectTopic(string projectId, string topicId) => s_projectTopic.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId))); /// <summary>Parses the given resource name string into a new <see cref="TopicName"/> 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}/topics/{topic}</c></description></item></list> /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TopicName"/> if successful.</returns> public static TopicName Parse(string topicName) => Parse(topicName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TopicName"/> 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}/topics/{topic}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="topicName">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="TopicName"/> if successful.</returns> public static TopicName Parse(string topicName, bool allowUnparsed) => TryParse(topicName, allowUnparsed, out TopicName 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="TopicName"/> 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}/topics/{topic}</c></description></item></list> /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TopicName"/>, 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 topicName, out TopicName result) => TryParse(topicName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TopicName"/> 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}/topics/{topic}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="topicName">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="TopicName"/>, 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 topicName, bool allowUnparsed, out TopicName result) { gax::GaxPreconditions.CheckNotNull(topicName, nameof(topicName)); gax::TemplatedResourceName resourceName; if (s_projectTopic.TryParseName(topicName, out resourceName)) { result = FromProjectTopic(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(topicName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TopicName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string topicId = null) { Type = type; UnparsedResource = unparsedResourceName; ProjectId = projectId; TopicId = topicId; } /// <summary> /// Constructs a new instance of a <see cref="TopicName"/> class from the component parts of pattern /// <c>projects/{project}/topics/{topic}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> public TopicName(string projectId, string topicId) : this(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId))) { } /// <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>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>Topic</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TopicId { 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.ProjectTopic: return s_projectTopic.Expand(ProjectId, TopicId); 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 TopicName); /// <inheritdoc/> public bool Equals(TopicName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TopicName a, TopicName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TopicName a, TopicName b) => !(a == b); } public partial class PubsubTarget { /// <summary> /// <see cref="gcsv::TopicName"/>-typed view over the <see cref="TopicName"/> resource name property. /// </summary> public gcsv::TopicName TopicNameAsTopicName { get => string.IsNullOrEmpty(TopicName) ? null : gcsv::TopicName.Parse(TopicName, allowUnparsed: true); set => TopicName = value?.ToString() ?? ""; } } }
using Aspose.Email.Mapi; using Aspose.Email.Storage.Mbox; using Aspose.Email.Storage.Pst; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Aspose.Email.Live.Demos.UI.Helpers { /// <summary> /// Auxiliary methods for working with MAPI. /// Written temporarily until a new version is released. /// /// EMAILNET-39534 Implement method of reading custom properties /// </summary> public static class MapiHelper { /// <summary> /// Set content id to attachment /// </summary> /// <param name="attach"></param> /// <param name="id"></param> public static void SetContentId(this MapiAttachment attach, object id) { attach.SetProperty(KnownPropertyList.AttachContentId, id); } public static Aspose.Email.Mapi.MapiMessage GetMapiMessageFromStream(Stream input) { var formatInfo = Email.Tools.FileFormatUtil.DetectFileFormat(input); input.Position = 0; switch (formatInfo.FileFormatType) { case Email.FileFormatType.Msg: return MapiMessage.Load(input, new Email.MsgLoadOptions()); case Email.FileFormatType.Eml: return MapiMessage.Load(input, new Email.EmlLoadOptions()); case Email.FileFormatType.Mht: return MapiMessage.Load(input, new Email.MhtmlLoadOptions()); case Email.FileFormatType.Tnef: return MapiMessage.Load(input, new Email.TnefLoadOptions()); default: throw new Exception("Invalid file format"); } } public static Aspose.Email.Mapi.MapiMessage GetMapiMessageFromStream(Stream input, out FileFormatInfo info) { info = Email.Tools.FileFormatUtil.DetectFileFormat(input); input.Position = 0; switch (info.FileFormatType) { case Email.FileFormatType.Msg: return MapiMessage.Load(input, new Email.MsgLoadOptions()); case Email.FileFormatType.Eml: return MapiMessage.Load(input, new Email.EmlLoadOptions()); case Email.FileFormatType.Mht: return MapiMessage.Load(input, new Email.MhtmlLoadOptions()); case Email.FileFormatType.Tnef: return MapiMessage.Load(input, new Email.TnefLoadOptions()); default: throw new Exception("Invalid file format"); } } public static MailMessage GetMailMessageFromStream(Stream input) { var formatInfo = Email.Tools.FileFormatUtil.DetectFileFormat(input); input.Position = 0; switch (formatInfo.FileFormatType) { case Email.FileFormatType.Msg: return MailMessage.Load(input, new Email.MsgLoadOptions()); case Email.FileFormatType.Eml: return MailMessage.Load(input, new Email.EmlLoadOptions()); case Email.FileFormatType.Mht: return MailMessage.Load(input, new Email.MhtmlLoadOptions()); case Email.FileFormatType.Tnef: return MailMessage.Load(input, new Email.TnefLoadOptions()); default: throw new Exception("Invalid file format"); } } ///<Summary> /// Add Custom Property ///</Summary> /// <param name="msg"></param> /// <param name="name"></param> /// <param name="value"></param> public static MapiProperty AddCustomProperty(this MapiMessage msg, string name, DateTime value) { var newProperty = MapiProperty.CreateMapiPropertyFromDateTime(msg.NamedPropertyMapping.GetNextAvailablePropertyId(MapiPropertyType.PT_SYSTIME), value); msg.AddCustomProperty(newProperty, name); return newProperty; } ///<Summary> /// Add Custom Property ///</Summary> /// <param name="msg"></param> /// <param name="name"></param> /// <param name="value"></param> public static MapiProperty AddCustomProperty(this MapiMessage msg, string name, bool value) { return msg.AddCustomProperty(name, MapiPropertyType.PT_BOOLEAN, BitConverter.GetBytes(value)); } ///<Summary> /// Add Custom Property ///</Summary> /// <param name="msg"></param> /// <param name="name"></param> /// <param name="value"></param> public static MapiProperty AddCustomProperty(this MapiMessage msg, string name, double value) { return msg.AddCustomProperty(name, MapiPropertyType.PT_DOUBLE, BitConverter.GetBytes(value)); } ///<Summary> /// Add Custom Property ///</Summary> /// <param name="msg"></param> /// <param name="name"></param> /// <param name="value"></param> public static MapiProperty AddCustomProperty(this MapiMessage msg, string name, long value) { return msg.AddCustomProperty(name, MapiPropertyType.PT_LONG, BitConverter.GetBytes(value)); } ///<Summary> /// Add Custom Property ///</Summary> /// <param name="msg"></param> /// <param name="name"></param> /// <param name="value"></param> public static MapiProperty AddCustomProperty(this MapiMessage msg, string name, string value) { return msg.AddCustomProperty(name, MapiPropertyType.PT_UNICODE, Encoding.Unicode.GetBytes(value)); } ///<Summary> /// Add Custom Property ///</Summary> /// <param name="msg"></param> /// <param name="name"></param> /// <param name="type"></param> /// <param name="valueBytes"></param> public static MapiProperty AddCustomProperty(this MapiMessage msg, string name, MapiPropertyType type, byte[] valueBytes) { var newProperty = new MapiProperty(msg.NamedPropertyMapping.GetNextAvailablePropertyId(type), 0, valueBytes); msg.AddCustomProperty(newProperty, name); return newProperty; } ///<Summary> /// Get Custom Properties ///</Summary> /// <param name="msg"></param> public static Dictionary<long, NamedMapiProperty> GetCustomProperties(this MapiMessage msg) { var customProperties = new Dictionary<long, NamedMapiProperty>(); // 0x00008540 is equivalent of MapiNamedPropertyId.PidLidPropertyDefinitionStream long tag = GetTagFromNamedProperty(0x00008540, msg); if (tag > 0) { byte[] data = msg.TryGetPropertyData(tag); List<string> names = GetCustomPropertiesNames(data); foreach (var name in names) { long tagCustomProp = GetTagFromNamedProperty(name, msg); if (tagCustomProp > 0) { MapiProperty customProp = msg.Properties[tagCustomProp]; if (customProp != null) { customProperties[tagCustomProp] = new NamedMapiProperty(name, customProp); } } } } return customProperties; } ///<Summary> /// Get Tag From Named Property ///</Summary> /// <param name="propertyId"></param> /// <param name="msg"></param> private static long GetTagFromNamedProperty(long propertyId, MapiMessage msg) { foreach (MapiNamedProperty namedProperty in msg.NamedProperties.Values) { PidLidPropertyDescriptor lidDescriptor = namedProperty.Descriptor as PidLidPropertyDescriptor; if (lidDescriptor != null && lidDescriptor.LongId == propertyId) { return namedProperty.Tag; } } return -1; } ///<Summary> /// Get Tag From Named Property ///</Summary> /// <param name="name"></param> /// <param name="msg"></param> private static long GetTagFromNamedProperty(string name, MapiMessage msg) { foreach (MapiNamedProperty namedProperty in msg.NamedProperties.Values) { if (namedProperty.NameId != null && name.Equals(namedProperty.NameId, StringComparison.OrdinalIgnoreCase)) { return namedProperty.Tag; } } return -1; } ///<Summary> /// Get Custom Properties Names ///</Summary> /// <param name="data"></param> private static List<string> GetCustomPropertiesNames(byte[] data) { List<string> result = new List<string>(); if (data != null) { BinaryReader reader = new BinaryReader(new MemoryStream(data), Encoding.Unicode); string name = string.Empty; short ver = reader.ReadInt16(); int numberOfProp = reader.ReadInt32(); while (result.Count < numberOfProp && reader.PeekChar() > -1) { //https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/ee415116%28v%3doffice.14%29 if (ver == 259) //0x0103 PropDefV2 { name = GetCustomPropertyNameV2(reader); } else //0x0102 PropDefV1 { name = GetCustomPropertyNameV1(reader); } if (!string.IsNullOrEmpty(name)) { result.Add(name); } } } return result; } ///<Summary> /// Get Custom Property Name V1 ///</Summary> /// <param name="reader"></param> private static string GetCustomPropertyNameV1(BinaryReader reader) { //https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/ee415114%28v%3doffice.14%29 string name = string.Empty; int PDO_IS_CUSTOM = 0x00000001; bool isCustom = (PDO_IS_CUSTOM & reader.ReadInt32()) == PDO_IS_CUSTOM;//Flags: DWORD (4 bytes) reader.ReadInt16();//VT: WORD (2 bytes) reader.ReadInt32();//DispId: DWORD (4 bytes) int nameIdLength = reader.ReadInt16();//NmidNameLength: WORD(2 bytes) name = new string(reader.ReadChars(nameIdLength)); ReadPackedAnsiString(reader);//NameANSI ReadPackedAnsiString(reader);//FormulaANSI ReadPackedAnsiString(reader);//ValidationRuleANSI ReadPackedAnsiString(reader);//ValidationTextANSI ReadPackedAnsiString(reader);//ErrorANSI return isCustom ? name : string.Empty; } ///<Summary> /// Get Custom Property Name V2 ///</Summary> /// <param name="reader"></param> private static string GetCustomPropertyNameV2(BinaryReader reader) { //https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/ee415114%28v%3doffice.14%29 string name = GetCustomPropertyNameV1(reader); reader.ReadInt32();//InternalType: DWORD (4 bytes) int size = 0; while ((size = reader.ReadInt32()) > 0)//SkipBlocks { reader.ReadBytes(size); } return name; } ///<Summary> /// Read Packed Ansi String ///</Summary> /// <param name="reader"></param> private static void ReadPackedAnsiString(BinaryReader reader) { //https://docs.microsoft.com/ru-ru/office/client-developer/outlook/mapi/packedansistring-stream-structure int length = reader.ReadByte(); if (length == 255) { length = reader.ReadInt16(); } else if (length == 0) { return; } reader.ReadBytes(length); } ///<Summary> /// Named Mapi Property ///</Summary> public class NamedMapiProperty { ///<Summary> /// Get or Set Name property ///</Summary> public string Name { get; private set; } ///<Summary> /// Property Property ///</Summary> public MapiProperty Property { get; private set; } ///<Summary> /// Named Mapi Property ///</Summary> public NamedMapiProperty(string name, MapiProperty customProp) { Name = name; Property = customProp; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; using System.Xml; using System.Xml.XPath; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Xml; using Umbraco.Web.Routing; using umbraco; using System.Linq; using umbraco.BusinessLogic; using umbraco.presentation.preview; using Umbraco.Core.Services; using GlobalSettings = umbraco.GlobalSettings; using Task = System.Threading.Tasks.Task; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { internal class PublishedContentCache : IPublishedContentCache { #region Routes cache private readonly RoutesCache _routesCache = new RoutesCache(!UnitTesting); private DomainHelper _domainHelper; private DomainHelper GetDomainHelper(IDomainService domainService) { return _domainHelper ?? (_domainHelper = new DomainHelper(domainService)); } // for INTERNAL, UNIT TESTS use ONLY internal RoutesCache RoutesCache { get { return _routesCache; } } // for INTERNAL, UNIT TESTS use ONLY internal static bool UnitTesting = false; public virtual IPublishedContent GetByRoute(UmbracoContext umbracoContext, bool preview, string route, bool? hideTopLevelNode = null) { if (route == null) throw new ArgumentNullException("route"); // try to get from cache if not previewing var contentId = preview ? 0 : _routesCache.GetNodeId(route); // if found id in cache then get corresponding content // and clear cache if not found - for whatever reason IPublishedContent content = null; if (contentId > 0) { content = GetById(umbracoContext, preview, contentId); if (content == null) _routesCache.ClearNode(contentId); } // still have nothing? actually determine the id hideTopLevelNode = hideTopLevelNode ?? GlobalSettings.HideTopLevelNodeFromPath; // default = settings content = content ?? DetermineIdByRoute(umbracoContext, preview, route, hideTopLevelNode.Value); // cache if we have a content and not previewing if (content != null && preview == false) AddToCacheIfDeepestRoute(umbracoContext, content, route); return content; } private void AddToCacheIfDeepestRoute(UmbracoContext umbracoContext, IPublishedContent content, string route) { var domainRootNodeId = route.StartsWith("/") ? -1 : int.Parse(route.Substring(0, route.IndexOf('/'))); // so we have a route that maps to a content... say "1234/path/to/content" - however, there could be a // domain set on "to" and route "4567/content" would also map to the same content - and due to how // urls computing work (by walking the tree up to the first domain we find) it is that second route // that would be returned - the "deepest" route - and that is the route we want to cache, *not* the // longer one - so make sure we don't cache the wrong route var deepest = UnitTesting == false && DomainHelper.ExistsDomainInPath(umbracoContext.Application.Services.DomainService.GetAll(false), content.Path, domainRootNodeId) == false; if (deepest) _routesCache.Store(content.Id, route); } public virtual string GetRouteById(UmbracoContext umbracoContext, bool preview, int contentId) { // try to get from cache if not previewing var route = preview ? null : _routesCache.GetRoute(contentId); // if found in cache then return if (route != null) return route; // else actually determine the route route = DetermineRouteById(umbracoContext, preview, contentId); // node not found if (route == null) return null; // find the content back, detect routes collisions: we should find ourselves back, // else it means that another content with "higher priority" is sharing the same route. // perf impact: // - non-colliding, adds one complete "by route" lookup, only on the first time a url is computed (then it's cached anyways) // - colliding, adds one "by route" lookup, the first time the url is computed, then one dictionary looked each time it is computed again // assuming no collisions, the impact is one complete "by route" lookup the first time each url is computed // // U4-9121 - this lookup is too expensive when computing a large amount of urls on a front-end (eg menu) // ... thinking about moving the lookup out of the path into its own async task, so we are not reporting errors // in the back-office anymore, but at least we are not polluting the cache // instead, refactored DeterminedIdByRoute to stop using XPath, with a 16x improvement according to benchmarks // will it be enough? var loopId = preview ? 0 : _routesCache.GetNodeId(route); // might be cached already in case of collision if (loopId == 0) { var content = DetermineIdByRoute(umbracoContext, preview, route, GlobalSettings.HideTopLevelNodeFromPath); // add the other route to cache so next time we have it already if (content != null && preview == false) AddToCacheIfDeepestRoute(umbracoContext, content, route); loopId = content == null ? 0 : content.Id; // though... 0 here would be quite weird? } // cache if we have a route and not previewing and it's not a colliding route // (the result of DetermineRouteById is always the deepest route) if (/*route != null &&*/ preview == false && loopId == contentId) _routesCache.Store(contentId, route); // return route if no collision, else report collision return loopId == contentId ? route : ("err/" + loopId); } IPublishedContent DetermineIdByRoute(UmbracoContext umbracoContext, bool preview, string route, bool hideTopLevelNode) { if (route == null) throw new ArgumentNullException("route"); //the route always needs to be lower case because we only store the urlName attribute in lower case route = route.ToLowerInvariant(); var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos)); //check if we can find the node in our xml cache var id = NavigateRoute(umbracoContext, preview, startNodeId, path, hideTopLevelNode); if (id > 0) return GetById(umbracoContext, preview, id); // if hideTopLevelNodePath is true then for url /foo we looked for /*/foo // but maybe that was the url of a non-default top-level node, so we also // have to look for /foo (see note in ApplyHideTopLevelNodeFromPath). if (hideTopLevelNode && path.Length > 1 && path.IndexOf('/', 1) < 0) { var id2 = NavigateRoute(umbracoContext, preview, startNodeId, path, false); if (id2 > 0) return GetById(umbracoContext, preview, id2); } return null; } private int NavigateRoute(UmbracoContext umbracoContext, bool preview, int startNodeId, string path, bool hideTopLevelNode) { var xml = GetXml(umbracoContext, preview); XmlElement elt; // empty path if (path == string.Empty || path == "/") { if (startNodeId > 0) { elt = xml.GetElementById(startNodeId.ToString(CultureInfo.InvariantCulture)); return elt == null ? -1 : startNodeId; } elt = null; var min = int.MaxValue; foreach (XmlElement e in xml.DocumentElement.ChildNodes) { var sortOrder = int.Parse(e.GetAttribute("sortOrder")); if (sortOrder < min) { min = sortOrder; elt = e; } } return elt == null ? -1 : int.Parse(elt.GetAttribute("id")); } // non-empty path elt = startNodeId <= 0 ? xml.DocumentElement : xml.GetElementById(startNodeId.ToString(CultureInfo.InvariantCulture)); if (elt == null) return -1; var urlParts = path.Split(SlashChar, StringSplitOptions.RemoveEmptyEntries); if (hideTopLevelNode && startNodeId <= 0) { foreach (XmlElement e in elt.ChildNodes) { var id = NavigateElementRoute(e, urlParts); if (id > 0) return id; } return -1; } return NavigateElementRoute(elt, urlParts); } private static bool UseLegacySchema { get { return UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema; } } private int NavigateElementRoute(XmlElement elt, string[] urlParts) { var found = true; var i = 0; while (found && i < urlParts.Length) { found = false; foreach (XmlElement child in elt.ChildNodes) { var noNode = UseLegacySchema ? child.Name != "node" : child.GetAttributeNode("isDoc") == null; if (noNode) continue; if (child.GetAttribute("urlName") != urlParts[i]) continue; found = true; elt = child; break; } i++; } return found ? int.Parse(elt.GetAttribute("id")) : -1; } string DetermineRouteById(UmbracoContext umbracoContext, bool preview, int contentId) { var elt = GetXml(umbracoContext, preview).GetElementById(contentId.ToString(CultureInfo.InvariantCulture)); if (elt == null) return null; var domainHelper = GetDomainHelper(umbracoContext.Application.Services.DomainService); // walk up from that node until we hit a node with a domain, // or we reach the content root, collecting urls in the way var pathParts = new List<string>(); var eltId = int.Parse(elt.GetAttribute("id")); var eltParentId = int.Parse(((XmlElement) elt.ParentNode).GetAttribute("id")); var e = elt; var id = eltId; var hasDomains = domainHelper.NodeHasDomains(id); while (hasDomains == false && id != -1) { // get the url var urlName = e.GetAttribute("urlName"); pathParts.Add(urlName); // move to parent node e = (XmlElement) e.ParentNode; id = int.Parse(e.GetAttribute("id")); hasDomains = id != -1 && domainHelper.NodeHasDomains(id); } // no domain, respect HideTopLevelNodeFromPath for legacy purposes if (hasDomains == false && GlobalSettings.HideTopLevelNodeFromPath) ApplyHideTopLevelNodeFromPath(umbracoContext, eltId, eltParentId, pathParts); // assemble the route pathParts.Reverse(); var path = "/" + string.Join("/", pathParts); // will be "/" or "/foo" or "/foo/bar" etc var route = (id == -1 ? "" : id.ToString(CultureInfo.InvariantCulture)) + path; return route; } static void ApplyHideTopLevelNodeFromPath(UmbracoContext umbracoContext, int nodeId, int parentId, IList<string> pathParts) { // in theory if hideTopLevelNodeFromPath is true, then there should be only once // top-level node, or else domains should be assigned. but for backward compatibility // we add this check - we look for the document matching "/" and if it's not us, then // we do not hide the top level path // it has to be taken care of in GetByRoute too so if // "/foo" fails (looking for "/*/foo") we try also "/foo". // this does not make much sense anyway esp. if both "/foo/" and "/bar/foo" exist, but // that's the way it works pre-4.10 and we try to be backward compat for the time being if (parentId == -1) { var rootNode = umbracoContext.ContentCache.GetByRoute("/", true); if (rootNode == null) throw new Exception("Failed to get node at /."); if (rootNode.Id == nodeId) // remove only if we're the default node pathParts.RemoveAt(pathParts.Count - 1); } else { pathParts.RemoveAt(pathParts.Count - 1); } } #endregion #region XPath Strings class XPathStringsDefinition { public int Version { get; private set; } public string RootDocuments { get; private set; } public XPathStringsDefinition(int version) { Version = version; switch (version) { // legacy XML schema case 0: RootDocuments = "/root/node"; break; // default XML schema as of 4.10 case 1: RootDocuments = "/root/* [@isDoc]"; break; default: throw new Exception(string.Format("Unsupported Xml schema version '{0}').", version)); } } } static XPathStringsDefinition _xPathStringsValue; static XPathStringsDefinition XPathStrings { get { // in theory XPathStrings should be a static variable that // we should initialize in a static ctor - but then test cases // that switch schemas fail - so cache and refresh when needed, // ie never when running the actual site var version = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? 0 : 1; if (_xPathStringsValue == null || _xPathStringsValue.Version != version) _xPathStringsValue = new XPathStringsDefinition(version); return _xPathStringsValue; } } #endregion #region Converters private static IPublishedContent ConvertToDocument(XmlNode xmlNode, bool isPreviewing) { return xmlNode == null ? null : XmlPublishedContent.Get(xmlNode, isPreviewing); } private static IEnumerable<IPublishedContent> ConvertToDocuments(XmlNodeList xmlNodes, bool isPreviewing) { return xmlNodes.Cast<XmlNode>() .Select(xmlNode => XmlPublishedContent.Get(xmlNode, isPreviewing)); } #endregion #region Getters public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId) { return ConvertToDocument(GetXml(umbracoContext, preview).GetElementById(nodeId.ToString(CultureInfo.InvariantCulture)), preview); } public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview) { return ConvertToDocuments(GetXml(umbracoContext, preview).SelectNodes(XPathStrings.RootDocuments), preview); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); if (string.IsNullOrWhiteSpace(xpath)) return null; var xml = GetXml(umbracoContext, preview); var node = vars == null ? xml.SelectSingleNode(xpath) : xml.SelectSingleNode(xpath, vars); return ConvertToDocument(node, preview); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); var xml = GetXml(umbracoContext, preview); var node = vars == null ? xml.SelectSingleNode(xpath) : xml.SelectSingleNode(xpath, vars); return ConvertToDocument(node, preview); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); if (string.IsNullOrWhiteSpace(xpath)) return Enumerable.Empty<IPublishedContent>(); var xml = GetXml(umbracoContext, preview); var nodes = vars == null ? xml.SelectNodes(xpath) : xml.SelectNodes(xpath, vars); return ConvertToDocuments(nodes, preview); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, params XPathVariable[] vars) { if (xpath == null) throw new ArgumentNullException("xpath"); var xml = GetXml(umbracoContext, preview); var nodes = vars == null ? xml.SelectNodes(xpath) : xml.SelectNodes(xpath, vars); return ConvertToDocuments(nodes, preview); } public virtual bool HasContent(UmbracoContext umbracoContext, bool preview) { var xml = GetXml(umbracoContext, preview); if (xml == null) return false; var node = xml.SelectSingleNode(XPathStrings.RootDocuments); return node != null; } public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview) { var xml = GetXml(umbracoContext, preview); return xml.CreateNavigator(); } public virtual bool XPathNavigatorIsNavigable { get { return false; } } #endregion #region Legacy Xml static readonly ConditionalWeakTable<UmbracoContext, PreviewContent> PreviewContentCache = new ConditionalWeakTable<UmbracoContext, PreviewContent>(); private Func<UmbracoContext, bool, XmlDocument> _xmlDelegate; /// <summary> /// Gets/sets the delegate used to retrieve the Xml content, generally the setter is only used for unit tests /// and by default if it is not set will use the standard delegate which ONLY works when in the context an Http Request /// </summary> /// <remarks> /// If not defined, we will use the standard delegate which ONLY works when in the context an Http Request /// mostly because the 'content' object heavily relies on HttpContext, SQL connections and a bunch of other stuff /// that when run inside of a unit test fails. /// </remarks> internal Func<UmbracoContext, bool, XmlDocument> GetXmlDelegate { get { return _xmlDelegate ?? (_xmlDelegate = (context, preview) => { if (preview) { var previewContent = PreviewContentCache.GetOrCreateValue(context); // will use the ctor with no parameters previewContent.EnsureInitialized(context.UmbracoUser, StateHelper.Cookies.Preview.GetValue(), true, () => { if (previewContent.ValidPreviewSet) previewContent.LoadPreviewset(); }); if (previewContent.ValidPreviewSet) return previewContent.XmlContent; } return content.Instance.XmlContent; }); } set { _xmlDelegate = value; } } internal XmlDocument GetXml(UmbracoContext umbracoContext, bool preview) { var xml = GetXmlDelegate(umbracoContext, preview); if (xml == null) throw new Exception("The Xml cache is corrupt. Use the Health Check data integrity dashboard to fix it."); return xml; } #endregion #region XPathQuery static readonly char[] SlashChar = new[] { '/' }; #endregion #region Detached public IPublishedProperty CreateDetachedProperty(PublishedPropertyType propertyType, object value, bool isPreviewing) { if (propertyType.IsDetachedOrNested == false) throw new ArgumentException("Property type is neither detached nor nested.", "propertyType"); return new XmlPublishedProperty(propertyType, isPreviewing, value.ToString()); } #endregion } }
using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Net; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using SpotifyAPI.SpotifyLocalAPI; // Changelog from v2.0 to v2.1 // // ** now on github ** // // fixes // - fixed automatic downloading not redownloading corrupted files // - fixed artist/song label text's being in each other's spot, don't know how I missed that // - fixed including "original mix" in search terms which would screw up the download // - fixed window resizing issues // - fixed track names with /'s looking like it's another directory instead of just part of the song name // - song names with /'s will have the /'s replaced with -'s // // additions // - added async/awaits/trys/catches in places where they should have been in the first place, allows for better download handling // - added download progress bar [requested by ElementalTree] // - added feature to automatically retry a download 3 times if the download completes with a <1MB file // - added option to have notification when downloads complete // // // TODO: Add queueing system for song downloads, probably going to use a List<string> and a foreach loop /* Changelog from v2.1 to v2.2 (Updated by Redder04) * * - Added as much comments as I could (im still a beginner so I don't understand most things) * - Added credits box to UI, makes it look more organized, and its "responsive" * - Changed InitializeComponent() to the end of the Main funciton instead of beginning. * - Modified startup process, more efficient * - Fixed Error when Program starts without a track playing in spotify, it crashes */ namespace SpottyMP3 { public partial class Main : Form { SpotifyLocalAPIClass spotify; SpotifyMusicHandler mh; SpotifyEventHandler eh; int tryNumber = 0; bool downloading = false; string lastDownloaded = string.Empty; WebClient client = new WebClient(); ToolTip tt = new ToolTip(); Stopwatch sw = new Stopwatch(); int time = 0; int version = 2; DateTime lastUpdate; long lastBytes = 0; public Main() { updateCheck(); spotify = new SpotifyLocalAPIClass(); //Creating a new instance of Spotify Local API if (!SpotifyLocalAPIClass.IsSpotifyRunning()) //If Spotify is not running then { spotify.RunSpotify(); //Run spotify Thread.Sleep(5000); if (!SpotifyLocalAPIClass.IsSpotifyRunning()) { MessageBox.Show("Spotify didn't open after 5 seconds, exiting"); Environment.Exit(1); } } if (!SpotifyLocalAPIClass.IsSpotifyWebHelperRunning()) { spotify.RunSpotifyWebHelper(); //Run Spotify Web Helper Thread.Sleep(5000); if (!SpotifyLocalAPIClass.IsSpotifyWebHelperRunning()) { MessageBox.Show("Spotify Web Helper didn't open after 5 seconds, exiting"); Environment.Exit(2); } } if (!spotify.Connect()) { Boolean retry = true; while (retry) { if (MessageBox.Show("SLAPI couldn't load!", "Error", MessageBoxButtons.RetryCancel) == System.Windows.Forms.DialogResult.Retry) { if (spotify.Connect()) retry = false; else retry = true; } else { this.Close(); return; } } } mh = spotify.GetMusicHandler(); eh = spotify.GetEventHandler(); InitializeComponent(); } //executeDownload(mh.GetCurrentTrack().GetArtistName(), mh.GetCurrentTrack().GetTrackName(), true); private async Task executeDownload(string artist, string name, bool tellIfAlreadyExists = false) { tryNumber = 0; time = 0; startdownload: try { if (downloading) { addToLog("Already downloading a song, ignoring requested download", logBox); return; } downloading = true; string term = artist + " - " + name; //Building search term term = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars())))).Replace(term, ""); //Removing any invalid characters? if (string.IsNullOrWhiteSpace(artist) || string.IsNullOrWhiteSpace(name) || mh.IsAdRunning()) //If there is no artist or no name or an ad is running return since theres nothing to download { downloading = false; return; } if (term.Length > 16) if (term.Substring(term.Length - 15).ToLower() == " - original mix") term = term.Substring(0, term.Length - 15); //Remove "Original Mix" if (term.Contains(" - feat")) term = term.Split(new string[] { " - feat" }, StringSplitOptions.None)[0]; //Remove feat lastDownloaded = term; if (!File.Exists(browseForFolderBox.Text + lastDownloaded + ".mp3")) //If the song wasent downloaded to the folder already { addToLog("Searching MP3Clan for term \"" + term + "\"", logBox); string pageSource = client.DownloadString(new Uri(string.Format("http://mp3clan.com/mp3_source.php?q={0}", term.Replace(" ", "+")))); //Perform search and get page source //Perfom a search query in your browser and you can view the source to understand the next line Match trackId = new Regex("<div class=\"mp3list-table\" id=\"(.+?)\">").Match(pageSource); //Checks if div exists in the page source //What is (.+?) if (!trackId.Success || string.IsNullOrWhiteSpace(trackId.Groups[1].Value)) //If there was no match or ...I don't know what is trackId.Groups[1].Value? Is it the ID of the div? { if (tryNumber < 3) //If try number is less than 3, retry download { downloading = false; tryNumber++; addToLog("Could not find TrackID, retrying " + tryNumber + "/3", logBox); goto startdownload; } else //If try number is greater than 3, then skip the download/give up { addToLog("Could not find TrackID, skipping download", logBox); downloading = false; return; } } addToLog("TrackId: " + trackId.Groups[1].Value, logBox); string dlLink = string.Format("http://mp3clan.com/app/get.php?mp3={0}", trackId.Groups[1].Value); addToLog("Downloading from link: " + dlLink, logBox); sw.Start(); //Start the download stopwatch await Task.WhenAll(downloadFileAsync(dlLink, lastDownloaded)); //Download the track } else { if (tellIfAlreadyExists) { addToLog("Song already downloaded", logBox); } downloading = false; } //FIle already downloaded FileInfo fileInfo = new FileInfo(browseForFolderBox.Text + lastDownloaded + ".mp3"); if (fileInfo.Length < 1000000 && retryIfUnder1Mb.Checked) //If length of file is less than 1mb and retry under 1mb is checked then retry download { if (tryNumber < 3) { downloading = false; tryNumber++; if (File.Exists(browseForFolderBox.Text + lastDownloaded + ".mp3")) File.Delete(browseForFolderBox.Text + lastDownloaded + ".mp3"); addToLog("File downloaded was under 1MB, redownloading try " + tryNumber + "/3", logBox); goto startdownload; } else { downloading = false; addToLog(term + " failed to download every try, skipping", logBox); if (Settings.Default.DownloadNotifications) notifyIcon.ShowBalloonTip(3000, "Download error", "The download for \"" + lastDownloaded + "\" failed to download.", ToolTipIcon.Error); } } downloading = false; } catch (Exception e) { downloading = false; tryNumber++; addToLog("Error downloading file, retrying " + tryNumber + "\n" + e.ToString(), logBox); goto startdownload; } } private async Task downloadFileAsync(string url, string term) { try { await client.DownloadFileTaskAsync(new Uri(url), string.Format(browseForFolderBox.Text + "\\" + term + ".mp3")); } // System.Net.WebException: An exception occurred during a WebClient request. ---> System.IO.IOException: Unable to read data from the transport connection: The connection was closed. catch (WebException) { addToLog("Error downloading file: connection closed", logBox); } catch (Exception e) { addToLog("Error downloading file:\n" + e.ToString(), logBox); } } void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { if (e.TotalBytesToReceive > 0) { try { if (lastBytes == 0) { lastUpdate = DateTime.Now; lastBytes = e.BytesReceived; return; } DateTime now = DateTime.Now; TimeSpan timeSpan = now - lastUpdate; long bytesChange = e.BytesReceived - lastBytes; long bytesPerSecond = 0; if (timeSpan.Seconds > 0) // stupid divide by zero errors bytesPerSecond = bytesChange / timeSpan.Seconds; downloadSpeedLabel.Text = bytesPerSecond / 1000 + "KB/s"; } catch (Exception exception) { MessageBox.Show(exception.ToString()); } downloadBytesLabel.Text = e.BytesReceived / 1000 + "/" + e.TotalBytesToReceive / 1000; downloadProgress.Maximum = (int)e.TotalBytesToReceive; downloadProgress.Value = (int)e.BytesReceived; } } void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { time = (int)sw.ElapsedMilliseconds / 1000; sw.Reset(); if (string.IsNullOrWhiteSpace(lastDownloaded)) return; int fileSize = (int)new FileInfo(browseForFolderBox.Text + "\\" + lastDownloaded + ".mp3").Length; int fileSizeKb = fileSize / 1000; if (fileSize > 1000000) { if (tryNumber == 0) addToLog("Download completed for \"" + lastDownloaded + "\" with " + fileSizeKb + "KB in " + time + " seconds in " + (tryNumber + 1) + " try", logBox); else addToLog("Download completed for \"" + lastDownloaded + "\" with " + fileSizeKb + "KB in " + time + " seconds in " + (tryNumber + 1) + " tries", logBox); if (Settings.Default.DownloadNotifications) notifyIcon.ShowBalloonTip(3000, "Download completed", "The download for \"" + lastDownloaded + "\" completed in " + time + " seconds.", ToolTipIcon.Info); } } void addToLog(string info, RichTextBox logBox) { if (String.IsNullOrWhiteSpace(logBox.Text)) { logBox.AppendText("[" + DateTime.Now.ToString("h:mm:ss tt") + "] " + info); } else { //logBox.AppendText("\n[" + DateTime.Now.ToString("h:mm:ss tt") + "] " + info); logBox.Text = "[" + DateTime.Now.ToString("h:mm:ss tt") + "] " + info + "\n" + logBox.Text; } } void updateCheck() { try { int latest = Convert.ToInt32(client.DownloadString("https://github.com/Scarsz/SpottyMP3/raw/master/version").Trim()); if (latest > version) { MessageBox.Show("This version of SpottyMP3 is outdated!"); Process.Start("https://github.com/Scarsz/SpottyMP3/releases"); } } catch (Exception) { addToLog("Update check failed", logBox); } } private async void main_Load(object sender, EventArgs e) { this.Text = "SpottyMP3 v2." + version; //Changes text to match version user is using addToLog("Initialization of SpottyMP3 v2." + version + " complete, enjoy!", logBox); spotify.Update(); adPlaying.Text = "AdPlaying: " + mh.IsAdRunning(); //Is an ad playing right now? songPlaying.Text = "Playing: " + mh.IsPlaying(); //Is a song playing right now? //If an add is not running then get the tracks image if (!mh.IsAdRunning()) currentPicture.Image = await spotify.GetMusicHandler().GetCurrentTrack().GetAlbumArtAsync(AlbumArtSize.SIZE_160); try { currentBar.Maximum = mh.GetCurrentTrack().GetLength() * 100; //Gets track length and sets the end of the track as maximum value of progress bar artistLinkLabel.Text = mh.GetCurrentTrack().GetArtistName(); //Gets Current tracks artist name artistLinkLabel.LinkClicked += (senderTwo, args) => Process.Start(mh.GetCurrentTrack().GetArtistURI()); songLinkLabel.Text = mh.GetCurrentTrack().GetTrackName(); //Gets Current tracks name songLinkLabel.LinkClicked += (senderTwo, args) => Process.Start(mh.GetCurrentTrack().GetTrackURI()); albumLinkLabel.Text = mh.GetCurrentTrack().GetAlbumName(); //Gets Current tracks album name albumLinkLabel.LinkClicked += (senderTwo, args) => Process.Start(mh.GetCurrentTrack().GetAlbumURI()); } catch (NullReferenceException) { } //Other contributers links, im going to add mine :) creatorLabel.LinkClicked += (senderTwo, args) => Process.Start("http://www.hackforums.net/showthread.php?tid=4819899"); downloadersourceLabel.LinkClicked += (senderTwo, args) => Process.Start("http://www.hackforums.net/showthread.php?tid=4497329"); ogcreatorLabel.LinkClicked += (senderTwo, args) => Process.Start("http://www.hackforums.net/showthread.php?tid=4506105"); redderLabel.LinkClicked += (senderTwo, args) => Process.Start("https://leakforums.net/user-49440"); client.DownloadProgressChanged += client_DownloadProgressChanged; client.DownloadFileCompleted += client_DownloadFileCompleted; eh.OnTrackChange += new SpotifyEventHandler.TrackChangeEventHandler(trackChange); eh.OnTrackTimeChange += new SpotifyEventHandler.TrackTimeChangeEventHandler(timeChange); eh.OnPlayStateChange += new SpotifyEventHandler.PlayStateEventHandler(playstateChange); eh.OnVolumeChange += new SpotifyEventHandler.VolumeChangeEventHandler(volumeChange); eh.SetSynchronizingObject(this); eh.ListenForEvents(true); if (string.IsNullOrWhiteSpace(Settings.Default.DownloadDestination)) //If there is no default download destination then set it to the program directory, else, set it to default download browseForFolderBox.Text = System.AppDomain.CurrentDomain.BaseDirectory; else browseForFolderBox.Text = Settings.Default.DownloadDestination; retryIfUnder1Mb.Checked = Settings.Default.DownloadRetry; liveDownloads.Checked = Settings.Default.DownloadAutomatically; showDownloadNotification.Checked = Settings.Default.DownloadNotifications; tt.AutoPopDelay = 5000; tt.InitialDelay = 1000; tt.ReshowDelay = 500; tt.SetToolTip(retryIfUnder1Mb, "Whether or not to retry downloading a song if it finishes downloading smaller than 1MB"); } private async void trackChange(TrackChangeEventArgs e) { currentBar.Maximum = mh.GetCurrentTrack().GetLength() * 100; artistLinkLabel.Text = e.new_track.GetArtistName(); songLinkLabel.Text = e.new_track.GetTrackName(); albumLinkLabel.Text = e.new_track.GetAlbumName(); adPlaying.Text = "AdPlaying: " + mh.IsAdRunning(); if (!mh.IsAdRunning()) currentPicture.Image = await e.new_track.GetAlbumArtAsync(AlbumArtSize.SIZE_640); if (Settings.Default.DownloadAutomatically) await executeDownload(mh.GetCurrentTrack().GetArtistName(), mh.GetCurrentTrack().GetTrackName()); } private void timeChange(TrackTimeChangeEventArgs e) { if (!mh.IsAdRunning()) { try { currentBar.Maximum = (int)mh.GetCurrentTrack().length * 100; currentBar.Value = (int)e.track_time * 100; } catch { currentBar.Maximum = currentBar.Maximum * 100; currentBar.Value = currentBar.Value * 100; } } } private void playstateChange(PlayStateEventArgs e) { songPlaying.Text = "Playing: " + mh.IsPlaying(); //Is a song playing right now? } private void volumeChange(VolumeChangeEventArgs e) { } private void previousButton_Click(object sender, EventArgs e) { mh.Previous(); } private void playButton_Click(object sender, EventArgs e) { mh.Play(); } private void pauseButton_Click(object sender, EventArgs e) { mh.Pause(); } private void nextButton_Click(object sender, EventArgs e) { mh.Skip(); } private async void downloadButton_Click(object sender, EventArgs e) { await executeDownload(mh.GetCurrentTrack().GetArtistName(), mh.GetCurrentTrack().GetTrackName(), true); } private async void liveDownloads_CheckedChanged(object sender, EventArgs e) { Settings.Default.DownloadAutomatically = liveDownloads.Checked; Settings.Default.Save(); if (Settings.Default.DownloadAutomatically && !mh.IsAdRunning()) await executeDownload(mh.GetCurrentTrack().GetArtistName(), mh.GetCurrentTrack().GetTrackName()); } private void retryIfUnder1Mb_CheckedChanged(object sender, EventArgs e) { Settings.Default.DownloadRetry = retryIfUnder1Mb.Checked; Settings.Default.Save(); } private void showDownloadNotification_CheckedChanged(object sender, EventArgs e) { Settings.Default.DownloadNotifications = showDownloadNotification.Checked; Settings.Default.Save(); } private void browseForFolderBox_Leave(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(browseForFolderBox.Text)) { browseForFolderBox.Text = Settings.Default.DownloadDestination; } else if (!Directory.Exists(browseForFolderBox.Text)) { addToLog("Selected folder doesn't exist, reverting to default", logBox); browseForFolderBox.Text = System.AppDomain.CurrentDomain.BaseDirectory; } if (browseForFolderBox.Text.Substring(browseForFolderBox.Text.Length - 1, 1) != "\\") browseForFolderBox.Text = browseForFolderBox.Text + "\\"; Settings.Default.DownloadDestination = browseForFolderBox.Text; Settings.Default.Save(); } private void browseForFolderPicture_Click(object sender, EventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.Description = "Select the folder for downloaded music to be saved to"; fbd.ShowDialog(); browseForFolderBox.Text = fbd.SelectedPath; browseForFolderBox.Focus(); logBox.Focus(); browseForFolderBox.Focus(); } private void main_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { notifyIcon.ShowBalloonTip(1000, "SpottyMP3 is still running", "SpottyMP3 has been minimized to the task tray", ToolTipIcon.Info); this.ShowInTaskbar = false; } } private void notifyIcon_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; } } }
using clrcore; using Morph.Collections; namespace Morph { public class Array //: ICloneable, ICollection, IList, IEnumerable { // Order is very important here since this function is called by the compiler private static unsafe Array compilerInstanceNewArray1(uint numberOfElements, void* vtbl) { return new Array(vtbl, numberOfElements); } // TODO! Will be translated into "inline" when the feature will be possible // "sizeOfElements" is duplicated due to the fact that the function will be inline, so the optimizer // might use it as "const" and replace MUL with bitwise shifts private static unsafe byte* compilerGetArrayOffset(Array arr, uint index, uint sizeofElements) { return arr.m_buffer + (index * sizeofElements); } private unsafe Array(void* vtbl, uint numberOfElements) { m_internalTypeVtbl = vtbl; m_numberOfElements = numberOfElements; VirtualTable.VirtualTableHeader* vtblHeader = VirtualTable.getVirtualTableHeader(vtbl); m_objectSize = vtblHeader->m_objectSize; if (VirtualTable.virtualTableGetInterfaceLocation(vtbl, Morph.ValueType.getRTTI()) == 0xFFFFFFFF) { // Allocating an array[] the memory per instance is sizeof(object). // If the object is structure (not this case), the size of instance is vtblHeader->m_objectSize // Otherwise, the size per instance is void* length m_objectSize = (ushort)(sizeof(void*)); } // Alignment note: The VTBL is already aligned by the compiler according to layout policy m_dataSize = m_objectSize * numberOfElements; m_buffer = (byte*)Morph.Imports.allocate(m_dataSize); clrcore.Memory.memset(m_buffer, 0, m_dataSize); } ~Array() { unsafe { if ((VirtualTable.virtualTableGetInterfaceLocation(m_internalTypeVtbl, Morph.ValueType.getRTTI()) == 0xFFFFFFFF)) { // Call destructor only for managed objects and not valuetype (structs) void** arr = (void**)m_buffer; for (uint i = 0; i < m_numberOfElements; i++, ++arr) { clrcore.GarbageCollector.garbageCollectorDecreaseReference(*arr); } } Morph.Imports.free((void*)m_buffer); } } internal unsafe byte* internalGetBuffer() { return m_buffer; } private unsafe void* m_internalTypeVtbl; private unsafe byte* m_buffer; private uint m_numberOfElements; private uint m_dataSize; private ushort m_objectSize; private int m_rank = 1; public int Rank { get { return m_rank; } } //see: http://msdn.microsoft.com/en-us/library/z50k9bft.aspx public unsafe static void Copy(Array sourceArray, Array destinationArray, int length) { Copy(sourceArray, 0, destinationArray, 0, length); } public unsafe static void Copy(Array sourceArray, int srcIndex, Array destinationArray, int dstIndex, int length) { //Check boundries: if (sourceArray == null) throw new System.ArgumentNullException("sourceArray is null"); if (destinationArray == null) throw new System.ArgumentNullException("destinationArray is null"); if (sourceArray.Rank != destinationArray.Rank) throw new System.RankException(); if (length < 0) throw new System.ArgumentOutOfRangeException("length", "Value has to be >= 0."); if (srcIndex < 0) throw new System.ArgumentOutOfRangeException("sourceIndex", "Value has to be >= 0."); if (dstIndex < 0) throw new System.ArgumentOutOfRangeException("destinationIndex", "Value has to be >= 0."); if (length > sourceArray.Length - srcIndex) throw new System.ArgumentException("length is greater than the number of elements from sourceIndex to the end of sourceArray."); if (length > destinationArray.Length - dstIndex) throw new System.ArgumentException("length is greater than the number of elements from destinationIndex to the end of destinationArray."); unsafe { bool dstIsValueType = VirtualTable.virtualTableGetInterfaceLocation(destinationArray.m_internalTypeVtbl, Morph.ValueType.getRTTI()) != 0xFFFFFFFF; bool srcIsValueType = VirtualTable.virtualTableGetInterfaceLocation(sourceArray.m_internalTypeVtbl, Morph.ValueType.getRTTI()) != 0xFFFFFFFF; if (dstIsValueType != srcIsValueType) { throw new System.InvalidCastException("Morph cannot copy value-type array to refernce-type array, or referenc-typ array to value-type array"); } if (sourceArray.m_objectSize != destinationArray.m_objectSize) { throw new System.InvalidCastException("Cannot copy arrays with different object-sizes"); } //if the destination is a value type and initialized - decrease ref counts. if (!(dstIsValueType)) { //use array.clear to remove the ref-counts Array.Clear(destinationArray, dstIndex, length); } //no copy clrcore.Memory.memmove(destinationArray.m_buffer + dstIndex * destinationArray.m_objectSize, sourceArray.m_buffer + srcIndex * sourceArray.m_objectSize, (uint) (length * sourceArray.m_objectSize)); //increase refcount if this is a reference-type array if (!dstIsValueType) { for (int i = 0; i < length; i++) { void** arr = (void**)destinationArray.m_buffer; if (arr[i] != null) { GarbageCollector.garbageCollectorIncreaseReference(arr[i]); } } } } } public unsafe static void Clear(Array array, int index, int length) { if (array == null) { throw new System.NullReferenceException(); } if (index < 0 || length < 0 || length + index > array.m_numberOfElements) { throw new System.IndexOutOfRangeException(); } unsafe{ if (VirtualTable.virtualTableGetInterfaceLocation(array.m_internalTypeVtbl, Morph.ValueType.getRTTI()) == 0xFFFFFFFF) { for (int i = 0; i < length; i++) { void** arr = (void**)array.m_buffer; if (arr[i] != null) { GarbageCollector.garbageCollectorDecreaseReference(arr[i]); } } } clrcore.Memory.memset(array.m_buffer + index * array.m_objectSize, 0, (uint)(length * array.m_objectSize)); } } public unsafe System.Object Clone() { Array result; result = new Array(m_internalTypeVtbl, m_numberOfElements); return result; } #region Properties public int Length { get { int length = this.GetLength(0); for (int i = 1; i < this.Rank; i++) { length *= this.GetLength(i); } return length; } } #endregion public static int LastIndexOf( Array array, Object value) { throw new System.NotImplementedException(); } public static int LastIndexOf(Array array, Object value, int startIndex) { throw new System.NotImplementedException(); } public static int LastIndexOf(Array array, Object value, int startIndex, int count) { throw new System.NotImplementedException(); } private unsafe int GetRank() { return m_rank; } public unsafe int GetLength(int dimension) { //TODO: add support for multiple dimenstions return (int) m_numberOfElements; } public int GetLowerBound(int dimension) { throw new System.NotImplementedException(); } //public void CopyTo(System.Array array, int index) //{ // if (array == null) // throw new System.ArgumentNullException("array"); // // The order of these exception checks may look strange, // // but that's how the microsoft runtime does it. // if (this.Rank > 1) // throw new System.RankException("Only single dimension arrays are supported."); // if (index + this.GetLength(0) > array.GetLowerBound(0) + array.GetLength(0)) // throw new System.ArgumentException("Destination array was not long " + // "enough. Check destIndex and length, and the array's " + // "lower bounds."); // if (array.Rank > 1) // throw new System.RankException("Only single dimension arrays are supported."); // if (index < 0) // throw new System.ArgumentOutOfRangeException("index", "Value has to be >= 0."); // Copy(Imports.convertToArray(this), this.GetLowerBound(0), array, index, this.GetLength(0)); //} //public static System.Array CreateInstance(System.Type elementType, int length) //{ // int[] lengths = { length }; // return CreateInstance(elementType, lengths); //} //public static System.Array CreateInstance(System.Type elementType, int length1, int length2) //{ // int[] lengths = { length1, length2 }; // return CreateInstance(elementType, lengths); //} //public static System.Array CreateInstance(System.Type elementType, int length1, int length2, int length3) //{ // int[] lengths = { length1, length2, length3 }; // return CreateInstance(elementType, lengths); //} //public static System.Array CreateInstance(System.Type elementType, params int[] lengths) //{ // if (elementType == null) // throw new System.ArgumentNullException("elementType"); // if (lengths == null) // throw new System.ArgumentNullException("lengths"); // if (lengths.Length > 255) // throw new System.TypeLoadException(); // int[] bounds = null; // elementType = elementType.UnderlyingSystemType; // //if (!elementType.IsSystemType) // // throw new System.ArgumentException("Type must be a type provided by the runtime.", "elementType"); // if (elementType.Equals(typeof(void))) // throw new System.NotSupportedException("Array type can not be void"); // if (elementType.ContainsGenericParameters) // throw new System.NotSupportedException("Array type can not be an open generic type"); // //if ((elementType is TypeBuilder) && !(elementType as TypeBuilder).IsCreated()) // // throw new System.NotSupportedException("Can't create an array of the unfinished type '" + elementType + "'."); // return CreateInstanceImpl(elementType, lengths, bounds); //} //public static System.Array CreateInstance(System.Type elementType, int[] lengths, int[] lowerBounds) //{ // if (elementType == null) // throw new System.ArgumentNullException("elementType"); // if (lengths == null) // throw new System.ArgumentNullException("lengths"); // if (lowerBounds == null) // throw new System.ArgumentNullException("lowerBounds"); // elementType = elementType.UnderlyingSystemType; // //if (!elementType.IsSystemType) // // throw new System.ArgumentException("Type must be a type provided by the runtime.", "elementType"); // if (elementType.Equals(typeof(void))) // throw new System.NotSupportedException("Array type can not be void"); // if (elementType.ContainsGenericParameters) // throw new System.NotSupportedException("Array type can not be an open generic type"); // if (lengths.Length < 1) // throw new System.ArgumentException("Arrays must contain >= 1 elements."); // if (lengths.Length != lowerBounds.Length) // throw new System.ArgumentException("Arrays must be of same size."); // for (int j = 0; j < lowerBounds.Length; j++) // { // if (lengths[j] < 0) // throw new System.ArgumentOutOfRangeException("lengths", "Each value has to be >= 0."); // if ((long)lowerBounds[j] + (long)lengths[j] > (long)Int32.MaxValue) // throw new System.ArgumentOutOfRangeException("lengths", "Length + bound must not exceed Int32.MaxValue."); // } // if (lengths.Length > 255) // throw new System.TypeLoadException(); // return CreateInstanceImpl(elementType, lengths, lowerBounds); //} //public int GetUpperBound(int dimension) //{ // return GetLowerBound(dimension) + GetLength(dimension) - 1; //} //public object GetValue(int index) //{ // if (Rank != 1) // throw new System.ArgumentException("Array was not a one-dimensional array."); // if (index < GetLowerBound(0) || index > GetUpperBound(0)) // throw new System.IndexOutOfRangeException("Index has to be between upper and lower bound of the array."); // return GetValueImpl(index - GetLowerBound(0)); //} //public object GetValue(int index1, int index2) //{ // int[] ind = { index1, index2 }; // return GetValue(ind); //} //public object GetValue(int index1, int index2, int index3) //{ // int[] ind = { index1, index2, index3 }; // return GetValue(ind); //} //object IList.this[int index] //{ // get // { // if (unchecked((uint)index) >= unchecked((uint)Length)) // throw new System.IndexOutOfRangeException("index"); // if (this.Rank > 1) // throw new System.ArgumentException("Only single dimension arrays are supported."); // return GetValueImpl(index); // } // set // { // if (unchecked((uint)index) >= unchecked((uint)Length)) // throw new System.IndexOutOfRangeException("index"); // if (this.Rank > 1) // throw new System.ArgumentException("Only single dimension arrays are supported."); // SetValueImpl(value, index); // } //} //int IList.Add(object value) //{ // throw new System.NotSupportedException(); //} //void IList.Clear() //{ // Array.Clear(Imports.convertToArray(this), this.GetLowerBound(0), this.Length); //} //bool IList.Contains(object value) //{ // if (this.Rank > 1) // throw new System.RankException("Only single dimension arrays are supported."); // int length = this.Length; // for (int i = 0; i < length; i++) // { // if (Object.Equals(this.GetValueImpl(i), value)) // return true; // } // return false; //} //int IList.IndexOf(object value) //{ // if (this.Rank > 1) // throw new System.RankException("Only single dimension arrays are supported."); // int length = this.Length; // for (int i = 0; i < length; i++) // { // if (Object.Equals(this.GetValueImpl(i), value)) // // array index may not be zero-based. // // use lower bound // return i + this.GetLowerBound(0); // } // unchecked // { // // lower bound may be MinValue // return this.GetLowerBound(0) - 1; // } //} //void IList.Insert(int index, object value) //{ // throw new System.NotSupportedException(); //} //void IList.Remove(object value) //{ // throw new System.NotSupportedException(); //} //void IList.RemoveAt(int index) //{ // throw new System.NotSupportedException(); //} //public static int IndexOf(Array array, object value) //{ // if (array == null) // throw new System.ArgumentNullException("array"); // return IndexOf(array, value, 0, array.Length); //} //public static int IndexOf(Array array, object value, int startIndex) //{ // if (array == null) // throw new System.ArgumentNullException("array"); // return IndexOf(array, value, startIndex, array.Length - startIndex); //} //public static int IndexOf(Array array, object value, int startIndex, int count) //{ // if (array == null) // throw new System.ArgumentNullException("array"); // if (array.Rank > 1) // throw new System.RankException("Only single dimension arrays are supported."); // // re-ordered to avoid possible integer overflow // if (count < 0 || startIndex < array.GetLowerBound(0) || startIndex - 1 > array.GetUpperBound(0) - count) // throw new System.ArgumentOutOfRangeException(); // int max = startIndex + count; // for (int i = startIndex; i < max; i++) // { // if (Object.Equals(array.GetValueImpl(i), value)) // return i; // } // return array.GetLowerBound(0) - 1; //} //int ICollection.Count //{ // get // { // return Length; // } //} //public bool IsSynchronized //{ // get // { // return false; // } //} //public object SyncRoot //{ // get // { // return this; // } //} //public bool IsFixedSize //{ // get // { // return true; // } //} //public bool IsReadOnly //{ // get // { // return false; // } //} //public IEnumerator GetEnumerator() //{ // return new SimpleEnumerator(this); //} //internal class SimpleEnumerator : IEnumerator, ICloneable //{ // Array enumeratee; // int currentpos; // int length; // public SimpleEnumerator(Array arrayToEnumerate) // { // this.enumeratee = arrayToEnumerate; // this.currentpos = -1; // this.length = arrayToEnumerate.Length; // } // public object Current // { // get // { // // Exception messages based on MS implementation // if (currentpos < 0) // throw new System.InvalidOperationException("Enumeration has not started."); // if (currentpos >= length) // throw new System.InvalidOperationException("Enumeration has already ended"); // // Current should not increase the position. So no ++ over here. // return enumeratee.GetValueImpl(currentpos); // } // } // public bool MoveNext() // { // //The docs say Current should throw an exception if last // //call to MoveNext returned false. This means currentpos // //should be set to length when returning false. // if (currentpos < length) // currentpos++; // if (currentpos < length) // return true; // else // return false; // } // public void Reset() // { // currentpos = -1; // } // public object Clone() // { // return MemberwiseClone(); // } //} //public static void Sort(Array array) //{ // Sort(array, (IComparer)null); //} //public static void Sort(Array keys, Array items) //{ // Sort(keys, items, (IComparer)null); //} //public static void Sort(Array array, IComparer comparer) //{ // if (array == null) // throw new System.ArgumentNullException("array"); // if (array.Rank > 1) // throw new System.RankException("Only single dimension arrays are supported."); // SortImpl(array, null, array.GetLowerBound(0), array.GetLength(0), comparer); //} //public static void Sort(Array array, int index, int length) //{ // Sort(array, index, length, (IComparer)null); //} //public static void Sort(Array keys, Array items, IComparer comparer) //{ // if (items == null) // { // Sort(keys, comparer); // return; // } // if (keys == null) // throw new System.ArgumentNullException("keys"); // if (keys.Rank > 1 || items.Rank > 1) // throw new System.RankException("Only single dimension arrays are supported."); // SortImpl(keys, items, keys.GetLowerBound(0), keys.GetLength(0), comparer); //} //public static void Sort(Array keys, Array items, int index, int length) //{ // Sort(keys, items, index, length, (IComparer)null); //} //public static void Sort(Array array, int index, int length, IComparer comparer) //{ // if (array == null) // throw new System.ArgumentNullException("array"); // if (array.Rank > 1) // throw new System.RankException("Only single dimension arrays are supported."); // if (index < array.GetLowerBound(0)) // throw new System.ArgumentOutOfRangeException("index"); // if (length < 0) // throw new System.ArgumentOutOfRangeException("length", "Value has to be >= 0."); // if (array.Length - (array.GetLowerBound(0) + index) < length) // throw new System.ArgumentException(); // SortImpl(array, null, index, length, comparer); //} //public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) //{ // if (items == null) // { // Sort(keys, index, length, comparer); // return; // } // if (keys == null) // throw new System.ArgumentNullException("keys"); // if (keys.Rank > 1 || items.Rank > 1) // throw new System.RankException(); // if (keys.GetLowerBound(0) != items.GetLowerBound(0)) // throw new System.ArgumentException(); // if (index < keys.GetLowerBound(0)) // throw new System.ArgumentOutOfRangeException("index"); // if (length < 0) // throw new System.ArgumentOutOfRangeException("length", "Value has to be >= 0."); // if (items.Length - (index + items.GetLowerBound(0)) < length || keys.Length - (index + keys.GetLowerBound(0)) < length) // throw new System.ArgumentException(); // SortImpl(keys, items, index, length, comparer); //} //private static void SortImpl(Array keys, Array items, int index, int length, IComparer comparer) //{ // if (length <= 1) // return; // int low = index; // int high = index + length - 1; // //if (comparer == null && items is object[]) // //{ // // if (keys is int[]) // // { // // qsort(keys as int[], items as object[], low, high); // // return; // // } // // if (keys is long[]) // // { // // qsort(keys as long[], items as object[], low, high); // // return; // // } // // if (keys is char[]) // // { // // qsort(keys as char[], items as object[], low, high); // // return; // // } // // if (keys is double[]) // // { // // qsort(keys as double[], items as object[], low, high); // // return; // // } // // if (keys is uint[]) // // { // // qsort(keys as uint[], items as object[], low, high); // // return; // // } // // if (keys is ulong[]) // // { // // qsort(keys as ulong[], items as object[], low, high); // // return; // // } // // if (keys is byte[]) // // { // // qsort(keys as byte[], items as object[], low, high); // // return; // // } // // if (keys is ushort[]) // // { // // qsort(keys as ushort[], items as object[], low, high); // // return; // // } // //} // if (comparer == null) // CheckComparerAvailable(keys, low, high); // try // { // qsort(keys, items, low, high, comparer); // } // catch (System.Exception e) // { // throw new System.InvalidOperationException("The comparer threw an exception.", e); // } //} //private static void qsort(Array keys, Array items, int low0, int high0, IComparer comparer) //{ // int low = low0; // int high = high0; // // Be careful with overflows // int mid = low + ((high - low) / 2); // object keyPivot = keys.GetValueImpl(mid); // IComparable cmpPivot = keyPivot as IComparable; // while (true) // { // // Move the walls in // if (comparer != null) // { // while (low < high0 && comparer.Compare(keyPivot, keys.GetValueImpl(low)) > 0) // ++low; // while (high > low0 && comparer.Compare(keyPivot, keys.GetValueImpl(high)) < 0) // --high; // } // else // { // if (keyPivot == null) // { // // This has the effect of moving the null values to the front if comparer is null // while (high > low0 && keys.GetValueImpl(high) != null) // --high; // while (low < high0 && keys.GetValueImpl(low) == null) // ++low; // } // else // { // while (low < high0 && cmpPivot.CompareTo(keys.GetValueImpl(low)) > 0) // ++low; // while (high > low0 && cmpPivot.CompareTo(keys.GetValueImpl(high)) < 0) // --high; // } // } // if (low <= high) // { // swap(keys, items, low, high); // ++low; // --high; // } // else // break; // } // if (low0 < high) // qsort(keys, items, low0, high, comparer); // if (low < high0) // qsort(keys, items, low, high0, comparer); //} //private static void CheckComparerAvailable(Array keys, int low, int high) //{ // // move null keys to beginning of array, // // ensure that non-null keys implement IComparable // for (int i = 0; i < high; i++) // { // object obj = keys.GetValueImpl(i); // if (obj == null) // continue; // if (!(obj is IComparable)) // { // string msg = "No IComparable interface found for type '" + obj.GetType().ToString() + "'."; // throw new System.InvalidOperationException(msg); // } // } //} //private static void swap(Array keys, Array items, int i, int j) //{ // object tmp = keys.GetValueImpl(i); // keys.SetValueImpl(keys.GetValueImpl(j), i); // keys.SetValueImpl(tmp, j); // if (items != null) // { // tmp = items.GetValueImpl(i); // items.SetValueImpl(items.GetValueImpl(j), i); // items.SetValueImpl(tmp, j); // } //} public static void Reverse(System.Array array) { //if (array == null) // throw new System.ArgumentNullException("array"); //Reverse(array, array.GetLowerBound(0), array.GetLength(0)); } public static void Reverse(System.Array array, int index, int length) { //if (array == null) // throw new System.ArgumentNullException("array"); //if (array.Rank > 1) // throw new System.RankException("Only single dimension arrays are supported."); //if (index < array.GetLowerBound(0) || length < 0) // throw new System.ArgumentOutOfRangeException(); //// re-ordered to avoid possible integer overflow //if (index > array.GetUpperBound(0) + 1 - length) // throw new System.ArgumentException(); //int end = index + length - 1; //object[] oarray = Imports.convertToArray(array) as object[]; //if (oarray != null) //{ // while (index < end) // { // object tmp = oarray[index]; // oarray[index] = oarray[end]; // oarray[end] = tmp; // ++index; // --end; // } // return; //} //int[] iarray = Imports.convertToArray(array) as int[]; //if (iarray != null) //{ // while (index < end) // { // int tmp = iarray[index]; // iarray[index] = iarray[end]; // iarray[end] = tmp; // ++index; // --end; // } // return; //} //// fallback //Swapper swapper = get_swapper(array); //while (index < end) //{ // swapper(index, end); // ++index; // --end; //} } //delegate void Swapper(int i, int j); //static Swapper get_swapper(Array array) //{ // if (Imports.convertToArray(array) is int[]) // return new Swapper(array.int_swapper); // if (Imports.convertToArray(array) is object[]) // { // return new Swapper(array.obj_swapper); // } // return new Swapper(array.slow_swapper); //} //void int_swapper(int i, int j) //{ // int[] array = Imports.convertToArray(this) as int[]; // int val = array[i]; // array[i] = array[j]; // array[j] = val; //} //void obj_swapper(int i, int j) //{ // object[] array = Imports.convertToArray(this) as object[]; // object val = array[i]; // array[i] = array[j]; // array[j] = val; //} //void slow_swapper(int i, int j) //{ // object val = GetValueImpl(i); // SetValueImpl(GetValue(j), i); // SetValueImpl(val, j); //} } }
#region License // Copyright 2014 MorseCode Software // 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 namespace MorseCode.RxMvvm.Observable.Property.Internal { using System; using System.Diagnostics.Contracts; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading.Tasks; using MorseCode.RxMvvm.Common; using MorseCode.RxMvvm.Common.DiscriminatedUnion; [Serializable] internal class CancellableAsyncCalculatedPropertyWithContext<TContext, TFirst, TSecond, T> : CalculatedPropertyBase<T>, ISerializable { #region Fields private readonly TContext context; private readonly IObservable<TFirst> firstProperty; private readonly IObservable<TSecond> secondProperty; private readonly TimeSpan throttleTime; private readonly Func<AsyncCalculationHelper, TContext, TFirst, TSecond, Task<T>> calculateValue; private readonly bool isLongRunningCalculation; private IDisposable scheduledTask; #endregion #region Constructors and Destructors internal CancellableAsyncCalculatedPropertyWithContext( TContext context, IObservable<TFirst> firstProperty, IObservable<TSecond> secondProperty, TimeSpan throttleTime, Func<AsyncCalculationHelper, TContext, TFirst, TSecond, Task<T>> calculateValue, bool isLongRunningCalculation) { Contract.Requires<ArgumentNullException>(firstProperty != null, "firstProperty"); Contract.Requires<ArgumentNullException>(secondProperty != null, "secondProperty"); Contract.Requires<ArgumentNullException>(calculateValue != null, "calculateValue"); Contract.Ensures(this.firstProperty != null); Contract.Ensures(this.secondProperty != null); Contract.Ensures(this.calculateValue != null); RxMvvmConfiguration.EnsureSerializableDelegateIfUsingSerialization(calculateValue); this.context = context; this.firstProperty = firstProperty; this.secondProperty = secondProperty; this.throttleTime = throttleTime; this.calculateValue = calculateValue; this.isLongRunningCalculation = isLongRunningCalculation; Func<AsyncCalculationHelper, TFirst, TSecond, Task<IDiscriminatedUnion<object, T, Exception>>> calculate = async (helper, first, second) => { IDiscriminatedUnion<object, T, Exception> discriminatedUnion; try { discriminatedUnion = DiscriminatedUnion.First<object, T, Exception>( await calculateValue(helper, context, first, second).ConfigureAwait(true)); } catch (Exception e) { discriminatedUnion = DiscriminatedUnion.Second<object, T, Exception>(e); } return discriminatedUnion; }; this.SetHelper( new CalculatedPropertyHelper( (resultSubject, isCalculatingSubject) => { CompositeDisposable d = new CompositeDisposable(); IScheduler scheduler = isLongRunningCalculation ? RxMvvmConfiguration.GetLongRunningCalculationScheduler() : RxMvvmConfiguration.GetCalculationScheduler(); IObservable<Tuple<TFirst, TSecond>> o = firstProperty.CombineLatest( secondProperty, Tuple.Create); o = throttleTime > TimeSpan.Zero ? o.Throttle(throttleTime, scheduler) : o.ObserveOn(scheduler); d.Add( o.Subscribe( v => { using (this.scheduledTask) { } isCalculatingSubject.OnNext(true); this.scheduledTask = scheduler.ScheduleAsync( async (s, t) => { try { await s.Yield(t).ConfigureAwait(true); IDiscriminatedUnion<object, T, Exception> result = await calculate( new AsyncCalculationHelper(s, t), v.Item1, v.Item2).ConfigureAwait(true); await s.Yield(t).ConfigureAwait(true); resultSubject.OnNext(result); } catch (OperationCanceledException) { } catch (Exception e) { resultSubject.OnNext( DiscriminatedUnion.Second<object, T, Exception>(e)); } isCalculatingSubject.OnNext(false); }); })); return d; })); } /// <summary> /// Initializes a new instance of the <see cref="CancellableAsyncCalculatedPropertyWithContext{TContext,TFirst,TSecond,T}"/> class from serialized data. /// </summary> /// <param name="info"> /// The serialization info. /// </param> /// <param name="context"> /// The serialization context. /// </param> [ContractVerification(false)] // ReSharper disable UnusedParameter.Local protected CancellableAsyncCalculatedPropertyWithContext(SerializationInfo info, StreamingContext context) // ReSharper restore UnusedParameter.Local : this( (TContext)(info.GetValue("c", typeof(TContext)) ?? default(TContext)), (IObservable<TFirst>)info.GetValue("p1", typeof(IObservable<TFirst>)), (IObservable<TSecond>)info.GetValue("p2", typeof(IObservable<TSecond>)), (TimeSpan)(info.GetValue("t", typeof(TimeSpan)) ?? default(TimeSpan)), (Func<AsyncCalculationHelper, TContext, TFirst, TSecond, Task<T>>) info.GetValue("f", typeof(Func<AsyncCalculationHelper, TContext, TFirst, TSecond, Task<T>>)), (bool)info.GetValue("l", typeof(bool))) { } #endregion #region Public Methods and Operators /// <summary> /// Gets the object data to serialize. /// </summary> /// <param name="info"> /// The serialization info. /// </param> /// <param name="streamingContext"> /// The serialization context. /// </param> [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public virtual void GetObjectData(SerializationInfo info, StreamingContext streamingContext) { info.AddValue("c", this.context); info.AddValue("p1", this.firstProperty); info.AddValue("p2", this.secondProperty); info.AddValue("t", this.throttleTime); info.AddValue("f", this.calculateValue); info.AddValue("l", this.isLongRunningCalculation); } #endregion #region Methods /// <summary> /// Disposes of the property. /// </summary> protected override void Dispose() { base.Dispose(); using (this.scheduledTask) { } } [ContractInvariantMethod] private void CodeContractsInvariants() { Contract.Invariant(this.firstProperty != null); Contract.Invariant(this.secondProperty != null); Contract.Invariant(this.calculateValue != null); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // ResourcesEtwProvider.cs // // // Managed event source for things that can version with MSCORLIB. // using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Text; using System.Runtime.CompilerServices; namespace System.Diagnostics.Tracing { // To use the framework provider // // \\clrmain\tools\Perfmonitor /nokernel /noclr /provider:8E9F5090-2D75-4d03-8A81-E5AFBF85DAF1 start // Run run your app // \\clrmain\tools\Perfmonitor stop // \\clrmain\tools\Perfmonitor print // // This will produce an XML file, where each event is pretty-printed with all its arguments nicely parsed. // [FriendAccessAllowed] [EventSource(Guid = "8E9F5090-2D75-4d03-8A81-E5AFBF85DAF1", Name = "System.Diagnostics.Eventing.FrameworkEventSource")] sealed internal class FrameworkEventSource : EventSource { // Defines the singleton instance for the Resources ETW provider public static readonly FrameworkEventSource Log = new FrameworkEventSource(); // Keyword definitions. These represent logical groups of events that can be turned on and off independently // Often each task has a keyword, but where tasks are determined by subsystem, keywords are determined by // usefulness to end users to filter. Generally users don't mind extra events if they are not high volume // so grouping low volume events together in a single keywords is OK (users can post-filter by task if desired) public static class Keywords { public const EventKeywords Loader = (EventKeywords)0x0001; // This is bit 0 public const EventKeywords ThreadPool = (EventKeywords)0x0002; public const EventKeywords NetClient = (EventKeywords)0x0004; // // This is a private event we do not want to expose to customers. It is to be used for profiling // uses of dynamic type loading by ProjectN applications running on the desktop CLR // public const EventKeywords DynamicTypeUsage = (EventKeywords)0x0008; public const EventKeywords ThreadTransfer = (EventKeywords)0x0010; } /// <summary>ETW tasks that have start/stop events.</summary> [FriendAccessAllowed] public static class Tasks // this name is important for EventSource { /// <summary>Begin / End - GetResponse.</summary> public const EventTask GetResponse = (EventTask)1; /// <summary>Begin / End - GetRequestStream</summary> public const EventTask GetRequestStream = (EventTask)2; /// <summary>Send / Receive - begin transfer/end transfer</summary> public const EventTask ThreadTransfer = (EventTask)3; } [FriendAccessAllowed] public static class Opcodes { public const EventOpcode ReceiveHandled = (EventOpcode)11; } // This predicate is used by consumers of this class to deteremine if the class has actually been initialized, // and therefore if the public statics are available for use. This is typically not a problem... if the static // class constructor fails, then attempts to access the statics (or even this property) will result in a // TypeInitializationException. However, that is not the case while the class loader is actually trying to construct // the TypeInitializationException instance to represent that failure, and some consumers of this class are on // that code path, specifically the resource manager. public static bool IsInitialized { get { return Log != null; } } // The FrameworkEventSource GUID is {8E9F5090-2D75-4d03-8A81-E5AFBF85DAF1} private FrameworkEventSource() : base(new Guid(0x8e9f5090, 0x2d75, 0x4d03, 0x8a, 0x81, 0xe5, 0xaf, 0xbf, 0x85, 0xda, 0xf1), "System.Diagnostics.Eventing.FrameworkEventSource") { } // WriteEvent overloads (to avoid the "params" EventSource.WriteEvent // optimized for common signatures (used by the ThreadTransferSend/Receive events) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, int arg2, string arg3, bool arg4) { if (IsEnabled()) { if (arg3 == null) arg3 = ""; fixed (char* string3Bytes = arg3) { EventSource.EventData* descrs = stackalloc EventSource.EventData[4]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)string3Bytes; descrs[2].Size = ((arg3.Length + 1) * 2); descrs[3].DataPointer = (IntPtr)(&arg4); descrs[3].Size = 4; WriteEventCore(eventId, 4, descrs); } } } // optimized for common signatures (used by the ThreadTransferSend/Receive events) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, int arg2, string arg3) { if (IsEnabled()) { if (arg3 == null) arg3 = ""; fixed (char* string3Bytes = arg3) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)string3Bytes; descrs[2].Size = ((arg3.Length + 1) * 2); WriteEventCore(eventId, 3, descrs); } } } // optimized for common signatures (used by the BeginGetResponse/BeginGetRequestStream events) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, string arg2, bool arg3, bool arg4) { if (IsEnabled()) { if (arg2 == null) arg2 = ""; fixed (char* string2Bytes = arg2) { EventSource.EventData* descrs = stackalloc EventSource.EventData[4]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)string2Bytes; descrs[1].Size = ((arg2.Length + 1) * 2); descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; descrs[3].DataPointer = (IntPtr)(&arg4); descrs[3].Size = 4; WriteEventCore(eventId, 4, descrs); } } } // optimized for common signatures (used by the EndGetRequestStream event) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, bool arg2, bool arg3) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; WriteEventCore(eventId, 3, descrs); } } // optimized for common signatures (used by the EndGetResponse event) [NonEvent, System.Security.SecuritySafeCritical] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")] private unsafe void WriteEvent(int eventId, long arg1, bool arg2, bool arg3, int arg4) { if (IsEnabled()) { EventSource.EventData* descrs = stackalloc EventSource.EventData[4]; descrs[0].DataPointer = (IntPtr)(&arg1); descrs[0].Size = 8; descrs[1].DataPointer = (IntPtr)(&arg2); descrs[1].Size = 4; descrs[2].DataPointer = (IntPtr)(&arg3); descrs[2].Size = 4; descrs[3].DataPointer = (IntPtr)(&arg4); descrs[3].Size = 4; WriteEventCore(eventId, 4, descrs); } } // ResourceManager Event Definitions [Event(1, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerLookupStarted(String baseName, String mainAssemblyName, String cultureName) { WriteEvent(1, baseName, mainAssemblyName, cultureName); } [Event(2, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerLookingForResourceSet(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(2, baseName, mainAssemblyName, cultureName); } [Event(3, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerFoundResourceSetInCache(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(3, baseName, mainAssemblyName, cultureName); } // After loading a satellite assembly, we already have the ResourceSet for this culture in // the cache. This can happen if you have an assembly load callback that called into this // instance of the ResourceManager. [Event(4, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerFoundResourceSetInCacheUnexpected(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(4, baseName, mainAssemblyName, cultureName); } // manifest resource stream lookup succeeded [Event(5, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerStreamFound(String baseName, String mainAssemblyName, String cultureName, String loadedAssemblyName, String resourceFileName) { if (IsEnabled()) WriteEvent(5, baseName, mainAssemblyName, cultureName, loadedAssemblyName, resourceFileName); } // manifest resource stream lookup failed [Event(6, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerStreamNotFound(String baseName, String mainAssemblyName, String cultureName, String loadedAssemblyName, String resourceFileName) { if (IsEnabled()) WriteEvent(6, baseName, mainAssemblyName, cultureName, loadedAssemblyName, resourceFileName); } [Event(7, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerGetSatelliteAssemblySucceeded(String baseName, String mainAssemblyName, String cultureName, String assemblyName) { if (IsEnabled()) WriteEvent(7, baseName, mainAssemblyName, cultureName, assemblyName); } [Event(8, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerGetSatelliteAssemblyFailed(String baseName, String mainAssemblyName, String cultureName, String assemblyName) { if (IsEnabled()) WriteEvent(8, baseName, mainAssemblyName, cultureName, assemblyName); } [Event(9, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(String baseName, String mainAssemblyName, String assemblyName, String resourceFileName) { if (IsEnabled()) WriteEvent(9, baseName, mainAssemblyName, assemblyName, resourceFileName); } [Event(10, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerCaseInsensitiveResourceStreamLookupFailed(String baseName, String mainAssemblyName, String assemblyName, String resourceFileName) { if (IsEnabled()) WriteEvent(10, baseName, mainAssemblyName, assemblyName, resourceFileName); } // Could not access the manifest resource the assembly [Event(11, Level = EventLevel.Error, Keywords = Keywords.Loader)] public void ResourceManagerManifestResourceAccessDenied(String baseName, String mainAssemblyName, String assemblyName, String canonicalName) { if (IsEnabled()) WriteEvent(11, baseName, mainAssemblyName, assemblyName, canonicalName); } // Neutral resources are sufficient for this culture. Skipping satellites [Event(12, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerNeutralResourcesSufficient(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(12, baseName, mainAssemblyName, cultureName); } [Event(13, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerNeutralResourceAttributeMissing(String mainAssemblyName) { if (IsEnabled()) WriteEvent(13, mainAssemblyName); } [Event(14, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerCreatingResourceSet(String baseName, String mainAssemblyName, String cultureName, String fileName) { if (IsEnabled()) WriteEvent(14, baseName, mainAssemblyName, cultureName, fileName); } [Event(15, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerNotCreatingResourceSet(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(15, baseName, mainAssemblyName, cultureName); } [Event(16, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerLookupFailed(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(16, baseName, mainAssemblyName, cultureName); } [Event(17, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerReleasingResources(String baseName, String mainAssemblyName) { if (IsEnabled()) WriteEvent(17, baseName, mainAssemblyName); } [Event(18, Level = EventLevel.Warning, Keywords = Keywords.Loader)] public void ResourceManagerNeutralResourcesNotFound(String baseName, String mainAssemblyName, String resName) { if (IsEnabled()) WriteEvent(18, baseName, mainAssemblyName, resName); } [Event(19, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerNeutralResourcesFound(String baseName, String mainAssemblyName, String resName) { if (IsEnabled()) WriteEvent(19, baseName, mainAssemblyName, resName); } [Event(20, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerAddingCultureFromConfigFile(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(20, baseName, mainAssemblyName, cultureName); } [Event(21, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerCultureNotFoundInConfigFile(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(21, baseName, mainAssemblyName, cultureName); } [Event(22, Level = EventLevel.Informational, Keywords = Keywords.Loader)] public void ResourceManagerCultureFoundInConfigFile(String baseName, String mainAssemblyName, String cultureName) { if (IsEnabled()) WriteEvent(22, baseName, mainAssemblyName, cultureName); } // ResourceManager Event Wrappers [NonEvent] public void ResourceManagerLookupStarted(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerLookupStarted(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerLookingForResourceSet(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerLookingForResourceSet(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerFoundResourceSetInCache(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerFoundResourceSetInCache(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerFoundResourceSetInCacheUnexpected(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerFoundResourceSetInCacheUnexpected(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerStreamFound(String baseName, Assembly mainAssembly, String cultureName, Assembly loadedAssembly, String resourceFileName) { if (IsEnabled()) ResourceManagerStreamFound(baseName, GetName(mainAssembly), cultureName, GetName(loadedAssembly), resourceFileName); } [NonEvent] public void ResourceManagerStreamNotFound(String baseName, Assembly mainAssembly, String cultureName, Assembly loadedAssembly, String resourceFileName) { if (IsEnabled()) ResourceManagerStreamNotFound(baseName, GetName(mainAssembly), cultureName, GetName(loadedAssembly), resourceFileName); } [NonEvent] public void ResourceManagerGetSatelliteAssemblySucceeded(String baseName, Assembly mainAssembly, String cultureName, String assemblyName) { if (IsEnabled()) ResourceManagerGetSatelliteAssemblySucceeded(baseName, GetName(mainAssembly), cultureName, assemblyName); } [NonEvent] public void ResourceManagerGetSatelliteAssemblyFailed(String baseName, Assembly mainAssembly, String cultureName, String assemblyName) { if (IsEnabled()) ResourceManagerGetSatelliteAssemblyFailed(baseName, GetName(mainAssembly), cultureName, assemblyName); } [NonEvent] public void ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(String baseName, Assembly mainAssembly, String assemblyName, String resourceFileName) { if (IsEnabled()) ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(baseName, GetName(mainAssembly), assemblyName, resourceFileName); } [NonEvent] public void ResourceManagerCaseInsensitiveResourceStreamLookupFailed(String baseName, Assembly mainAssembly, String assemblyName, String resourceFileName) { if (IsEnabled()) ResourceManagerCaseInsensitiveResourceStreamLookupFailed(baseName, GetName(mainAssembly), assemblyName, resourceFileName); } [NonEvent] public void ResourceManagerManifestResourceAccessDenied(String baseName, Assembly mainAssembly, String assemblyName, String canonicalName) { if (IsEnabled()) ResourceManagerManifestResourceAccessDenied(baseName, GetName(mainAssembly), assemblyName, canonicalName); } [NonEvent] public void ResourceManagerNeutralResourcesSufficient(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerNeutralResourcesSufficient(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerNeutralResourceAttributeMissing(Assembly mainAssembly) { if (IsEnabled()) ResourceManagerNeutralResourceAttributeMissing(GetName(mainAssembly)); } [NonEvent] public void ResourceManagerCreatingResourceSet(String baseName, Assembly mainAssembly, String cultureName, String fileName) { if (IsEnabled()) ResourceManagerCreatingResourceSet(baseName, GetName(mainAssembly), cultureName, fileName); } [NonEvent] public void ResourceManagerNotCreatingResourceSet(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerNotCreatingResourceSet(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerLookupFailed(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerLookupFailed(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerReleasingResources(String baseName, Assembly mainAssembly) { if (IsEnabled()) ResourceManagerReleasingResources(baseName, GetName(mainAssembly)); } [NonEvent] public void ResourceManagerNeutralResourcesNotFound(String baseName, Assembly mainAssembly, String resName) { if (IsEnabled()) ResourceManagerNeutralResourcesNotFound(baseName, GetName(mainAssembly), resName); } [NonEvent] public void ResourceManagerNeutralResourcesFound(String baseName, Assembly mainAssembly, String resName) { if (IsEnabled()) ResourceManagerNeutralResourcesFound(baseName, GetName(mainAssembly), resName); } [NonEvent] public void ResourceManagerAddingCultureFromConfigFile(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerAddingCultureFromConfigFile(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerCultureNotFoundInConfigFile(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerCultureNotFoundInConfigFile(baseName, GetName(mainAssembly), cultureName); } [NonEvent] public void ResourceManagerCultureFoundInConfigFile(String baseName, Assembly mainAssembly, String cultureName) { if (IsEnabled()) ResourceManagerCultureFoundInConfigFile(baseName, GetName(mainAssembly), cultureName); } private static string GetName(Assembly assembly) { if (assembly == null) return "<<NULL>>"; else return assembly.FullName; } [Event(30, Level = EventLevel.Verbose, Keywords = Keywords.ThreadPool|Keywords.ThreadTransfer)] public void ThreadPoolEnqueueWork(long workID) { WriteEvent(30, workID); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadPoolEnqueueWorkObject(object workID) { // convert the Object Id to a long ThreadPoolEnqueueWork((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref workID))); } [Event(31, Level = EventLevel.Verbose, Keywords = Keywords.ThreadPool|Keywords.ThreadTransfer)] public void ThreadPoolDequeueWork(long workID) { WriteEvent(31, workID); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadPoolDequeueWorkObject(object workID) { // convert the Object Id to a long ThreadPoolDequeueWork((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref workID))); } // In the desktop runtime they don't use Tasks for the point at which the response happens, which means that the // Activity ID created by start using implicit activity IDs does not match. Thus disable implicit activities (until we fix that) [Event(140, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable, Task = Tasks.GetResponse, Opcode = EventOpcode.Start, Version = 1)] private void GetResponseStart(long id, string uri, bool success, bool synchronous) { WriteEvent(140, id, uri, success, synchronous); } [Event(141, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable, Task = Tasks.GetResponse, Opcode = EventOpcode.Stop, Version = 1)] private void GetResponseStop(long id, bool success, bool synchronous, int statusCode) { WriteEvent(141, id, success, synchronous, statusCode); } // In the desktop runtime they don't use Tasks for the point at which the response happens, which means that the // Activity ID created by start using implicit activity IDs does not match. Thus disable implicit activities (until we fix that) [Event(142, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable, Task = Tasks.GetRequestStream, Opcode = EventOpcode.Start, Version = 1)] private void GetRequestStreamStart(long id, string uri, bool success, bool synchronous) { WriteEvent(142, id, uri, success, synchronous); } [Event(143, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable, Task = Tasks.GetRequestStream, Opcode = EventOpcode.Stop, Version = 1)] private void GetRequestStreamStop(long id, bool success, bool synchronous) { WriteEvent(143, id, success, synchronous); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void BeginGetResponse(object id, string uri, bool success, bool synchronous) { if (IsEnabled()) GetResponseStart(IdForObject(id), uri, success, synchronous); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void EndGetResponse(object id, bool success, bool synchronous, int statusCode) { if (IsEnabled()) GetResponseStop(IdForObject(id), success, synchronous, statusCode); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void BeginGetRequestStream(object id, string uri, bool success, bool synchronous) { if (IsEnabled()) GetRequestStreamStart(IdForObject(id), uri, success, synchronous); } [NonEvent, System.Security.SecuritySafeCritical] public unsafe void EndGetRequestStream(object id, bool success, bool synchronous) { if (IsEnabled()) GetRequestStreamStop(IdForObject(id), success, synchronous); } // id - represents a correlation ID that allows correlation of two activities, one stamped by // ThreadTransferSend, the other by ThreadTransferReceive // kind - identifies the transfer: values below 64 are reserved for the runtime. Currently used values: // 1 - managed Timers ("roaming" ID) // 2 - managed async IO operations (FileStream, PipeStream, a.o.) // 3 - WinRT dispatch operations // info - any additional information user code might consider interesting [Event(150, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = EventOpcode.Send)] public void ThreadTransferSend(long id, int kind, string info, bool multiDequeues) { if (IsEnabled()) WriteEvent(150, id, kind, info, multiDequeues); } // id - is a managed object. it gets translated to the object's address. ETW listeners must // keep track of GC movements in order to correlate the value passed to XyzSend with the // (possibly changed) value passed to XyzReceive [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadTransferSendObj(object id, int kind, string info, bool multiDequeues) { ThreadTransferSend((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info, multiDequeues); } // id - represents a correlation ID that allows correlation of two activities, one stamped by // ThreadTransferSend, the other by ThreadTransferReceive // kind - identifies the transfer: values below 64 are reserved for the runtime. Currently used values: // 1 - managed Timers ("roaming" ID) // 2 - managed async IO operations (FileStream, PipeStream, a.o.) // 3 - WinRT dispatch operations // info - any additional information user code might consider interesting [Event(151, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = EventOpcode.Receive)] public void ThreadTransferReceive(long id, int kind, string info) { if (IsEnabled()) WriteEvent(151, id, kind, info); } // id - is a managed object. it gets translated to the object's address. ETW listeners must // keep track of GC movements in order to correlate the value passed to XyzSend with the // (possibly changed) value passed to XyzReceive [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadTransferReceiveObj(object id, int kind, string info) { ThreadTransferReceive((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info); } // id - represents a correlation ID that allows correlation of two activities, one stamped by // ThreadTransferSend, the other by ThreadTransferReceive // kind - identifies the transfer: values below 64 are reserved for the runtime. Currently used values: // 1 - managed Timers ("roaming" ID) // 2 - managed async IO operations (FileStream, PipeStream, a.o.) // 3 - WinRT dispatch operations // info - any additional information user code might consider interesting [Event(152, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = Opcodes.ReceiveHandled)] public void ThreadTransferReceiveHandled(long id, int kind, string info) { if (IsEnabled()) WriteEvent(152, id, kind, info); } // id - is a managed object. it gets translated to the object's address. ETW listeners must // keep track of GC movements in order to correlate the value passed to XyzSend with the // (possibly changed) value passed to XyzReceive [NonEvent, System.Security.SecuritySafeCritical] public unsafe void ThreadTransferReceiveHandledObj(object id, int kind, string info) { ThreadTransferReceive((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info); } // return a stable ID for a an object. We use the hash code which is not truely unique but is // close enough for now at least. we add to it 0x7FFFFFFF00000000 to make it distinguishable // from the style of ID that simply casts the object reference to a long (since old versions of the // runtime will emit IDs of that form). private static long IdForObject(object obj) { return obj.GetHashCode() + 0x7FFFFFFF00000000; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; namespace OpenSim.Region.Framework.Scenes { public class EntityManager : IEnumerable<EntityBase> { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly Dictionary<UUID, EntityBase> m_eb_uuid = new Dictionary<UUID, EntityBase>(); private readonly Dictionary<uint, EntityBase> m_eb_localID = new Dictionary<uint, EntityBase>(); //private readonly Dictionary<UUID, ScenePresence> m_pres_uuid = new Dictionary<UUID, ScenePresence>(); private readonly Object m_lock = new Object(); [Obsolete("Use Add() instead.")] public void Add(UUID id, EntityBase eb) { Add(eb); } private void PrepUpdate(EntityBase entity) { try { // This can be simplified a lot for normal production use but the extra debugging here is // to help identify if, and which, error cases may be occurring in practice. EntityBase oldEntity = null; if (m_eb_uuid.ContainsKey(entity.UUID)) { oldEntity = m_eb_uuid[entity.UUID]; if (Object.ReferenceEquals(entity, oldEntity)) m_log.WarnFormat("Add Entity: redundant add for UUID {0} {1}", entity.UUID.ToString(), entity.LocalId.ToString()); else // Not the same, even if it has the same values. if (m_eb_localID.ContainsKey(entity.LocalId)) m_log.ErrorFormat("Add Entity: duplicate add for UUID {0} {1}", entity.UUID.ToString(), entity.LocalId.ToString()); else m_log.ErrorFormat("Add Entity: update for UUID {0} to {1} from {2}", entity.UUID.ToString(), entity.LocalId.ToString(), oldEntity.LocalId.ToString()); } else if (m_eb_uuid.ContainsKey(entity.UUID)) { oldEntity = m_eb_localID[entity.LocalId]; if (Object.ReferenceEquals(entity, oldEntity)) m_log.WarnFormat("Add Entity: redundant add for LocalId {0} {1}", entity.LocalId.ToString(), entity.UUID.ToString()); else // Not the same, even if it has the same values. if (m_eb_uuid.ContainsKey(entity.UUID)) m_log.ErrorFormat("Add Entity: duplicate add for LocalId {0} {1}", entity.LocalId.ToString(), entity.UUID.ToString()); else m_log.ErrorFormat("Add Entity: update for LocalId {0} to {1} from {2}", entity.LocalId.ToString(), entity.UUID.ToString(), oldEntity.UUID.ToString()); } if (oldEntity != null) { // We have at least a partial conflict, remove any old entries. if (m_eb_localID.ContainsKey(oldEntity.LocalId)) m_eb_localID.Remove(oldEntity.LocalId); if (m_eb_uuid.ContainsKey(oldEntity.UUID)) m_eb_uuid.Remove(oldEntity.UUID); } } catch (Exception e) { m_log.ErrorFormat("Add Entity failed: {0}", e.Message); } } public void Add(EntityBase entity) { lock (m_lock) { try { PrepUpdate(entity); m_eb_uuid.Add(entity.UUID, entity); m_eb_localID.Add(entity.LocalId, entity); } catch (Exception e) { m_log.ErrorFormat("Add Entity failed: {0}", e.Message); } } } public void Clear() { lock (m_lock) { m_eb_uuid.Clear(); m_eb_localID.Clear(); } } public int Count { get { lock (m_lock) { return m_eb_uuid.Count; } } } public bool ContainsKey(UUID id) { lock (m_lock) { try { return m_eb_uuid.ContainsKey(id); } catch { return false; } } } public bool ContainsKey(uint localID) { lock (m_lock) { try { return m_eb_localID.ContainsKey(localID); } catch { return false; } } } public bool Remove(uint localID) { lock (m_lock) { try { bool a = m_eb_uuid.Remove(m_eb_localID[localID].UUID); if (!a) { m_log.ErrorFormat("[EntityManager]: Remove(localID) m_eb_uuid: Remove Entity failed for {0}", localID); } bool b = m_eb_localID.Remove(localID); if (!b) { m_log.ErrorFormat("[EntityManager]: Remove(localID) m_eb_localID: Remove Entity failed for {0}", localID); } return a && b; } catch (Exception) { m_log.ErrorFormat("Remove Entity failed for {0}", localID); return false; } } } public bool Remove(UUID id) { lock (m_lock) { try { bool a = m_eb_localID.Remove(m_eb_uuid[id].LocalId); if (!a) { m_log.ErrorFormat("[EntityManager]: Remove(UUID) m_eb_localID: Remove Entity failed for {0}", id); } bool b = m_eb_uuid.Remove(id); if (!b) { m_log.ErrorFormat("[EntityManager]: Remove(UUID) m_eb_uuid: Remove Entity failed for {0}", id); } return a && b; } catch (Exception) { m_log.ErrorFormat("Remove Entity failed for {0}", id); return false; } } } public List<EntityBase> GetAllByType<T>() { List<EntityBase> tmp = new List<EntityBase>(); lock (m_lock) { try { foreach (KeyValuePair<UUID, EntityBase> pair in m_eb_uuid) { if (pair.Value is T) { tmp.Add(pair.Value); } } } catch (Exception e) { m_log.ErrorFormat("GetAllByType failed for {0}", e); tmp = null; } } return tmp; } public List<EntityBase> GetEntities() { lock (m_lock) { return new List<EntityBase>(m_eb_uuid.Values); } } public EntityBase this[UUID id] { get { lock (m_lock) { try { return m_eb_uuid[id]; } catch { return null; } } } set { Add(value); } } public EntityBase this[uint localID] { get { lock (m_lock) { try { return m_eb_localID[localID]; } catch { return null; } } } set { Add(value); } } public bool TryGetValue(UUID key, out EntityBase obj) { lock (m_lock) { return m_eb_uuid.TryGetValue(key, out obj); } } public bool TryGetValue(uint key, out EntityBase obj) { lock (m_lock) { return m_eb_localID.TryGetValue(key, out obj); } } /// <summary> /// This could be optimised to work on the list 'live' rather than making a safe copy and iterating that. /// </summary> /// <returns></returns> public IEnumerator<EntityBase> GetEnumerator() { return GetEntities().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } internal void SwapChildToRootAgent(UUID userId, uint oldLocalId, uint newLocalId) { lock (m_lock) { try { EntityBase e; if (!m_eb_uuid.TryGetValue(userId, out e)) { m_log.ErrorFormat("[EntityManager]: SwapChildToRootAgent(UUID) could not find agent with ID {0} to swap", userId); return; } bool a = m_eb_localID.Remove(oldLocalId); if (!a) { m_log.ErrorFormat("[EntityManager]: SwapChildToRootAgent(UUID) could not find agent with local ID {0} to swap", oldLocalId); return; } m_eb_localID.Add(newLocalId, e); return; } catch (Exception) { m_log.ErrorFormat("[EntityManager]: SwapChildToRootAgent Entity failed for {0}", userId); return; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace EventFeedback.Web.Api.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using VkNet.Enums.Filters; using VkNet.Enums.SafetyEnums; using VkNet.Model; using VkNet.Model.RequestParams; using VkNet.Utils; namespace VkNet.Categories { /// <inheritdoc /> public partial class GroupsCategory { /// <inheritdoc /> public Task<bool> JoinAsync(long? groupId, bool? notSure = null) { return TypeHelper.TryInvokeMethodAsync(func: () =>Join(groupId: groupId, notSure: notSure)); } /// <inheritdoc /> public Task<bool> LeaveAsync(long groupId) { return TypeHelper.TryInvokeMethodAsync(func: () =>Leave(groupId: groupId)); } /// <inheritdoc /> public Task<VkCollection<Group>> GetAsync(GroupsGetParams @params, bool skipAuthorization = false) { return TypeHelper.TryInvokeMethodAsync(func: () => Get(@params: @params, skipAuthorization: skipAuthorization)); } /// <inheritdoc /> public Task<ReadOnlyCollection<Group>> GetByIdAsync(IEnumerable<string> groupIds , string groupId , GroupsFields fields , bool skipAuthorization = false) { return TypeHelper.TryInvokeMethodAsync(func: () => GetById(groupIds: groupIds, groupId: groupId, fields: fields, skipAuthorization: skipAuthorization)); } /// <inheritdoc /> public Task<VkCollection<User>> GetMembersAsync(GroupsGetMembersParams @params, bool skipAuthorization = false) { return TypeHelper.TryInvokeMethodAsync(func: () => GetMembers(@params: @params, skipAuthorization: skipAuthorization)); } /// <inheritdoc /> public Task<ReadOnlyCollection<GroupMember>> IsMemberAsync(string groupId , long? userId , IEnumerable<long> userIds , bool? extended , bool skipAuthorization = false) { return TypeHelper.TryInvokeMethodAsync(func: () => IsMember(groupId: groupId , userId: userId , userIds: userIds , extended: extended , skipAuthorization: skipAuthorization)); } /// <inheritdoc /> public Task<VkCollection<Group>> SearchAsync(GroupsSearchParams @params, bool skipAuthorization = false) { return TypeHelper.TryInvokeMethodAsync(func: () => Search(@params: @params, skipAuthorization: skipAuthorization)); } /// <inheritdoc /> public Task<VkCollection<Group>> GetInvitesAsync(long? count, long? offset, bool? extended = null) { return TypeHelper.TryInvokeMethodAsync(func: () => GetInvites(count: count, offset: offset, extended: extended)); } /// <inheritdoc /> public Task<bool> BanUserAsync(GroupsBanUserParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () =>BanUser(@params: @params)); } /// <inheritdoc /> public Task<VkCollection<GetBannedResult>> GetBannedAsync(long groupId , long? offset = null , long? count = null , GroupsFields fields = null , long? ownerId = null) { return TypeHelper.TryInvokeMethodAsync(func: () => GetBanned(groupId: groupId, offset: offset, count: count, fields: fields, ownerId: ownerId)); } /// <inheritdoc /> public Task<bool> UnbanUserAsync(long groupId, long userId) { return TypeHelper.TryInvokeMethodAsync(func: () =>UnbanUser(groupId: groupId, userId: userId)); } /// <inheritdoc /> public Task<bool> EditManagerAsync(GroupsEditManagerParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () =>EditManager(@params: @params)); } /// <inheritdoc /> public Task<GroupsEditParams> GetSettingsAsync(ulong groupId) { return TypeHelper.TryInvokeMethodAsync(func: () =>GetSettings(groupId: groupId)); } /// <inheritdoc /> public Task<bool> EditAsync(GroupsEditParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () =>Edit(@params: @params)); } /// <inheritdoc /> public Task<bool> EditPlaceAsync(long groupId, Place place = null) { return TypeHelper.TryInvokeMethodAsync(func: () =>EditPlace(groupId: groupId, place: place)); } /// <inheritdoc /> public Task<VkCollection<User>> GetInvitedUsersAsync(long groupId , long? offset = null , long? count = null , UsersFields fields = null , NameCase nameCase = null) { return TypeHelper.TryInvokeMethodAsync(func: () => GetInvitedUsers(groupId: groupId, offset: offset, count: count, fields: fields, nameCase: nameCase)); } /// <inheritdoc /> public Task<bool> InviteAsync(long groupId, long userId, long? captchaSid, string captchaKey) { return TypeHelper.TryInvokeMethodAsync(func: () => Invite(groupId: groupId, userId: userId, captchaSid: captchaSid, captchaKey: captchaKey)); } /// <inheritdoc /> public Task<ExternalLink> AddLinkAsync(long groupId, Uri link, string text) { return TypeHelper.TryInvokeMethodAsync(func: () =>AddLink(groupId: groupId, link: link, text: text)); } /// <inheritdoc /> public Task<bool> DeleteLinkAsync(long groupId, ulong linkId) { return TypeHelper.TryInvokeMethodAsync(func: () =>DeleteLink(groupId: groupId, linkId: linkId)); } /// <inheritdoc /> public Task<bool> EditLinkAsync(long groupId, ulong linkId, string text) { return TypeHelper.TryInvokeMethodAsync(func: () =>EditLink(groupId: groupId, linkId: linkId, text: text)); } /// <inheritdoc /> public Task<bool> ReorderLinkAsync(long groupId, long linkId, long? after) { return TypeHelper.TryInvokeMethodAsync(func: () => ReorderLink(groupId: groupId, linkId: linkId, after: after)); } /// <inheritdoc /> public Task<bool> RemoveUserAsync(long groupId, long userId) { return TypeHelper.TryInvokeMethodAsync(func: () =>RemoveUser(groupId: groupId, userId: userId)); } /// <inheritdoc /> public Task<bool> ApproveRequestAsync(long groupId, long userId) { return TypeHelper.TryInvokeMethodAsync(func: () =>ApproveRequest(groupId: groupId, userId: userId)); } /// <inheritdoc /> public Task<Group> CreateAsync(string title , string description , GroupType type , GroupSubType? subtype , uint? publicCategory = null) { return TypeHelper.TryInvokeMethodAsync(func: () => Create(title: title , description: description , type: type , subtype: subtype , publicCategory: publicCategory)); } /// <inheritdoc /> public Task<VkCollection<User>> GetRequestsAsync(long groupId, long? offset, long? count, UsersFields fields) { return TypeHelper.TryInvokeMethodAsync(func: () => GetRequests(groupId: groupId, offset: offset, count: count, fields: fields)); } /// <inheritdoc /> public Task<VkCollection<Group>> GetCatalogAsync(ulong? categoryId = null, ulong? subcategoryId = null) { return TypeHelper.TryInvokeMethodAsync(func: () => GetCatalog(categoryId: categoryId, subcategoryId: subcategoryId)); } /// <inheritdoc /> public Task<GroupsCatalogInfo> GetCatalogInfoAsync(bool? extended = null, bool? subcategories = null) { return TypeHelper.TryInvokeMethodAsync(func: () => GetCatalogInfo(extended: extended, subcategories: subcategories)); } /// <inheritdoc /> public Task<long> AddCallbackServerAsync(ulong groupId, string url, string title, string secretKey = null) { return TypeHelper.TryInvokeMethodAsync(func: () => AddCallbackServer(groupId: groupId, url: url, title: title, secretKey: secretKey)); } /// <inheritdoc /> public Task<bool> DeleteCallbackServerAsync(ulong groupId, ulong serverId) { return TypeHelper.TryInvokeMethodAsync(func: () =>DeleteCallbackServer(groupId: groupId, serverId: serverId)); } /// <inheritdoc /> public Task<bool> EditCallbackServerAsync(ulong groupId, ulong serverId, string url, string title, string secretKey) { return TypeHelper.TryInvokeMethodAsync(func: () => EditCallbackServer(groupId: groupId, serverId: serverId, url: url, title: title, secretKey: secretKey)); } /// <inheritdoc /> public Task<string> GetCallbackConfirmationCodeAsync(ulong groupId) { return TypeHelper.TryInvokeMethodAsync(func: () =>GetCallbackConfirmationCode(groupId: groupId)); } /// <inheritdoc /> public Task<VkCollection<CallbackServerItem>> GetCallbackServersAsync(ulong groupId, IEnumerable<ulong> serverIds = null) { return TypeHelper.TryInvokeMethodAsync(func: () =>GetCallbackServers(groupId: groupId, serverIds: serverIds)); } /// <inheritdoc /> public Task<CallbackSettings> GetCallbackSettingsAsync(ulong groupId, ulong serverId) { return TypeHelper.TryInvokeMethodAsync(func: () =>GetCallbackSettings(groupId: groupId, serverId: serverId)); } /// <inheritdoc /> public Task<bool> SetCallbackSettingsAsync(CallbackServerParams @params) { return TypeHelper.TryInvokeMethodAsync(func: () =>SetCallbackSettings(@params: @params)); } /// <inheritdoc /> public Task<LongPollServerResponse> GetLongPollServerAsync(ulong groupId) { return TypeHelper.TryInvokeMethodAsync(func: () =>GetLongPollServer(groupId: groupId)); } } }
// 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. namespace System.ServiceModel.Channels { using Microsoft.Xml; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Security; using Microsoft.Xml.Schema; using System.Collections.ObjectModel; using System.Collections.Generic; using WsdlNS = System.Web.Services.Description; // implemented by Indigo Transports internal interface ITransportPolicyImport { void ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext); } public class TransportBindingElementImporter : IWsdlImportExtension, IPolicyImportExtension { void IWsdlImportExtension.BeforeImport(WsdlNS.ServiceDescriptionCollection wsdlDocuments, XmlSchemaSet xmlSchemas, ICollection<XmlElement> policy) { WsdlImporter.SoapInPolicyWorkaroundHelper.InsertAdHocTransportPolicy(wsdlDocuments); } void IWsdlImportExtension.ImportContract(WsdlImporter importer, WsdlContractConversionContext context) { } void IWsdlImportExtension.ImportEndpoint(WsdlImporter importer, WsdlEndpointConversionContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } #pragma warning disable 56506 // elliotw, these properties cannot be null in this context if (context.Endpoint.Binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context.Endpoint.Binding"); } #pragma warning disable 56506 // brianmcn, CustomBinding.Elements never be null TransportBindingElement transportBindingElement = GetBindingElements(context).Find<TransportBindingElement>(); bool transportHandledExternaly = (transportBindingElement != null) && !StateHelper.IsRegisteredTransportBindingElement(importer, context); if (transportHandledExternaly) return; #pragma warning disable 56506 // elliotw, these properties cannot be null in this context WsdlNS.SoapBinding soapBinding = (WsdlNS.SoapBinding)context.WsdlBinding.Extensions.Find(typeof(WsdlNS.SoapBinding)); if (soapBinding != null && transportBindingElement == null) { CreateLegacyTransportBindingElement(importer, soapBinding, context); } // Try to import WS-Addressing address from the port if (context.WsdlPort != null) { ImportAddress(context, transportBindingElement); } } private static BindingElementCollection GetBindingElements(WsdlEndpointConversionContext context) { Binding binding = context.Endpoint.Binding; BindingElementCollection elements = binding is CustomBinding ? ((CustomBinding)binding).Elements : binding.CreateBindingElements(); return elements; } private static CustomBinding ConvertToCustomBinding(WsdlEndpointConversionContext context) { CustomBinding customBinding = context.Endpoint.Binding as CustomBinding; if (customBinding == null) { customBinding = new CustomBinding(context.Endpoint.Binding); context.Endpoint.Binding = customBinding; } return customBinding; } private static void ImportAddress(WsdlEndpointConversionContext context, TransportBindingElement transportBindingElement) { EndpointAddress address = context.Endpoint.Address = WsdlImporter.WSAddressingHelper.ImportAddress(context.WsdlPort); if (address != null) { context.Endpoint.Address = address; // Replace the http BE with https BE only if the uri scheme is https and the transport binding element is a HttpTransportBindingElement but not HttpsTransportBindingElement if (address.Uri.Scheme == /*TODO: Uri.UriSchemeHttps*/ "https" && transportBindingElement is HttpTransportBindingElement && !(transportBindingElement is HttpsTransportBindingElement)) { BindingElementCollection elements = ConvertToCustomBinding(context).Elements; elements.Remove(transportBindingElement); elements.Add(CreateHttpsFromHttp(transportBindingElement as HttpTransportBindingElement)); } } } private static void CreateLegacyTransportBindingElement(WsdlImporter importer, WsdlNS.SoapBinding soapBinding, WsdlEndpointConversionContext context) { // We create a transportBindingElement based on the SoapBinding's Transport TransportBindingElement transportBindingElement = CreateTransportBindingElements(soapBinding.Transport, null); if (transportBindingElement != null) { ConvertToCustomBinding(context).Elements.Add(transportBindingElement); StateHelper.RegisterTransportBindingElement(importer, context); } } private static HttpsTransportBindingElement CreateHttpsFromHttp(HttpTransportBindingElement http) { if (http == null) return new HttpsTransportBindingElement(); HttpsTransportBindingElement https = HttpsTransportBindingElement.CreateFromHttpBindingElement(http); return https; } void IPolicyImportExtension.ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext) { XmlQualifiedName wsdlBindingQName; string transportUri = WsdlImporter.SoapInPolicyWorkaroundHelper.FindAdHocTransportPolicy(policyContext, out wsdlBindingQName); if (transportUri != null && !policyContext.BindingElements.Contains(typeof(TransportBindingElement))) { TransportBindingElement transportBindingElement = CreateTransportBindingElements(transportUri, policyContext); if (transportBindingElement != null) { ITransportPolicyImport transportPolicyImport = transportBindingElement as ITransportPolicyImport; if (transportPolicyImport != null) transportPolicyImport.ImportPolicy(importer, policyContext); policyContext.BindingElements.Add(transportBindingElement); StateHelper.RegisterTransportBindingElement(importer, wsdlBindingQName); } } } private static TransportBindingElement CreateTransportBindingElements(string transportUri, PolicyConversionContext policyContext) { TransportBindingElement transportBindingElement = null; // Try and Create TransportBindingElement switch (transportUri) { case TransportPolicyConstants.HttpTransportUri: transportBindingElement = GetHttpTransportBindingElement(policyContext); break; case TransportPolicyConstants.TcpTransportUri: transportBindingElement = new TcpTransportBindingElement(); break; case TransportPolicyConstants.NamedPipeTransportUri: // Not supported on .NET Core yet. // transportBindingElement = new NamedPipeTransportBindingElement(); // break; case TransportPolicyConstants.PeerTransportUri: throw new NotImplementedException(); case TransportPolicyConstants.WebSocketTransportUri: HttpTransportBindingElement httpTransport = GetHttpTransportBindingElement(policyContext); httpTransport.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always; httpTransport.WebSocketSettings.SubProtocol = WebSocketTransportSettings.SoapSubProtocol; transportBindingElement = httpTransport; break; default: // There may be another registered converter that can handle this transport. break; } return transportBindingElement; } private static HttpTransportBindingElement GetHttpTransportBindingElement(PolicyConversionContext policyContext) { if (policyContext != null) { WSSecurityPolicy sp = null; PolicyAssertionCollection policyCollection = policyContext.GetBindingAssertions(); if (WSSecurityPolicy.TryGetSecurityPolicyDriver(policyCollection, out sp) && sp.ContainsWsspHttpsTokenAssertion(policyCollection)) { HttpsTransportBindingElement httpsBinding = new HttpsTransportBindingElement(); httpsBinding.MessageSecurityVersion = sp.GetSupportedMessageSecurityVersion(SecurityVersion.WSSecurity11); return httpsBinding; } } return new HttpTransportBindingElement(); } } internal static class StateHelper { private readonly static object s_stateBagKey = new object(); private static Dictionary<XmlQualifiedName, XmlQualifiedName> GetGeneratedTransportBindingElements(MetadataImporter importer) { object retValue; if (!importer.State.TryGetValue(StateHelper.s_stateBagKey, out retValue)) { retValue = new Dictionary<XmlQualifiedName, XmlQualifiedName>(); importer.State.Add(StateHelper.s_stateBagKey, retValue); } return (Dictionary<XmlQualifiedName, XmlQualifiedName>)retValue; } internal static void RegisterTransportBindingElement(MetadataImporter importer, XmlQualifiedName wsdlBindingQName) { GetGeneratedTransportBindingElements(importer)[wsdlBindingQName] = wsdlBindingQName; } internal static void RegisterTransportBindingElement(MetadataImporter importer, WsdlEndpointConversionContext context) { XmlQualifiedName wsdlBindingQName = new XmlQualifiedName(context.WsdlBinding.Name, context.WsdlBinding.ServiceDescription.TargetNamespace); GetGeneratedTransportBindingElements(importer)[wsdlBindingQName] = wsdlBindingQName; } internal static bool IsRegisteredTransportBindingElement(WsdlImporter importer, WsdlEndpointConversionContext context) { XmlQualifiedName key = new XmlQualifiedName(context.WsdlBinding.Name, context.WsdlBinding.ServiceDescription.TargetNamespace); return GetGeneratedTransportBindingElements(importer).ContainsKey(key); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Addresses /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class UM : EduHubEntity { #region Navigation Property Cache private KGT Cache_COUNTRY_KGT; #endregion #region Foreign Navigation Properties private IReadOnlyList<DF> Cache_UMKEY_DF_HOMEKEY; private IReadOnlyList<DF> Cache_UMKEY_DF_MAILKEY; private IReadOnlyList<DF> Cache_UMKEY_DF_BILLINGKEY; private IReadOnlyList<PE> Cache_UMKEY_PE_HOMEKEY; private IReadOnlyList<PE> Cache_UMKEY_PE_MAILKEY; private IReadOnlyList<PE> Cache_UMKEY_PE_LEAVEKEY; private IReadOnlyList<SAM> Cache_UMKEY_SAM_ADDRESSKEY; private IReadOnlyList<SAM> Cache_UMKEY_SAM_MAILKEY; private IReadOnlyList<SF> Cache_UMKEY_SF_HOMEKEY; private IReadOnlyList<SF> Cache_UMKEY_SF_MAILKEY; private IReadOnlyList<STTRIPS> Cache_UMKEY_STTRIPS_AM_PICKUP_ADDRESS_ID; private IReadOnlyList<STTRIPS> Cache_UMKEY_STTRIPS_PM_SETDOWN_ADDRESS_ID; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Address ID /// </summary> public int UMKEY { get; internal set; } /// <summary> /// Three address lines (third line used for overseas addresses) /// [Alphanumeric (30)] /// </summary> public string ADDRESS01 { get; internal set; } /// <summary> /// Three address lines (third line used for overseas addresses) /// [Alphanumeric (30)] /// </summary> public string ADDRESS02 { get; internal set; } /// <summary> /// Three address lines (third line used for overseas addresses) /// [Alphanumeric (30)] /// </summary> public string ADDRESS03 { get; internal set; } /// <summary> /// State code (if Australian address) /// [Uppercase Alphanumeric (3)] /// </summary> public string STATE { get; internal set; } /// <summary> /// Postcode (if Australian address) /// [Alphanumeric (4)] /// </summary> public string POSTCODE { get; internal set; } /// <summary> /// Phone no /// [Uppercase Alphanumeric (20)] /// </summary> public string TELEPHONE { get; internal set; } /// <summary> /// Home Mobile no /// [Uppercase Alphanumeric (20)] /// </summary> public string MOBILE { get; internal set; } /// <summary> /// This phone no is silent? (Y/N) /// [Uppercase Alphanumeric (1)] /// </summary> public string SILENT { get; internal set; } /// <summary> /// Fax no /// [Uppercase Alphanumeric (20)] /// </summary> public string FAX { get; internal set; } /// <summary> /// Link to KAP to allow for access to postcodes when entering an address: NOTE this should NOT be a foreign key to KAP as the user is free to enter different data in ADDRESS03 and POSTCODE /// [Alphanumeric (34)] /// </summary> public string KAP_LINK { get; internal set; } /// <summary> /// Country (default '1101' code for Australia) /// [Uppercase Alphanumeric (6)] /// </summary> public string COUNTRY { get; internal set; } /// <summary> /// Australia Post address identifier /// </summary> public int? DPID { get; internal set; } /// <summary> /// Australia Post barcode numbers /// [Alphanumeric (37)] /// </summary> public string BARCODE { get; internal set; } /// <summary> /// Latitude of address for Geospatial referencing /// </summary> public double? LATITUDE { get; internal set; } /// <summary> /// Longitude of address for Geospatial referencing /// </summary> public double? LONGITUDE { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last write operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// KGT (Countries) related entity by [UM.COUNTRY]-&gt;[KGT.COUNTRY] /// Country (default '1101' code for Australia) /// </summary> public KGT COUNTRY_KGT { get { if (COUNTRY == null) { return null; } if (Cache_COUNTRY_KGT == null) { Cache_COUNTRY_KGT = Context.KGT.FindByCOUNTRY(COUNTRY); } return Cache_COUNTRY_KGT; } } #endregion #region Foreign Navigation Properties /// <summary> /// DF (Families) related entities by [UM.UMKEY]-&gt;[DF.HOMEKEY] /// Address ID /// </summary> public IReadOnlyList<DF> UMKEY_DF_HOMEKEY { get { if (Cache_UMKEY_DF_HOMEKEY == null && !Context.DF.TryFindByHOMEKEY(UMKEY, out Cache_UMKEY_DF_HOMEKEY)) { Cache_UMKEY_DF_HOMEKEY = new List<DF>().AsReadOnly(); } return Cache_UMKEY_DF_HOMEKEY; } } /// <summary> /// DF (Families) related entities by [UM.UMKEY]-&gt;[DF.MAILKEY] /// Address ID /// </summary> public IReadOnlyList<DF> UMKEY_DF_MAILKEY { get { if (Cache_UMKEY_DF_MAILKEY == null && !Context.DF.TryFindByMAILKEY(UMKEY, out Cache_UMKEY_DF_MAILKEY)) { Cache_UMKEY_DF_MAILKEY = new List<DF>().AsReadOnly(); } return Cache_UMKEY_DF_MAILKEY; } } /// <summary> /// DF (Families) related entities by [UM.UMKEY]-&gt;[DF.BILLINGKEY] /// Address ID /// </summary> public IReadOnlyList<DF> UMKEY_DF_BILLINGKEY { get { if (Cache_UMKEY_DF_BILLINGKEY == null && !Context.DF.TryFindByBILLINGKEY(UMKEY, out Cache_UMKEY_DF_BILLINGKEY)) { Cache_UMKEY_DF_BILLINGKEY = new List<DF>().AsReadOnly(); } return Cache_UMKEY_DF_BILLINGKEY; } } /// <summary> /// PE (Employees) related entities by [UM.UMKEY]-&gt;[PE.HOMEKEY] /// Address ID /// </summary> public IReadOnlyList<PE> UMKEY_PE_HOMEKEY { get { if (Cache_UMKEY_PE_HOMEKEY == null && !Context.PE.TryFindByHOMEKEY(UMKEY, out Cache_UMKEY_PE_HOMEKEY)) { Cache_UMKEY_PE_HOMEKEY = new List<PE>().AsReadOnly(); } return Cache_UMKEY_PE_HOMEKEY; } } /// <summary> /// PE (Employees) related entities by [UM.UMKEY]-&gt;[PE.MAILKEY] /// Address ID /// </summary> public IReadOnlyList<PE> UMKEY_PE_MAILKEY { get { if (Cache_UMKEY_PE_MAILKEY == null && !Context.PE.TryFindByMAILKEY(UMKEY, out Cache_UMKEY_PE_MAILKEY)) { Cache_UMKEY_PE_MAILKEY = new List<PE>().AsReadOnly(); } return Cache_UMKEY_PE_MAILKEY; } } /// <summary> /// PE (Employees) related entities by [UM.UMKEY]-&gt;[PE.LEAVEKEY] /// Address ID /// </summary> public IReadOnlyList<PE> UMKEY_PE_LEAVEKEY { get { if (Cache_UMKEY_PE_LEAVEKEY == null && !Context.PE.TryFindByLEAVEKEY(UMKEY, out Cache_UMKEY_PE_LEAVEKEY)) { Cache_UMKEY_PE_LEAVEKEY = new List<PE>().AsReadOnly(); } return Cache_UMKEY_PE_LEAVEKEY; } } /// <summary> /// SAM (School Association Members) related entities by [UM.UMKEY]-&gt;[SAM.ADDRESSKEY] /// Address ID /// </summary> public IReadOnlyList<SAM> UMKEY_SAM_ADDRESSKEY { get { if (Cache_UMKEY_SAM_ADDRESSKEY == null && !Context.SAM.TryFindByADDRESSKEY(UMKEY, out Cache_UMKEY_SAM_ADDRESSKEY)) { Cache_UMKEY_SAM_ADDRESSKEY = new List<SAM>().AsReadOnly(); } return Cache_UMKEY_SAM_ADDRESSKEY; } } /// <summary> /// SAM (School Association Members) related entities by [UM.UMKEY]-&gt;[SAM.MAILKEY] /// Address ID /// </summary> public IReadOnlyList<SAM> UMKEY_SAM_MAILKEY { get { if (Cache_UMKEY_SAM_MAILKEY == null && !Context.SAM.TryFindByMAILKEY(UMKEY, out Cache_UMKEY_SAM_MAILKEY)) { Cache_UMKEY_SAM_MAILKEY = new List<SAM>().AsReadOnly(); } return Cache_UMKEY_SAM_MAILKEY; } } /// <summary> /// SF (Staff) related entities by [UM.UMKEY]-&gt;[SF.HOMEKEY] /// Address ID /// </summary> public IReadOnlyList<SF> UMKEY_SF_HOMEKEY { get { if (Cache_UMKEY_SF_HOMEKEY == null && !Context.SF.TryFindByHOMEKEY(UMKEY, out Cache_UMKEY_SF_HOMEKEY)) { Cache_UMKEY_SF_HOMEKEY = new List<SF>().AsReadOnly(); } return Cache_UMKEY_SF_HOMEKEY; } } /// <summary> /// SF (Staff) related entities by [UM.UMKEY]-&gt;[SF.MAILKEY] /// Address ID /// </summary> public IReadOnlyList<SF> UMKEY_SF_MAILKEY { get { if (Cache_UMKEY_SF_MAILKEY == null && !Context.SF.TryFindByMAILKEY(UMKEY, out Cache_UMKEY_SF_MAILKEY)) { Cache_UMKEY_SF_MAILKEY = new List<SF>().AsReadOnly(); } return Cache_UMKEY_SF_MAILKEY; } } /// <summary> /// STTRIPS (Student Trips) related entities by [UM.UMKEY]-&gt;[STTRIPS.AM_PICKUP_ADDRESS_ID] /// Address ID /// </summary> public IReadOnlyList<STTRIPS> UMKEY_STTRIPS_AM_PICKUP_ADDRESS_ID { get { if (Cache_UMKEY_STTRIPS_AM_PICKUP_ADDRESS_ID == null && !Context.STTRIPS.TryFindByAM_PICKUP_ADDRESS_ID(UMKEY, out Cache_UMKEY_STTRIPS_AM_PICKUP_ADDRESS_ID)) { Cache_UMKEY_STTRIPS_AM_PICKUP_ADDRESS_ID = new List<STTRIPS>().AsReadOnly(); } return Cache_UMKEY_STTRIPS_AM_PICKUP_ADDRESS_ID; } } /// <summary> /// STTRIPS (Student Trips) related entities by [UM.UMKEY]-&gt;[STTRIPS.PM_SETDOWN_ADDRESS_ID] /// Address ID /// </summary> public IReadOnlyList<STTRIPS> UMKEY_STTRIPS_PM_SETDOWN_ADDRESS_ID { get { if (Cache_UMKEY_STTRIPS_PM_SETDOWN_ADDRESS_ID == null && !Context.STTRIPS.TryFindByPM_SETDOWN_ADDRESS_ID(UMKEY, out Cache_UMKEY_STTRIPS_PM_SETDOWN_ADDRESS_ID)) { Cache_UMKEY_STTRIPS_PM_SETDOWN_ADDRESS_ID = new List<STTRIPS>().AsReadOnly(); } return Cache_UMKEY_STTRIPS_PM_SETDOWN_ADDRESS_ID; } } #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 Xunit; namespace System.Linq.Expressions.Tests { public static class NonLiftedComparisonNotEqualNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableBoolTest(bool useInterpreter) { bool?[] values = new bool?[] { null, true, false }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableBool(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableFloat(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableSByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonNotEqualNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonNotEqualNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyComparisonNotEqualNullableBool(bool? a, bool? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(bool?)), Expression.Constant(b, typeof(bool?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonNotEqualNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.NotEqual( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a != b; bool result = f(); Assert.Equal(expected, result); } #endregion } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.IO; using System.Text; using System.Diagnostics; using System.Collections.Specialized; using Axiom.Core; using Axiom.Graphics; using Axiom.Scripting; namespace Axiom.SceneManagers.Bsp { /// <summary> /// Class for managing Quake3 custom shaders. /// </summary> /// <remarks> /// Quake3 uses .shader files to define custom shaders which are the rough equivelent of OGRE material scripts. /// When a surface texture is mentioned in a level file, it includes no file extension /// meaning that it can either be a standard texture image (+lightmap) if there is only a .jpg or .tga /// file, or it may refer to a custom shader if a shader with that name is included in one of the .shader /// files in the scripts/ folder. Because there are multiple shaders per file you have to parse all the /// .shader files available to know if there is a custom shader available. This class is designed to parse /// all the .shader files available and save their settings for future use. </p> /// I choose not to set up Material instances for shaders found since they may or may not be used by a level, /// so it would be very wasteful to set up Materials since they load texture images for each layer (apart from the /// lightmap). Once the usage of a shader is confirmed, a full Material instance can be set up from it.</p> /// Because this is a subclass of ResourceManager, any files mentioned will be searched for in any path or /// archive added to the resource paths/archives. See <see cref="ResourceManager"/> for details. /// </remarks> public class Quake3ShaderManager : ResourceManager { #region Singleton implementation protected static Quake3ShaderManager instance; public static Quake3ShaderManager Instance { get { return instance; } } static Quake3ShaderManager() { instance = new Quake3ShaderManager(); } protected Quake3ShaderManager() { } #endregion #region Methods public void ParseShaderFile(Stream stream) { StreamReader file = new StreamReader(stream, Encoding.ASCII); string line; Quake3Shader shader = null; while((line = file.ReadLine()) != null) { line = line.Trim(); // Ignore comments & blanks if((line != String.Empty) && !line.StartsWith("//")) { if(shader == null) { LogManager.Instance.Write("Creating {0}...", line); // No current shader // So first valid data should be a shader name shader = (Quake3Shader) Create(line); // Skip to and over next brace ParseHelper.SkipToNextOpenBrace(file); } else { // Already in a shader if(line == "}") { LogManager.Instance.Write("End of shader."); shader = null; } else if(line == "{") { LogManager.Instance.Write("New pass..."); ParseNewShaderPass(file, shader); } else { LogManager.Instance.Write("New attrib, {0}...", line); ParseShaderAttrib(line.ToLower(), shader); } } } } } public void ParseAllSources(string extension) { Stream chunk; StringCollection shaderFiles = ResourceManager.GetAllCommonNamesLike("", extension); for(int i = 0; i < shaderFiles.Count; i++) { if((chunk = ResourceManager.FindCommonResourceData(shaderFiles[i])) == null) continue; ParseShaderFile(chunk); } } protected void ParseNewShaderPass(StreamReader stream, Quake3Shader shader) { string line; ShaderPass pass = new ShaderPass(); // Default pass details pass.animNumFrames = 0; pass.blend = LayerBlendOperation.Replace; pass.blendDest = SceneBlendFactor.Zero; pass.depthFunc = CompareFunction.LessEqual; pass.flags = 0; pass.rgbGenFunc = ShaderGen.Identity; pass.tcModRotate = 0; pass.tcModScale[0] = pass.tcModScale[1] = 1.0f; pass.tcModScroll[0] = pass.tcModScroll[1] = 0.0f; pass.tcModStretchWave = ShaderWaveType.None; pass.tcModTransform[0] = pass.tcModTransform[1] = 0.0f; pass.tcModTurbOn = false; pass.tcModTurb[0] = pass.tcModTurb[1] = pass.tcModTurb[2] = pass.tcModTurb[3] = 0.0f; pass.texGen = ShaderTextureGen.Base; pass.addressMode = TextureAddressing.Wrap; pass.customBlend = false; pass.alphaVal = 0; pass.alphaFunc = CompareFunction.AlwaysPass; shader.Pass.Add(pass); while((line = stream.ReadLine()) != null) { line = line.Trim(); // Ignore comments & blanks if((line != String.Empty) && !line.StartsWith("//")) { if(line == "}") return; else ParseShaderPassAttrib(line, shader, pass); } } } protected void ParseShaderAttrib(string line, Quake3Shader shader) { string[] attribParams = line.Replace("(", "").Replace(")", "").Split(' ', '\t'); if(attribParams[0] == "skyparms") { if(attribParams[1] != "-") { shader.Farbox = true; shader.FarboxName = attribParams[1]; } if(attribParams[2] != "-") { shader.SkyDome = true; if(attribParams[2] == "full") shader.CloudHeight = 512; else shader.CloudHeight = StringConverter.ParseFloat(attribParams[2]); } // nearbox not supported } else if(attribParams[0] == "cull") { if((attribParams[1] == "diable") || (attribParams[1] == "none")) shader.CullingMode = ManualCullingMode.None; else if(attribParams[1] == "front") shader.CullingMode = ManualCullingMode.Front; else if(attribParams[1] == "back") shader.CullingMode = ManualCullingMode.Back; } else if (attribParams[0] == "deformvertexes") { // TODO } else if(attribParams[0] == "fogparms") { string[] fogValues = new string[4]; Array.Copy(attribParams, 1, fogValues, 0, 4); /*shader.Fog = true; shader.FogColour = StringConverter.ParseColor(fogValues); shader.FogDistance = StringConverter.ParseFloat(attribParams[4]);*/ } } protected void ParseShaderPassAttrib(string line, Quake3Shader shader, ShaderPass pass) { string[] attribParams = line.Split(' ', '\t'); attribParams[0] = attribParams[0].ToLower(); LogManager.Instance.Write("Attrib {0}", attribParams[0]); if((attribParams[0] != "map") && (attribParams[0] != "clampmap") && (attribParams[0] != "animmap")) { // lower case all except textures for (int i = 1; i < attribParams.Length; i++) { attribParams[i] = attribParams[i].ToLower(); } } // MAP if(attribParams[0] == "map") { pass.textureName = attribParams[1]; if (attribParams[1].ToLower() == "$lightmap") { pass.texGen = ShaderTextureGen.Lightmap; } } // CLAMPMAP else if(attribParams[0] == "clampmap") { pass.textureName = attribParams[1]; if(attribParams[1].ToLower() == "$lightmap") pass.texGen = ShaderTextureGen.Lightmap; pass.addressMode = TextureAddressing.Clamp; } // ANIMMAP else if(attribParams[0] == "animmap") { pass.animFps = StringConverter.ParseFloat(attribParams[1]); pass.animNumFrames = attribParams.Length - 2; for(uint frame = 0; frame < pass.animNumFrames; frame++) pass.frames[frame] = attribParams[frame + 2]; } // BLENDFUNC else if(attribParams[0] == "blendfunc") { if((attribParams[1] == "add") || (attribParams[1] == "gl_add")) { pass.blend = LayerBlendOperation.Add; pass.blendDest = SceneBlendFactor.One; pass.blendSrc = SceneBlendFactor.One; } else if((attribParams[1] == "filter") || (attribParams[1] == "gl_filter")) { pass.blend = LayerBlendOperation.Modulate; pass.blendDest = SceneBlendFactor.Zero; pass.blendSrc = SceneBlendFactor.DestColor; } else if((attribParams[1] == "blend") || (attribParams[1] == "gl_blend")) { pass.blend = LayerBlendOperation.AlphaBlend; pass.blendDest = SceneBlendFactor.OneMinusSourceAlpha; pass.blendSrc = SceneBlendFactor.SourceAlpha; } else { // Manual blend pass.blendSrc = ConvertBlendFunc(attribParams[1]); pass.blendDest = ConvertBlendFunc(attribParams[2]); // Detect common blends if((pass.blendSrc == SceneBlendFactor.One) && (pass.blendDest == SceneBlendFactor.Zero)) pass.blend = LayerBlendOperation.Replace; else if((pass.blendSrc == SceneBlendFactor.One) && (pass.blendDest == SceneBlendFactor.One)) pass.blend = LayerBlendOperation.Add; else if(((pass.blendSrc == SceneBlendFactor.Zero) && (pass.blendDest == SceneBlendFactor.SourceColor)) || ((pass.blendSrc == SceneBlendFactor.DestColor) && (pass.blendDest == SceneBlendFactor.Zero))) pass.blend = LayerBlendOperation.Modulate; else if((pass.blendSrc == SceneBlendFactor.SourceAlpha) && (pass.blendDest == SceneBlendFactor.OneMinusSourceAlpha)) pass.blend = LayerBlendOperation.AlphaBlend; else pass.customBlend = true; // NB other custom blends might not work due to OGRE trying to use multitexture over multipass } } // RGBGEN else if(attribParams[0] == "rgbgen") { // TODO } // ALPHAGEN else if(attribParams[0] == "alphagen") { // TODO } // TCGEN else if(attribParams[0] == "tcgen") { if(attribParams[1] == "base") pass.texGen = ShaderTextureGen.Base; else if(attribParams[1] == "lightmap") pass.texGen = ShaderTextureGen.Lightmap; else if(attribParams[1] == "environment") pass.texGen = ShaderTextureGen.Environment; } // TCMOD else if(attribParams[0] == "tcmod") { if(attribParams[1] == "rotate") { pass.tcModRotate = -StringConverter.ParseFloat(attribParams[2]) / 360; // +ve is clockwise degrees in Q3 shader, anticlockwise complete rotations in Ogre } else if(attribParams[1] == "scroll") { pass.tcModScroll[0] = StringConverter.ParseFloat(attribParams[2]); pass.tcModScroll[1] = StringConverter.ParseFloat(attribParams[3]); } else if(attribParams[1] == "scale") { pass.tcModScale[0] = StringConverter.ParseFloat(attribParams[2]); pass.tcModScale[1] = StringConverter.ParseFloat(attribParams[3]); } else if(attribParams[1] == "stretch") { if(attribParams[2] == "sin") pass.tcModStretchWave = ShaderWaveType.Sin; else if(attribParams[2] == "triangle") pass.tcModStretchWave = ShaderWaveType.Triangle; else if(attribParams[2] == "square") pass.tcModStretchWave = ShaderWaveType.Square; else if(attribParams[2] == "sawtooth") pass.tcModStretchWave = ShaderWaveType.SawTooth; else if(attribParams[2] == "inversesawtooth") pass.tcModStretchWave = ShaderWaveType.InverseSawtooth; pass.tcModStretchParams[0] = StringConverter.ParseFloat(attribParams[3]); pass.tcModStretchParams[1] = StringConverter.ParseFloat(attribParams[4]); pass.tcModStretchParams[2] = StringConverter.ParseFloat(attribParams[5]); pass.tcModStretchParams[3] = StringConverter.ParseFloat(attribParams[6]); } } // TURB else if(attribParams[0] == "turb") { pass.tcModTurbOn = true; pass.tcModTurb[0] = StringConverter.ParseFloat(attribParams[2]); pass.tcModTurb[1] = StringConverter.ParseFloat(attribParams[3]); pass.tcModTurb[2] = StringConverter.ParseFloat(attribParams[4]); pass.tcModTurb[3] = StringConverter.ParseFloat(attribParams[5]); } // DEPTHFUNC else if(attribParams[0] == "depthfunc") { // TODO } // DEPTHWRITE else if(attribParams[0] == "depthwrite") { // TODO } // ALPHAFUNC else if(attribParams[0] == "alphafunc") { if(attribParams[1] == "gt0") { pass.alphaVal = 0; pass.alphaFunc = CompareFunction.Greater; } else if(attribParams[1] == "ge128") { pass.alphaVal = 128; pass.alphaFunc = CompareFunction.GreaterEqual; } else if(attribParams[1] == "lt128") { pass.alphaVal = 128; pass.alphaFunc = CompareFunction.Less; } } } protected SceneBlendFactor ConvertBlendFunc(string q3func) { if(q3func == "gl_one") return SceneBlendFactor.One; else if(q3func == "gl_zero") return SceneBlendFactor.Zero; else if(q3func == "gl_dst_color") return SceneBlendFactor.DestColor; else if(q3func == "gl_src_color") return SceneBlendFactor.SourceColor; else if(q3func == "gl_one_minus_dest_color") return SceneBlendFactor.OneMinusDestColor; else if(q3func == "gl_src_alpha") return SceneBlendFactor.SourceAlpha; else if(q3func == "gl_one_minus_src_alpha") return SceneBlendFactor.OneMinusSourceAlpha; // Default if unrecognised return SceneBlendFactor.One; } #endregion #region ResourceManager implementation public override Resource Create(string name) { Quake3Shader s = new Quake3Shader(name); Load(s, 1); return s; } #endregion } }
using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Codecs.Lucene40 { /* * 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 IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using DocsEnum = Lucene.Net.Index.DocsEnum; using FieldInfo = Lucene.Net.Index.FieldInfo; using FieldInfos = Lucene.Net.Index.FieldInfos; using Fields = Lucene.Net.Index.Fields; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexInput = Lucene.Net.Store.IndexInput; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using SegmentInfo = Lucene.Net.Index.SegmentInfo; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; /// <summary> /// Lucene 4.0 Term Vectors reader. /// <para/> /// It reads .tvd, .tvf, and .tvx files. /// </summary> /// <seealso cref="Lucene40TermVectorsFormat"/> public class Lucene40TermVectorsReader : TermVectorsReader, IDisposable { internal const sbyte STORE_POSITIONS_WITH_TERMVECTOR = 0x1; internal const sbyte STORE_OFFSET_WITH_TERMVECTOR = 0x2; internal const sbyte STORE_PAYLOAD_WITH_TERMVECTOR = 0x4; /// <summary> /// Extension of vectors fields file. </summary> internal const string VECTORS_FIELDS_EXTENSION = "tvf"; /// <summary> /// Extension of vectors documents file. </summary> internal const string VECTORS_DOCUMENTS_EXTENSION = "tvd"; /// <summary> /// Extension of vectors index file. </summary> internal const string VECTORS_INDEX_EXTENSION = "tvx"; internal const string CODEC_NAME_FIELDS = "Lucene40TermVectorsFields"; internal const string CODEC_NAME_DOCS = "Lucene40TermVectorsDocs"; internal const string CODEC_NAME_INDEX = "Lucene40TermVectorsIndex"; internal const int VERSION_NO_PAYLOADS = 0; internal const int VERSION_PAYLOADS = 1; internal const int VERSION_START = VERSION_NO_PAYLOADS; internal const int VERSION_CURRENT = VERSION_PAYLOADS; internal static readonly long HEADER_LENGTH_FIELDS = CodecUtil.HeaderLength(CODEC_NAME_FIELDS); internal static readonly long HEADER_LENGTH_DOCS = CodecUtil.HeaderLength(CODEC_NAME_DOCS); internal static readonly long HEADER_LENGTH_INDEX = CodecUtil.HeaderLength(CODEC_NAME_INDEX); private FieldInfos fieldInfos; private IndexInput tvx; private IndexInput tvd; private IndexInput tvf; private int size; private int numTotalDocs; /// <summary> /// Used by clone. </summary> internal Lucene40TermVectorsReader(FieldInfos fieldInfos, IndexInput tvx, IndexInput tvd, IndexInput tvf, int size, int numTotalDocs) { this.fieldInfos = fieldInfos; this.tvx = tvx; this.tvd = tvd; this.tvf = tvf; this.size = size; this.numTotalDocs = numTotalDocs; } /// <summary> /// Sole constructor. </summary> public Lucene40TermVectorsReader(Directory d, SegmentInfo si, FieldInfos fieldInfos, IOContext context) { string segment = si.Name; int size = si.DocCount; bool success = false; try { string idxName = IndexFileNames.SegmentFileName(segment, "", VECTORS_INDEX_EXTENSION); tvx = d.OpenInput(idxName, context); int tvxVersion = CodecUtil.CheckHeader(tvx, CODEC_NAME_INDEX, VERSION_START, VERSION_CURRENT); string fn = IndexFileNames.SegmentFileName(segment, "", VECTORS_DOCUMENTS_EXTENSION); tvd = d.OpenInput(fn, context); int tvdVersion = CodecUtil.CheckHeader(tvd, CODEC_NAME_DOCS, VERSION_START, VERSION_CURRENT); fn = IndexFileNames.SegmentFileName(segment, "", VECTORS_FIELDS_EXTENSION); tvf = d.OpenInput(fn, context); int tvfVersion = CodecUtil.CheckHeader(tvf, CODEC_NAME_FIELDS, VERSION_START, VERSION_CURRENT); if (Debugging.AssertsEnabled) { Debugging.Assert(HEADER_LENGTH_INDEX == tvx.GetFilePointer()); Debugging.Assert(HEADER_LENGTH_DOCS == tvd.GetFilePointer()); Debugging.Assert(HEADER_LENGTH_FIELDS == tvf.GetFilePointer()); Debugging.Assert(tvxVersion == tvdVersion); Debugging.Assert(tvxVersion == tvfVersion); } numTotalDocs = (int)(tvx.Length - HEADER_LENGTH_INDEX >> 4); this.size = numTotalDocs; if (Debugging.AssertsEnabled) Debugging.Assert(size == 0 || numTotalDocs == size); this.fieldInfos = fieldInfos; success = true; } finally { // With lock-less commits, it's entirely possible (and // fine) to hit a FileNotFound exception above. In // this case, we want to explicitly close any subset // of things that were opened so that we don't have to // wait for a GC to do so. if (!success) { try { Dispose(); } // ensure we throw our original exception #pragma warning disable 168 catch (Exception t) #pragma warning restore 168 { } } } } // Used for bulk copy when merging internal virtual IndexInput TvdStream => tvd; // Used for bulk copy when merging internal virtual IndexInput TvfStream => tvf; // Not private to avoid synthetic access$NNN methods internal virtual void SeekTvx(int docNum) { tvx.Seek(docNum * 16L + HEADER_LENGTH_INDEX); } /// <summary> /// Retrieve the length (in bytes) of the tvd and tvf /// entries for the next <paramref name="numDocs"/> starting with /// <paramref name="startDocID"/>. This is used for bulk copying when /// merging segments, if the field numbers are /// congruent. Once this returns, the tvf &amp; tvd streams /// are seeked to the <paramref name="startDocID"/>. /// </summary> internal void RawDocs(int[] tvdLengths, int[] tvfLengths, int startDocID, int numDocs) { if (tvx == null) { Arrays.Fill(tvdLengths, 0); Arrays.Fill(tvfLengths, 0); return; } SeekTvx(startDocID); long tvdPosition = tvx.ReadInt64(); tvd.Seek(tvdPosition); long tvfPosition = tvx.ReadInt64(); tvf.Seek(tvfPosition); long lastTvdPosition = tvdPosition; long lastTvfPosition = tvfPosition; int count = 0; while (count < numDocs) { int docID = startDocID + count + 1; if (Debugging.AssertsEnabled) Debugging.Assert(docID <= numTotalDocs); if (docID < numTotalDocs) { tvdPosition = tvx.ReadInt64(); tvfPosition = tvx.ReadInt64(); } else { tvdPosition = tvd.Length; tvfPosition = tvf.Length; if (Debugging.AssertsEnabled) Debugging.Assert(count == numDocs - 1); } tvdLengths[count] = (int)(tvdPosition - lastTvdPosition); tvfLengths[count] = (int)(tvfPosition - lastTvfPosition); count++; lastTvdPosition = tvdPosition; lastTvfPosition = tvfPosition; } } protected override void Dispose(bool disposing) { if (disposing) IOUtils.Dispose(tvx, tvd, tvf); } /// <summary> /// The number of documents in the reader. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> internal virtual int Count => size; private class TVFields : Fields { private readonly Lucene40TermVectorsReader outerInstance; private readonly int[] fieldNumbers; private readonly long[] fieldFPs; private readonly IDictionary<int, int> fieldNumberToIndex = new Dictionary<int, int>(); public TVFields(Lucene40TermVectorsReader outerInstance, int docID) { this.outerInstance = outerInstance; outerInstance.SeekTvx(docID); outerInstance.tvd.Seek(outerInstance.tvx.ReadInt64()); int fieldCount = outerInstance.tvd.ReadVInt32(); if (Debugging.AssertsEnabled) Debugging.Assert(fieldCount >= 0); if (fieldCount != 0) { fieldNumbers = new int[fieldCount]; fieldFPs = new long[fieldCount]; for (int fieldUpto = 0; fieldUpto < fieldCount; fieldUpto++) { int fieldNumber = outerInstance.tvd.ReadVInt32(); fieldNumbers[fieldUpto] = fieldNumber; fieldNumberToIndex[fieldNumber] = fieldUpto; } long position = outerInstance.tvx.ReadInt64(); fieldFPs[0] = position; for (int fieldUpto = 1; fieldUpto < fieldCount; fieldUpto++) { position += outerInstance.tvd.ReadVInt64(); fieldFPs[fieldUpto] = position; } } else { // TODO: we can improve writer here, eg write 0 into // tvx file, so we know on first read from tvx that // this doc has no TVs fieldNumbers = null; fieldFPs = null; } } public override IEnumerator<string> GetEnumerator() { return GetFieldInfoEnumerable().GetEnumerator(); } private IEnumerable<string> GetFieldInfoEnumerable() { int fieldUpto = 0; while (fieldNumbers != null && fieldUpto < fieldNumbers.Length) { yield return outerInstance.fieldInfos.FieldInfo(fieldNumbers[fieldUpto++]).Name; } } public override Terms GetTerms(string field) { FieldInfo fieldInfo = outerInstance.fieldInfos.FieldInfo(field); if (fieldInfo == null) { // No such field return null; } int fieldIndex; if (!fieldNumberToIndex.TryGetValue(fieldInfo.Number, out fieldIndex)) { // Term vectors were not indexed for this field return null; } return new TVTerms(outerInstance, fieldFPs[fieldIndex]); } public override int Count { get { if (fieldNumbers == null) { return 0; } else { return fieldNumbers.Length; } } } } private class TVTerms : Terms { private readonly Lucene40TermVectorsReader outerInstance; private readonly int numTerms; private readonly long tvfFPStart; private readonly bool storePositions; private readonly bool storeOffsets; private readonly bool storePayloads; public TVTerms(Lucene40TermVectorsReader outerInstance, long tvfFP) { this.outerInstance = outerInstance; outerInstance.tvf.Seek(tvfFP); numTerms = outerInstance.tvf.ReadVInt32(); byte bits = outerInstance.tvf.ReadByte(); storePositions = (bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0; storeOffsets = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0; storePayloads = (bits & STORE_PAYLOAD_WITH_TERMVECTOR) != 0; tvfFPStart = outerInstance.tvf.GetFilePointer(); } public override TermsEnum GetEnumerator() { var termsEnum = new TVTermsEnum(outerInstance); termsEnum.Reset(numTerms, tvfFPStart, storePositions, storeOffsets, storePayloads); return termsEnum; } public override TermsEnum GetEnumerator(TermsEnum reuse) { TVTermsEnum termsEnum; #pragma warning disable IDE0038 // Use pattern matching if (reuse is null || !(reuse is TVTermsEnum)) #pragma warning restore IDE0038 // Use pattern matching { termsEnum = new TVTermsEnum(outerInstance); } else { var reusable = (TVTermsEnum)reuse; if (reusable.CanReuse(outerInstance.tvf)) termsEnum = reusable; else termsEnum = new TVTermsEnum(outerInstance); } termsEnum.Reset(numTerms, tvfFPStart, storePositions, storeOffsets, storePayloads); return termsEnum; } public override long Count => numTerms; public override long SumTotalTermFreq => -1; public override long SumDocFreq => // Every term occurs in just one doc: numTerms; public override int DocCount => 1; public override IComparer<BytesRef> Comparer => // TODO: really indexer hardwires // this...? I guess codec could buffer and re-sort... BytesRef.UTF8SortedAsUnicodeComparer; public override bool HasFreqs => true; public override bool HasOffsets => storeOffsets; public override bool HasPositions => storePositions; public override bool HasPayloads => storePayloads; } private class TVTermsEnum : TermsEnum { private readonly IndexInput origTVF; private readonly IndexInput tvf; private int numTerms; private int nextTerm; private int freq; private readonly BytesRef lastTerm = new BytesRef(); private readonly BytesRef term = new BytesRef(); private bool storePositions; private bool storeOffsets; private bool storePayloads; private long tvfFP; private int[] positions; private int[] startOffsets; private int[] endOffsets; // one shared byte[] for any term's payloads private int[] payloadOffsets; private int lastPayloadLength; private byte[] payloadData; // NOTE: tvf is pre-positioned by caller public TVTermsEnum(Lucene40TermVectorsReader outerInstance) { this.origTVF = outerInstance.tvf; tvf = (IndexInput)origTVF.Clone(); } public virtual bool CanReuse(IndexInput tvf) { return tvf == origTVF; } public virtual void Reset(int numTerms, long tvfFPStart, bool storePositions, bool storeOffsets, bool storePayloads) { this.numTerms = numTerms; this.storePositions = storePositions; this.storeOffsets = storeOffsets; this.storePayloads = storePayloads; nextTerm = 0; tvf.Seek(tvfFPStart); tvfFP = tvfFPStart; positions = null; startOffsets = null; endOffsets = null; payloadOffsets = null; payloadData = null; lastPayloadLength = -1; } // NOTE: slow! (linear scan) public override SeekStatus SeekCeil(BytesRef text) { if (nextTerm != 0) { int cmp = text.CompareTo(term); if (cmp < 0) { nextTerm = 0; tvf.Seek(tvfFP); } else if (cmp == 0) { return SeekStatus.FOUND; } } while (MoveNext()) { int cmp = text.CompareTo(term); if (cmp < 0) { return SeekStatus.NOT_FOUND; } else if (cmp == 0) { return SeekStatus.FOUND; } } return SeekStatus.END; } public override void SeekExact(long ord) { throw new NotSupportedException(); } public override bool MoveNext() { if (nextTerm >= numTerms) { return false; } term.CopyBytes(lastTerm); int start = tvf.ReadVInt32(); int deltaLen = tvf.ReadVInt32(); term.Length = start + deltaLen; term.Grow(term.Length); tvf.ReadBytes(term.Bytes, start, deltaLen); freq = tvf.ReadVInt32(); if (storePayloads) { positions = new int[freq]; payloadOffsets = new int[freq]; int totalPayloadLength = 0; int pos = 0; for (int posUpto = 0; posUpto < freq; posUpto++) { int code = tvf.ReadVInt32(); pos += (int)((uint)code >> 1); positions[posUpto] = pos; if ((code & 1) != 0) { // length change lastPayloadLength = tvf.ReadVInt32(); } payloadOffsets[posUpto] = totalPayloadLength; totalPayloadLength += lastPayloadLength; if (Debugging.AssertsEnabled) Debugging.Assert(totalPayloadLength >= 0); } payloadData = new byte[totalPayloadLength]; tvf.ReadBytes(payloadData, 0, payloadData.Length); } // no payloads else if (storePositions) { // TODO: we could maybe reuse last array, if we can // somehow be careful about consumer never using two // D&PEnums at once... positions = new int[freq]; int pos = 0; for (int posUpto = 0; posUpto < freq; posUpto++) { pos += tvf.ReadVInt32(); positions[posUpto] = pos; } } if (storeOffsets) { startOffsets = new int[freq]; endOffsets = new int[freq]; int offset = 0; for (int posUpto = 0; posUpto < freq; posUpto++) { startOffsets[posUpto] = offset + tvf.ReadVInt32(); offset = endOffsets[posUpto] = startOffsets[posUpto] + tvf.ReadVInt32(); } } lastTerm.CopyBytes(term); nextTerm++; return true; } [Obsolete("Use MoveNext() and Term instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public override BytesRef Next() { if (MoveNext()) return term; return null; } public override BytesRef Term => term; public override long Ord => throw new NotSupportedException(); public override int DocFreq => 1; public override long TotalTermFreq => freq; public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) // ignored { TVDocsEnum docsEnum; if (reuse != null && reuse is TVDocsEnum) { docsEnum = (TVDocsEnum)reuse; } else { docsEnum = new TVDocsEnum(); } docsEnum.Reset(liveDocs, freq); return docsEnum; } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { if (!storePositions && !storeOffsets) { return null; } TVDocsAndPositionsEnum docsAndPositionsEnum; if (reuse != null && reuse is TVDocsAndPositionsEnum) { docsAndPositionsEnum = (TVDocsAndPositionsEnum)reuse; } else { docsAndPositionsEnum = new TVDocsAndPositionsEnum(); } docsAndPositionsEnum.Reset(liveDocs, positions, startOffsets, endOffsets, payloadOffsets, payloadData); return docsAndPositionsEnum; } public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer; } // NOTE: sort of a silly class, since you can get the // freq() already by TermsEnum.totalTermFreq private class TVDocsEnum : DocsEnum { private bool didNext; private int doc = -1; private int freq; private IBits liveDocs; public override int Freq => freq; public override int DocID => doc; public override int NextDoc() { if (!didNext && (liveDocs == null || liveDocs.Get(0))) { didNext = true; return (doc = 0); } else { return (doc = NO_MORE_DOCS); } } public override int Advance(int target) { return SlowAdvance(target); } public virtual void Reset(IBits liveDocs, int freq) { this.liveDocs = liveDocs; this.freq = freq; this.doc = -1; didNext = false; } public override long GetCost() { return 1; } } private sealed class TVDocsAndPositionsEnum : DocsAndPositionsEnum { private bool didNext; private int doc = -1; private int nextPos; private IBits liveDocs; private int[] positions; private int[] startOffsets; private int[] endOffsets; private int[] payloadOffsets; private readonly BytesRef payload = new BytesRef(); private byte[] payloadBytes; public override int Freq { get { if (positions != null) { return positions.Length; } else { if (Debugging.AssertsEnabled) Debugging.Assert(startOffsets != null); return startOffsets.Length; } } } public override int DocID => doc; public override int NextDoc() { if (!didNext && (liveDocs == null || liveDocs.Get(0))) { didNext = true; return (doc = 0); } else { return (doc = NO_MORE_DOCS); } } public override int Advance(int target) { return SlowAdvance(target); } public void Reset(IBits liveDocs, int[] positions, int[] startOffsets, int[] endOffsets, int[] payloadLengths, byte[] payloadBytes) { this.liveDocs = liveDocs; this.positions = positions; this.startOffsets = startOffsets; this.endOffsets = endOffsets; this.payloadOffsets = payloadLengths; this.payloadBytes = payloadBytes; this.doc = -1; didNext = false; nextPos = 0; } public override BytesRef GetPayload() { if (payloadOffsets == null) { return null; } else { int off = payloadOffsets[nextPos - 1]; int end = nextPos == payloadOffsets.Length ? payloadBytes.Length : payloadOffsets[nextPos]; if (end - off == 0) { return null; } payload.Bytes = payloadBytes; payload.Offset = off; payload.Length = end - off; return payload; } } public override int NextPosition() { //if (Debugging.AssertsEnabled) Debugging.Assert((positions != null && nextPos < positions.Length) || startOffsets != null && nextPos < startOffsets.Length); // LUCENENET: The above assertion was for control flow when testing. In Java, it would throw an AssertionError, which is // caught by the BaseTermVectorsFormatTestCase.assertEquals(RandomTokenStream tk, FieldType ft, Terms terms) method in the // part that is checking for an error after reading to the end of the enumerator. // In .NET it is more natural to throw an InvalidOperationException in this case, since we would potentially get an // IndexOutOfRangeException if we didn't, which doesn't really provide good feedback as to what the cause is. // This matches the behavior of Lucene 8.x. See #267. if (((positions != null && nextPos < positions.Length) || startOffsets != null && nextPos < startOffsets.Length) == false) throw new InvalidOperationException("Read past last position"); if (positions != null) { return positions[nextPos++]; } else { nextPos++; return -1; } } public override int StartOffset { get { if (startOffsets == null) { return -1; } else { return startOffsets[nextPos - 1]; } } } public override int EndOffset { get { if (endOffsets == null) { return -1; } else { return endOffsets[nextPos - 1]; } } } public override long GetCost() { return 1; } } public override Fields Get(int docID) { if (tvx != null) { Fields fields = new TVFields(this, docID); if (fields.Count == 0) { // TODO: we can improve writer here, eg write 0 into // tvx file, so we know on first read from tvx that // this doc has no TVs return null; } else { return fields; } } else { return null; } } public override object Clone() { IndexInput cloneTvx = null; IndexInput cloneTvd = null; IndexInput cloneTvf = null; // These are null when a TermVectorsReader was created // on a segment that did not have term vectors saved if (tvx != null && tvd != null && tvf != null) { cloneTvx = (IndexInput)tvx.Clone(); cloneTvd = (IndexInput)tvd.Clone(); cloneTvf = (IndexInput)tvf.Clone(); } return new Lucene40TermVectorsReader(fieldInfos, cloneTvx, cloneTvd, cloneTvf, size, numTotalDocs); } public override long RamBytesUsed() { return 0; } public override void CheckIntegrity() { } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// CustomerLoyaltyRedemption /// </summary> [DataContract] public partial class CustomerLoyaltyRedemption : IEquatable<CustomerLoyaltyRedemption>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CustomerLoyaltyRedemption" /> class. /// </summary> /// <param name="couponCode">Coupon code.</param> /// <param name="couponCodeOid">Coupon code OID.</param> /// <param name="couponUsed">Coupon used.</param> /// <param name="descriptionForCustomer">Description for customer.</param> /// <param name="expirationDts">Expiration date.</param> /// <param name="giftCertificateCode">Gift certificate code.</param> /// <param name="giftCertificateOid">Gift certificate oid.</param> /// <param name="loyaltyLedgerOid">Loyalty ledger OID.</param> /// <param name="loyaltyPoints">Loyalty points.</param> /// <param name="loyaltyRedemptionOid">Loyalty redemption OID.</param> /// <param name="orderId">Order id.</param> /// <param name="redemptionDts">Redemption date.</param> /// <param name="remainingBalance">Remaining balance.</param> public CustomerLoyaltyRedemption(string couponCode = default(string), int? couponCodeOid = default(int?), bool? couponUsed = default(bool?), string descriptionForCustomer = default(string), string expirationDts = default(string), string giftCertificateCode = default(string), int? giftCertificateOid = default(int?), int? loyaltyLedgerOid = default(int?), int? loyaltyPoints = default(int?), int? loyaltyRedemptionOid = default(int?), string orderId = default(string), string redemptionDts = default(string), decimal? remainingBalance = default(decimal?)) { this.CouponCode = couponCode; this.CouponCodeOid = couponCodeOid; this.CouponUsed = couponUsed; this.DescriptionForCustomer = descriptionForCustomer; this.ExpirationDts = expirationDts; this.GiftCertificateCode = giftCertificateCode; this.GiftCertificateOid = giftCertificateOid; this.LoyaltyLedgerOid = loyaltyLedgerOid; this.LoyaltyPoints = loyaltyPoints; this.LoyaltyRedemptionOid = loyaltyRedemptionOid; this.OrderId = orderId; this.RedemptionDts = redemptionDts; this.RemainingBalance = remainingBalance; } /// <summary> /// Coupon code /// </summary> /// <value>Coupon code</value> [DataMember(Name="coupon_code", EmitDefaultValue=false)] public string CouponCode { get; set; } /// <summary> /// Coupon code OID /// </summary> /// <value>Coupon code OID</value> [DataMember(Name="coupon_code_oid", EmitDefaultValue=false)] public int? CouponCodeOid { get; set; } /// <summary> /// Coupon used /// </summary> /// <value>Coupon used</value> [DataMember(Name="coupon_used", EmitDefaultValue=false)] public bool? CouponUsed { get; set; } /// <summary> /// Description for customer /// </summary> /// <value>Description for customer</value> [DataMember(Name="description_for_customer", EmitDefaultValue=false)] public string DescriptionForCustomer { get; set; } /// <summary> /// Expiration date /// </summary> /// <value>Expiration date</value> [DataMember(Name="expiration_dts", EmitDefaultValue=false)] public string ExpirationDts { get; set; } /// <summary> /// Gift certificate code /// </summary> /// <value>Gift certificate code</value> [DataMember(Name="gift_certificate_code", EmitDefaultValue=false)] public string GiftCertificateCode { get; set; } /// <summary> /// Gift certificate oid /// </summary> /// <value>Gift certificate oid</value> [DataMember(Name="gift_certificate_oid", EmitDefaultValue=false)] public int? GiftCertificateOid { get; set; } /// <summary> /// Loyalty ledger OID /// </summary> /// <value>Loyalty ledger OID</value> [DataMember(Name="loyalty_ledger_oid", EmitDefaultValue=false)] public int? LoyaltyLedgerOid { get; set; } /// <summary> /// Loyalty points /// </summary> /// <value>Loyalty points</value> [DataMember(Name="loyalty_points", EmitDefaultValue=false)] public int? LoyaltyPoints { get; set; } /// <summary> /// Loyalty redemption OID /// </summary> /// <value>Loyalty redemption OID</value> [DataMember(Name="loyalty_redemption_oid", EmitDefaultValue=false)] public int? LoyaltyRedemptionOid { get; set; } /// <summary> /// Order id /// </summary> /// <value>Order id</value> [DataMember(Name="order_id", EmitDefaultValue=false)] public string OrderId { get; set; } /// <summary> /// Redemption date /// </summary> /// <value>Redemption date</value> [DataMember(Name="redemption_dts", EmitDefaultValue=false)] public string RedemptionDts { get; set; } /// <summary> /// Remaining balance /// </summary> /// <value>Remaining balance</value> [DataMember(Name="remaining_balance", EmitDefaultValue=false)] public decimal? RemainingBalance { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CustomerLoyaltyRedemption {\n"); sb.Append(" CouponCode: ").Append(CouponCode).Append("\n"); sb.Append(" CouponCodeOid: ").Append(CouponCodeOid).Append("\n"); sb.Append(" CouponUsed: ").Append(CouponUsed).Append("\n"); sb.Append(" DescriptionForCustomer: ").Append(DescriptionForCustomer).Append("\n"); sb.Append(" ExpirationDts: ").Append(ExpirationDts).Append("\n"); sb.Append(" GiftCertificateCode: ").Append(GiftCertificateCode).Append("\n"); sb.Append(" GiftCertificateOid: ").Append(GiftCertificateOid).Append("\n"); sb.Append(" LoyaltyLedgerOid: ").Append(LoyaltyLedgerOid).Append("\n"); sb.Append(" LoyaltyPoints: ").Append(LoyaltyPoints).Append("\n"); sb.Append(" LoyaltyRedemptionOid: ").Append(LoyaltyRedemptionOid).Append("\n"); sb.Append(" OrderId: ").Append(OrderId).Append("\n"); sb.Append(" RedemptionDts: ").Append(RedemptionDts).Append("\n"); sb.Append(" RemainingBalance: ").Append(RemainingBalance).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as CustomerLoyaltyRedemption); } /// <summary> /// Returns true if CustomerLoyaltyRedemption instances are equal /// </summary> /// <param name="input">Instance of CustomerLoyaltyRedemption to be compared</param> /// <returns>Boolean</returns> public bool Equals(CustomerLoyaltyRedemption input) { if (input == null) return false; return ( this.CouponCode == input.CouponCode || (this.CouponCode != null && this.CouponCode.Equals(input.CouponCode)) ) && ( this.CouponCodeOid == input.CouponCodeOid || (this.CouponCodeOid != null && this.CouponCodeOid.Equals(input.CouponCodeOid)) ) && ( this.CouponUsed == input.CouponUsed || (this.CouponUsed != null && this.CouponUsed.Equals(input.CouponUsed)) ) && ( this.DescriptionForCustomer == input.DescriptionForCustomer || (this.DescriptionForCustomer != null && this.DescriptionForCustomer.Equals(input.DescriptionForCustomer)) ) && ( this.ExpirationDts == input.ExpirationDts || (this.ExpirationDts != null && this.ExpirationDts.Equals(input.ExpirationDts)) ) && ( this.GiftCertificateCode == input.GiftCertificateCode || (this.GiftCertificateCode != null && this.GiftCertificateCode.Equals(input.GiftCertificateCode)) ) && ( this.GiftCertificateOid == input.GiftCertificateOid || (this.GiftCertificateOid != null && this.GiftCertificateOid.Equals(input.GiftCertificateOid)) ) && ( this.LoyaltyLedgerOid == input.LoyaltyLedgerOid || (this.LoyaltyLedgerOid != null && this.LoyaltyLedgerOid.Equals(input.LoyaltyLedgerOid)) ) && ( this.LoyaltyPoints == input.LoyaltyPoints || (this.LoyaltyPoints != null && this.LoyaltyPoints.Equals(input.LoyaltyPoints)) ) && ( this.LoyaltyRedemptionOid == input.LoyaltyRedemptionOid || (this.LoyaltyRedemptionOid != null && this.LoyaltyRedemptionOid.Equals(input.LoyaltyRedemptionOid)) ) && ( this.OrderId == input.OrderId || (this.OrderId != null && this.OrderId.Equals(input.OrderId)) ) && ( this.RedemptionDts == input.RedemptionDts || (this.RedemptionDts != null && this.RedemptionDts.Equals(input.RedemptionDts)) ) && ( this.RemainingBalance == input.RemainingBalance || (this.RemainingBalance != null && this.RemainingBalance.Equals(input.RemainingBalance)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.CouponCode != null) hashCode = hashCode * 59 + this.CouponCode.GetHashCode(); if (this.CouponCodeOid != null) hashCode = hashCode * 59 + this.CouponCodeOid.GetHashCode(); if (this.CouponUsed != null) hashCode = hashCode * 59 + this.CouponUsed.GetHashCode(); if (this.DescriptionForCustomer != null) hashCode = hashCode * 59 + this.DescriptionForCustomer.GetHashCode(); if (this.ExpirationDts != null) hashCode = hashCode * 59 + this.ExpirationDts.GetHashCode(); if (this.GiftCertificateCode != null) hashCode = hashCode * 59 + this.GiftCertificateCode.GetHashCode(); if (this.GiftCertificateOid != null) hashCode = hashCode * 59 + this.GiftCertificateOid.GetHashCode(); if (this.LoyaltyLedgerOid != null) hashCode = hashCode * 59 + this.LoyaltyLedgerOid.GetHashCode(); if (this.LoyaltyPoints != null) hashCode = hashCode * 59 + this.LoyaltyPoints.GetHashCode(); if (this.LoyaltyRedemptionOid != null) hashCode = hashCode * 59 + this.LoyaltyRedemptionOid.GetHashCode(); if (this.OrderId != null) hashCode = hashCode * 59 + this.OrderId.GetHashCode(); if (this.RedemptionDts != null) hashCode = hashCode * 59 + this.RedemptionDts.GetHashCode(); if (this.RemainingBalance != null) hashCode = hashCode * 59 + this.RemainingBalance.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
/* 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 *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Reflection; using System.Linq; using System.Data.SqlTypes; using System.Diagnostics; using Microsoft.Research.DryadLinq.Internal; using Microsoft.Research.DryadLinq; namespace Microsoft.Research.DryadLinq { /// <summary> /// The interface for providing user-defined serialization for a .NET type. /// If a class T implements DryadLinqSerializer{T}, DryadLinq will use the /// read and write methods of the class to do serialization. /// </summary> /// <typeparam name="T">The .NET type to be serialized.</typeparam> public interface IDryadLinqSerializer<T> { /// <summary> /// Reads a record of type T from the specified reader. /// </summary> /// <param name="reader">The reader to read from.</param> /// <returns>A record of type T</returns> T Read(DryadLinqBinaryReader reader); /// <summary> /// Writes a record of type T to the specified writer. /// </summary> /// <param name="writer">The writer to write to.</param> /// <param name="x">The record to write.</param> void Write(DryadLinqBinaryWriter writer, T x); } } #pragma warning disable 1591 namespace Microsoft.Research.DryadLinq.Internal { public abstract class DryadLinqSerializer<T> : IDryadLinqSerializer<T> { public DryadLinqSerializer() { } public abstract T Read(DryadLinqBinaryReader reader); public abstract void Write(DryadLinqBinaryWriter writer, T x); } internal struct DryadLinqSequence<T> : IEnumerable<T> { private T[] elements; internal DryadLinqSequence(T[] elems) { this.elements = elems; } internal int Count() { return this.elements.Length; } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } internal IEnumerator<T> GetEnumerator() { foreach (T x in this.elements) { yield return x; } } } // The only use is to handle Nullable<T>. public static class StructDryadLinqSerialization<T, S> where T : struct where S : DryadLinqSerializer<T>, new() { private static S serializer = new S(); public static void Read(DryadLinqBinaryReader reader, out Nullable<T> val) { bool hasValue = reader.ReadBool(); if (hasValue) { val = serializer.Read(reader); } else { val = null; } } public static void Write(DryadLinqBinaryWriter writer, Nullable<T> val) { writer.Write(val.HasValue); if (val.HasValue) { serializer.Write(writer, val.Value); } } } public static class StructDryadLinqSerialization<T1, T2, S1, S2> where T1 : struct where T2 : struct where S1 : DryadLinqSerializer<T1>, new() where S2 : DryadLinqSerializer<T2>, new() { private static S1 serializer1 = new S1(); private static S2 serializer2 = new S2(); } // A workaround to deal with some limitation of C# generics public static class DryadLinqSerialization<T, S> where S : DryadLinqSerializer<T>, new() { private static S serializer = new S(); public static void Read(DryadLinqBinaryReader reader, out List<T> list) { int cnt = reader.ReadInt32(); list = new List<T>(cnt); for (int i = 0; i < cnt; i++) { list.Add(serializer.Read(reader)); } } public static void Write(DryadLinqBinaryWriter writer, List<T> list) { writer.Write(list.Count); foreach (T elem in list) { serializer.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out LinkedList<T> list) { int cnt = reader.ReadInt32(); list = new LinkedList<T>(); for (int i = 0; i < cnt; i++) { list.AddLast(serializer.Read(reader)); } } public static void Write(DryadLinqBinaryWriter writer, LinkedList<T> list) { writer.Write(list.Count); foreach (T elem in list) { serializer.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out Queue<T> queue) { int cnt = reader.ReadInt32(); queue = new Queue<T>(cnt); for (int i = 0; i < cnt; i++) { queue.Enqueue(serializer.Read(reader)); } } public static void Write(DryadLinqBinaryWriter writer, Queue<T> queue) { writer.Write(queue.Count); foreach (T elem in queue) { serializer.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out Stack<T> stack) { int cnt = reader.ReadInt32(); stack = new Stack<T>(cnt); for (int i = 0; i < cnt; i++) { stack.Push(serializer.Read(reader)); } } public static void Write(DryadLinqBinaryWriter writer, Stack<T> stack) { writer.Write(stack.Count); foreach (T elem in stack) { serializer.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out HashSet<T> set) { int cnt = reader.ReadInt32(); set = new HashSet<T>(); for (int i = 0; i < cnt; i++) { set.Add(serializer.Read(reader)); } } public static void Write(DryadLinqBinaryWriter writer, HashSet<T> set) { writer.Write(set.Count); foreach (T elem in set) { serializer.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out Collection<T> set) { int cnt = reader.ReadInt32(); set = new Collection<T>(); for (int i = 0; i < cnt; i++) { set.Add(serializer.Read(reader)); } } public static void Write(DryadLinqBinaryWriter writer, Collection<T> set) { writer.Write(set.Count); foreach (T elem in set) { serializer.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out ReadOnlyCollection<T> set) { int cnt = reader.ReadInt32(); List<T> lst = new List<T>(cnt); for (int i = 0; i < cnt; i++) { lst.Add(serializer.Read(reader)); } set = new ReadOnlyCollection<T>(lst); } public static void Write(DryadLinqBinaryWriter writer, ReadOnlyCollection<T> set) { writer.Write(set.Count); foreach (T elem in set) { serializer.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out IEnumerable<T> seq) { int cnt = reader.ReadInt32(); T[] elems = new T[cnt]; for (int i = 0; i < cnt; i++) { elems[i] = serializer.Read(reader); } seq = new DryadLinqSequence<T>(elems); } public static void Write(DryadLinqBinaryWriter writer, IEnumerable<T> seq) { writer.Write(seq.Count()); foreach (T elem in seq) { serializer.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out IList<T> seq) { int cnt = reader.ReadInt32(); seq = new List<T>(cnt); for (int i = 0; i < cnt; i++) { seq.Add(serializer.Read(reader)); } } public static void Write(DryadLinqBinaryWriter writer, IList<T> seq) { writer.Write(seq.Count); foreach (T elem in seq) { serializer.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out ForkValue<T> val) { val = new ForkValue<T>(); if (reader.ReadBool()) { val.Value = serializer.Read(reader); } } public static void Write(DryadLinqBinaryWriter writer, ForkValue<T> val) { writer.Write(val.HasValue); if (val.HasValue) { serializer.Write(writer, val.Value); } } public static void Read(DryadLinqBinaryReader reader, out AggregateValue<T> aggVal) { long cnt = reader.ReadInt64(); T val = default(T); if (cnt > 0) { val = serializer.Read(reader); } aggVal = new AggregateValue<T>(val, cnt); } public static void Write(DryadLinqBinaryWriter writer, AggregateValue<T> aggVal) { writer.Write(aggVal.Count); if (aggVal.Count > 0) { serializer.Write(writer, aggVal.Value); } } public static void Read(DryadLinqBinaryReader reader, out IndexedValue<T> indexedVal) { int index = reader.ReadInt32(); T val = serializer.Read(reader); indexedVal = new IndexedValue<T>(index, val); } public static void Write(DryadLinqBinaryWriter writer, IndexedValue<T> indexedVal) { writer.Write(indexedVal.Index); serializer.Write(writer, indexedVal.Value); } } public static class DryadLinqSerialization<T1, T2, S1, S2> where S1 : DryadLinqSerializer<T1>, new() where S2 : DryadLinqSerializer<T2>, new() { private static S1 serializer1 = new S1(); private static S2 serializer2 = new S2(); public static void Read(DryadLinqBinaryReader reader, out Dictionary<T1, T2> dict) { int cnt = reader.ReadInt32(); dict = new Dictionary<T1, T2>(cnt); for (int i = 0; i < cnt; i++) { T1 key = serializer1.Read(reader); T2 val = serializer2.Read(reader); dict.Add(key, val); } } public static void Write(DryadLinqBinaryWriter writer, Dictionary<T1, T2> dict) { writer.Write(dict.Count); foreach (KeyValuePair<T1, T2> elem in dict) { serializer1.Write(writer, elem.Key); serializer2.Write(writer, elem.Value); } } public static void Read(DryadLinqBinaryReader reader, out SortedDictionary<T1, T2> dict) { int cnt = reader.ReadInt32(); dict = new SortedDictionary<T1, T2>(); for (int i = 0; i < cnt; i++) { T1 key = serializer1.Read(reader); T2 val = serializer2.Read(reader); dict.Add(key, val); } } public static void Write(DryadLinqBinaryWriter writer, SortedDictionary<T1, T2> dict) { writer.Write(dict.Count); foreach (KeyValuePair<T1, T2> elem in dict) { serializer1.Write(writer, elem.Key); serializer2.Write(writer, elem.Value); } } public static void Read(DryadLinqBinaryReader reader, out SortedList<T1, T2> list) { int cnt = reader.ReadInt32(); list = new SortedList<T1, T2>(cnt); for (int i = 0; i < cnt; i++) { T1 key = serializer1.Read(reader); T2 value = serializer2.Read(reader); list.Add(key, value); } } public static void Write(DryadLinqBinaryWriter writer, SortedList<T1, T2> list) { writer.Write(list.Count); foreach (KeyValuePair<T1, T2> elem in list) { serializer1.Write(writer, elem.Key); serializer2.Write(writer, elem.Value); } } public static void Read(DryadLinqBinaryReader reader, out IGrouping<T1, T2> group) { T1 key = serializer1.Read(reader); int len = reader.ReadInt32(); Grouping<T1, T2> realGroup = new Grouping<T1, T2>(key, len); for (int i = 0; i < len; i++) { realGroup.AddItem(serializer2.Read(reader)); } group = realGroup; } public static void Write(DryadLinqBinaryWriter writer, IGrouping<T1, T2> group) { serializer1.Write(writer, group.Key); writer.Write(group.Count()); foreach (T2 elem in group) { serializer2.Write(writer, elem); } } public static void Read(DryadLinqBinaryReader reader, out KeyValuePair<T1, T2> kv) { T1 key = serializer1.Read(reader); T2 val = serializer2.Read(reader); kv = new KeyValuePair<T1, T2>(key, val); } public static void Write(DryadLinqBinaryWriter writer, KeyValuePair<T1, T2> kv) { serializer1.Write(writer, kv.Key); serializer2.Write(writer, kv.Value); } public static void Read(DryadLinqBinaryReader reader, out Pair<T1, T2> pair) { T1 x = serializer1.Read(reader); T2 y = serializer2.Read(reader); pair = new Pair<T1, T2>(x, y); } public static void Write(DryadLinqBinaryWriter writer, Pair<T1, T2> pair) { serializer1.Write(writer, pair.Key); serializer2.Write(writer, pair.Value); } public static void Read(DryadLinqBinaryReader reader, out ForkTuple<T1, T2> val) { val = new ForkTuple<T1, T2>(); if (reader.ReadBool()) { val.First = serializer1.Read(reader); } if (reader.ReadBool()) { val.Second = serializer2.Read(reader); } } public static void Write(DryadLinqBinaryWriter writer, ForkTuple<T1, T2> val) { writer.Write(val.HasFirst); if (val.HasFirst) { serializer1.Write(writer, val.First); } writer.Write(val.HasSecond); if (val.HasSecond) { serializer2.Write(writer, val.Second); } } public static void Read(DryadLinqBinaryReader reader, out DryadLinqGrouping<T1, T2> group) { T1 key = serializer1.Read(reader); int cnt = reader.ReadInt32(); T2[] elems = new T2[cnt]; for (int i = 0; i < cnt; i++) { elems[i] = serializer2.Read(reader); } group = new DryadLinqGrouping<T1, T2>(key, elems); } public static void Write(DryadLinqBinaryWriter writer, DryadLinqGrouping<T1, T2> group) { serializer1.Write(writer, group.Key); writer.Write(group.Count()); foreach (T2 elem in group) { serializer2.Write(writer, elem); } } } public static class DryadLinqSerialization<T1, T2, T3, S1, S2, S3> where S1 : DryadLinqSerializer<T1>, new() where S2 : DryadLinqSerializer<T2>, new() where S3 : DryadLinqSerializer<T3>, new() { } public sealed class ByteDryadLinqSerializer : DryadLinqSerializer<byte> { public override byte Read(DryadLinqBinaryReader reader) { return reader.ReadUByte(); } public override void Write(DryadLinqBinaryWriter writer, byte x) { writer.Write(x); } } public sealed class SByteDryadLinqSerializer : DryadLinqSerializer<sbyte> { public override sbyte Read(DryadLinqBinaryReader reader) { return reader.ReadSByte(); } public override void Write(DryadLinqBinaryWriter writer, sbyte x) { writer.Write(x); } } public sealed class BoolDryadLinqSerializer : DryadLinqSerializer<bool> { public override bool Read(DryadLinqBinaryReader reader) { return reader.ReadBool(); } public override void Write(DryadLinqBinaryWriter writer, bool x) { writer.Write(x); } } public sealed class CharDryadLinqSerializer : DryadLinqSerializer<char> { public override char Read(DryadLinqBinaryReader reader) { return reader.ReadChar(); } public override void Write(DryadLinqBinaryWriter writer, char x) { writer.Write(x); } } public sealed class Int16DryadLinqSerializer : DryadLinqSerializer<Int16> { public override Int16 Read(DryadLinqBinaryReader reader) { return reader.ReadInt16(); } public override void Write(DryadLinqBinaryWriter writer, Int16 x) { writer.Write(x); } } public sealed class UInt16DryadLinqSerializer : DryadLinqSerializer<UInt16> { public override UInt16 Read(DryadLinqBinaryReader reader) { return reader.ReadUInt16(); } public override void Write(DryadLinqBinaryWriter writer, UInt16 x) { writer.Write(x); } } public sealed class Int32DryadLinqSerializer : DryadLinqSerializer<Int32> { public override Int32 Read(DryadLinqBinaryReader reader) { return reader.ReadInt32(); } public override void Write(DryadLinqBinaryWriter writer, Int32 x) { writer.Write(x); } } public sealed class UInt32DryadLinqSerializer : DryadLinqSerializer<UInt32> { public override UInt32 Read(DryadLinqBinaryReader reader) { return reader.ReadUInt32(); } public override void Write(DryadLinqBinaryWriter writer, UInt32 x) { writer.Write(x); } } public sealed class Int64DryadLinqSerializer : DryadLinqSerializer<Int64> { public override Int64 Read(DryadLinqBinaryReader reader) { return reader.ReadInt64(); } public override void Write(DryadLinqBinaryWriter writer, Int64 x) { writer.Write(x); } } public sealed class UInt64DryadLinqSerializer : DryadLinqSerializer<UInt64> { public override UInt64 Read(DryadLinqBinaryReader reader) { return reader.ReadUInt64(); } public override void Write(DryadLinqBinaryWriter writer, UInt64 x) { writer.Write(x); } } public sealed class SingleDryadLinqSerializer : DryadLinqSerializer<float> { public override float Read(DryadLinqBinaryReader reader) { return reader.ReadSingle(); } public override void Write(DryadLinqBinaryWriter writer, float x) { writer.Write(x); } } public sealed class DoubleDryadLinqSerializer : DryadLinqSerializer<double> { public override double Read(DryadLinqBinaryReader reader) { return reader.ReadDouble(); } public override void Write(DryadLinqBinaryWriter writer, double x) { writer.Write(x); } } public sealed class DecimalDryadLinqSerializer : DryadLinqSerializer<decimal> { public override decimal Read(DryadLinqBinaryReader reader) { return reader.ReadDecimal(); } public override void Write(DryadLinqBinaryWriter writer, decimal x) { writer.Write(x); } } public sealed class DateTimeDryadLinqSerializer : DryadLinqSerializer<DateTime> { public override DateTime Read(DryadLinqBinaryReader reader) { return reader.ReadDateTime(); } public override void Write(DryadLinqBinaryWriter writer, DateTime x) { writer.Write(x); } } public sealed class StringDryadLinqSerializer : DryadLinqSerializer<string> { public override string Read(DryadLinqBinaryReader reader) { return reader.ReadString(); } public override void Write(DryadLinqBinaryWriter writer, string x) { writer.Write(x); } } public sealed class GuidDryadLinqSerializer : DryadLinqSerializer<Guid> { public override Guid Read(DryadLinqBinaryReader reader) { return reader.ReadGuid(); } public override void Write(DryadLinqBinaryWriter writer, Guid x) { writer.Write(x); } } public sealed class SqlDateTimeDryadLinqSerializer : DryadLinqSerializer<SqlDateTime> { public override SqlDateTime Read(DryadLinqBinaryReader reader) { return reader.ReadSqlDateTime(); } public override void Write(DryadLinqBinaryWriter writer, SqlDateTime x) { writer.Write(x); } } public sealed class LineRecordDryadLinqSerializer : DryadLinqSerializer<LineRecord> { public override LineRecord Read(DryadLinqBinaryReader reader) { string line = reader.ReadString(); return new LineRecord(line); } public override void Write(DryadLinqBinaryWriter writer, LineRecord x) { writer.Write(x.Line); } } }
using System.Collections.Generic; using System.Xml.Linq; namespace WixSharp { /// <summary> /// /// </summary> /// <seealso cref="WixSharp.Feature" /> public partial class FeatureSet : Feature { /// <summary> /// Creates <see cref="FeatureSet"/> from the specified <see cref="Feature"/> items. /// </summary> /// <param name="features">The features.</param> /// <returns></returns> public static FeatureSet Of(params Feature[] features) => new FeatureSet(features); /// <summary> /// Initializes a new instance of the <see cref="FeatureSet"/> class. /// </summary> /// <param name="features">The features.</param> public FeatureSet(params Feature[] features) => Items = features; /// <summary> /// The embedded <see cref="Feature"/> items. /// </summary> public Feature[] Items; } /// <summary> /// Defines WiX Feature. /// <para> /// All installable WiX components belong to one or more features. By default, if no <see cref="Feature"/>s are defined by user, Wix# creates "Complete" /// feature, which contains all installable components. /// </para> /// </summary> /// <example> /// <list type="bullet"> /// /// <item> /// <description>The example of defining <see cref="Feature"/>s explicitly: /// <code> /// Feature binaries = new Feature("My Product Binaries"); /// Feature docs = new Feature("My Product Documentation"); /// /// var project = /// new Project("My Product", /// new Dir(@"%ProgramFiles%\My Company\My Product", /// new File(binaries, @"AppFiles\MyApp.exe", /// ... /// </code> /// </description> /// </item> /// /// <item> /// <description>The example of defining nested features . /// <code> /// Feature binaries = new Feature("My Product Binaries"); /// Feature docs = new Feature("My Product Documentation"); /// Feature docViewers = new Feature("Documentation viewers"); /// docs.Children.Add(docViewers); /// ... /// </code> /// </description> /// </item> /// /// <item> /// <description>The example of defining "Complete" <see cref="Feature"/> implicitly. /// Note <see cref="File"/> constructor does not use <see cref="Feature"/> argument. /// <code> /// var project = /// new Project("My Product", /// new Dir(@"%ProgramFiles%\My Company\My Product", /// new File(@"AppFiles\MyApp.exe", /// ... /// </code> /// </description> /// </item> /// </list> /// </example> public partial class Feature : WixEntity { /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class. /// </summary> public Feature() { } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> public Feature(string name) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> public Feature(string name, string description) : this(name) { Description = description; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> public Feature(string name, bool isEnabled) : this(name) { IsEnabled = isEnabled; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> public Feature(string name, string description, bool isEnabled) : this(name) { Description = description; IsEnabled = isEnabled; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> /// <param name="allowChange">Defines if setup allows the user interface to display an option to change the <see cref="Feature"/> state to Absent.</param> public Feature(string name, string description, bool isEnabled, bool allowChange) : this(name, description, isEnabled) { AllowChange = allowChange; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> /// <param name="allowChange">Defines if setup allows the user interface to display an option to change the <see cref="Feature"/> state to Absent.</param> public Feature(string name, bool isEnabled, bool allowChange) : this(name, isEnabled) { AllowChange = allowChange; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> /// <param name="configurableDir">The default path of the feature <c>ConfigurableDirectory</c>. If set to non-empty string, MSI runtime will place /// <c>Configure</c> button for the feature in the <c>Feature Selection</c> dialog.</param> public Feature(string name, string description, string configurableDir) : this(name, description) { ConfigurableDir = configurableDir; } /// <summary> /// Initializes a new instance of the <see cref="Feature"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">The feature name.</param> /// <param name="description">The feature description.</param> /// <param name="isEnabled">Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input.</param> /// <param name="allowChange">Defines if setup allows the user interface to display an option to change the <see cref="Feature"/> state to Absent.</param> /// <param name="configurableDir">The default path of the feature <c>ConfigurableDirectory</c>. If set to non-empty string, MSI runtime will place /// <c>Configure</c> button for the feature in the <c>Feature Selection</c> dialog.</param> public Feature(string name, string description, bool isEnabled, bool allowChange, string configurableDir) : this(name, description, isEnabled) { AllowChange = allowChange; ConfigurableDir = configurableDir; } /// <summary> /// <para> /// Defines if the <see cref="Feature"/> is enabled at startup. /// Use this parameter if the feature should be disabled by default and only enabled after /// processing the <c>Condition Table</c> or user input. /// </para> /// The default value is <c>true</c>. /// </summary> public bool IsEnabled = true; /// <summary> /// <para> /// Defines if setup allows the user interface to display an option to change the <see cref="Feature"/> state to Absent. /// </para> /// <para>This property is translated into WiX Feature.Absent attribute.</para> /// The default value is <c>true</c>. /// </summary> public bool AllowChange = true; /// <summary> /// The feature description. /// </summary> public string Description = ""; /// <summary> /// The default path of the feature <c>ConfigurableDirectory</c>. If set to non-empty string, MSI runtime will place /// <c>Configure</c> button for the feature in the <c>Feature Selection</c> dialog. /// <para>Specify the Id of a Directory that can be configured by the user at installation /// time. This identifier must be a public property and therefore completely uppercase. </para> /// </summary> public string ConfigurableDir = ""; internal Feature Parent; /// <summary> /// Child <see cref="Feature"/>. To be added in the nested Features scenarios. /// </summary> public List<Feature> Children = new List<Feature>(); /// <summary> /// Adds the specified nested features. /// </summary> /// <param name="features">The features.</param> /// <returns></returns> public Feature Add(params Feature[] features) { Children.AddRange(features); features.ForEach(x => x.Parent = this); return this; } /// <summary> /// Defines the installation <see cref="Condition"/>, which is to be checked during the installation to /// determine if the feature should be installed on the target system. /// </summary> public FeatureCondition Condition = null; /// <summary> /// Determines the initial display of this feature in the feature tree. /// </summary> public FeatureDisplay? Display; /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { return Name; } internal XElement ToXml() { var element = new XElement("Feature"); element.SetAttribute("Id", Id) .SetAttribute("Title", Name) .SetAttribute("Absent", AllowChange ? "allow" : "disallow") .SetAttribute("Level", IsEnabled ? "1" : "2") .SetAttribute("Description", Description) .SetAttribute("Display", Display) .SetAttribute("ConfigurableDirectory", ConfigurableDir) .AddAttributes(Attributes); if (Condition != null) element.Add( //intentionally leaving out AddAttributes(...) as Level is the only valid attribute on */Feature/Condition new XElement("Condition", new XAttribute("Level", Condition.Level), new XCData(Condition.ToCData()))); return element; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace NorthwindRepository{ /// <summary> /// Strongly-typed collection for the Invoice class. /// </summary> [Serializable] public partial class InvoiceCollection : ReadOnlyList<Invoice, InvoiceCollection> { public InvoiceCollection() {} } /// <summary> /// This is Read-only wrapper class for the Invoices view. /// </summary> [Serializable] public partial class Invoice : ReadOnlyRecord<Invoice>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Invoices", TableType.View, DataService.GetInstance("NorthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarShipName = new TableSchema.TableColumn(schema); colvarShipName.ColumnName = "ShipName"; colvarShipName.DataType = DbType.String; colvarShipName.MaxLength = 40; colvarShipName.AutoIncrement = false; colvarShipName.IsNullable = true; colvarShipName.IsPrimaryKey = false; colvarShipName.IsForeignKey = false; colvarShipName.IsReadOnly = false; schema.Columns.Add(colvarShipName); TableSchema.TableColumn colvarShipAddress = new TableSchema.TableColumn(schema); colvarShipAddress.ColumnName = "ShipAddress"; colvarShipAddress.DataType = DbType.String; colvarShipAddress.MaxLength = 60; colvarShipAddress.AutoIncrement = false; colvarShipAddress.IsNullable = true; colvarShipAddress.IsPrimaryKey = false; colvarShipAddress.IsForeignKey = false; colvarShipAddress.IsReadOnly = false; schema.Columns.Add(colvarShipAddress); TableSchema.TableColumn colvarShipCity = new TableSchema.TableColumn(schema); colvarShipCity.ColumnName = "ShipCity"; colvarShipCity.DataType = DbType.String; colvarShipCity.MaxLength = 15; colvarShipCity.AutoIncrement = false; colvarShipCity.IsNullable = true; colvarShipCity.IsPrimaryKey = false; colvarShipCity.IsForeignKey = false; colvarShipCity.IsReadOnly = false; schema.Columns.Add(colvarShipCity); TableSchema.TableColumn colvarShipRegion = new TableSchema.TableColumn(schema); colvarShipRegion.ColumnName = "ShipRegion"; colvarShipRegion.DataType = DbType.String; colvarShipRegion.MaxLength = 15; colvarShipRegion.AutoIncrement = false; colvarShipRegion.IsNullable = true; colvarShipRegion.IsPrimaryKey = false; colvarShipRegion.IsForeignKey = false; colvarShipRegion.IsReadOnly = false; schema.Columns.Add(colvarShipRegion); TableSchema.TableColumn colvarShipPostalCode = new TableSchema.TableColumn(schema); colvarShipPostalCode.ColumnName = "ShipPostalCode"; colvarShipPostalCode.DataType = DbType.String; colvarShipPostalCode.MaxLength = 10; colvarShipPostalCode.AutoIncrement = false; colvarShipPostalCode.IsNullable = true; colvarShipPostalCode.IsPrimaryKey = false; colvarShipPostalCode.IsForeignKey = false; colvarShipPostalCode.IsReadOnly = false; schema.Columns.Add(colvarShipPostalCode); TableSchema.TableColumn colvarShipCountry = new TableSchema.TableColumn(schema); colvarShipCountry.ColumnName = "ShipCountry"; colvarShipCountry.DataType = DbType.String; colvarShipCountry.MaxLength = 15; colvarShipCountry.AutoIncrement = false; colvarShipCountry.IsNullable = true; colvarShipCountry.IsPrimaryKey = false; colvarShipCountry.IsForeignKey = false; colvarShipCountry.IsReadOnly = false; schema.Columns.Add(colvarShipCountry); TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema); colvarCustomerID.ColumnName = "CustomerID"; colvarCustomerID.DataType = DbType.String; colvarCustomerID.MaxLength = 5; colvarCustomerID.AutoIncrement = false; colvarCustomerID.IsNullable = true; colvarCustomerID.IsPrimaryKey = false; colvarCustomerID.IsForeignKey = false; colvarCustomerID.IsReadOnly = false; schema.Columns.Add(colvarCustomerID); TableSchema.TableColumn colvarCustomerName = new TableSchema.TableColumn(schema); colvarCustomerName.ColumnName = "CustomerName"; colvarCustomerName.DataType = DbType.String; colvarCustomerName.MaxLength = 40; colvarCustomerName.AutoIncrement = false; colvarCustomerName.IsNullable = false; colvarCustomerName.IsPrimaryKey = false; colvarCustomerName.IsForeignKey = false; colvarCustomerName.IsReadOnly = false; schema.Columns.Add(colvarCustomerName); TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema); colvarAddress.ColumnName = "Address"; colvarAddress.DataType = DbType.String; colvarAddress.MaxLength = 60; colvarAddress.AutoIncrement = false; colvarAddress.IsNullable = true; colvarAddress.IsPrimaryKey = false; colvarAddress.IsForeignKey = false; colvarAddress.IsReadOnly = false; schema.Columns.Add(colvarAddress); TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema); colvarRegion.ColumnName = "Region"; colvarRegion.DataType = DbType.String; colvarRegion.MaxLength = 15; colvarRegion.AutoIncrement = false; colvarRegion.IsNullable = true; colvarRegion.IsPrimaryKey = false; colvarRegion.IsForeignKey = false; colvarRegion.IsReadOnly = false; schema.Columns.Add(colvarRegion); TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema); colvarPostalCode.ColumnName = "PostalCode"; colvarPostalCode.DataType = DbType.String; colvarPostalCode.MaxLength = 10; colvarPostalCode.AutoIncrement = false; colvarPostalCode.IsNullable = true; colvarPostalCode.IsPrimaryKey = false; colvarPostalCode.IsForeignKey = false; colvarPostalCode.IsReadOnly = false; schema.Columns.Add(colvarPostalCode); TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema); colvarCountry.ColumnName = "Country"; colvarCountry.DataType = DbType.String; colvarCountry.MaxLength = 15; colvarCountry.AutoIncrement = false; colvarCountry.IsNullable = true; colvarCountry.IsPrimaryKey = false; colvarCountry.IsForeignKey = false; colvarCountry.IsReadOnly = false; schema.Columns.Add(colvarCountry); TableSchema.TableColumn colvarSalesperson = new TableSchema.TableColumn(schema); colvarSalesperson.ColumnName = "Salesperson"; colvarSalesperson.DataType = DbType.String; colvarSalesperson.MaxLength = 31; colvarSalesperson.AutoIncrement = false; colvarSalesperson.IsNullable = false; colvarSalesperson.IsPrimaryKey = false; colvarSalesperson.IsForeignKey = false; colvarSalesperson.IsReadOnly = false; schema.Columns.Add(colvarSalesperson); TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema); colvarOrderID.ColumnName = "OrderID"; colvarOrderID.DataType = DbType.Int32; colvarOrderID.MaxLength = 0; colvarOrderID.AutoIncrement = false; colvarOrderID.IsNullable = false; colvarOrderID.IsPrimaryKey = false; colvarOrderID.IsForeignKey = false; colvarOrderID.IsReadOnly = false; schema.Columns.Add(colvarOrderID); TableSchema.TableColumn colvarOrderDate = new TableSchema.TableColumn(schema); colvarOrderDate.ColumnName = "OrderDate"; colvarOrderDate.DataType = DbType.DateTime; colvarOrderDate.MaxLength = 0; colvarOrderDate.AutoIncrement = false; colvarOrderDate.IsNullable = true; colvarOrderDate.IsPrimaryKey = false; colvarOrderDate.IsForeignKey = false; colvarOrderDate.IsReadOnly = false; schema.Columns.Add(colvarOrderDate); TableSchema.TableColumn colvarRequiredDate = new TableSchema.TableColumn(schema); colvarRequiredDate.ColumnName = "RequiredDate"; colvarRequiredDate.DataType = DbType.DateTime; colvarRequiredDate.MaxLength = 0; colvarRequiredDate.AutoIncrement = false; colvarRequiredDate.IsNullable = true; colvarRequiredDate.IsPrimaryKey = false; colvarRequiredDate.IsForeignKey = false; colvarRequiredDate.IsReadOnly = false; schema.Columns.Add(colvarRequiredDate); TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema); colvarShippedDate.ColumnName = "ShippedDate"; colvarShippedDate.DataType = DbType.DateTime; colvarShippedDate.MaxLength = 0; colvarShippedDate.AutoIncrement = false; colvarShippedDate.IsNullable = true; colvarShippedDate.IsPrimaryKey = false; colvarShippedDate.IsForeignKey = false; colvarShippedDate.IsReadOnly = false; schema.Columns.Add(colvarShippedDate); TableSchema.TableColumn colvarShipperName = new TableSchema.TableColumn(schema); colvarShipperName.ColumnName = "ShipperName"; colvarShipperName.DataType = DbType.String; colvarShipperName.MaxLength = 40; colvarShipperName.AutoIncrement = false; colvarShipperName.IsNullable = false; colvarShipperName.IsPrimaryKey = false; colvarShipperName.IsForeignKey = false; colvarShipperName.IsReadOnly = false; schema.Columns.Add(colvarShipperName); TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema); colvarProductID.ColumnName = "ProductID"; colvarProductID.DataType = DbType.Int32; colvarProductID.MaxLength = 0; colvarProductID.AutoIncrement = false; colvarProductID.IsNullable = false; colvarProductID.IsPrimaryKey = false; colvarProductID.IsForeignKey = false; colvarProductID.IsReadOnly = false; schema.Columns.Add(colvarProductID); TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema); colvarProductName.ColumnName = "ProductName"; colvarProductName.DataType = DbType.String; colvarProductName.MaxLength = 40; colvarProductName.AutoIncrement = false; colvarProductName.IsNullable = false; colvarProductName.IsPrimaryKey = false; colvarProductName.IsForeignKey = false; colvarProductName.IsReadOnly = false; schema.Columns.Add(colvarProductName); TableSchema.TableColumn colvarUnitPrice = new TableSchema.TableColumn(schema); colvarUnitPrice.ColumnName = "UnitPrice"; colvarUnitPrice.DataType = DbType.Currency; colvarUnitPrice.MaxLength = 0; colvarUnitPrice.AutoIncrement = false; colvarUnitPrice.IsNullable = false; colvarUnitPrice.IsPrimaryKey = false; colvarUnitPrice.IsForeignKey = false; colvarUnitPrice.IsReadOnly = false; schema.Columns.Add(colvarUnitPrice); TableSchema.TableColumn colvarQuantity = new TableSchema.TableColumn(schema); colvarQuantity.ColumnName = "Quantity"; colvarQuantity.DataType = DbType.Int16; colvarQuantity.MaxLength = 0; colvarQuantity.AutoIncrement = false; colvarQuantity.IsNullable = false; colvarQuantity.IsPrimaryKey = false; colvarQuantity.IsForeignKey = false; colvarQuantity.IsReadOnly = false; schema.Columns.Add(colvarQuantity); TableSchema.TableColumn colvarDiscount = new TableSchema.TableColumn(schema); colvarDiscount.ColumnName = "Discount"; colvarDiscount.DataType = DbType.Single; colvarDiscount.MaxLength = 0; colvarDiscount.AutoIncrement = false; colvarDiscount.IsNullable = false; colvarDiscount.IsPrimaryKey = false; colvarDiscount.IsForeignKey = false; colvarDiscount.IsReadOnly = false; schema.Columns.Add(colvarDiscount); TableSchema.TableColumn colvarExtendedPrice = new TableSchema.TableColumn(schema); colvarExtendedPrice.ColumnName = "ExtendedPrice"; colvarExtendedPrice.DataType = DbType.Currency; colvarExtendedPrice.MaxLength = 0; colvarExtendedPrice.AutoIncrement = false; colvarExtendedPrice.IsNullable = true; colvarExtendedPrice.IsPrimaryKey = false; colvarExtendedPrice.IsForeignKey = false; colvarExtendedPrice.IsReadOnly = false; schema.Columns.Add(colvarExtendedPrice); TableSchema.TableColumn colvarFreight = new TableSchema.TableColumn(schema); colvarFreight.ColumnName = "Freight"; colvarFreight.DataType = DbType.Currency; colvarFreight.MaxLength = 0; colvarFreight.AutoIncrement = false; colvarFreight.IsNullable = true; colvarFreight.IsPrimaryKey = false; colvarFreight.IsForeignKey = false; colvarFreight.IsReadOnly = false; schema.Columns.Add(colvarFreight); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["NorthwindRepository"].AddSchema("Invoices",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public Invoice() { SetSQLProps(); SetDefaults(); MarkNew(); } public Invoice(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public Invoice(object keyID) { SetSQLProps(); LoadByKey(keyID); } public Invoice(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("ShipName")] [Bindable(true)] public string ShipName { get { return GetColumnValue<string>("ShipName"); } set { SetColumnValue("ShipName", value); } } [XmlAttribute("ShipAddress")] [Bindable(true)] public string ShipAddress { get { return GetColumnValue<string>("ShipAddress"); } set { SetColumnValue("ShipAddress", value); } } [XmlAttribute("ShipCity")] [Bindable(true)] public string ShipCity { get { return GetColumnValue<string>("ShipCity"); } set { SetColumnValue("ShipCity", value); } } [XmlAttribute("ShipRegion")] [Bindable(true)] public string ShipRegion { get { return GetColumnValue<string>("ShipRegion"); } set { SetColumnValue("ShipRegion", value); } } [XmlAttribute("ShipPostalCode")] [Bindable(true)] public string ShipPostalCode { get { return GetColumnValue<string>("ShipPostalCode"); } set { SetColumnValue("ShipPostalCode", value); } } [XmlAttribute("ShipCountry")] [Bindable(true)] public string ShipCountry { get { return GetColumnValue<string>("ShipCountry"); } set { SetColumnValue("ShipCountry", value); } } [XmlAttribute("CustomerID")] [Bindable(true)] public string CustomerID { get { return GetColumnValue<string>("CustomerID"); } set { SetColumnValue("CustomerID", value); } } [XmlAttribute("CustomerName")] [Bindable(true)] public string CustomerName { get { return GetColumnValue<string>("CustomerName"); } set { SetColumnValue("CustomerName", value); } } [XmlAttribute("Address")] [Bindable(true)] public string Address { get { return GetColumnValue<string>("Address"); } set { SetColumnValue("Address", value); } } [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>("City"); } set { SetColumnValue("City", value); } } [XmlAttribute("Region")] [Bindable(true)] public string Region { get { return GetColumnValue<string>("Region"); } set { SetColumnValue("Region", value); } } [XmlAttribute("PostalCode")] [Bindable(true)] public string PostalCode { get { return GetColumnValue<string>("PostalCode"); } set { SetColumnValue("PostalCode", value); } } [XmlAttribute("Country")] [Bindable(true)] public string Country { get { return GetColumnValue<string>("Country"); } set { SetColumnValue("Country", value); } } [XmlAttribute("Salesperson")] [Bindable(true)] public string Salesperson { get { return GetColumnValue<string>("Salesperson"); } set { SetColumnValue("Salesperson", value); } } [XmlAttribute("OrderID")] [Bindable(true)] public int OrderID { get { return GetColumnValue<int>("OrderID"); } set { SetColumnValue("OrderID", value); } } [XmlAttribute("OrderDate")] [Bindable(true)] public DateTime? OrderDate { get { return GetColumnValue<DateTime?>("OrderDate"); } set { SetColumnValue("OrderDate", value); } } [XmlAttribute("RequiredDate")] [Bindable(true)] public DateTime? RequiredDate { get { return GetColumnValue<DateTime?>("RequiredDate"); } set { SetColumnValue("RequiredDate", value); } } [XmlAttribute("ShippedDate")] [Bindable(true)] public DateTime? ShippedDate { get { return GetColumnValue<DateTime?>("ShippedDate"); } set { SetColumnValue("ShippedDate", value); } } [XmlAttribute("ShipperName")] [Bindable(true)] public string ShipperName { get { return GetColumnValue<string>("ShipperName"); } set { SetColumnValue("ShipperName", value); } } [XmlAttribute("ProductID")] [Bindable(true)] public int ProductID { get { return GetColumnValue<int>("ProductID"); } set { SetColumnValue("ProductID", value); } } [XmlAttribute("ProductName")] [Bindable(true)] public string ProductName { get { return GetColumnValue<string>("ProductName"); } set { SetColumnValue("ProductName", value); } } [XmlAttribute("UnitPrice")] [Bindable(true)] public decimal UnitPrice { get { return GetColumnValue<decimal>("UnitPrice"); } set { SetColumnValue("UnitPrice", value); } } [XmlAttribute("Quantity")] [Bindable(true)] public short Quantity { get { return GetColumnValue<short>("Quantity"); } set { SetColumnValue("Quantity", value); } } [XmlAttribute("Discount")] [Bindable(true)] public float Discount { get { return GetColumnValue<float>("Discount"); } set { SetColumnValue("Discount", value); } } [XmlAttribute("ExtendedPrice")] [Bindable(true)] public decimal? ExtendedPrice { get { return GetColumnValue<decimal?>("ExtendedPrice"); } set { SetColumnValue("ExtendedPrice", value); } } [XmlAttribute("Freight")] [Bindable(true)] public decimal? Freight { get { return GetColumnValue<decimal?>("Freight"); } set { SetColumnValue("Freight", value); } } #endregion #region Columns Struct public struct Columns { public static string ShipName = @"ShipName"; public static string ShipAddress = @"ShipAddress"; public static string ShipCity = @"ShipCity"; public static string ShipRegion = @"ShipRegion"; public static string ShipPostalCode = @"ShipPostalCode"; public static string ShipCountry = @"ShipCountry"; public static string CustomerID = @"CustomerID"; public static string CustomerName = @"CustomerName"; public static string Address = @"Address"; public static string City = @"City"; public static string Region = @"Region"; public static string PostalCode = @"PostalCode"; public static string Country = @"Country"; public static string Salesperson = @"Salesperson"; public static string OrderID = @"OrderID"; public static string OrderDate = @"OrderDate"; public static string RequiredDate = @"RequiredDate"; public static string ShippedDate = @"ShippedDate"; public static string ShipperName = @"ShipperName"; public static string ProductID = @"ProductID"; public static string ProductName = @"ProductName"; public static string UnitPrice = @"UnitPrice"; public static string Quantity = @"Quantity"; public static string Discount = @"Discount"; public static string ExtendedPrice = @"ExtendedPrice"; public static string Freight = @"Freight"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// 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. // The RegexReplacement class represents a substitution string for // use when using regexes to search/replace, etc. It's logically // a sequence intermixed (1) constant strings and (2) group numbers. using System.Collections; using System.Collections.Generic; using System.IO; namespace System.Text.RegularExpressions { internal sealed class RegexReplacement { // Constants for special insertion patterns internal const int Specials = 4; internal const int LeftPortion = -1; internal const int RightPortion = -2; internal const int LastGroup = -3; internal const int WholeString = -4; private readonly string _rep; private readonly List<string> _strings; // table of string constants private readonly List<int> _rules; // negative -> group #, positive -> string # /// <summary> /// Since RegexReplacement shares the same parser as Regex, /// the constructor takes a RegexNode which is a concatenation /// of constant strings and backreferences. /// </summary> internal RegexReplacement(string rep, RegexNode concat, Hashtable _caps) { if (concat.Type() != RegexNode.Concatenate) throw new ArgumentException(SR.ReplacementError); StringBuilder sb = StringBuilderCache.Acquire(); List<string> strings = new List<string>(); List<int> rules = new List<int>(); for (int i = 0; i < concat.ChildCount(); i++) { RegexNode child = concat.Child(i); switch (child.Type()) { case RegexNode.Multi: sb.Append(child._str); break; case RegexNode.One: sb.Append(child._ch); break; case RegexNode.Ref: if (sb.Length > 0) { rules.Add(strings.Count); strings.Add(sb.ToString()); sb.Length = 0; } int slot = child._m; if (_caps != null && slot >= 0) slot = (int)_caps[slot]; rules.Add(-Specials - 1 - slot); break; default: throw new ArgumentException(SR.ReplacementError); } } if (sb.Length > 0) { rules.Add(strings.Count); strings.Add(sb.ToString()); } StringBuilderCache.Release(sb); _rep = rep; _strings = strings; _rules = rules; } /// <summary> /// Given a Match, emits into the StringBuilder the evaluated /// substitution pattern. /// </summary> private void ReplacementImpl(StringBuilder sb, Match match) { for (int i = 0; i < _rules.Count; i++) { int r = _rules[i]; if (r >= 0) // string lookup sb.Append(_strings[r]); else if (r < -Specials) // group lookup sb.Append(match.GroupToStringImpl(-Specials - 1 - r)); else { switch (-Specials - 1 - r) { // special insertion patterns case LeftPortion: sb.Append(match.GetLeftSubstring()); break; case RightPortion: sb.Append(match.GetRightSubstring()); break; case LastGroup: sb.Append(match.LastGroupToStringImpl()); break; case WholeString: sb.Append(match.GetOriginalString()); break; } } } } /// <summary> /// Given a Match, emits into the List<string> the evaluated /// Right-to-Left substitution pattern. /// </summary> private void ReplacementImplRTL(List<string> al, Match match) { for (int i = _rules.Count - 1; i >= 0; i--) { int r = _rules[i]; if (r >= 0) // string lookup al.Add(_strings[r]); else if (r < -Specials) // group lookup al.Add(match.GroupToStringImpl(-Specials - 1 - r)); else { switch (-Specials - 1 - r) { // special insertion patterns case LeftPortion: al.Add(match.GetLeftSubstring()); break; case RightPortion: al.Add(match.GetRightSubstring()); break; case LastGroup: al.Add(match.LastGroupToStringImpl()); break; case WholeString: al.Add(match.GetOriginalString()); break; } } } } /// <summary> /// The original pattern string /// </summary> internal string Pattern { get { return _rep; } } /// <summary> /// Returns the replacement result for a single match /// </summary> internal string Replacement(Match match) { StringBuilder sb = StringBuilderCache.Acquire(); ReplacementImpl(sb, match); return StringBuilderCache.GetStringAndRelease(sb); } // Three very similar algorithms appear below: replace (pattern), // replace (evaluator), and split. /// <summary> /// Replaces all occurrences of the regex in the string with the /// replacement pattern. /// /// Note that the special case of no matches is handled on its own: /// with no matches, the input string is returned unchanged. /// The right-to-left case is split out because StringBuilder /// doesn't handle right-to-left string building directly very well. /// </summary> internal string Replace(Regex regex, string input, int count, int startat) { if (count < -1) throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall); if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative); if (count == 0) return input; Match match = regex.Match(input, startat); if (!match.Success) { return input; } else { StringBuilder sb = StringBuilderCache.Acquire(); if (!regex.RightToLeft) { int prevat = 0; do { if (match.Index != prevat) sb.Append(input, prevat, match.Index - prevat); prevat = match.Index + match.Length; ReplacementImpl(sb, match); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) sb.Append(input, prevat, input.Length - prevat); } else { List<string> al = new List<string>(); int prevat = input.Length; do { if (match.Index + match.Length != prevat) al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); prevat = match.Index; ReplacementImplRTL(al, match); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat > 0) sb.Append(input, 0, prevat); for (int i = al.Count - 1; i >= 0; i--) { sb.Append(al[i]); } } return StringBuilderCache.GetStringAndRelease(sb); } } /// <summary> /// Replaces all occurrences of the regex in the string with the /// replacement evaluator. /// /// Note that the special case of no matches is handled on its own: /// with no matches, the input string is returned unchanged. /// The right-to-left case is split out because StringBuilder /// doesn't handle right-to-left string building directly very well. /// </summary> internal static string Replace(MatchEvaluator evaluator, Regex regex, string input, int count, int startat) { if (evaluator == null) throw new ArgumentNullException(nameof(evaluator)); if (count < -1) throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall); if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative); if (count == 0) return input; Match match = regex.Match(input, startat); if (!match.Success) { return input; } else { StringBuilder sb = StringBuilderCache.Acquire(); if (!regex.RightToLeft) { int prevat = 0; do { if (match.Index != prevat) sb.Append(input, prevat, match.Index - prevat); prevat = match.Index + match.Length; sb.Append(evaluator(match)); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat < input.Length) sb.Append(input, prevat, input.Length - prevat); } else { List<string> al = new List<string>(); int prevat = input.Length; do { if (match.Index + match.Length != prevat) al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); prevat = match.Index; al.Add(evaluator(match)); if (--count == 0) break; match = match.NextMatch(); } while (match.Success); if (prevat > 0) sb.Append(input, 0, prevat); for (int i = al.Count - 1; i >= 0; i--) { sb.Append(al[i]); } } return StringBuilderCache.GetStringAndRelease(sb); } } /// <summary> /// Does a split. In the right-to-left case we reorder the /// array to be forwards. /// </summary> internal static string[] Split(Regex regex, string input, int count, int startat) { if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.CountTooSmall); if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative); string[] result; if (count == 1) { result = new string[1]; result[0] = input; return result; } count -= 1; Match match = regex.Match(input, startat); if (!match.Success) { result = new string[1]; result[0] = input; return result; } else { List<string> al = new List<string>(); if (!regex.RightToLeft) { int prevat = 0; for (; ;) { al.Add(input.Substring(prevat, match.Index - prevat)); prevat = match.Index + match.Length; // add all matched capture groups to the list. for (int i = 1; i < match.Groups.Count; i++) { if (match.IsMatched(i)) al.Add(match.Groups[i].ToString()); } if (--count == 0) break; match = match.NextMatch(); if (!match.Success) break; } al.Add(input.Substring(prevat, input.Length - prevat)); } else { int prevat = input.Length; for (; ;) { al.Add(input.Substring(match.Index + match.Length, prevat - match.Index - match.Length)); prevat = match.Index; // add all matched capture groups to the list. for (int i = 1; i < match.Groups.Count; i++) { if (match.IsMatched(i)) al.Add(match.Groups[i].ToString()); } if (--count == 0) break; match = match.NextMatch(); if (!match.Success) break; } al.Add(input.Substring(0, prevat)); al.Reverse(0, al.Count); } return al.ToArray(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForIndexersTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) => new Tuple<DiagnosticAnalyzer, CodeFixProvider>( new UseExpressionBodyForIndexersDiagnosticAnalyzer(), new UseExpressionBodyForIndexersCodeFixProvider()); private static readonly Dictionary<OptionKey, object> UseExpressionBody = new Dictionary<OptionKey, object> { { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CodeStyleOptions.TrueWithNoneEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.FalseWithNoneEnforcement }, }; private static readonly Dictionary<OptionKey, object> UseBlockBody = new Dictionary<OptionKey, object> { { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CodeStyleOptions.FalseWithNoneEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.FalseWithNoneEnforcement } }; private static readonly Dictionary<OptionKey, object> UseBlockBodyExceptAccessor = new Dictionary<OptionKey, object> { { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CodeStyleOptions.FalseWithNoneEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.TrueWithNoneEnforcement } }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { await TestAsync( @"class C { int this[int i] { get { [|return|] Bar(); } } }", @"class C { int this[int i] => Bar(); }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithSetter() { await TestMissingAsync( @"class C { int this[int i] { get { [|return|] Bar(); } set { } } }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingOnSetter1() { await TestMissingAsync( @"class C { int this[int i] { set { [|Bar|](); } } }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { await TestAsync( @"class C { int this[int i] { get { [|throw|] new NotImplementedException(); } } }", @"class C { int this[int i] => throw new NotImplementedException(); }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { await TestAsync( @"class C { int this[int i] { get { [|throw|] new NotImplementedException(); // comment } } }", @"class C { int this[int i] => throw new NotImplementedException(); // comment }", compareTokens: false, options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { await TestAsync( @"class C { int this[int i] [|=>|] Bar(); }", @"class C { int this[int i] { get { return Bar(); } } }", options: UseBlockBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyIfAccessorWantExpression1() { await TestAsync( @"class C { int this[int i] [|=>|] Bar(); }", @"class C { int this[int i] { get => Bar(); } }", options: UseBlockBodyExceptAccessor); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { await TestAsync( @"class C { int this[int i] [|=>|] throw new NotImplementedException(); }", @"class C { int this[int i] { get { throw new NotImplementedException(); } } }", options: UseBlockBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { await TestAsync( @"class C { int this[int i] [|=>|] throw new NotImplementedException(); // comment }", @"class C { int this[int i] { get { throw new NotImplementedException(); // comment } } }", compareTokens: false, options: UseBlockBody); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.Linq.Expressions.Interpreter { internal abstract class OffsetInstruction : Instruction { internal const int Unknown = Int32.MinValue; internal const int CacheSize = 32; // the offset to jump to (relative to this instruction): protected int _offset = Unknown; public abstract Instruction[] Cache { get; } public Instruction Fixup(int offset) { Debug.Assert(_offset == Unknown && offset != Unknown); _offset = offset; var cache = Cache; if (cache != null && offset >= 0 && offset < cache.Length) { return cache[offset] ?? (cache[offset] = this); } return this; } public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) { return ToString() + (_offset != Unknown ? " -> " + (instructionIndex + _offset) : ""); } public override string ToString() { return InstructionName + (_offset == Unknown ? "(?)" : "(" + _offset + ")"); } } internal sealed class BranchFalseInstruction : OffsetInstruction { private static Instruction[] s_cache; public override string InstructionName { get { return "BranchFalse"; } } public override Instruction[] Cache { get { if (s_cache == null) { s_cache = new Instruction[CacheSize]; } return s_cache; } } internal BranchFalseInstruction() { } public override int ConsumedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); if (!(bool)frame.Pop()) { return _offset; } return +1; } } internal sealed class BranchTrueInstruction : OffsetInstruction { private static Instruction[] s_cache; public override string InstructionName { get { return "BranchTrue"; } } public override Instruction[] Cache { get { if (s_cache == null) { s_cache = new Instruction[CacheSize]; } return s_cache; } } internal BranchTrueInstruction() { } public override int ConsumedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); if ((bool)frame.Pop()) { return _offset; } return +1; } } internal sealed class CoalescingBranchInstruction : OffsetInstruction { private static Instruction[] s_cache; public override string InstructionName { get { return "CoalescingBranch"; } } public override Instruction[] Cache { get { if (s_cache == null) { s_cache = new Instruction[CacheSize]; } return s_cache; } } internal CoalescingBranchInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); if (frame.Peek() != null) { return _offset; } return +1; } } internal class BranchInstruction : OffsetInstruction { private static Instruction[][][] s_caches; public override string InstructionName { get { return "Branch"; } } public override Instruction[] Cache { get { if (s_caches == null) { s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; } return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]); } } internal readonly bool _hasResult; internal readonly bool _hasValue; internal BranchInstruction() : this(false, false) { } public BranchInstruction(bool hasResult, bool hasValue) { _hasResult = hasResult; _hasValue = hasValue; } public override int ConsumedStack { get { return _hasValue ? 1 : 0; } } public override int ProducedStack { get { return _hasResult ? 1 : 0; } } public override int Run(InterpretedFrame frame) { Debug.Assert(_offset != Unknown); return _offset; } } internal abstract class IndexedBranchInstruction : Instruction { protected const int CacheSize = 32; internal readonly int _labelIndex; public IndexedBranchInstruction(int labelIndex) { _labelIndex = labelIndex; } public RuntimeLabel GetLabel(InterpretedFrame frame) { Debug.Assert(_labelIndex != UnknownInstrIndex); return frame.Interpreter._labels[_labelIndex]; } public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) { Debug.Assert(_labelIndex != UnknownInstrIndex); int targetIndex = labelIndexer(_labelIndex); return ToString() + (targetIndex != BranchLabel.UnknownIndex ? " -> " + targetIndex : ""); } public override string ToString() { Debug.Assert(_labelIndex != UnknownInstrIndex); return InstructionName + "[" + _labelIndex + "]"; } } /// <summary> /// This instruction implements a goto expression that can jump out of any expression. /// It pops values (arguments) from the evaluation stack that the expression tree nodes in between /// the goto expression and the target label node pushed and not consumed yet. /// A goto expression can jump into a node that evaluates arguments only if it carries /// a value and jumps right after the first argument (the carried value will be used as the first argument). /// Goto can jump into an arbitrary child of a BlockExpression since the block doesn't accumulate values /// on evaluation stack as its child expressions are being evaluated. /// /// Goto needs to execute any finally blocks on the way to the target label. /// <example> /// { /// f(1, 2, try { g(3, 4, try { goto L } finally { ... }, 6) } finally { ... }, 7, 8) /// L: ... /// } /// </example> /// The goto expression here jumps to label L while having 4 items on evaluation stack (1, 2, 3 and 4). /// The jump needs to execute both finally blocks, the first one on stack level 4 the /// second one on stack level 2. So, it needs to jump the first finally block, pop 2 items from the stack, /// run second finally block and pop another 2 items from the stack and set instruction pointer to label L. /// /// Goto also needs to rethrow ThreadAbortException iff it jumps out of a catch handler and /// the current thread is in "abort requested" state. /// </summary> internal sealed class GotoInstruction : IndexedBranchInstruction { private const int Variants = 8; private static readonly GotoInstruction[] s_cache = new GotoInstruction[Variants * CacheSize]; public override string InstructionName { get { return "Goto"; } } private readonly bool _hasResult; private readonly bool _hasValue; private readonly bool _labelTargetGetsValue; // The values should technically be Consumed = 1, Produced = 1 for gotos that target a label whose continuation depth // is different from the current continuation depth. This is because we will consume one continuation from the _continuations // and at meantime produce a new _pendingContinuation. However, in case of forward gotos, we don't not know that is the // case until the label is emitted. By then the consumed and produced stack information is useless. // The important thing here is that the stack balance is 0. public override int ConsumedContinuations { get { return 0; } } public override int ProducedContinuations { get { return 0; } } public override int ConsumedStack { get { return _hasValue ? 1 : 0; } } public override int ProducedStack { get { return _hasResult ? 1 : 0; } } private GotoInstruction(int targetIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue) : base(targetIndex) { _hasResult = hasResult; _hasValue = hasValue; _labelTargetGetsValue = labelTargetGetsValue; } internal static GotoInstruction Create(int labelIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue) { if (labelIndex < CacheSize) { var index = Variants * labelIndex | (labelTargetGetsValue ? 4 : 0) | (hasResult ? 2 : 0) | (hasValue ? 1 : 0); return s_cache[index] ?? (s_cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue)); } return new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue); } public override int Run(InterpretedFrame frame) { // Are we jumping out of catch/finally while aborting the current thread? #if FEATURE_THREAD_ABORT Interpreter.AbortThreadIfRequested(frame, _labelIndex); #endif // goto the target label or the current finally continuation: object value = _hasValue ? frame.Pop() : Interpreter.NoValue; return frame.Goto(_labelIndex, _labelTargetGetsValue ? value : Interpreter.NoValue, gotoExceptionHandler: false); } } internal sealed class EnterTryCatchFinallyInstruction : IndexedBranchInstruction { private readonly bool _hasFinally = false; private TryCatchFinallyHandler _tryHandler; internal void SetTryHandler(TryCatchFinallyHandler tryHandler) { Debug.Assert(_tryHandler == null && tryHandler != null, "the tryHandler can be set only once"); _tryHandler = tryHandler; } public override int ProducedContinuations { get { return _hasFinally ? 1 : 0; } } private EnterTryCatchFinallyInstruction(int targetIndex, bool hasFinally) : base(targetIndex) { _hasFinally = hasFinally; } internal static EnterTryCatchFinallyInstruction CreateTryFinally(int labelIndex) { return new EnterTryCatchFinallyInstruction(labelIndex, true); } internal static EnterTryCatchFinallyInstruction CreateTryCatch() { return new EnterTryCatchFinallyInstruction(UnknownInstrIndex, false); } public override int Run(InterpretedFrame frame) { Debug.Assert(_tryHandler != null, "the tryHandler must be set already"); if (_hasFinally) { // Push finally. frame.PushContinuation(_labelIndex); } int prevInstrIndex = frame.InstructionIndex; frame.InstructionIndex++; // Start to run the try/catch/finally blocks var instructions = frame.Interpreter.Instructions.Instructions; ExceptionHandler exHandler; try { // run the try block int index = frame.InstructionIndex; while (index >= _tryHandler.TryStartIndex && index < _tryHandler.TryEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } // we finish the try block and is about to jump out of the try/catch blocks if (index == _tryHandler.GotoEndTargetIndex) { // run the 'Goto' that jumps out of the try/catch/finally blocks Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/catch/finally"); frame.InstructionIndex += instructions[index].Run(frame); } } catch (Exception exception) when (_tryHandler.HasHandler(frame, ref exception, out exHandler)) { Debug.Assert(!(exception is RethrowException)); frame.InstructionIndex += frame.Goto(exHandler.LabelIndex, exception, gotoExceptionHandler: true); #if FEATURE_THREAD_ABORT // stay in the current catch so that ThreadAbortException is not rethrown by CLR: var abort = exception as ThreadAbortException; if (abort != null) { Interpreter.AnyAbortException = abort; frame.CurrentAbortHandler = exHandler; } #endif bool rethrow = false; try { // run the catch block int index = frame.InstructionIndex; while (index >= exHandler.HandlerStartIndex && index < exHandler.HandlerEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } // we finish the catch block and is about to jump out of the try/catch blocks if (index == _tryHandler.GotoEndTargetIndex) { // run the 'Goto' that jumps out of the try/catch/finally blocks Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/catch/finally"); frame.InstructionIndex += instructions[index].Run(frame); } } catch (RethrowException) { // a rethrow instruction in a catch block gets to run rethrow = true; } if (rethrow) { throw; } } finally { if (_tryHandler.IsFinallyBlockExist) { // We get to the finally block in two paths: // 1. Jump from the try/catch blocks. This includes two sub-routes: // a. 'Goto' instruction in the middle of try/catch block // b. try/catch block runs to its end. Then the 'Goto(end)' will be trigger to jump out of the try/catch block // 2. Exception thrown from the try/catch blocks // In the first path, the continuation mechanism works and frame.InstructionIndex will be updated to point to the first instruction of the finally block // In the second path, the continuation mechanism is not involved and frame.InstructionIndex is not updated #if DEBUG bool isFromJump = frame.IsJumpHappened(); Debug.Assert(!isFromJump || (isFromJump && _tryHandler.FinallyStartIndex == frame.InstructionIndex), "we should already jump to the first instruction of the finally"); #endif // run the finally block // we cannot jump out of the finally block, and we cannot have an immediate rethrow in it int index = frame.InstructionIndex = _tryHandler.FinallyStartIndex; while (index >= _tryHandler.FinallyStartIndex && index < _tryHandler.FinallyEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } } } return frame.InstructionIndex - prevInstrIndex; } public override string InstructionName { get { return _hasFinally ? "EnterTryFinally" : "EnterTryCatch"; } } public override string ToString() { return _hasFinally ? "EnterTryFinally[" + _labelIndex + "]" : "EnterTryCatch"; } } internal sealed class EnterTryFaultInstruction : IndexedBranchInstruction { private TryFaultHandler _tryHandler; internal void SetTryHandler(TryFaultHandler tryHandler) { Debug.Assert(tryHandler != null); Debug.Assert(_tryHandler == null, "the tryHandler can be set only once"); _tryHandler = tryHandler; } public override int ProducedContinuations => 1; internal EnterTryFaultInstruction(int targetIndex) : base(targetIndex) { } public override int Run(InterpretedFrame frame) { Debug.Assert(_tryHandler != null, "the tryHandler must be set already"); // Push fault. frame.PushContinuation(_labelIndex); int prevInstrIndex = frame.InstructionIndex; frame.InstructionIndex++; // Start to run the try/fault blocks var instructions = frame.Interpreter.Instructions.Instructions; // C# 6 has no direct support for fault blocks, but they can be faked or coerced out of the compiler // in several ways. Catch-and-rethrow can work in specific cases, but not generally as the double-pass // will not work correctly with filters higher up the call stack. Iterators can be used to produce real // fault blocks, but it depends on an implementation detail rather than a guarantee, and is rather // indirect. This leaves using a finally block and not doing anything in it if the body ran to // completion, which is the approach used here. bool ranWithoutFault = false; try { // run the try block int index = frame.InstructionIndex; while (index >= _tryHandler.TryStartIndex && index < _tryHandler.TryEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } // run the 'Goto' that jumps out of the try/fault blocks Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumps out the try/fault"); // if we've arrived here there was no exception thrown. As the fault block won't run, we need to // pop the continuation for it here, before Gotoing the end of the try/fault. ranWithoutFault = true; frame.RemoveContinuation(); frame.InstructionIndex += instructions[index].Run(frame); } finally { if (!ranWithoutFault) { // run the fault block // we cannot jump out of the finally block, and we cannot have an immediate rethrow in it int index = frame.InstructionIndex = _tryHandler.FinallyStartIndex; while (index >= _tryHandler.FinallyStartIndex && index < _tryHandler.FinallyEndIndex) { index += instructions[index].Run(frame); frame.InstructionIndex = index; } } } return frame.InstructionIndex - prevInstrIndex; } public override string InstructionName => "EnterTryFault"; } /// <summary> /// The first instruction of finally block. /// </summary> internal sealed class EnterFinallyInstruction : IndexedBranchInstruction { private readonly static EnterFinallyInstruction[] s_cache = new EnterFinallyInstruction[CacheSize]; public override string InstructionName { get { return "EnterFinally"; } } public override int ProducedStack { get { return 2; } } public override int ConsumedContinuations { get { return 1; } } private EnterFinallyInstruction(int labelIndex) : base(labelIndex) { } internal static EnterFinallyInstruction Create(int labelIndex) { if (labelIndex < CacheSize) { return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFinallyInstruction(labelIndex)); } return new EnterFinallyInstruction(labelIndex); } public override int Run(InterpretedFrame frame) { // If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown // in this case we need to set the stack depth // Else we were getting into this finally block from a 'Goto' jump, and the stack depth is already set properly if (!frame.IsJumpHappened()) { frame.SetStackDepth(GetLabel(frame).StackDepth); } frame.PushPendingContinuation(); frame.RemoveContinuation(); return 1; } } /// <summary> /// The last instruction of finally block. /// </summary> internal sealed class LeaveFinallyInstruction : Instruction { internal static readonly Instruction Instance = new LeaveFinallyInstruction(); public override int ConsumedStack { get { return 2; } } public override string InstructionName { get { return "LeaveFinally"; } } private LeaveFinallyInstruction() { } public override int Run(InterpretedFrame frame) { frame.PopPendingContinuation(); // If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown // In this case we just return 1, and the real instruction index will be calculated by GotoHandler later if (!frame.IsJumpHappened()) { return 1; } // jump to goto target or to the next finally: return frame.YieldToPendingContinuation(); } } internal sealed class EnterFaultInstruction : IndexedBranchInstruction { private readonly static EnterFaultInstruction[] s_cache = new EnterFaultInstruction[CacheSize]; public override string InstructionName => "EnterFault"; public override int ProducedStack => 2; private EnterFaultInstruction(int labelIndex) : base(labelIndex) { } internal static EnterFaultInstruction Create(int labelIndex) { if (labelIndex < CacheSize) { return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFaultInstruction(labelIndex)); } return new EnterFaultInstruction(labelIndex); } public override int Run(InterpretedFrame frame) { Debug.Assert(!frame.IsJumpHappened()); frame.SetStackDepth(GetLabel(frame).StackDepth); frame.PushPendingContinuation(); frame.RemoveContinuation(); return 1; } } internal sealed class LeaveFaultInstruction : Instruction { internal static readonly Instruction Instance = new LeaveFaultInstruction(); public override int ConsumedStack => 2; public override int ConsumedContinuations => 1; public override string InstructionName => "LeaveFault"; private LeaveFaultInstruction() { } public override int Run(InterpretedFrame frame) { frame.PopPendingContinuation(); Debug.Assert(!frame.IsJumpHappened()); // Just return 1, and the real instruction index will be calculated by GotoHandler later return 1; } } // no-op: we need this just to balance the stack depth and aid debugging of the instruction list. internal sealed class EnterExceptionFilterInstruction : Instruction { internal static readonly EnterExceptionFilterInstruction Instance = new EnterExceptionFilterInstruction(); private EnterExceptionFilterInstruction() { } public override string InstructionName => "EnterExceptionFilter"; public override int ConsumedStack => 0; // The exception is pushed onto the stack in the filter runner. public override int ProducedStack => 1; [ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution. public override int Run(InterpretedFrame frame) => 1; } // no-op: we need this just to balance the stack depth and aid debugging of the instruction list. internal sealed class LeaveExceptionFilterInstruction : Instruction { internal static readonly LeaveExceptionFilterInstruction Instance = new LeaveExceptionFilterInstruction(); private LeaveExceptionFilterInstruction() { } public override string InstructionName => "LeaveExceptionFilter"; // The boolean result is popped from the stack in the filter runner. public override int ConsumedStack => 1; public override int ProducedStack => 0; [ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution. public override int Run(InterpretedFrame frame) => 1; } // no-op: we need this just to balance the stack depth. internal sealed class EnterExceptionHandlerInstruction : Instruction { internal static readonly EnterExceptionHandlerInstruction Void = new EnterExceptionHandlerInstruction(false); internal static readonly EnterExceptionHandlerInstruction NonVoid = new EnterExceptionHandlerInstruction(true); // True if try-expression is non-void. private readonly bool _hasValue; public override string InstructionName { get { return "EnterExceptionHandler"; } } private EnterExceptionHandlerInstruction(bool hasValue) { _hasValue = hasValue; } // If an exception is throws in try-body the expression result of try-body is not evaluated and loaded to the stack. // So the stack doesn't contain the try-body's value when we start executing the handler. // However, while emitting instructions try block falls thru the catch block with a value on stack. // We need to declare it consumed so that the stack state upon entry to the handler corresponds to the real // stack depth after throw jumped to this catch block. public override int ConsumedStack { get { return _hasValue ? 1 : 0; } } // A variable storing the current exception is pushed to the stack by exception handling. // Catch handlers: The value is immediately popped and stored into a local. public override int ProducedStack { get { return 1; } } [ExcludeFromCodeCoverage] // Known to be a no-op, this instruction is skipped on execution. public override int Run(InterpretedFrame frame) { // nop (the exception value is pushed by the interpreter in HandleCatch) return 1; } } /// <summary> /// The last instruction of a catch exception handler. /// </summary> internal sealed class LeaveExceptionHandlerInstruction : IndexedBranchInstruction { private static LeaveExceptionHandlerInstruction[] s_cache = new LeaveExceptionHandlerInstruction[2 * CacheSize]; private readonly bool _hasValue; public override string InstructionName { get { return "LeaveExceptionHandler"; } } // The catch block yields a value if the body is non-void. This value is left on the stack. public override int ConsumedStack { get { return _hasValue ? 1 : 0; } } public override int ProducedStack { get { return _hasValue ? 1 : 0; } } private LeaveExceptionHandlerInstruction(int labelIndex, bool hasValue) : base(labelIndex) { _hasValue = hasValue; } internal static LeaveExceptionHandlerInstruction Create(int labelIndex, bool hasValue) { if (labelIndex < CacheSize) { int index = (2 * labelIndex) | (hasValue ? 1 : 0); return s_cache[index] ?? (s_cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue)); } return new LeaveExceptionHandlerInstruction(labelIndex, hasValue); } public override int Run(InterpretedFrame frame) { // CLR rethrows ThreadAbortException when leaving catch handler if abort is requested on the current thread. #if FEATURE_THREAD_ABORT Interpreter.AbortThreadIfRequested(frame, _labelIndex); #endif return GetLabel(frame).Index - frame.InstructionIndex; } } internal sealed class ThrowInstruction : Instruction { internal static readonly ThrowInstruction Throw = new ThrowInstruction(true, false); internal static readonly ThrowInstruction VoidThrow = new ThrowInstruction(false, false); internal static readonly ThrowInstruction Rethrow = new ThrowInstruction(true, true); internal static readonly ThrowInstruction VoidRethrow = new ThrowInstruction(false, true); private readonly bool _hasResult, _rethrow; public override string InstructionName { get { return "Throw"; } } private ThrowInstruction(bool hasResult, bool isRethrow) { _hasResult = hasResult; _rethrow = isRethrow; } public override int ProducedStack { get { return _hasResult ? 1 : 0; } } public override int ConsumedStack { get { return 1; } } public override int Run(InterpretedFrame frame) { var ex = (Exception)frame.Pop(); if (_rethrow) { throw new RethrowException(); } throw ex; } } internal sealed class IntSwitchInstruction<T> : Instruction { private readonly Dictionary<T, int> _cases; public override string InstructionName { get { return "IntSwitch"; } } internal IntSwitchInstruction(Dictionary<T, int> cases) { Assert.NotNull(cases); _cases = cases; } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 0; } } public override int Run(InterpretedFrame frame) { int target; return _cases.TryGetValue((T)frame.Pop(), out target) ? target : 1; } } internal sealed class StringSwitchInstruction : Instruction { private readonly Dictionary<string, int> _cases; private readonly StrongBox<int> _nullCase; public override string InstructionName { get { return "StringSwitch"; } } internal StringSwitchInstruction(Dictionary<string, int> cases, StrongBox<int> nullCase) { Assert.NotNull(cases); Assert.NotNull(nullCase); _cases = cases; _nullCase = nullCase; } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 0; } } public override int Run(InterpretedFrame frame) { object value = frame.Pop(); if (value == null) { return _nullCase.Value; } int target; return _cases.TryGetValue((string)value, out target) ? target : 1; } } }
// *********************************************************************** // Copyright (c) 2015-2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using NUnit.Common; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnitLite { public class TextUI { public ExtendedTextWriter Writer { get; } private readonly TextReader _reader; private readonly NUnitLiteOptions _options; private readonly bool _displayBeforeTest; private readonly bool _displayAfterTest; private readonly bool _displayBeforeOutput; #region Constructor public TextUI(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options) { Writer = writer; _reader = reader; _options = options; string labelsOption = options.DisplayTestLabels?.ToUpperInvariant() ?? "ON"; _displayBeforeTest = labelsOption == "ALL" || labelsOption == "BEFORE"; _displayAfterTest = labelsOption == "AFTER"; _displayBeforeOutput = _displayBeforeTest || _displayAfterTest || labelsOption == "ON"; } #endregion #region Public Methods #region DisplayHeader /// <summary> /// Writes the header. /// </summary> public void DisplayHeader() { Assembly executingAssembly = GetType().GetTypeInfo().Assembly; AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly); Version version = assemblyName.Version; string copyright = "Copyright (C) 2018 Charlie Poole, Rob Prouse"; string build = ""; var copyrightAttr = executingAssembly.GetCustomAttribute<AssemblyCopyrightAttribute>(); if (copyrightAttr != null) copyright = copyrightAttr.Copyright; var configAttr = executingAssembly.GetCustomAttribute<AssemblyConfigurationAttribute>(); if (configAttr != null) build = string.Format("({0})", configAttr.Configuration); WriteHeader(String.Format("NUnitLite {0} {1}", version.ToString(3), build)); WriteSubHeader(copyright); Writer.WriteLine(); } #endregion #region DisplayTestFiles public void DisplayTestFiles(IEnumerable<string> testFiles) { WriteSectionHeader("Test Files"); foreach (string testFile in testFiles) Writer.WriteLine(ColorStyle.Default, " " + testFile); Writer.WriteLine(); } #endregion #region DisplayHelp public void DisplayHelp() { WriteHeader("Usage: NUNITLITE-RUNNER assembly [options]"); WriteHeader(" USER-EXECUTABLE [options]"); Writer.WriteLine(); WriteHelpLine("Runs a set of NUnitLite tests from the console."); Writer.WriteLine(); WriteSectionHeader("Assembly:"); WriteHelpLine(" File name or path of the assembly from which to execute tests. Required"); WriteHelpLine(" when using the nunitlite-runner executable to run the tests. Not allowed"); WriteHelpLine(" when running a self-executing user test assembly."); Writer.WriteLine(); WriteSectionHeader("Options:"); using (var sw = new StringWriter()) { _options.WriteOptionDescriptions(sw); Writer.Write(ColorStyle.Help, sw.ToString()); } WriteSectionHeader("Notes:"); WriteHelpLine(" * File names may be listed by themselves, with a relative path or "); WriteHelpLine(" using an absolute path. Any relative path is based on the current "); WriteHelpLine(" directory."); Writer.WriteLine(); WriteHelpLine(" * On Windows, options may be prefixed by a '/' character if desired"); Writer.WriteLine(); WriteHelpLine(" * Options that take values may use an equal sign or a colon"); WriteHelpLine(" to separate the option from its value."); Writer.WriteLine(); WriteHelpLine(" * Several options that specify processing of XML output take"); WriteHelpLine(" an output specification as a value. A SPEC may take one of"); WriteHelpLine(" the following forms:"); WriteHelpLine(" --OPTION:filename"); WriteHelpLine(" --OPTION:filename;format=formatname"); Writer.WriteLine(); WriteHelpLine(" The --result option may use any of the following formats:"); WriteHelpLine(" nunit3 - the native XML format for NUnit 3"); WriteHelpLine(" nunit2 - legacy XML format used by earlier releases of NUnit"); Writer.WriteLine(); WriteHelpLine(" The --explore option may use any of the following formats:"); WriteHelpLine(" nunit3 - the native XML format for NUnit 3"); WriteHelpLine(" cases - a text file listing the full names of all test cases."); WriteHelpLine(" If --explore is used without any specification following, a list of"); WriteHelpLine(" test cases is output to the console."); Writer.WriteLine(); } #endregion #region DisplayRuntimeEnvironment /// <summary> /// Displays info about the runtime environment. /// </summary> public void DisplayRuntimeEnvironment() { WriteSectionHeader("Runtime Environment"); #if NETSTANDARD1_4 || NETSTANDARD2_0 Writer.WriteLabelLine(" OS Version: ", System.Runtime.InteropServices.RuntimeInformation.OSDescription); #else Writer.WriteLabelLine(" OS Version: ", OSPlatform.CurrentPlatform); #endif #if NETSTANDARD1_4 Writer.WriteLabelLine(" CLR Version: ", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription); #else Writer.WriteLabelLine(" CLR Version: ", Environment.Version); #endif Writer.WriteLine(); } #endregion #region Test Discovery Report public void DisplayDiscoveryReport(TimeStamp startTime, TimeStamp endTime) { WriteSectionHeader("Test Discovery"); foreach (string filter in _options.PreFilters) Writer.WriteLabelLine(" Pre-Filter: ", filter); Writer.WriteLabelLine(" Start time: ", startTime.DateTime.ToString("u")); Writer.WriteLabelLine(" End time: ", endTime.DateTime.ToString("u")); double elapsedSeconds = TimeStamp.TicksToSeconds(endTime.Ticks - startTime.Ticks); Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", elapsedSeconds)); Writer.WriteLine(); } #endregion #region DisplayTestFilters public void DisplayTestFilters() { if (_options.TestList.Count > 0 || _options.WhereClauseSpecified) { WriteSectionHeader("Test Filters"); foreach (string testName in _options.TestList) Writer.WriteLabelLine(" Test: ", testName); if (_options.WhereClauseSpecified) Writer.WriteLabelLine(" Where: ", _options.WhereClause.Trim()); Writer.WriteLine(); } } #endregion #region DisplayRunSettings public void DisplayRunSettings() { WriteSectionHeader("Run Settings"); if (_options.DefaultTimeout >= 0) Writer.WriteLabelLine(" Default timeout: ", _options.DefaultTimeout); #if PARALLEL Writer.WriteLabelLine( " Number of Test Workers: ", _options.NumberOfTestWorkers >= 0 ? _options.NumberOfTestWorkers : Math.Max(Environment.ProcessorCount, 2)); #endif Writer.WriteLabelLine(" Work Directory: ", _options.WorkDirectory ?? Directory.GetCurrentDirectory()); Writer.WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off"); if (_options.TeamCity) Writer.WriteLine(ColorStyle.Value, " Display TeamCity Service Messages"); Writer.WriteLine(); } #endregion #region TestStarted public void TestStarted(ITest test) { if (_displayBeforeTest && !test.IsSuite) WriteLabelLine(test.FullName); } #endregion #region TestFinished private bool _testCreatedOutput = false; private bool _needsNewLine = false; public void TestFinished(ITestResult result) { if (result.Output.Length > 0) { if (_displayBeforeOutput) WriteLabelLine(result.Test.FullName); WriteOutput(result.Output); if (!result.Output.EndsWith("\n")) Writer.WriteLine(); } if (!result.Test.IsSuite) { if (_displayAfterTest) WriteLabelLineAfterTest(result.Test.FullName, result.ResultState); } if (result.Test is TestAssembly && _testCreatedOutput) { Writer.WriteLine(); _testCreatedOutput = false; } } #endregion #region TestOutput public void TestOutput(TestOutput output) { if (_displayBeforeOutput && output.TestName != null) WriteLabelLine(output.TestName); WriteOutput(output.Stream == "Error" ? ColorStyle.Error : ColorStyle.Output, output.Text); } #endregion #region WaitForUser public void WaitForUser(string message) { // Ignore if we don't have a TextReader if (_reader != null) { Writer.WriteLine(ColorStyle.Label, message); _reader.ReadLine(); } } #endregion #region Test Result Reports #region DisplaySummaryReport public void DisplaySummaryReport(ResultSummary summary) { var status = summary.ResultState.Status; var overallResult = status.ToString(); if (overallResult == "Skipped") overallResult = "Warning"; ColorStyle overallStyle = status == TestStatus.Passed ? ColorStyle.Pass : status == TestStatus.Failed ? ColorStyle.Failure : status == TestStatus.Skipped ? ColorStyle.Warning : ColorStyle.Output; if (_testCreatedOutput) Writer.WriteLine(); WriteSectionHeader("Test Run Summary"); Writer.WriteLabelLine(" Overall result: ", overallResult, overallStyle); WriteSummaryCount(" Test Count: ", summary.TestCount); WriteSummaryCount(", Passed: ", summary.PassCount); WriteSummaryCount(", Failed: ", summary.FailedCount, ColorStyle.Failure); WriteSummaryCount(", Warnings: ", summary.WarningCount, ColorStyle.Warning); WriteSummaryCount(", Inconclusive: ", summary.InconclusiveCount); WriteSummaryCount(", Skipped: ", summary.TotalSkipCount); Writer.WriteLine(); if (summary.FailedCount > 0) { WriteSummaryCount(" Failed Tests - Failures: ", summary.FailureCount, ColorStyle.Failure); WriteSummaryCount(", Errors: ", summary.ErrorCount, ColorStyle.Error); WriteSummaryCount(", Invalid: ", summary.InvalidCount, ColorStyle.Error); Writer.WriteLine(); } if (summary.TotalSkipCount > 0) { WriteSummaryCount(" Skipped Tests - Ignored: ", summary.IgnoreCount, ColorStyle.Warning); WriteSummaryCount(", Explicit: ", summary.ExplicitCount); WriteSummaryCount(", Other: ", summary.SkipCount); Writer.WriteLine(); } Writer.WriteLabelLine(" Start time: ", summary.StartTime.ToString("u")); Writer.WriteLabelLine(" End time: ", summary.EndTime.ToString("u")); Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", summary.Duration)); Writer.WriteLine(); } private void WriteSummaryCount(string label, int count) { Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture)); } private void WriteSummaryCount(string label, int count, ColorStyle color) { Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture), count > 0 ? color : ColorStyle.Value); } #endregion #region DisplayErrorsAndFailuresReport public void DisplayErrorsFailuresAndWarningsReport(ITestResult result) { _reportIndex = 0; WriteSectionHeader("Errors, Failures and Warnings"); DisplayErrorsFailuresAndWarnings(result); Writer.WriteLine(); if (_options.StopOnError) { Writer.WriteLine(ColorStyle.Failure, "Execution terminated after first error"); Writer.WriteLine(); } } #endregion #region DisplayNotRunReport public void DisplayNotRunReport(ITestResult result) { _reportIndex = 0; WriteSectionHeader("Tests Not Run"); DisplayNotRunResults(result); Writer.WriteLine(); } #endregion #region DisplayFullReport #if FULL // Not currently used, but may be reactivated /// <summary> /// Prints a full report of all results /// </summary> public void DisplayFullReport(ITestResult result) { WriteLine(ColorStyle.SectionHeader, "All Test Results -"); _writer.WriteLine(); DisplayAllResults(result, " "); _writer.WriteLine(); } #endif #endregion #endregion #region DisplayWarning public void DisplayWarning(string text) { Writer.WriteLine(ColorStyle.Warning, text); } #endregion #region DisplayError public void DisplayError(string text) { Writer.WriteLine(ColorStyle.Error, text); } #endregion #region DisplayErrors public void DisplayErrors(IList<string> messages) { foreach (string message in messages) DisplayError(message); } #endregion #endregion #region Helper Methods private void DisplayErrorsFailuresAndWarnings(ITestResult result) { bool display = result.ResultState.Status == TestStatus.Failed || result.ResultState.Status == TestStatus.Warning; if (result.Test.IsSuite) { if (display) { var suite = result.Test as TestSuite; var site = result.ResultState.Site; if (suite.TestType == "Theory" || site == FailureSite.SetUp || site == FailureSite.TearDown) DisplayTestResult(result); if (site == FailureSite.SetUp) return; } foreach (ITestResult childResult in result.Children) DisplayErrorsFailuresAndWarnings(childResult); } else if (display) DisplayTestResult(result); } private void DisplayNotRunResults(ITestResult result) { if (result.HasChildren) foreach (ITestResult childResult in result.Children) DisplayNotRunResults(childResult); else if (result.ResultState.Status == TestStatus.Skipped) DisplayTestResult(result); } private static readonly char[] TRIM_CHARS = new char[] { '\r', '\n' }; private int _reportIndex; private void DisplayTestResult(ITestResult result) { ResultState resultState = result.ResultState; string fullName = result.FullName; string message = result.Message; string stackTrace = result.StackTrace; string reportId = (++_reportIndex).ToString(); int numAsserts = result.AssertionResults.Count; if (numAsserts > 0) { int assertionCounter = 0; string assertId = reportId; foreach (var assertion in result.AssertionResults) { if (numAsserts > 1) assertId = string.Format("{0}-{1}", reportId, ++assertionCounter); ColorStyle style = GetColorStyle(resultState); string status = assertion.Status.ToString(); DisplayTestResult(style, assertId, status, fullName, assertion.Message, assertion.StackTrace); } } else { ColorStyle style = GetColorStyle(resultState); string status = GetResultStatus(resultState); DisplayTestResult(style, reportId, status, fullName, message, stackTrace); } } private void DisplayTestResult(ColorStyle style, string prefix, string status, string fullName, string message, string stackTrace) { Writer.WriteLine(); Writer.WriteLine( style, string.Format("{0}) {1} : {2}", prefix, status, fullName)); if (!string.IsNullOrEmpty(message)) Writer.WriteLine(style, message.TrimEnd(TRIM_CHARS)); if (!string.IsNullOrEmpty(stackTrace)) Writer.WriteLine(style, stackTrace.TrimEnd(TRIM_CHARS)); } private static ColorStyle GetColorStyle(ResultState resultState) { ColorStyle style = ColorStyle.Output; switch (resultState.Status) { case TestStatus.Failed: style = ColorStyle.Failure; break; case TestStatus.Warning: style = ColorStyle.Warning; break; case TestStatus.Skipped: style = resultState.Label == "Ignored" ? ColorStyle.Warning : ColorStyle.Output; break; case TestStatus.Passed: style = ColorStyle.Pass; break; } return style; } private static string GetResultStatus(ResultState resultState) { string status = resultState.Label; if (string.IsNullOrEmpty(status)) status = resultState.Status.ToString(); if (status == "Failed" || status == "Error") { var site = resultState.Site.ToString(); if (site == "SetUp" || site == "TearDown") status = site + " " + status; } return status; } #if FULL private void DisplayAllResults(ITestResult result, string indent) { string status = null; ColorStyle style = ColorStyle.Output; switch (result.ResultState.Status) { case TestStatus.Failed: status = "FAIL"; style = ColorStyle.Failure; break; case TestStatus.Skipped: if (result.ResultState.Label == "Ignored") { status = "IGN "; style = ColorStyle.Warning; } else { status = "SKIP"; style = ColorStyle.Output; } break; case TestStatus.Inconclusive: status = "INC "; style = ColorStyle.Output; break; case TestStatus.Passed: status = "OK "; style = ColorStyle.Pass; break; } WriteLine(style, status + indent + result.Name); if (result.HasChildren) foreach (ITestResult childResult in result.Children) PrintAllResults(childResult, indent + " "); } #endif private void WriteHeader(string text) { Writer.WriteLine(ColorStyle.Header, text); } private void WriteSubHeader(string text) { Writer.WriteLine(ColorStyle.SubHeader, text); } private void WriteSectionHeader(string text) { Writer.WriteLine(ColorStyle.SectionHeader, text); } private void WriteHelpLine(string text) { Writer.WriteLine(ColorStyle.Help, text); } private string _currentLabel; private void WriteLabelLine(string label) { if (label != _currentLabel) { WriteNewLineIfNeeded(); Writer.WriteLine(ColorStyle.SectionHeader, "=> " + label); _testCreatedOutput = true; _currentLabel = label; } } private void WriteLabelLineAfterTest(string label, ResultState resultState) { WriteNewLineIfNeeded(); string status = string.IsNullOrEmpty(resultState.Label) ? resultState.Status.ToString() : resultState.Label; Writer.Write(GetColorForResultStatus(status), status); Writer.WriteLine(ColorStyle.SectionHeader, " => " + label); _currentLabel = label; } private void WriteNewLineIfNeeded() { if (_needsNewLine) { Writer.WriteLine(); _needsNewLine = false; } } private void WriteOutput(string text) { WriteOutput(ColorStyle.Output, text); } private void WriteOutput(ColorStyle color, string text) { Writer.Write(color, text); _testCreatedOutput = true; _needsNewLine = !text.EndsWith("\n"); } private static ColorStyle GetColorForResultStatus(string status) { switch (status) { case "Passed": return ColorStyle.Pass; case "Failed": return ColorStyle.Failure; case "Error": case "Invalid": case "Cancelled": return ColorStyle.Error; case "Warning": case "Ignored": return ColorStyle.Warning; default: return ColorStyle.Output; } } #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. // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.CompilerServices; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Security.Permissions; using System.Threading; using MdToken = System.Reflection.MetadataToken; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_ParameterInfo))] [System.Runtime.InteropServices.ComVisible(true)] public class ParameterInfo : _ParameterInfo, ICustomAttributeProvider, IObjectReference { #region Legacy Protected Members protected String NameImpl; protected Type ClassImpl; protected int PositionImpl; protected ParameterAttributes AttrsImpl; protected Object DefaultValueImpl; // cannot cache this as it may be non agile user defined enum protected MemberInfo MemberImpl; #endregion #region Legacy Private Members // These are here only for backwards compatibility -- they are not set // until this instance is serialized, so don't rely on their values from // arbitrary code. #pragma warning disable 169 [OptionalField] private IntPtr _importer; [OptionalField] private int _token; [OptionalField] private bool bExtraConstChecked; #pragma warning restore 169 #endregion #region Constructor protected ParameterInfo() { } #endregion #region Internal Members // this is an internal api for DynamicMethod. A better solution is to change the relationship // between ParameterInfo and ParameterBuilder so that a ParameterBuilder can be seen as a writer // api over a ParameterInfo. However that is a possible breaking change so it needs to go through some process first internal void SetName(String name) { NameImpl = name; } internal void SetAttributes(ParameterAttributes attributes) { AttrsImpl = attributes; } #endregion #region Public Methods public virtual Type ParameterType { get { return ClassImpl; } } public virtual String Name { get { return NameImpl; } } public virtual bool HasDefaultValue { get { throw new NotImplementedException(); } } public virtual Object DefaultValue { get { throw new NotImplementedException(); } } public virtual Object RawDefaultValue { get { throw new NotImplementedException(); } } public virtual int Position { get { return PositionImpl; } } public virtual ParameterAttributes Attributes { get { return AttrsImpl; } } public virtual MemberInfo Member { get { Contract.Ensures(Contract.Result<MemberInfo>() != null); return MemberImpl; } } public bool IsIn { get { return((Attributes & ParameterAttributes.In) != 0); } } public bool IsOut { get { return((Attributes & ParameterAttributes.Out) != 0); } } #if FEATURE_USE_LCID public bool IsLcid { get { return((Attributes & ParameterAttributes.Lcid) != 0); } } #endif public bool IsRetval { get { return((Attributes & ParameterAttributes.Retval) != 0); } } public bool IsOptional { get { return((Attributes & ParameterAttributes.Optional) != 0); } } public virtual int MetadataToken { get { // This API was made virtual in V4. Code compiled against V2 might use // "call" rather than "callvirt" to call it. // This makes sure those code still works. RuntimeParameterInfo rtParam = this as RuntimeParameterInfo; if (rtParam != null) return rtParam.MetadataToken; // return a null token return (int)MetadataTokenType.ParamDef; } } public virtual Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; } public virtual Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; } #endregion #region Object Overrides public override String ToString() { return ParameterType.FormatTypeName() + " " + Name; } #endregion public virtual IEnumerable<CustomAttributeData> CustomAttributes { get { return GetCustomAttributesData(); } } #region ICustomAttributeProvider public virtual Object[] GetCustomAttributes(bool inherit) { return EmptyArray<Object>.Value; } public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); return EmptyArray<Object>.Value; } public virtual bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); return false; } public virtual IList<CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } #endregion #region _ParameterInfo implementation #if !FEATURE_CORECLR void _ParameterInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _ParameterInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _ParameterInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _ParameterInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif #endregion #region IObjectReference // In V4 RuntimeParameterInfo is introduced. // To support deserializing ParameterInfo instances serialized in earlier versions // we need to implement IObjectReference. [System.Security.SecurityCritical] public object GetRealObject(StreamingContext context) { Contract.Ensures(Contract.Result<Object>() != null); // Once all the serializable fields have come in we can set up the real // instance based on just two of them (MemberImpl and PositionImpl). if (MemberImpl == null) throw new SerializationException(Environment.GetResourceString(ResId.Serialization_InsufficientState)); ParameterInfo[] args = null; switch (MemberImpl.MemberType) { case MemberTypes.Constructor: case MemberTypes.Method: if (PositionImpl == -1) { if (MemberImpl.MemberType == MemberTypes.Method) return ((MethodInfo)MemberImpl).ReturnParameter; else throw new SerializationException(Environment.GetResourceString(ResId.Serialization_BadParameterInfo)); } else { args = ((MethodBase)MemberImpl).GetParametersNoCopy(); if (args != null && PositionImpl < args.Length) return args[PositionImpl]; else throw new SerializationException(Environment.GetResourceString(ResId.Serialization_BadParameterInfo)); } case MemberTypes.Property: args = ((RuntimePropertyInfo)MemberImpl).GetIndexParametersNoCopy(); if (args != null && PositionImpl > -1 && PositionImpl < args.Length) return args[PositionImpl]; else throw new SerializationException(Environment.GetResourceString(ResId.Serialization_BadParameterInfo)); default: throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NoParameterInfo)); } } #endregion } [Serializable] internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable { #region Static Members [System.Security.SecurityCritical] // auto-generated internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig) { Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); ParameterInfo dummy; return GetParameters(method, member, sig, out dummy, false); } [System.Security.SecurityCritical] // auto-generated internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig) { Contract.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); ParameterInfo returnParameter; GetParameters(method, member, sig, out returnParameter, true); return returnParameter; } [System.Security.SecurityCritical] // auto-generated internal unsafe static ParameterInfo[] GetParameters( IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter) { returnParameter = null; int sigArgCount = sig.Arguments.Length; ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount]; int tkMethodDef = RuntimeMethodHandle.GetMethodDef(methodHandle); int cParamDefs = 0; // Not all methods have tokens. Arrays, pointers and byRef types do not have tokens as they // are generated on the fly by the runtime. if (!MdToken.IsNullToken(tkMethodDef)) { MetadataImport scope = RuntimeTypeHandle.GetMetadataImport(RuntimeMethodHandle.GetDeclaringType(methodHandle)); MetadataEnumResult tkParamDefs; scope.EnumParams(tkMethodDef, out tkParamDefs); cParamDefs = tkParamDefs.Length; // Not all parameters have tokens. Parameters may have no token // if they have no name and no attributes. if (cParamDefs > sigArgCount + 1 /* return type */) throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch")); for (int i = 0; i < cParamDefs; i++) { #region Populate ParameterInfos ParameterAttributes attr; int position, tkParamDef = tkParamDefs[i]; scope.GetParamDefProps(tkParamDef, out position, out attr); position--; if (fetchReturnParameter == true && position == -1) { // more than one return parameter? if (returnParameter != null) throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch")); returnParameter = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member); } else if (fetchReturnParameter == false && position >= 0) { // position beyong sigArgCount? if (position >= sigArgCount) throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch")); args[position] = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member); } #endregion } } // Fill in empty ParameterInfos for those without tokens if (fetchReturnParameter) { if (returnParameter == null) { returnParameter = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member); } } else { if (cParamDefs < args.Length + 1) { for (int i = 0; i < args.Length; i++) { if (args[i] != null) continue; args[i] = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, i, (ParameterAttributes)0, member); } } } return args; } #endregion #region Private Statics private static readonly Type s_DecimalConstantAttributeType = typeof(DecimalConstantAttribute); private static readonly Type s_CustomConstantAttributeType = typeof(CustomConstantAttribute); #endregion #region Private Data Members // These are new in Whidbey, so we cannot serialize them directly or we break backwards compatibility. [NonSerialized] private int m_tkParamDef; [NonSerialized] private MetadataImport m_scope; [NonSerialized] private Signature m_signature; [NonSerialized] private volatile bool m_nameIsCached = false; [NonSerialized] private readonly bool m_noMetadata = false; [NonSerialized] private bool m_noDefaultValue = false; [NonSerialized] private MethodBase m_originalMember = null; #endregion #region Internal Properties internal MethodBase DefiningMethod { get { MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase; Contract.Assert(result != null); return result; } } #endregion #region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints. [System.Security.SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); // We could be serializing for consumption by a pre-Whidbey // endpoint. Therefore we set up all the serialized fields to look // just like a v1.0/v1.1 instance. // Need to set the type to ParameterInfo so that pre-Whidbey and Whidbey code // can deserialize this. This is also why we cannot simply use [OnSerializing]. info.SetType(typeof(ParameterInfo)); // Use the properties intead of the fields in case the fields haven't been et // _importer, bExtraConstChecked, and m_cachedData don't need to be set // Now set the legacy fields that the current implementation doesn't // use any more. Note that _importer is a raw pointer that should // never have been serialized in V1. We set it to zero here; if the // deserializer uses it (by calling GetCustomAttributes() on this // instance) they'll AV, but at least it will be a well defined // exception and not a random AV. info.AddValue("AttrsImpl", Attributes); info.AddValue("ClassImpl", ParameterType); info.AddValue("DefaultValueImpl", DefaultValue); info.AddValue("MemberImpl", Member); info.AddValue("NameImpl", Name); info.AddValue("PositionImpl", Position); info.AddValue("_token", m_tkParamDef); } #endregion #region Constructor // used by RuntimePropertyInfo internal RuntimeParameterInfo(RuntimeParameterInfo accessor, RuntimePropertyInfo property) : this(accessor, (MemberInfo)property) { m_signature = property.Signature; } private RuntimeParameterInfo(RuntimeParameterInfo accessor, MemberInfo member) { // Change ownership MemberImpl = member; // The original owner should always be a method, because this method is only used to // change the owner from a method to a property. m_originalMember = accessor.MemberImpl as MethodBase; Contract.Assert(m_originalMember != null); // Populate all the caches -- we inherit this behavior from RTM NameImpl = accessor.Name; m_nameIsCached = true; ClassImpl = accessor.ParameterType; PositionImpl = accessor.Position; AttrsImpl = accessor.Attributes; // Strictly speeking, property's don't contain paramter tokens // However we need this to make ca's work... oh well... m_tkParamDef = MdToken.IsNullToken(accessor.MetadataToken) ? (int)MetadataTokenType.ParamDef : accessor.MetadataToken; m_scope = accessor.m_scope; } private RuntimeParameterInfo( Signature signature, MetadataImport scope, int tkParamDef, int position, ParameterAttributes attributes, MemberInfo member) { Contract.Requires(member != null); Contract.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport)); Contract.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef)); PositionImpl = position; MemberImpl = member; m_signature = signature; m_tkParamDef = MdToken.IsNullToken(tkParamDef) ? (int)MetadataTokenType.ParamDef : tkParamDef; m_scope = scope; AttrsImpl = attributes; ClassImpl = null; NameImpl = null; } // ctor for no metadata MethodInfo in the DynamicMethod and RuntimeMethodInfo cases internal RuntimeParameterInfo(MethodInfo owner, String name, Type parameterType, int position) { MemberImpl = owner; NameImpl = name; m_nameIsCached = true; m_noMetadata = true; ClassImpl = parameterType; PositionImpl = position; AttrsImpl = ParameterAttributes.None; m_tkParamDef = (int)MetadataTokenType.ParamDef; m_scope = MetadataImport.EmptyImport; } #endregion #region Public Methods public override Type ParameterType { get { // only instance of ParameterInfo has ClassImpl, all its subclasses don't if (ClassImpl == null) { RuntimeType parameterType; if (PositionImpl == -1) parameterType = m_signature.ReturnType; else parameterType = m_signature.Arguments[PositionImpl]; Contract.Assert(parameterType != null); // different thread could only write ClassImpl to the same value, so a race condition is not a problem here ClassImpl = parameterType; } return ClassImpl; } } public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (!m_nameIsCached) { if (!MdToken.IsNullToken(m_tkParamDef)) { string name; name = m_scope.GetName(m_tkParamDef).ToString(); NameImpl = name; } // other threads could only write it to true, so a race condition is OK // this field is volatile, so the write ordering is guaranteed m_nameIsCached = true; } // name may be null return NameImpl; } } public override bool HasDefaultValue { get { if (m_noMetadata || m_noDefaultValue) return false; object defaultValue = GetDefaultValueInternal(false); return (defaultValue != DBNull.Value); } } public override Object DefaultValue { get { return GetDefaultValue(false); } } public override Object RawDefaultValue { get { return GetDefaultValue(true); } } private Object GetDefaultValue(bool raw) { // OLD COMMENT (Is this even true?) // Cannot cache because default value could be non-agile user defined enumeration. // OLD COMMENT ends if (m_noMetadata) return null; // for dynamic method we pretend to have cached the value so we do not go to metadata object defaultValue = GetDefaultValueInternal(raw); if (defaultValue == DBNull.Value) { #region Handle case if no default value was found if (IsOptional) { // If the argument is marked as optional then the default value is Missing.Value. defaultValue = Type.Missing; } #endregion } return defaultValue; } // returns DBNull.Value if the parameter doesn't have a default value [System.Security.SecuritySafeCritical] private Object GetDefaultValueInternal(bool raw) { Contract.Assert(!m_noMetadata); if (m_noDefaultValue) return DBNull.Value; object defaultValue = null; // Why check the parameter type only for DateTime and only for the ctor arguments? // No check on the parameter type is done for named args and for Decimal. // We should move this after MdToken.IsNullToken(m_tkParamDef) and combine it // with the other custom attribute logic. But will that be a breaking change? // For a DateTime parameter on which both an md constant and a ca constant are set, // which one should win? if (ParameterType == typeof(DateTime)) { if (raw) { CustomAttributeTypedArgument value = CustomAttributeData.Filter( CustomAttributeData.GetCustomAttributes(this), typeof(DateTimeConstantAttribute), 0); if (value.ArgumentType != null) return new DateTime((long)value.Value); } else { object[] dt = GetCustomAttributes(typeof(DateTimeConstantAttribute), false); if (dt != null && dt.Length != 0) return ((DateTimeConstantAttribute)dt[0]).Value; } } #region Look for a default value in metadata if (!MdToken.IsNullToken(m_tkParamDef)) { // This will return DBNull.Value if no constant value is defined on m_tkParamDef in the metadata. defaultValue = MdConstant.GetValue(m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw); } #endregion if (defaultValue == DBNull.Value) { #region Look for a default value in the custom attributes if (raw) { foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(this)) { Type attrType = attr.Constructor.DeclaringType; if (attrType == typeof(DateTimeConstantAttribute)) { defaultValue = DateTimeConstantAttribute.GetRawDateTimeConstant(attr); } else if (attrType == typeof(DecimalConstantAttribute)) { defaultValue = DecimalConstantAttribute.GetRawDecimalConstant(attr); } else if (attrType.IsSubclassOf(s_CustomConstantAttributeType)) { defaultValue = CustomConstantAttribute.GetRawConstant(attr); } } } else { Object[] CustomAttrs = GetCustomAttributes(s_CustomConstantAttributeType, false); if (CustomAttrs.Length != 0) { defaultValue = ((CustomConstantAttribute)CustomAttrs[0]).Value; } else { CustomAttrs = GetCustomAttributes(s_DecimalConstantAttributeType, false); if (CustomAttrs.Length != 0) { defaultValue = ((DecimalConstantAttribute)CustomAttrs[0]).Value; } } } #endregion } if (defaultValue == DBNull.Value) m_noDefaultValue = true; return defaultValue; } internal RuntimeModule GetRuntimeModule() { RuntimeMethodInfo method = Member as RuntimeMethodInfo; RuntimeConstructorInfo constructor = Member as RuntimeConstructorInfo; RuntimePropertyInfo property = Member as RuntimePropertyInfo; if (method != null) return method.GetRuntimeModule(); else if (constructor != null) return constructor.GetRuntimeModule(); else if (property != null) return property.GetRuntimeModule(); else return null; } public override int MetadataToken { get { return m_tkParamDef; } } public override Type[] GetRequiredCustomModifiers() { return m_signature.GetCustomModifiers(PositionImpl + 1, true); } public override Type[] GetOptionalCustomModifiers() { return m_signature.GetCustomModifiers(PositionImpl + 1, false); } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { if (MdToken.IsNullToken(m_tkParamDef)) return EmptyArray<Object>.Value; return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); if (MdToken.IsNullToken(m_tkParamDef)) return EmptyArray<Object>.Value; RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); if (MdToken.IsNullToken(m_tkParamDef)) return false; RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #if FEATURE_REMOTING #region Remoting Cache private RemotingParameterCachedData m_cachedData; internal RemotingParameterCachedData RemotingCache { get { // This grabs an internal copy of m_cachedData and uses // that instead of looking at m_cachedData directly because // the cache may get cleared asynchronously. This prevents // us from having to take a lock. RemotingParameterCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingParameterCachedData(this); RemotingParameterCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING } }
using Orchard.ContentManagement; using Orchard.ContentManagement.Handlers; using Orchard.ContentManagement.MetaData; using Orchard.Core.Common.Models; using Orchard.Data; using Orchard.Localization; using Orchard.Security; using Orchard.Services; using System.Linq; namespace Orchard.Core.Common.Handlers { public class CommonPartHandler : ContentHandler { private readonly IClock _clock; private readonly IAuthenticationService _authenticationService; private readonly IContentManager _contentManager; private readonly IContentDefinitionManager _contentDefinitionManager; public CommonPartHandler( IRepository<CommonPartRecord> commonRepository, IRepository<CommonPartVersionRecord> commonVersionRepository, IClock clock, IAuthenticationService authenticationService, IContentManager contentManager, IContentDefinitionManager contentDefinitionManager) { _clock = clock; _authenticationService = authenticationService; _contentManager = contentManager; _contentDefinitionManager = contentDefinitionManager; T = NullLocalizer.Instance; Filters.Add(StorageFilter.For(commonRepository)); Filters.Add(StorageFilter.For(commonVersionRepository)); OnActivated<CommonPart>(PropertySetHandlers); OnInitializing<CommonPart>(AssignCreatingOwner); OnInitializing<CommonPart>(AssignCreatingDates); OnLoading<CommonPart>((context, part) => LazyLoadHandlers(part)); OnVersioning<CommonPart>((context, part, newVersionPart) => LazyLoadHandlers(newVersionPart)); OnUpdateEditorShape<CommonPart>(AssignUpdateDates); OnVersioning<CommonPart>(AssignVersioningDates); OnPublishing<CommonPart>(AssignPublishingDates); OnRemoving<CommonPart>(AssignRemovingDates); OnIndexing<CommonPart>((context, commonPart) => { var utcNow = _clock.UtcNow; context.DocumentIndex .Add("type", commonPart.ContentItem.ContentType).Store() .Add("created", commonPart.CreatedUtc ?? utcNow).Store() .Add("published", commonPart.PublishedUtc ?? utcNow).Store() .Add("modified", commonPart.ModifiedUtc ?? utcNow).Store(); if (commonPart.Container != null) { context.DocumentIndex.Add("container-id", commonPart.Container.Id).Store(); } if (commonPart.Owner != null) { context.DocumentIndex.Add("author", commonPart.Owner.UserName).Store(); } }); } public Localizer T { get; set; } protected override void Activating(ActivatingContentContext context) { if (ContentTypeWithACommonPart(context.ContentType)) context.Builder.Weld<ContentPart<CommonPartVersionRecord>>(); } protected bool ContentTypeWithACommonPart(string typeName) { //Note: What about content type handlers which activate "CommonPart" in code? var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(typeName); if (contentTypeDefinition != null) return contentTypeDefinition.Parts.Any(part => part.PartDefinition.Name == "CommonPart"); return false; } protected void AssignCreatingOwner(InitializingContentContext context, CommonPart part) { // and use the current user as Owner if (part.Record.OwnerId == 0) { part.Owner = _authenticationService.GetAuthenticatedUser(); } } protected void AssignCreatingDates(InitializingContentContext context, CommonPart part) { // assign default create/modified dates var utcNow = _clock.UtcNow; part.CreatedUtc = utcNow; part.ModifiedUtc = utcNow; part.VersionCreatedUtc = utcNow; part.VersionModifiedUtc = utcNow; part.VersionModifiedBy = GetUserName(); } private void AssignUpdateDates(UpdateEditorContext context, CommonPart part) { var utcNow = _clock.UtcNow; part.ModifiedUtc = utcNow; part.VersionModifiedUtc = utcNow; part.VersionModifiedBy = GetUserName(); } private void AssignRemovingDates(RemoveContentContext context, CommonPart part) { var utcNow = _clock.UtcNow; part.ModifiedUtc = utcNow; part.VersionModifiedUtc = utcNow; part.VersionModifiedBy = GetUserName(); } protected void AssignVersioningDates(VersionContentContext context, CommonPart existing, CommonPart building) { var utcNow = _clock.UtcNow; // assign the created date building.VersionCreatedUtc = utcNow; // assign modified date for the new version building.VersionModifiedUtc = utcNow; building.VersionModifiedBy = GetUserName(); // publish date should be null until publish method called building.VersionPublishedUtc = null; // assign the created building.CreatedUtc = existing.CreatedUtc ?? utcNow; // persist any published dates building.PublishedUtc = existing.PublishedUtc; // assign modified date for the new version building.ModifiedUtc = utcNow; } protected void AssignPublishingDates(PublishContentContext context, CommonPart part) { var utcNow = _clock.UtcNow; part.PublishedUtc = utcNow; part.VersionPublishedUtc = utcNow; } protected void LazyLoadHandlers(CommonPart part) { // add handlers that will load content for id's just-in-time part.OwnerField.Loader(() => _contentManager.Get<IUser>(part.Record.OwnerId)); part.ContainerField.Loader(() => part.Record.Container == null ? null : _contentManager.Get(part.Record.Container.Id)); } protected static void PropertySetHandlers(ActivatedContentContext context, CommonPart part) { // add handlers that will update records when part properties are set part.OwnerField.Setter(user => { part.Record.OwnerId = user == null ? 0 : user.ContentItem.Id; return user; }); // Force call to setter if we had already set a value if (part.OwnerField.Value != null) part.OwnerField.Value = part.OwnerField.Value; part.ContainerField.Setter(container => { part.Record.Container = container == null ? null : container.ContentItem.Record; return container; }); // Force call to setter if we had already set a value if (part.ContainerField.Value != null) part.ContainerField.Value = part.ContainerField.Value; } private string GetUserName() { var user = _authenticationService.GetAuthenticatedUser(); return user == null ? string.Empty : user.UserName; } } }
namespace Alchemi.Console.PropertiesDialogs { partial class ExecutorProperties { /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExecutorProperties)); this.label10 = new System.Windows.Forms.Label(); this.txPingTime = new System.Windows.Forms.TextBox(); this.chkDedicated = new System.Windows.Forms.CheckBox(); this.chkConnected = new System.Windows.Forms.CheckBox(); this.txPort = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.txId = new System.Windows.Forms.TextBox(); this.label9 = new System.Windows.Forms.Label(); this.txUsername = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.tabAdvanced = new System.Windows.Forms.TabPage(); this.label12 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.txOS = new System.Windows.Forms.TextBox(); this.txArch = new System.Windows.Forms.TextBox(); this.txMaxCPU = new System.Windows.Forms.TextBox(); this.txNumCPUs = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.txMaxDisk = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.tabPerf = new System.Windows.Forms.TabPage(); this.panel1 = new System.Windows.Forms.Panel(); this.plotSurface = new NPlot.Windows.PlotSurface2D(); this.tmRefreshSystem = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.tabGeneral.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.iconBox)).BeginInit(); this.tabs.SuspendLayout(); this.tabAdvanced.SuspendLayout(); this.tabPerf.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // btnOK // this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // imgListSmall // this.imgListSmall.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgListSmall.ImageStream"))); this.imgListSmall.Images.SetKeyName(0, ""); this.imgListSmall.Images.SetKeyName(1, ""); this.imgListSmall.Images.SetKeyName(2, ""); this.imgListSmall.Images.SetKeyName(3, ""); this.imgListSmall.Images.SetKeyName(4, ""); this.imgListSmall.Images.SetKeyName(5, ""); this.imgListSmall.Images.SetKeyName(6, ""); this.imgListSmall.Images.SetKeyName(7, ""); this.imgListSmall.Images.SetKeyName(8, ""); this.imgListSmall.Images.SetKeyName(9, ""); this.imgListSmall.Images.SetKeyName(10, ""); this.imgListSmall.Images.SetKeyName(11, ""); this.imgListSmall.Images.SetKeyName(12, ""); // // tabGeneral // this.tabGeneral.Controls.Add(this.label10); this.tabGeneral.Controls.Add(this.txPingTime); this.tabGeneral.Controls.Add(this.chkDedicated); this.tabGeneral.Controls.Add(this.chkConnected); this.tabGeneral.Controls.Add(this.txPort); this.tabGeneral.Controls.Add(this.label2); this.tabGeneral.Controls.Add(this.txId); this.tabGeneral.Controls.Add(this.label9); this.tabGeneral.Controls.Add(this.txUsername); this.tabGeneral.Controls.Add(this.label3); this.tabGeneral.Controls.SetChildIndex(this.iconBox, 0); this.tabGeneral.Controls.SetChildIndex(this.lbName, 0); this.tabGeneral.Controls.SetChildIndex(this.lineLabel, 0); this.tabGeneral.Controls.SetChildIndex(this.label3, 0); this.tabGeneral.Controls.SetChildIndex(this.txUsername, 0); this.tabGeneral.Controls.SetChildIndex(this.label9, 0); this.tabGeneral.Controls.SetChildIndex(this.txId, 0); this.tabGeneral.Controls.SetChildIndex(this.label2, 0); this.tabGeneral.Controls.SetChildIndex(this.txPort, 0); this.tabGeneral.Controls.SetChildIndex(this.chkConnected, 0); this.tabGeneral.Controls.SetChildIndex(this.chkDedicated, 0); this.tabGeneral.Controls.SetChildIndex(this.txPingTime, 0); this.tabGeneral.Controls.SetChildIndex(this.label10, 0); // // tabs // this.tabs.Controls.Add(this.tabAdvanced); this.tabs.Controls.Add(this.tabPerf); this.tabs.Controls.SetChildIndex(this.tabPerf, 0); this.tabs.Controls.SetChildIndex(this.tabAdvanced, 0); this.tabs.Controls.SetChildIndex(this.tabGeneral, 0); // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(16, 176); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(75, 13); this.label10.TabIndex = 42; this.label10.Text = "Last ping time:"; // // txPingTime // this.txPingTime.BackColor = System.Drawing.Color.White; this.txPingTime.Location = new System.Drawing.Point(96, 176); this.txPingTime.Name = "txPingTime"; this.txPingTime.ReadOnly = true; this.txPingTime.Size = new System.Drawing.Size(144, 20); this.txPingTime.TabIndex = 41; this.txPingTime.Text = "txPingTime"; // // chkDedicated // this.chkDedicated.AutoCheck = false; this.chkDedicated.Location = new System.Drawing.Point(16, 240); this.chkDedicated.Name = "chkDedicated"; this.chkDedicated.Size = new System.Drawing.Size(80, 24); this.chkDedicated.TabIndex = 40; this.chkDedicated.Text = "Dedicated"; // // chkConnected // this.chkConnected.AutoCheck = false; this.chkConnected.Location = new System.Drawing.Point(16, 208); this.chkConnected.Name = "chkConnected"; this.chkConnected.Size = new System.Drawing.Size(80, 24); this.chkConnected.TabIndex = 39; this.chkConnected.Text = "Connected"; // // txPort // this.txPort.BackColor = System.Drawing.Color.White; this.txPort.Location = new System.Drawing.Point(96, 112); this.txPort.Name = "txPort"; this.txPort.ReadOnly = true; this.txPort.Size = new System.Drawing.Size(48, 20); this.txPort.TabIndex = 38; this.txPort.Text = "txPort"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(16, 112); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(29, 13); this.label2.TabIndex = 37; this.label2.Text = "Port:"; // // txId // this.txId.BackColor = System.Drawing.Color.White; this.txId.Location = new System.Drawing.Point(96, 80); this.txId.Name = "txId"; this.txId.ReadOnly = true; this.txId.Size = new System.Drawing.Size(216, 20); this.txId.TabIndex = 36; this.txId.Text = "txId"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(16, 82); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(19, 13); this.label9.TabIndex = 35; this.label9.Text = "Id:"; // // txUsername // this.txUsername.BackColor = System.Drawing.Color.White; this.txUsername.Location = new System.Drawing.Point(96, 144); this.txUsername.Name = "txUsername"; this.txUsername.ReadOnly = true; this.txUsername.Size = new System.Drawing.Size(144, 20); this.txUsername.TabIndex = 34; this.txUsername.Text = "txUsername"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(16, 144); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(58, 13); this.label3.TabIndex = 33; this.label3.Text = "Username:"; // // tabAdvanced // this.tabAdvanced.Controls.Add(this.label12); this.tabAdvanced.Controls.Add(this.label11); this.tabAdvanced.Controls.Add(this.label6); this.tabAdvanced.Controls.Add(this.txOS); this.tabAdvanced.Controls.Add(this.txArch); this.tabAdvanced.Controls.Add(this.txMaxCPU); this.tabAdvanced.Controls.Add(this.txNumCPUs); this.tabAdvanced.Controls.Add(this.label8); this.tabAdvanced.Controls.Add(this.txMaxDisk); this.tabAdvanced.Controls.Add(this.label7); this.tabAdvanced.Controls.Add(this.label4); this.tabAdvanced.Controls.Add(this.label5); this.tabAdvanced.Location = new System.Drawing.Point(4, 22); this.tabAdvanced.Name = "tabAdvanced"; this.tabAdvanced.Size = new System.Drawing.Size(328, 318); this.tabAdvanced.TabIndex = 2; this.tabAdvanced.Text = "Advanced"; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(248, 114); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(26, 13); this.label12.TabIndex = 35; this.label12.Text = "MB."; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(248, 82); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(30, 13); this.label11.TabIndex = 34; this.label11.Text = "Mhz."; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(16, 80); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(58, 13); this.label6.TabIndex = 29; this.label6.Text = "Max. CPU:"; // // txOS // this.txOS.BackColor = System.Drawing.Color.White; this.txOS.Location = new System.Drawing.Point(112, 48); this.txOS.Name = "txOS"; this.txOS.ReadOnly = true; this.txOS.Size = new System.Drawing.Size(200, 20); this.txOS.TabIndex = 26; this.txOS.Text = "txOS"; // // txArch // this.txArch.BackColor = System.Drawing.Color.White; this.txArch.Location = new System.Drawing.Point(112, 16); this.txArch.Name = "txArch"; this.txArch.ReadOnly = true; this.txArch.Size = new System.Drawing.Size(200, 20); this.txArch.TabIndex = 24; this.txArch.Text = "txArch"; // // txMaxCPU // this.txMaxCPU.BackColor = System.Drawing.Color.White; this.txMaxCPU.Location = new System.Drawing.Point(112, 80); this.txMaxCPU.Name = "txMaxCPU"; this.txMaxCPU.ReadOnly = true; this.txMaxCPU.Size = new System.Drawing.Size(128, 20); this.txMaxCPU.TabIndex = 28; this.txMaxCPU.Text = "txMaxCPU"; // // txNumCPUs // this.txNumCPUs.BackColor = System.Drawing.Color.White; this.txNumCPUs.Location = new System.Drawing.Point(112, 144); this.txNumCPUs.Name = "txNumCPUs"; this.txNumCPUs.ReadOnly = true; this.txNumCPUs.Size = new System.Drawing.Size(40, 20); this.txNumCPUs.TabIndex = 32; this.txNumCPUs.Text = "txNumCPUs"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(16, 144); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(59, 13); this.label8.TabIndex = 33; this.label8.Text = "# of CPUs:"; // // txMaxDisk // this.txMaxDisk.BackColor = System.Drawing.Color.White; this.txMaxDisk.Location = new System.Drawing.Point(112, 112); this.txMaxDisk.Name = "txMaxDisk"; this.txMaxDisk.ReadOnly = true; this.txMaxDisk.Size = new System.Drawing.Size(128, 20); this.txMaxDisk.TabIndex = 30; this.txMaxDisk.Text = "txMaxDisk"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(16, 112); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(73, 13); this.label7.TabIndex = 31; this.label7.Text = "Max. Storage:"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(16, 16); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(67, 13); this.label4.TabIndex = 25; this.label4.Text = "Architecture:"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(16, 48); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(93, 13); this.label5.TabIndex = 27; this.label5.Text = "Operating System:"; // // tabPerf // this.tabPerf.Controls.Add(this.panel1); this.tabPerf.Location = new System.Drawing.Point(4, 22); this.tabPerf.Name = "tabPerf"; this.tabPerf.Size = new System.Drawing.Size(328, 318); this.tabPerf.TabIndex = 3; this.tabPerf.Text = "Performance"; // // panel1 // this.panel1.BackColor = System.Drawing.SystemColors.Control; this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.panel1.Controls.Add(this.plotSurface); this.panel1.Location = new System.Drawing.Point(8, 8); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(312, 304); this.panel1.TabIndex = 28; // // plotSurface // this.plotSurface.Anchor = System.Windows.Forms.AnchorStyles.None; this.plotSurface.AutoScaleAutoGeneratedAxes = false; this.plotSurface.AutoScaleTitle = false; this.plotSurface.BackColor = System.Drawing.SystemColors.ControlLightLight; this.plotSurface.DateTimeToolTip = false; this.plotSurface.Legend = null; this.plotSurface.LegendZOrder = -1; this.plotSurface.Location = new System.Drawing.Point(2, 2); this.plotSurface.Name = "plotSurface"; this.plotSurface.RightMenu = null; this.plotSurface.ShowCoordinates = true; this.plotSurface.Size = new System.Drawing.Size(304, 296); this.plotSurface.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; this.plotSurface.TabIndex = 0; this.plotSurface.Text = "plotSurface2D1"; this.plotSurface.Title = ""; this.plotSurface.TitleFont = new System.Drawing.Font("Arial", 7F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.plotSurface.XAxis1 = null; this.plotSurface.XAxis2 = null; this.plotSurface.YAxis1 = null; this.plotSurface.YAxis2 = null; // // tmRefreshSystem // this.tmRefreshSystem.Interval = 2000; this.tmRefreshSystem.Tick += new System.EventHandler(this.tmRefreshSystem_Tick); // // ExecutorProperties2 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(352, 389); this.Name = "ExecutorProperties2"; this.Text = "Executor Properties"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.tabGeneral.ResumeLayout(false); this.tabGeneral.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.iconBox)).EndInit(); this.tabs.ResumeLayout(false); this.tabAdvanced.ResumeLayout(false); this.tabAdvanced.PerformLayout(); this.tabPerf.ResumeLayout(false); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox txPingTime; private System.Windows.Forms.CheckBox chkDedicated; private System.Windows.Forms.CheckBox chkConnected; private System.Windows.Forms.TextBox txPort; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txId; private System.Windows.Forms.Label label9; private System.Windows.Forms.TextBox txUsername; private System.Windows.Forms.Label label3; private System.Windows.Forms.TabPage tabAdvanced; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox txOS; private System.Windows.Forms.TextBox txArch; private System.Windows.Forms.TextBox txMaxCPU; private System.Windows.Forms.TextBox txNumCPUs; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox txMaxDisk; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.TabPage tabPerf; private System.Windows.Forms.Panel panel1; private NPlot.Windows.PlotSurface2D plotSurface; private System.Windows.Forms.Timer tmRefreshSystem; } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using Epi; using Epi.Windows; using Epi.Windows.Controls; using System.Data; using Epi.Analysis; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; using Epi.Data.Services; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for Summarize command /// </summary> public partial class SummarizeDialog : CommandDesignDialog { #region Private Class Members #endregion Private Class Members #region Constructor /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public SummarizeDialog() { InitializeComponent(); } /// <summary> /// Constructor for the Summarize Dialog /// </summary> /// <param name="frm"></param> public SummarizeDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } #endregion Constructors #region Event Handlers /// <summary> /// Clears all user input /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnClear_Click(object sender, System.EventArgs e) { cmbAggregate.Text = string.Empty; cmbVar.Text = string.Empty; txtIntoVar.Text = string.Empty; lbxVar.Items.Clear(); cmbGroupBy.Text = string.Empty; lbxGroupBy.Text = string.Empty; cmbWeight.Text = string.Empty; txtOutput.Text = string.Empty; lbxGroupBy.Items.Clear(); cmbWeight.SelectedIndex = -1; cmbAggregate.Focus(); } /// <summary> /// Loads the aggregate combo box /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void SummarizeDialog_Load(object sender, System.EventArgs e) { LoadAggregates(); //Localization.LocalizeComboBoxItems(cmbAggregate,false); LoadVariables(); } /// <summary> /// Populate lbxvar with aggregate command each time Apply is clicked /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnApply_Click(object sender, System.EventArgs e) { //WordBuilder appends a space in each append and here there should be no space between two colons System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(txtIntoVar.Text).Append(StringLiterals.SPACE); sb.Append(StringLiterals.COLON); sb.Append(StringLiterals.COLON); sb.Append(StringLiterals.SPACE); string aggregate = ((SupportedAggregate)(System.Convert.ToInt32(cmbAggregate.SelectedValue))).ToString(); sb.Append(aggregate); sb.Append(Util.InsertInParantheses(cmbVar.Text)); lbxVar.Items.Add(sb.ToString()); cmbAggregate.Text = string.Empty ; cmbVar.Text = string.Empty; txtIntoVar.Text = string.Empty; btnApply.Enabled = false; txtOutput_TextChanged(txtOutput,e); } /// <summary> /// Enable OK and SaveOnly only when after aggregate variable is built and an output table name is provided /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void txtOutput_TextChanged(object sender, System.EventArgs e) { CheckForInputSufficiency(); } /// <summary> /// Sets enabled property of Apply button /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void SetEnabledApply(object sender, System.EventArgs e) { if ((!string.IsNullOrEmpty(cmbAggregate.Text)) && (!string.IsNullOrEmpty(cmbVar.Text)) && (!string.IsNullOrEmpty(txtIntoVar.Text.Trim()))) { btnApply.Enabled = true; } else { btnApply.Enabled = false; } } /// <summary> /// Handles the SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbGroupBy_SelectedIndexChanged(object sender, System.EventArgs e) { lbxGroupBy.Items.Add(cmbGroupBy.SelectedItem.ToString()); } /// <summary> /// Handles the DoubleClick event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void lbxGroupBy_DoubleClick(object sender, System.EventArgs e) { if (lbxGroupBy.Items.Count > 0) { lbxGroupBy.Items.RemoveAt(lbxGroupBy.SelectedIndex); } } /// <summary> /// Opens a process to show the related help topic /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> protected override void btnHelp_Click(object sender, System.EventArgs e) { System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-summarize.html"); } #endregion //Event Handlers #region Protected Methods /// <summary> /// Validates the input provided by the user /// </summary> /// <returns></returns> protected override bool ValidateInput() { base.ValidateInput (); if (lbxVar.Items.Count == 0) { ErrorMessages.Add(SharedStrings.NO_AGGREGATE_SPECIFIED); } if (string.IsNullOrEmpty(txtOutput.Text.Trim())) { ErrorMessages.Add(SharedStrings.OUTPUT_TABLE_NOT_SPECIFIED); } return (ErrorMessages.Count == 0); } /// <summary> /// Generates command text /// </summary> protected override void GenerateCommand() { WordBuilder command = new WordBuilder(); command.Append(CommandNames.SUMMARIZE); //Append aggregates foreach (string item in lbxVar.Items) { command.Append(item); } //Append output table command.Append(CommandNames.TO); command.Append(txtOutput.Text.Trim()); //Append strata variables if (lbxGroupBy.Items.Count > 0) { command.Append(CommandNames.STRATAVAR); command.Append(StringLiterals.EQUAL); foreach (string item in lbxGroupBy.Items) { command.Append(item); } } //Append weighted variables if (cmbWeight.SelectedItem != null && !string.IsNullOrEmpty(cmbWeight.SelectedItem.ToString())) { command.Append(CommandNames.WEIGHTVAR); command.Append(StringLiterals.EQUAL); command.Append(cmbWeight.SelectedItem.ToString()); } CommandText = command.ToString(); } /// <summary> /// Sets the enabled property of OK and SaveOnly button /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); btnOK.Enabled = inputValid; btnSaveOnly.Enabled = inputValid; } #endregion //Protected Methods #region Private Methods private void Construct() { if (!this.DesignMode) { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); } } /// <summary> /// Attach aggregates /// </summary> private void LoadAggregates() { LocalizedComboBox cbx = cmbAggregate; DataView dv = AppData.Instance.SupportedAggregatesDataTable.DefaultView; cbx.DataSource = dv; cbx.DisplayMember = ColumnNames.NAME; cbx.ValueMember = ColumnNames.ID; cbx.SelectedIndex = -1; cbx.SkipTranslation = false; } private void LoadVariables() { //First get the list of all variables // DataTable variables = GetAllVariablesAsDataTable(true, true, false, false); //DataTable variables = GetMemoryRegion().GetVariablesAsDataTable( // VariableType.DataSource | // VariableType.Standard); ////Sort the data //System.Data.DataView dv = variables.DefaultView; //dv.Sort = ColumnNames.NAME; //cmbVar.DataSource = dv; //cmbVar.DisplayMember = ColumnNames.NAME; //cmbVar.ValueMember = ColumnNames.NAME; VariableType scopeWord = VariableType.DataSource | VariableType.Standard; FillVariableCombo(cmbVar, scopeWord); cmbVar.SelectedIndex = -1; FillVariableCombo(cmbGroupBy, scopeWord); cmbGroupBy.SelectedIndex = -1; FillVariableCombo(cmbWeight, scopeWord); cmbWeight.SelectedIndex = -1; } #endregion //Private Methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.NativeFormat; using Internal.TypeSystem; using Internal.Runtime.CallConverter; using ThunkKind = Internal.Runtime.TypeLoader.CallConverterThunk.ThunkKind; namespace Internal.Runtime.TypeLoader { internal enum CallConversionInfoRegistrationKind { UsesMethodSignatureAndGenericArgs, UsesArgIteratorData } internal class CallConversionInfo : IEquatable<CallConversionInfo> { private CallConversionInfo() { } private static int s_callConvertersCount = 0; private static volatile CallConversionInfo[] s_callConverters = new CallConversionInfo[512]; private static Lock s_callConvertersCacheLock = new Lock(); private static LowLevelDictionary<CallConversionInfo, int> s_callConvertersCache = new LowLevelDictionary<CallConversionInfo, int>(); private CallConversionInfoRegistrationKind _registrationKind; // // Thunk data // private ThunkKind _thunkKind; private IntPtr _targetFunctionPointer; private IntPtr _instantiatingArg; private ArgIteratorData _argIteratorData; private bool[] _paramsByRefForced; // // Method signature and generic context info. Signatures are parsed lazily when they are really needed // private RuntimeSignature _methodSignature; private volatile bool _signatureParsed; private RuntimeTypeHandle[] _typeArgs; private RuntimeTypeHandle[] _methodArgs; private int? _hashCode; #if CCCONVERTER_TRACE internal string ThunkKindString() { switch (_thunkKind) { case ThunkKind.StandardToStandardInstantiating: return "StandardToStandardInstantiating"; case ThunkKind.StandardToGenericInstantiating: return "StandardToGenericInstantiating"; case ThunkKind.StandardToGenericInstantiatingIfNotHasThis: return "StandardToGenericInstantiatingIfNotHasThis"; case ThunkKind.StandardToGeneric: return "StandardToGeneric"; case ThunkKind.GenericToStandard: return "GenericToStandard"; case ThunkKind.StandardUnboxing: return "StandardUnboxing"; case ThunkKind.StandardUnboxingAndInstantiatingGeneric: return "StandardUnboxingAndInstantiatingGeneric"; case ThunkKind.GenericToStandardWithTargetPointerArg: return "GenericToStandardWithTargetPointerArg"; case ThunkKind.GenericToStandardWithTargetPointerArgAndParamArg: return "GenericToStandardWithTargetPointerArgAndParamArg"; case ThunkKind.GenericToStandardWithTargetPointerArgAndMaybeParamArg: return "GenericToStandardWithTargetPointerArgAndMaybeParamArg"; case ThunkKind.DelegateInvokeOpenStaticThunk: return "DelegateInvokeOpenStaticThunk"; case ThunkKind.DelegateInvokeClosedStaticThunk: return "DelegateInvokeClosedStaticThunk"; case ThunkKind.DelegateInvokeOpenInstanceThunk: return "DelegateInvokeOpenInstanceThunk"; case ThunkKind.DelegateInvokeInstanceClosedOverGenericMethodThunk: return "DelegateInvokeInstanceClosedOverGenericMethodThunk"; case ThunkKind.DelegateMulticastThunk: return "DelegateMulticastThunk"; case ThunkKind.DelegateObjectArrayThunk: return "DelegateObjectArrayThunk"; case ThunkKind.DelegateDynamicInvokeThunk: return "DelegateDynamicInvokeThunk"; case ThunkKind.ReflectionDynamicInvokeThunk: return "ReflectionDynamicInvokeThunk"; } return ((int)_thunkKind).LowLevelToString(); } #endif public override bool Equals(object obj) { if (this == obj) return true; CallConversionInfo other = obj as CallConversionInfo; if (other == null) return false; return Equals(other); } public bool Equals(CallConversionInfo other) { if (_registrationKind != other._registrationKind) return false; if (_thunkKind != other._thunkKind) return false; if (_targetFunctionPointer != other._targetFunctionPointer) return false; if (_instantiatingArg != other._instantiatingArg) return false; switch (_registrationKind) { case CallConversionInfoRegistrationKind.UsesMethodSignatureAndGenericArgs: { return (_methodSignature.StructuralEquals(other._methodSignature) && ArraysAreEqual(_typeArgs, other._typeArgs) && ArraysAreEqual(_methodArgs, other._methodArgs)); } case CallConversionInfoRegistrationKind.UsesArgIteratorData: { return _argIteratorData.Equals(other._argIteratorData) && ArraysAreEqual(_paramsByRefForced, other._paramsByRefForced); } } Debug.Assert(false, "UNREACHABLE"); return false; } private bool ArraysAreEqual<T>(T[] array1, T[] array2) { if (array1 == null) return array2 == null; if (array2 == null || array1.Length != array2.Length) return false; for (int i = 0; i < array1.Length; i++) if (!array1[i].Equals(array2[i])) return false; return true; } public override int GetHashCode() { if (!_hashCode.HasValue) { int hashCode = 79 + 971 * (int)_thunkKind + 83 * (_targetFunctionPointer.GetHashCode() >> 7) + 13 * (_instantiatingArg.GetHashCode() >> 3); switch (_registrationKind) { case CallConversionInfoRegistrationKind.UsesMethodSignatureAndGenericArgs: hashCode ^= _methodSignature.GetHashCode(); hashCode = _typeArgs == null ? hashCode : TypeHashingAlgorithms.ComputeGenericInstanceHashCode(hashCode, _typeArgs); hashCode = _methodArgs == null ? hashCode : TypeHashingAlgorithms.ComputeGenericInstanceHashCode(hashCode, _methodArgs); break; case CallConversionInfoRegistrationKind.UsesArgIteratorData: hashCode ^= _argIteratorData.GetHashCode(); break; } _hashCode = hashCode; } return _hashCode.Value; } #region Construction // // Lazily parse the method signature, and construct the call converter data // private void EnsureCallConversionInfoLoaded() { if (_signatureParsed) return; lock (this) { // Check if race was won by another thread and the signature got parsed if (_signatureParsed) return; TypeSystemContext context = TypeSystemContextFactory.Create(); { Instantiation typeInstantiation = Instantiation.Empty; Instantiation methodInstantiation = Instantiation.Empty; if (_typeArgs != null && _typeArgs.Length > 0) typeInstantiation = context.ResolveRuntimeTypeHandles(_typeArgs); if (_methodArgs != null && _methodArgs.Length > 0) methodInstantiation = context.ResolveRuntimeTypeHandles(_methodArgs); bool hasThis; TypeDesc[] parameters; bool[] paramsByRefForced; if (!TypeLoaderEnvironment.Instance.GetCallingConverterDataFromMethodSignature(context, _methodSignature, typeInstantiation, methodInstantiation, out hasThis, out parameters, out paramsByRefForced)) { Debug.Assert(false); Environment.FailFast("Failed to get type handles for parameters in method signature"); } Debug.Assert(parameters != null && parameters.Length >= 1); bool[] byRefParameters = new bool[parameters.Length]; RuntimeTypeHandle[] parameterHandles = new RuntimeTypeHandle[parameters.Length]; for (int j = 0; j < parameters.Length; j++) { ByRefType parameterAsByRefType = parameters[j] as ByRefType; if (parameterAsByRefType != null) { parameterAsByRefType.ParameterType.RetrieveRuntimeTypeHandleIfPossible(); parameterHandles[j] = parameterAsByRefType.ParameterType.RuntimeTypeHandle; byRefParameters[j] = true; } else { parameters[j].RetrieveRuntimeTypeHandleIfPossible(); parameterHandles[j] = parameters[j].RuntimeTypeHandle; byRefParameters[j] = false; } Debug.Assert(!parameterHandles[j].IsNull()); } // Build thunk data TypeHandle thReturnType = new TypeHandle(CallConverterThunk.GetByRefIndicatorAtIndex(0, byRefParameters), parameterHandles[0]); TypeHandle[] thParameters = null; if (parameters.Length > 1) { thParameters = new TypeHandle[parameters.Length - 1]; for (int i = 1; i < parameters.Length; i++) { thParameters[i - 1] = new TypeHandle(CallConverterThunk.GetByRefIndicatorAtIndex(i, byRefParameters), parameterHandles[i]); } } _argIteratorData = new ArgIteratorData(hasThis, false, thParameters, thReturnType); // StandardToStandard thunks don't actually need any parameters to change their ABI // so don't force any params to be adjusted if (!StandardToStandardThunk) { _paramsByRefForced = paramsByRefForced; } } TypeSystemContextFactory.Recycle(context); _signatureParsed = true; } } public static int RegisterCallConversionInfo(ThunkKind thunkKind, IntPtr targetPointer, RuntimeSignature methodSignature, IntPtr instantiatingArg, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs) { CallConversionInfo newConversionInfo = new CallConversionInfo(); newConversionInfo._registrationKind = CallConversionInfoRegistrationKind.UsesMethodSignatureAndGenericArgs; newConversionInfo._thunkKind = thunkKind; newConversionInfo._targetFunctionPointer = targetPointer; newConversionInfo._methodSignature = methodSignature; newConversionInfo._instantiatingArg = instantiatingArg; newConversionInfo._typeArgs = typeArgs; newConversionInfo._methodArgs = methodArgs; newConversionInfo._signatureParsed = false; return AddConverter(newConversionInfo); } public static int RegisterCallConversionInfo(ThunkKind thunkKind, IntPtr targetPointer, IntPtr instantiatingArg, bool hasThis, TypeHandle returnType, TypeHandle[] parameterTypes, bool[] paramsByRefForced) { CallConversionInfo newConversionInfo = new CallConversionInfo(); newConversionInfo._registrationKind = CallConversionInfoRegistrationKind.UsesArgIteratorData; newConversionInfo._thunkKind = thunkKind; newConversionInfo._targetFunctionPointer = targetPointer; newConversionInfo._instantiatingArg = instantiatingArg; newConversionInfo._argIteratorData = new ArgIteratorData(hasThis, false, parameterTypes, returnType); newConversionInfo._paramsByRefForced = paramsByRefForced; newConversionInfo._signatureParsed = true; return AddConverter(newConversionInfo); } public static int RegisterCallConversionInfo(ThunkKind thunkKind, IntPtr targetPointer, IntPtr instantiatingArg, ArgIteratorData argIteratorData, bool[] paramsByRefForced) { Debug.Assert(argIteratorData != null); CallConversionInfo newConversionInfo = new CallConversionInfo(); newConversionInfo._registrationKind = CallConversionInfoRegistrationKind.UsesArgIteratorData; newConversionInfo._thunkKind = thunkKind; newConversionInfo._targetFunctionPointer = targetPointer; newConversionInfo._instantiatingArg = instantiatingArg; newConversionInfo._argIteratorData = argIteratorData; newConversionInfo._paramsByRefForced = paramsByRefForced; newConversionInfo._signatureParsed = true; return AddConverter(newConversionInfo); } private static int AddConverter(CallConversionInfo newConversionInfo) { using (LockHolder.Hold(s_callConvertersCacheLock)) { int converterId; if (s_callConvertersCache.TryGetValue(newConversionInfo, out converterId)) { Debug.Assert(converterId < s_callConvertersCount && s_callConverters[converterId].Equals(newConversionInfo)); return converterId; } if (s_callConvertersCount >= s_callConverters.Length) { CallConversionInfo[] newArray = new CallConversionInfo[s_callConverters.Length * 2]; Array.Copy(s_callConverters, newArray, s_callConvertersCount); s_callConverters = newArray; } s_callConverters[s_callConvertersCount++] = newConversionInfo; s_callConvertersCache[newConversionInfo] = s_callConvertersCount - 1; return s_callConvertersCount - 1; } } #endregion public static CallConversionInfo GetConverter(int id) { return s_callConverters[id]; } #region Conversion Properties public IntPtr TargetFunctionPointer { get { return _targetFunctionPointer; } } public bool StandardToStandardThunk { get { switch (_thunkKind) { case ThunkKind.StandardToStandardInstantiating: return true; default: return false; } } } public bool CallerHasExtraParameterWhichIsFunctionTarget { get { switch (_thunkKind) { case ThunkKind.GenericToStandardWithTargetPointerArg: case ThunkKind.GenericToStandardWithTargetPointerArgAndParamArg: case ThunkKind.GenericToStandardWithTargetPointerArgAndMaybeParamArg: return true; } return false; } } public bool CalleeMayHaveParamType { get { return _thunkKind == ThunkKind.GenericToStandardWithTargetPointerArgAndMaybeParamArg; } } public bool IsUnboxingThunk { get { switch (_thunkKind) { case ThunkKind.StandardUnboxing: case ThunkKind.StandardUnboxingAndInstantiatingGeneric: return true; } return false; } } public bool IsDelegateThunk { get { switch (_thunkKind) { case ThunkKind.DelegateInvokeOpenStaticThunk: case ThunkKind.DelegateInvokeClosedStaticThunk: case ThunkKind.DelegateInvokeOpenInstanceThunk: case ThunkKind.DelegateInvokeInstanceClosedOverGenericMethodThunk: case ThunkKind.DelegateMulticastThunk: case ThunkKind.DelegateObjectArrayThunk: case ThunkKind.DelegateDynamicInvokeThunk: return true; } return false; } } public bool TargetDelegateFunctionIsExtraFunctionPointerOrDataField { get { switch (_thunkKind) { case ThunkKind.DelegateInvokeOpenStaticThunk: case ThunkKind.DelegateInvokeClosedStaticThunk: case ThunkKind.DelegateInvokeOpenInstanceThunk: case ThunkKind.DelegateInvokeInstanceClosedOverGenericMethodThunk: return true; } return false; } } public bool IsOpenInstanceDelegateThunk { get { return _thunkKind == ThunkKind.DelegateInvokeOpenInstanceThunk; } } public bool IsClosedStaticDelegate { get { return _thunkKind == ThunkKind.DelegateInvokeClosedStaticThunk; } } public bool IsMulticastDelegate { get { return _thunkKind == ThunkKind.DelegateMulticastThunk; } } public bool IsObjectArrayDelegateThunk { get { return _thunkKind == ThunkKind.DelegateObjectArrayThunk; } } public bool IsDelegateDynamicInvokeThunk { get { return _thunkKind == ThunkKind.DelegateDynamicInvokeThunk; } } public bool IsReflectionDynamicInvokerThunk { get { return _thunkKind == ThunkKind.ReflectionDynamicInvokeThunk; } } public bool IsAnyDynamicInvokerThunk { get { switch (_thunkKind) { case ThunkKind.DelegateDynamicInvokeThunk: case ThunkKind.ReflectionDynamicInvokeThunk: return true; } return false; } } public bool IsStaticDelegateThunk { get { switch (_thunkKind) { case ThunkKind.DelegateInvokeOpenStaticThunk: case ThunkKind.DelegateInvokeClosedStaticThunk: return true; } return false; } } public bool IsThisPointerInDelegateData { get { switch (_thunkKind) { case ThunkKind.DelegateInvokeOpenInstanceThunk: case ThunkKind.DelegateInvokeInstanceClosedOverGenericMethodThunk: case ThunkKind.DelegateMulticastThunk: case ThunkKind.DelegateDynamicInvokeThunk: return true; } return false; } } public IntPtr InstantiatingStubArgument { get { return _instantiatingArg; } } public ArgIteratorData ArgIteratorData { get { EnsureCallConversionInfoLoaded(); return _argIteratorData; } } public bool CalleeHasParamType { get { switch (_thunkKind) { case ThunkKind.StandardUnboxingAndInstantiatingGeneric: case ThunkKind.GenericToStandardWithTargetPointerArgAndParamArg: case ThunkKind.StandardToGenericInstantiating: case ThunkKind.StandardToStandardInstantiating: case ThunkKind.StandardToGenericPassthruInstantiating: return true; case ThunkKind.StandardToGenericPassthruInstantiatingIfNotHasThis: case ThunkKind.StandardToGenericInstantiatingIfNotHasThis: EnsureCallConversionInfoLoaded(); return !_argIteratorData.HasThis(); } return false; } } public bool CallerHasParamType { get { switch (_thunkKind) { case ThunkKind.GenericToStandardWithTargetPointerArgAndParamArg: case ThunkKind.StandardToGenericPassthruInstantiating: return true; case ThunkKind.StandardToGenericPassthruInstantiatingIfNotHasThis: return CalleeHasParamType; } return false; } } private bool ForcedByRefParametersAreCaller { get { switch (_thunkKind) { case ThunkKind.GenericToStandard: case ThunkKind.GenericToStandardWithTargetPointerArg: case ThunkKind.GenericToStandardWithTargetPointerArgAndParamArg: case ThunkKind.GenericToStandardWithTargetPointerArgAndMaybeParamArg: return true; } return false; } } public bool[] CallerForcedByRefData { get { EnsureCallConversionInfoLoaded(); if (ForcedByRefParametersAreCaller && !IsDelegateThunk) { return _paramsByRefForced; } else { return null; } } } public bool[] CalleeForcedByRefData { get { EnsureCallConversionInfoLoaded(); if (!ForcedByRefParametersAreCaller && !IsDelegateThunk) { return _paramsByRefForced; } else { return null; } } } #endregion } }
using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Windows.Forms; namespace MagiWol { internal partial class QuickWakeForm : Form { public QuickWakeForm() { InitializeComponent(); this.Font = SystemFonts.MessageBoxFont; var fixedSizeFont = new Font("Courier New", base.Font.Size, base.Font.Style); this.textMac.Font = fixedSizeFont; this.textSecureOn.Font = fixedSizeFont; foreach (Control iControl in new Control[] { textMac, textSecureOn, checkBroadcastAddress, checkBroadcastPort }) { //because of Mono erp.SetIconPadding(iControl, 4); erp.SetIconAlignment(iControl, ErrorIconAlignment.MiddleLeft); } } public QuickWakeForm(MagiWolDocument.AddressItem address) : this() { if (address != null) { textMac.Text = address.Mac; textSecureOn.Text = address.SecureOn; if (address.IsBroadcastHostValid) { checkBroadcastAddress.Checked = true; textBroadcastAddress.Text = address.BroadcastHost; } if (address.IsBroadcastPortValid) { checkBroadcastPort.Checked = true; textBroadcastPort.Text = address.BroadcastPort.ToString(CultureInfo.CurrentCulture); } } } private void DetailForm_Load(object sender, EventArgs e) { checkProtocolIPv4.Checked = Settings.UseIPv4; checkProtocolIPv6.Checked = Settings.UseIPv6; checkProtocol_CheckedChanged(null, null); textBroadcastAddress.Text = Settings.BroadcastHost; textBroadcastPort.Text = Settings.BroadcastPort.ToString(CultureInfo.InvariantCulture); CheckForm(); } private void buttonOk_Click(object sender, EventArgs e) { var destination = new MagiWolDocument.AddressItem(); destination.Title = null; destination.Mac = textMac.Text; destination.SecureOn = textSecureOn.Text; string host; if (checkBroadcastAddress.Checked) { if (string.IsNullOrEmpty(textBroadcastAddress.Text.Trim()) == false) { host = textBroadcastAddress.Text.Trim(); destination.IsBroadcastHostValid = true; } else { host = Settings.BroadcastHost; destination.IsBroadcastHostValid = false; } } else { host = destination.BroadcastHost; destination.IsBroadcastHostValid = false; } int port; if (checkBroadcastPort.Checked) { if (int.TryParse(textBroadcastPort.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out port)) { if ((port >= 0) || (port <= 65535)) { destination.IsBroadcastPortValid = true; } else { port = Settings.BroadcastPort; destination.IsBroadcastPortValid = false; } } else { port = Settings.BroadcastPort; destination.IsBroadcastPortValid = false; } } else { port = destination.BroadcastPort; destination.IsBroadcastPortValid = false; } destination.BroadcastHost = host; destination.BroadcastPort = port; destination.Notes = null; } private void checkProtocol_CheckedChanged(object sender, EventArgs e) { if (sender != null) { var chb = (CheckBox)sender; if ((checkProtocolIPv4.Checked == false) && (checkProtocolIPv6.Checked == false)) { chb.Checked = true; } } labelBroadcastAddress.Enabled = checkProtocolIPv4.Checked; textBroadcastAddress.Enabled = checkProtocolIPv4.Checked && checkBroadcastAddress.Checked; } private void checkBroadcastAddress_CheckedChanged(object sender, EventArgs e) { textBroadcastAddress.Enabled = checkBroadcastAddress.Checked; } private void checkBroadcastPort_CheckedChanged(object sender, EventArgs e) { textBroadcastPort.Enabled = checkBroadcastPort.Checked; } private void textBroadcastAddress_Validating(object sender, CancelEventArgs e) { if (string.IsNullOrEmpty(textBroadcastAddress.Text.Trim())) { checkBroadcastAddress.Checked = false; textBroadcastAddress.Text = Settings.BroadcastHost; } } private void textBroadcastPort_Validating(object sender, CancelEventArgs e) { int port; if (!(int.TryParse(textBroadcastPort.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) && (port >= 0) && (port <= 65535))) { textBroadcastPort.Text = Settings.BroadcastPort.ToString(CultureInfo.InvariantCulture); } } private void DetailForm_Shown(object sender, EventArgs e) { textMac.SelectAll(); } private void buttonTest_Click(object sender, EventArgs e) { try { try { Cursor.Current = Cursors.WaitCursor; try { if (checkProtocolIPv4.Checked) { Magic.SendMagicPacket(textMac.Text, textSecureOn.Text, textBroadcastAddress.Text, checkBroadcastAddress.Checked, textBroadcastPort.Text, checkBroadcastPort.Checked); } if (checkProtocolIPv6.Checked) { Magic.SendMagicPacketIPv6(textMac.Text, textSecureOn.Text, textBroadcastPort.Text, checkBroadcastPort.Checked); } } catch (InvalidOperationException ex) { Medo.MessageBox.ShowError(this, ex.Message); } System.Threading.Thread.Sleep(Settings.WolSleepInterval); } finally { Cursor.Current = Cursors.Default; } } catch (FormatException ex) { Medo.MessageBox.ShowError(this, ex.Message); } } private void textMac_TextChanged(object sender, EventArgs e) { CheckForm(); } private void textSecureOn_TextChanged(object sender, EventArgs e) { CheckForm(); } private void textBroadcastAddress_TextChanged(object sender, EventArgs e) { CheckForm(); } private void textBroadcastPort_TextChanged(object sender, EventArgs e) { CheckForm(); } private void CheckForm() { if (!Medo.Net.WakeOnLan.IsMacAddressValid(textMac.Text)) { erp.SetError(textMac, "MAC address is not valid."); } else { erp.SetError(textMac, null); } if (!Medo.Net.WakeOnLan.IsSecureOnPasswordValid(textSecureOn.Text)) { erp.SetError(textSecureOn, "SecureOn password is not valid."); } else { erp.SetError(textSecureOn, null); } if (checkBroadcastAddress.Checked) { if (string.IsNullOrEmpty(textBroadcastAddress.Text.Trim())) { erp.SetError(checkBroadcastAddress, "Host cannot be empty."); } else { erp.SetError(checkBroadcastAddress, null); } } else { erp.SetError(checkBroadcastAddress, null); } int port; if (checkBroadcastPort.Checked) { if (int.TryParse(textBroadcastPort.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) && ((port >= 0) && (port <= 65535))) { erp.SetError(checkBroadcastPort, null); } else { erp.SetError(checkBroadcastPort, "Port is not valid."); } } else { erp.SetError(checkBroadcastPort, null); } buttonWake.Enabled = (Medo.Net.WakeOnLan.IsMacAddressValid(textMac.Text)); } } }